org.el (org-indent-line): Fix table formulas indenting
[org-mode.git] / lisp / org.el
bloba307ca62abb8ce02a777fae5c9a956253d035382
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 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-timestamps-up "org-clock" ())
119 (declare-function org-clock-timestamps-down "org-clock" ())
120 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122 (declare-function orgtbl-mode "org-table" (&optional arg))
123 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
124 (declare-function org-beamer-mode "org-beamer" ())
125 (declare-function org-table-edit-field "org-table" (arg))
126 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
127 (declare-function org-id-get-create "org-id" (&optional force))
128 (declare-function org-id-find-id-file "org-id" (id))
129 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
130 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
131 (declare-function org-table-align "org-table" ())
132 (declare-function org-table-paste-rectangle "org-table" ())
133 (declare-function org-table-maybe-eval-formula "org-table" ())
134 (declare-function org-table-maybe-recalculate-line "org-table" ())
136 ;; load languages based on value of `org-babel-load-languages'
137 (defvar org-babel-load-languages)
139 ;;;###autoload
140 (defun org-babel-do-load-languages (sym value)
141 "Load the languages defined in `org-babel-load-languages'."
142 (set-default sym value)
143 (mapc (lambda (pair)
144 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
145 (if active
146 (progn
147 (require (intern (concat "ob-" lang))))
148 (progn
149 (funcall 'fmakunbound
150 (intern (concat "org-babel-execute:" lang)))
151 (funcall 'fmakunbound
152 (intern (concat "org-babel-expand-body:" lang)))))))
153 org-babel-load-languages))
155 (defcustom org-babel-load-languages '((emacs-lisp . t))
156 "Languages which can be evaluated in Org-mode buffers.
157 This list can be used to load support for any of the languages
158 below, note that each language will depend on a different set of
159 system executables and/or Emacs modes. When a language is
160 \"loaded\", then code blocks in that language can be evaluated
161 with `org-babel-execute-src-block' bound by default to C-c
162 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
163 be set to remove code block evaluation from the C-c C-c
164 keybinding. By default only Emacs Lisp (which has no
165 requirements) is loaded."
166 :group 'org-babel
167 :set 'org-babel-do-load-languages
168 :version "24.1"
169 :type '(alist :tag "Babel Languages"
170 :key-type
171 (choice
172 (const :tag "Awk" awk)
173 (const :tag "C" C)
174 (const :tag "R" R)
175 (const :tag "Asymptote" asymptote)
176 (const :tag "Calc" calc)
177 (const :tag "Clojure" clojure)
178 (const :tag "CSS" css)
179 (const :tag "Ditaa" ditaa)
180 (const :tag "Dot" dot)
181 (const :tag "Emacs Lisp" emacs-lisp)
182 (const :tag "Fortran" fortran)
183 (const :tag "Gnuplot" gnuplot)
184 (const :tag "Haskell" haskell)
185 (const :tag "IO" io)
186 (const :tag "Java" java)
187 (const :tag "Javascript" js)
188 (const :tag "LaTeX" latex)
189 (const :tag "Ledger" ledger)
190 (const :tag "Lilypond" lilypond)
191 (const :tag "Lisp" lisp)
192 (const :tag "Maxima" maxima)
193 (const :tag "Matlab" matlab)
194 (const :tag "Mscgen" mscgen)
195 (const :tag "Ocaml" ocaml)
196 (const :tag "Octave" octave)
197 (const :tag "Org" org)
198 (const :tag "Perl" perl)
199 (const :tag "Pico Lisp" picolisp)
200 (const :tag "PlantUML" plantuml)
201 (const :tag "Python" python)
202 (const :tag "Ruby" ruby)
203 (const :tag "Sass" sass)
204 (const :tag "Scala" scala)
205 (const :tag "Scheme" scheme)
206 (const :tag "Screen" screen)
207 (const :tag "Shell Script" sh)
208 (const :tag "Shen" shen)
209 (const :tag "Sql" sql)
210 (const :tag "Sqlite" sqlite))
211 :value-type (boolean :tag "Activate" :value t)))
213 ;;;; Customization variables
214 (defcustom org-clone-delete-id nil
215 "Remove ID property of clones of a subtree.
216 When non-nil, clones of a subtree don't inherit the ID property.
217 Otherwise they inherit the ID property with a new unique
218 identifier."
219 :type 'boolean
220 :version "24.1"
221 :group 'org-id)
223 ;;; Version
224 (require 'org-compat)
225 (org-check-version)
227 ;;;###autoload
228 (defun org-version (&optional here full message)
229 "Show the org-mode version in the echo area.
230 With prefix argument HERE, insert it at point.
231 When FULL is non-nil, use a verbose version string.
232 When MESSAGE is non-nil, display a message with the version."
233 (interactive "P")
234 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
235 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
236 (org-trash (or
237 (and (fboundp 'org-release) (fboundp 'org-git-version))
238 (load (concat org-dir "org-version.el")
239 'noerror 'nomessage 'nosuffix)))
240 (org-version (org-release))
241 (git-version (org-git-version))
242 (version (format "Org-mode version %s (%s @ %s)"
243 org-version
244 git-version
245 (if org-install-dir
246 (if (string= org-dir org-install-dir)
247 org-install-dir
248 (concat "mixed installation! " org-install-dir " and " org-dir))
249 "org-loaddefs.el can not be found!")))
250 (_version (if full version org-version)))
251 (if (org-called-interactively-p 'interactive)
252 (if here
253 (insert version)
254 (message version))
255 (if message (message _version))
256 _version)))
258 (defconst org-version (org-version))
260 ;;; Compatibility constants
262 ;;; The custom variables
264 (defgroup org nil
265 "Outline-based notes management and organizer."
266 :tag "Org"
267 :group 'outlines
268 :group 'calendar)
270 (defcustom org-mode-hook nil
271 "Mode hook for Org-mode, run after the mode was turned on."
272 :group 'org
273 :type 'hook)
275 (defcustom org-load-hook nil
276 "Hook that is run after org.el has been loaded."
277 :group 'org
278 :type 'hook)
280 (defcustom org-log-buffer-setup-hook nil
281 "Hook that is run after an Org log buffer is created."
282 :group 'org
283 :version "24.1"
284 :type 'hook)
286 (defvar org-modules) ; defined below
287 (defvar org-modules-loaded nil
288 "Have the modules been loaded already?")
290 (defun org-load-modules-maybe (&optional force)
291 "Load all extensions listed in `org-modules'."
292 (when (or force (not org-modules-loaded))
293 (mapc (lambda (ext)
294 (condition-case nil (require ext)
295 (error (message "Problems while trying to load feature `%s'" ext))))
296 org-modules)
297 (setq org-modules-loaded t)))
299 (defun org-set-modules (var value)
300 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
301 (set var value)
302 (when (featurep 'org)
303 (org-load-modules-maybe 'force)))
305 (when (org-bound-and-true-p org-modules)
306 (let ((a (member 'org-infojs org-modules)))
307 (and a (setcar a 'org-jsinfo))))
309 (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)
310 "Modules that should always be loaded together with org.el.
311 If a description starts with <C>, the file is not part of Emacs
312 and loading it will require that you have downloaded and properly installed
313 the org-mode distribution.
315 You can also use this system to load external packages (i.e. neither Org
316 core modules, nor modules from the CONTRIB directory). Just add symbols
317 to the end of the list. If the package is called org-xyz.el, then you need
318 to add the symbol `xyz', and the package must have a call to
320 (provide 'org-xyz)"
321 :group 'org
322 :set 'org-set-modules
323 :type
324 '(set :greedy t
325 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
326 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
327 (const :tag " crypt: Encryption of subtrees" org-crypt)
328 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
329 (const :tag " docview: Links to doc-view buffers" org-docview)
330 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
331 (const :tag " id: Global IDs for identifying entries" org-id)
332 (const :tag " info: Links to Info nodes" org-info)
333 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
334 (const :tag " habit: Track your consistency with habits" org-habit)
335 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
336 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
337 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
338 (const :tag " mew Links to Mew folders/messages" org-mew)
339 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
340 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
341 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
342 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
343 (const :tag " vm: Links to VM folders/messages" org-vm)
344 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
345 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
346 (const :tag " mouse: Additional mouse support" org-mouse)
347 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
349 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
350 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
351 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
352 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
353 (const :tag "C collector: Collect properties into tables" org-collector)
354 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
355 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
356 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
357 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
358 (const :tag "C eval: Include command output as text" org-eval)
359 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
360 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
361 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
362 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
363 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
365 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
367 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
368 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
369 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
370 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
371 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
372 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
373 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
374 (const :tag "C mtags: Support for muse-like tags" org-mtags)
375 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
376 (const :tag "C registry: A registry for Org-mode links" org-registry)
377 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
378 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
379 (const :tag "C secretary: Team management with org-mode" org-secretary)
380 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
381 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
382 (const :tag "C track: Keep up with Org-mode development" org-track)
383 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
384 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
385 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
387 (defcustom org-support-shift-select nil
388 "Non-nil means make shift-cursor commands select text when possible.
390 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
391 start selecting a region, or enlarge regions started in this way.
392 In Org-mode, in special contexts, these same keys are used for
393 other purposes, important enough to compete with shift selection.
394 Org tries to balance these needs by supporting `shift-select-mode'
395 outside these special contexts, under control of this variable.
397 The default of this variable is nil, to avoid confusing behavior. Shifted
398 cursor keys will then execute Org commands in the following contexts:
399 - on a headline, changing TODO state (left/right) and priority (up/down)
400 - on a time stamp, changing the time
401 - in a plain list item, changing the bullet type
402 - in a property definition line, switching between allowed values
403 - in the BEGIN line of a clock table (changing the time block).
404 Outside these contexts, the commands will throw an error.
406 When this variable is t and the cursor is not in a special
407 context, Org-mode will support shift-selection for making and
408 enlarging regions. To make this more effective, the bullet
409 cycling will no longer happen anywhere in an item line, but only
410 if the cursor is exactly on the bullet.
412 If you set this variable to the symbol `always', then the keys
413 will not be special in headlines, property lines, and item lines,
414 to make shift selection work there as well. If this is what you
415 want, you can use the following alternative commands: `C-c C-t'
416 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
417 can be used to switch TODO sets, `C-c -' to cycle item bullet
418 types, and properties can be edited by hand or in column view.
420 However, when the cursor is on a timestamp, shift-cursor commands
421 will still edit the time stamp - this is just too good to give up.
423 XEmacs user should have this variable set to nil, because
424 `shift-select-mode' is in Emacs 23 or later only."
425 :group 'org
426 :type '(choice
427 (const :tag "Never" nil)
428 (const :tag "When outside special context" t)
429 (const :tag "Everywhere except timestamps" always)))
431 (defcustom org-loop-over-headlines-in-active-region nil
432 "Shall some commands act upon headlines in the active region?
434 When set to `t', some commands will be performed in all headlines
435 within the active region.
437 When set to `start-level', some commands will be performed in all
438 headlines within the active region, provided that these headlines
439 are of the same level than the first one.
441 When set to a string, those commands will be performed on the
442 matching headlines within the active region. Such string must be
443 a tags/property/todo match as it is used in the agenda tags view.
445 The list of commands is: `org-schedule', `org-deadline',
446 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
447 `org-archive-to-archive-sibling'. The archiving commands skip
448 already archived entries."
449 :type '(choice (const :tag "Don't loop" nil)
450 (const :tag "All headlines in active region" t)
451 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
452 (string :tag "Tags/Property/Todo matcher"))
453 :version "24.1"
454 :group 'org-todo
455 :group 'org-archive)
457 (defgroup org-startup nil
458 "Options concerning startup of Org-mode."
459 :tag "Org Startup"
460 :group 'org)
462 (defcustom org-startup-folded t
463 "Non-nil means entering Org-mode will switch to OVERVIEW.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
467 #+STARTUP: fold (or `overview', this is equivalent)
468 #+STARTUP: nofold (or `showall', this is equivalent)
469 #+STARTUP: content
470 #+STARTUP: showeverything"
471 :group 'org-startup
472 :type '(choice
473 (const :tag "nofold: show all" nil)
474 (const :tag "fold: overview" t)
475 (const :tag "content: all headlines" content)
476 (const :tag "show everything, even drawers" showeverything)))
478 (defcustom org-startup-truncated t
479 "Non-nil means entering Org-mode will set `truncate-lines'.
480 This is useful since some lines containing links can be very long and
481 uninteresting. Also tables look terrible when wrapped."
482 :group 'org-startup
483 :type 'boolean)
485 (defcustom org-startup-indented nil
486 "Non-nil means turn on `org-indent-mode' on startup.
487 This can also be configured on a per-file basis by adding one of
488 the following lines anywhere in the buffer:
490 #+STARTUP: indent
491 #+STARTUP: noindent"
492 :group 'org-structure
493 :type '(choice
494 (const :tag "Not" nil)
495 (const :tag "Globally (slow on startup in large files)" t)))
497 (defcustom org-use-sub-superscripts t
498 "Non-nil means interpret \"_\" and \"^\" for export.
499 When this option is turned on, you can use TeX-like syntax for sub- and
500 superscripts. Several characters after \"_\" or \"^\" will be
501 considered as a single item - so grouping with {} is normally not
502 needed. For example, the following things will be parsed as single
503 sub- or superscripts.
505 10^24 or 10^tau several digits will be considered 1 item.
506 10^-12 or 10^-tau a leading sign with digits or a word
507 x^2-y^3 will be read as x^2 - y^3, because items are
508 terminated by almost any nonword/nondigit char.
509 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
511 Still, ambiguity is possible - so when in doubt use {} to enclose the
512 sub/superscript. If you set this variable to the symbol `{}',
513 the braces are *required* in order to trigger interpretations as
514 sub/superscript. This can be helpful in documents that need \"_\"
515 frequently in plain text.
517 Not all export backends support this, but HTML does.
519 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
520 :group 'org-startup
521 :group 'org-export-translation
522 :version "24.1"
523 :type '(choice
524 (const :tag "Always interpret" t)
525 (const :tag "Only with braces" {})
526 (const :tag "Never interpret" nil)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
532 (defcustom org-startup-with-beamer-mode nil
533 "Non-nil means turn on `org-beamer-mode' on startup.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
537 #+STARTUP: beamer"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-startup-align-all-tables nil
543 "Non-nil means align all tables when visiting a file.
544 This is useful when the column width in tables is forced with <N> cookies
545 in table fields. Such tables will look correct only after the first re-align.
546 This can also be configured on a per-file basis by adding one of
547 the following lines anywhere in the buffer:
548 #+STARTUP: align
549 #+STARTUP: noalign"
550 :group 'org-startup
551 :type 'boolean)
553 (defcustom org-startup-with-inline-images nil
554 "Non-nil means show inline images when loading a new Org file.
555 This can also be configured on a per-file basis by adding one of
556 the following lines anywhere in the buffer:
557 #+STARTUP: inlineimages
558 #+STARTUP: noinlineimages"
559 :group 'org-startup
560 :version "24.1"
561 :type 'boolean)
563 (defcustom org-insert-mode-line-in-empty-file nil
564 "Non-nil means insert the first line setting Org-mode in empty files.
565 When the function `org-mode' is called interactively in an empty file, this
566 normally means that the file name does not automatically trigger Org-mode.
567 To ensure that the file will always be in Org-mode in the future, a
568 line enforcing Org-mode will be inserted into the buffer, if this option
569 has been set."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-replace-disputed-keys nil
574 "Non-nil means use alternative key bindings for some keys.
575 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
576 These keys are also used by other packages like shift-selection-mode'
577 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
578 If you want to use Org-mode together with one of these other modes,
579 or more generally if you would like to move some Org-mode commands to
580 other keys, set this variable and configure the keys with the variable
581 `org-disputed-keys'.
583 This option is only relevant at load-time of Org-mode, and must be set
584 *before* org.el is loaded. Changing it requires a restart of Emacs to
585 become effective."
586 :group 'org-startup
587 :type 'boolean)
589 (defcustom org-use-extra-keys nil
590 "Non-nil means use extra key sequence definitions for certain commands.
591 This happens automatically if you run XEmacs or if `window-system'
592 is nil. This variable lets you do the same manually. You must
593 set it before loading org.
595 Example: on Carbon Emacs 22 running graphically, with an external
596 keyboard on a Powerbook, the default way of setting M-left might
597 not work for either Alt or ESC. Setting this variable will make
598 it work for ESC."
599 :group 'org-startup
600 :type 'boolean)
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
605 (defcustom org-disputed-keys
606 '(([(shift up)] . [(meta p)])
607 ([(shift down)] . [(meta n)])
608 ([(shift left)] . [(meta -)])
609 ([(shift right)] . [(meta +)])
610 ([(control shift right)] . [(meta shift +)])
611 ([(control shift left)] . [(meta shift -)]))
612 "Keys for which Org-mode and other modes compete.
613 This is an alist, cars are the default keys, second element specifies
614 the alternative to use when `org-replace-disputed-keys' is t.
616 Keys can be specified in any syntax supported by `define-key'.
617 The value of this option takes effect only at Org-mode's startup,
618 therefore you'll have to restart Emacs to apply it after changing."
619 :group 'org-startup
620 :type 'alist)
622 (defun org-key (key)
623 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
624 Or return the original if not disputed.
625 Also apply the translations defined in `org-xemacs-key-equivalents'."
626 (when org-replace-disputed-keys
627 (let* ((nkey (key-description key))
628 (x (org-find-if (lambda (x)
629 (equal (key-description (car x)) nkey))
630 org-disputed-keys)))
631 (setq key (if x (cdr x) key))))
632 (when (featurep 'xemacs)
633 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
634 key)
636 (defun org-find-if (predicate seq)
637 (catch 'exit
638 (while seq
639 (if (funcall predicate (car seq))
640 (throw 'exit (car seq))
641 (pop seq)))))
643 (defun org-defkey (keymap key def)
644 "Define a key, possibly translated, as returned by `org-key'."
645 (define-key keymap (org-key key) def))
647 (defcustom org-ellipsis nil
648 "The ellipsis to use in the Org-mode outline.
649 When nil, just use the standard three dots. When a string, use that instead,
650 When a face, use the standard 3 dots, but with the specified face.
651 The change affects only Org-mode (which will then use its own display table).
652 Changing this requires executing `M-x org-mode' in a buffer to become
653 effective."
654 :group 'org-startup
655 :type '(choice (const :tag "Default" nil)
656 (face :tag "Face" :value org-warning)
657 (string :tag "String" :value "...#")))
659 (defvar org-display-table nil
660 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
662 (defgroup org-keywords nil
663 "Keywords in Org-mode."
664 :tag "Org Keywords"
665 :group 'org)
667 (defcustom org-deadline-string "DEADLINE:"
668 "String to mark deadline entries.
669 A deadline is this string, followed by a time stamp. Should be a word,
670 terminated by a colon. You can insert a schedule keyword and
671 a timestamp with \\[org-deadline].
672 Changes become only effective after restarting Emacs."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-scheduled-string "SCHEDULED:"
677 "String to mark scheduled TODO entries.
678 A schedule is this string, followed by a time stamp. Should be a word,
679 terminated by a colon. You can insert a schedule keyword and
680 a timestamp with \\[org-schedule].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-closed-string "CLOSED:"
686 "String used as the prefix for timestamps logging closing a TODO entry."
687 :group 'org-keywords
688 :type 'string)
690 (defcustom org-clock-string "CLOCK:"
691 "String used as prefix for timestamps clocking work hours on an item."
692 :group 'org-keywords
693 :type 'string)
695 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
696 org-scheduled-string "\\|"
697 org-deadline-string "\\|"
698 org-closed-string "\\|"
699 org-clock-string "\\)")
700 "Matches a line with planning or clock info.")
702 (defcustom org-comment-string "COMMENT"
703 "Entries starting with this keyword will never be exported.
704 An entry can be toggled between COMMENT and normal with
705 \\[org-toggle-comment].
706 Changes become only effective after restarting Emacs."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-quote-string "QUOTE"
711 "Entries starting with this keyword will be exported in fixed-width font.
712 Quoting applies only to the text in the entry following the headline, and does
713 not extend beyond the next headline, even if that is lower level.
714 An entry can be toggled between QUOTE and normal with
715 \\[org-toggle-fixed-width-section]."
716 :group 'org-keywords
717 :type 'string)
719 (defconst org-repeat-re
720 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
721 "Regular expression for specifying repeated events.
722 After a match, group 1 contains the repeat expression.")
724 (defgroup org-structure nil
725 "Options concerning the general structure of Org-mode files."
726 :tag "Org Structure"
727 :group 'org)
729 (defgroup org-reveal-location nil
730 "Options about how to make context of a location visible."
731 :tag "Org Reveal Location"
732 :group 'org-structure)
734 (defconst org-context-choice
735 '(choice
736 (const :tag "Always" t)
737 (const :tag "Never" nil)
738 (repeat :greedy t :tag "Individual contexts"
739 (cons
740 (choice :tag "Context"
741 (const agenda)
742 (const org-goto)
743 (const occur-tree)
744 (const tags-tree)
745 (const link-search)
746 (const mark-goto)
747 (const bookmark-jump)
748 (const isearch)
749 (const default))
750 (boolean))))
751 "Contexts for the reveal options.")
753 (defcustom org-show-hierarchy-above '((default . t))
754 "Non-nil means show full hierarchy when revealing a location.
755 Org-mode often shows locations in an org-mode file which might have
756 been invisible before. When this is set, the hierarchy of headings
757 above the exposed location is shown.
758 Turning this off for example for sparse trees makes them very compact.
759 Instead of t, this can also be an alist specifying this option for different
760 contexts. Valid contexts are
761 agenda when exposing an entry from the agenda
762 org-goto when using the command `org-goto' on key C-c C-j
763 occur-tree when using the command `org-occur' on key C-c /
764 tags-tree when constructing a sparse tree based on tags matches
765 link-search when exposing search matches associated with a link
766 mark-goto when exposing the jump goal of a mark
767 bookmark-jump when exposing a bookmark location
768 isearch when exiting from an incremental search
769 default default for all contexts not set explicitly"
770 :group 'org-reveal-location
771 :type org-context-choice)
773 (defcustom org-show-following-heading '((default . nil))
774 "Non-nil means show following heading when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the heading following the
777 match is shown.
778 Turning this off for example for sparse trees makes them very compact,
779 but makes it harder to edit the location of the match. In such a case,
780 use the command \\[org-reveal] to show more context.
781 Instead of t, this can also be an alist specifying this option for different
782 contexts. See `org-show-hierarchy-above' for valid contexts."
783 :group 'org-reveal-location
784 :type org-context-choice)
786 (defcustom org-show-siblings '((default . nil) (isearch t))
787 "Non-nil means show all sibling heading when revealing a location.
788 Org-mode often shows locations in an org-mode file which might have
789 been invisible before. When this is set, the sibling of the current entry
790 heading are all made visible. If `org-show-hierarchy-above' is t,
791 the same happens on each level of the hierarchy above the current entry.
793 By default this is on for the isearch context, off for all other contexts.
794 Turning this off for example for sparse trees makes them very compact,
795 but makes it harder to edit the location of the match. In such a case,
796 use the command \\[org-reveal] to show more context.
797 Instead of t, this can also be an alist specifying this option for different
798 contexts. See `org-show-hierarchy-above' for valid contexts."
799 :group 'org-reveal-location
800 :type org-context-choice)
802 (defcustom org-show-entry-below '((default . nil))
803 "Non-nil means show the entry below a headline when revealing a location.
804 Org-mode often shows locations in an org-mode file which might have
805 been invisible before. When this is set, the text below the headline that is
806 exposed is also shown.
808 By default this is off for all contexts.
809 Instead of t, this can also be an alist specifying this option for different
810 contexts. See `org-show-hierarchy-above' for valid contexts."
811 :group 'org-reveal-location
812 :type org-context-choice)
814 (defcustom org-indirect-buffer-display 'other-window
815 "How should indirect tree buffers be displayed?
816 This applies to indirect buffers created with the commands
817 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
818 Valid values are:
819 current-window Display in the current window
820 other-window Just display in another window.
821 dedicated-frame Create one new frame, and re-use it each time.
822 new-frame Make a new frame each time. Note that in this case
823 previously-made indirect buffers are kept, and you need to
824 kill these buffers yourself."
825 :group 'org-structure
826 :group 'org-agenda-windows
827 :type '(choice
828 (const :tag "In current window" current-window)
829 (const :tag "In current frame, other window" other-window)
830 (const :tag "Each time a new frame" new-frame)
831 (const :tag "One dedicated frame" dedicated-frame)))
833 (defcustom org-use-speed-commands nil
834 "Non-nil means activate single letter commands at beginning of a headline.
835 This may also be a function to test for appropriate locations where speed
836 commands should be active."
837 :group 'org-structure
838 :type '(choice
839 (const :tag "Never" nil)
840 (const :tag "At beginning of headline stars" t)
841 (function)))
843 (defcustom org-speed-commands-user nil
844 "Alist of additional speed commands.
845 This list will be checked before `org-speed-commands-default'
846 when the variable `org-use-speed-commands' is non-nil
847 and when the cursor is at the beginning of a headline.
848 The car if each entry is a string with a single letter, which must
849 be assigned to `self-insert-command' in the global map.
850 The cdr is either a command to be called interactively, a function
851 to be called, or a form to be evaluated.
852 An entry that is just a list with a single string will be interpreted
853 as a descriptive headline that will be added when listing the speed
854 commands in the Help buffer using the `?' speed command."
855 :group 'org-structure
856 :type '(repeat :value ("k" . ignore)
857 (choice :value ("k" . ignore)
858 (list :tag "Descriptive Headline" (string :tag "Headline"))
859 (cons :tag "Letter and Command"
860 (string :tag "Command letter")
861 (choice
862 (function)
863 (sexp))))))
865 (defgroup org-cycle nil
866 "Options concerning visibility cycling in Org-mode."
867 :tag "Org Cycle"
868 :group 'org-structure)
870 (defcustom org-cycle-skip-children-state-if-no-children t
871 "Non-nil means skip CHILDREN state in entries that don't have any."
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-max-level nil
876 "Maximum level which should still be subject to visibility cycling.
877 Levels higher than this will, for cycling, be treated as text, not a headline.
878 When `org-odd-levels-only' is set, a value of N in this variable actually
879 means 2N-1 stars as the limiting headline.
880 When nil, cycle all levels.
881 Note that the limiting level of cycling is also influenced by
882 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
883 `org-inlinetask-min-level' is, cycling will be limited to levels one less
884 than its value."
885 :group 'org-cycle
886 :type '(choice
887 (const :tag "No limit" nil)
888 (integer :tag "Maximum level")))
890 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
891 "Names of drawers. Drawers are not opened by cycling on the headline above.
892 Drawers only open with a TAB on the drawer line itself. A drawer looks like
893 this:
894 :DRAWERNAME:
895 .....
896 :END:
897 The drawer \"PROPERTIES\" is special for capturing properties through
898 the property API.
900 Drawers can be defined on the per-file basis with a line like:
902 #+DRAWERS: HIDDEN STATE PROPERTIES"
903 :group 'org-structure
904 :group 'org-cycle
905 :type '(repeat (string :tag "Drawer Name")))
907 (defcustom org-hide-block-startup nil
908 "Non-nil means entering Org-mode will fold all blocks.
909 This can also be set in on a per-file basis with
911 #+STARTUP: hideblocks
912 #+STARTUP: showblocks"
913 :group 'org-startup
914 :group 'org-cycle
915 :type 'boolean)
917 (defcustom org-cycle-global-at-bob nil
918 "Cycle globally if cursor is at beginning of buffer and not at a headline.
919 This makes it possible to do global cycling without having to use S-TAB or
920 \\[universal-argument] TAB. For this special case to work, the first line
921 of the buffer must not be a headline -- it may be empty or some other text.
922 When used in this way, `org-cycle-hook' is disabled temporarily to make
923 sure the cursor stays at the beginning of the buffer. When this option is
924 nil, don't do anything special at the beginning of the buffer."
925 :group 'org-cycle
926 :type 'boolean)
928 (defcustom org-cycle-level-after-item/entry-creation t
929 "Non-nil means cycle entry level or item indentation in new empty entries.
931 When the cursor is at the end of an empty headline, i.e with only stars
932 and maybe a TODO keyword, TAB will then switch the entry to become a child,
933 and then all possible ancestor states, before returning to the original state.
934 This makes data entry extremely fast: M-RET to create a new headline,
935 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
937 When the cursor is at the end of an empty plain list item, one TAB will
938 make it a subitem, two or more tabs will back up to make this an item
939 higher up in the item hierarchy."
940 :group 'org-cycle
941 :type 'boolean)
943 (defcustom org-cycle-emulate-tab t
944 "Where should `org-cycle' emulate TAB.
945 nil Never
946 white Only in completely white lines
947 whitestart Only at the beginning of lines, before the first non-white char
948 t Everywhere except in headlines
949 exc-hl-bol Everywhere except at the start of a headline
950 If TAB is used in a place where it does not emulate TAB, the current subtree
951 visibility is cycled."
952 :group 'org-cycle
953 :type '(choice (const :tag "Never" nil)
954 (const :tag "Only in completely white lines" white)
955 (const :tag "Before first char in a line" whitestart)
956 (const :tag "Everywhere except in headlines" t)
957 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
960 (defcustom org-cycle-separator-lines 2
961 "Number of empty lines needed to keep an empty line between collapsed trees.
962 If you leave an empty line between the end of a subtree and the following
963 headline, this empty line is hidden when the subtree is folded.
964 Org-mode will leave (exactly) one empty line visible if the number of
965 empty lines is equal or larger to the number given in this variable.
966 So the default 2 means at least 2 empty lines after the end of a subtree
967 are needed to produce free space between a collapsed subtree and the
968 following headline.
970 If the number is negative, and the number of empty lines is at least -N,
971 all empty lines are shown.
973 Special case: when 0, never leave empty lines in collapsed view."
974 :group 'org-cycle
975 :type 'integer)
976 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
978 (defcustom org-pre-cycle-hook nil
979 "Hook that is run before visibility cycling is happening.
980 The function(s) in this hook must accept a single argument which indicates
981 the new state that will be set right after running this hook. The
982 argument is a symbol. Before a global state change, it can have the values
983 `overview', `content', or `all'. Before a local state change, it can have
984 the values `folded', `children', or `subtree'."
985 :group 'org-cycle
986 :type 'hook)
988 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
989 org-cycle-hide-drawers
990 org-cycle-show-empty-lines
991 org-optimize-window-after-visibility-change)
992 "Hook that is run after `org-cycle' has changed the buffer visibility.
993 The function(s) in this hook must accept a single argument which indicates
994 the new state that was set by the most recent `org-cycle' command. The
995 argument is a symbol. After a global state change, it can have the values
996 `overview', `contents', or `all'. After a local state change, it can have
997 the values `folded', `children', or `subtree'."
998 :group 'org-cycle
999 :type 'hook)
1001 (defgroup org-edit-structure nil
1002 "Options concerning structure editing in Org-mode."
1003 :tag "Org Edit Structure"
1004 :group 'org-structure)
1006 (defcustom org-odd-levels-only nil
1007 "Non-nil means skip even levels and only use odd levels for the outline.
1008 This has the effect that two stars are being added/taken away in
1009 promotion/demotion commands. It also influences how levels are
1010 handled by the exporters.
1011 Changing it requires restart of `font-lock-mode' to become effective
1012 for fontification also in regions already fontified.
1013 You may also set this on a per-file basis by adding one of the following
1014 lines to the buffer:
1016 #+STARTUP: odd
1017 #+STARTUP: oddeven"
1018 :group 'org-edit-structure
1019 :group 'org-appearance
1020 :type 'boolean)
1022 (defcustom org-adapt-indentation t
1023 "Non-nil means adapt indentation to outline node level.
1025 When this variable is set, Org assumes that you write outlines by
1026 indenting text in each node to align with the headline (after the stars).
1027 The following issues are influenced by this variable:
1029 - When this is set and the *entire* text in an entry is indented, the
1030 indentation is increased by one space in a demotion command, and
1031 decreased by one in a promotion command. If any line in the entry
1032 body starts with text at column 0, indentation is not changed at all.
1034 - Property drawers and planning information is inserted indented when
1035 this variable s set. When nil, they will not be indented.
1037 - TAB indents a line relative to context. The lines below a headline
1038 will be indented when this variable is set.
1040 Note that this is all about true indentation, by adding and removing
1041 space characters. See also `org-indent.el' which does level-dependent
1042 indentation in a virtual way, i.e. at display time in Emacs."
1043 :group 'org-edit-structure
1044 :type 'boolean)
1046 (defcustom org-special-ctrl-a/e nil
1047 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1049 When t, `C-a' will bring back the cursor to the beginning of the
1050 headline text, i.e. after the stars and after a possible TODO
1051 keyword. In an item, this will be the position after bullet and
1052 check-box, if any. When the cursor is already at that position,
1053 another `C-a' will bring it to the beginning of the line.
1055 `C-e' will jump to the end of the headline, ignoring the presence
1056 of tags in the headline. A second `C-e' will then jump to the
1057 true end of the line, after any tags. This also means that, when
1058 this variable is non-nil, `C-e' also will never jump beyond the
1059 end of the heading of a folded section, i.e. not after the
1060 ellipses.
1062 When set to the symbol `reversed', the first `C-a' or `C-e' works
1063 normally, going to the true line boundary first. Only a directly
1064 following, identical keypress will bring the cursor to the
1065 special positions.
1067 This may also be a cons cell where the behavior for `C-a' and
1068 `C-e' is set separately."
1069 :group 'org-edit-structure
1070 :type '(choice
1071 (const :tag "off" nil)
1072 (const :tag "on: after stars/bullet and before tags first" t)
1073 (const :tag "reversed: true line boundary first" reversed)
1074 (cons :tag "Set C-a and C-e separately"
1075 (choice :tag "Special C-a"
1076 (const :tag "off" nil)
1077 (const :tag "on: after stars/bullet first" t)
1078 (const :tag "reversed: before stars/bullet first" reversed))
1079 (choice :tag "Special C-e"
1080 (const :tag "off" nil)
1081 (const :tag "on: before tags first" t)
1082 (const :tag "reversed: after tags first" reversed)))))
1083 (if (fboundp 'defvaralias)
1084 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1086 (defcustom org-special-ctrl-k nil
1087 "Non-nil means `C-k' will behave specially in headlines.
1088 When nil, `C-k' will call the default `kill-line' command.
1089 When t, the following will happen while the cursor is in the headline:
1091 - When the cursor is at the beginning of a headline, kill the entire
1092 line and possible the folded subtree below the line.
1093 - When in the middle of the headline text, kill the headline up to the tags.
1094 - When after the headline text, kill the tags."
1095 :group 'org-edit-structure
1096 :type 'boolean)
1098 (defcustom org-ctrl-k-protect-subtree nil
1099 "Non-nil means, do not delete a hidden subtree with C-k.
1100 When set to the symbol `error', simply throw an error when C-k is
1101 used to kill (part-of) a headline that has hidden text behind it.
1102 Any other non-nil value will result in a query to the user, if it is
1103 OK to kill that hidden subtree. When nil, kill without remorse."
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not protect hidden subtrees" nil)
1108 (const :tag "Protect hidden subtrees with a security query" t)
1109 (const :tag "Never kill a hidden subtree with C-k" error)))
1111 (defcustom org-catch-invisible-edits nil
1112 "Check if in invisible region before inserting or deleting a character.
1113 Valid values are:
1115 nil Do not check, so just do invisible edits.
1116 error Throw an error and do nothing.
1117 show Make point visible, and do the requested edit.
1118 show-and-error Make point visible, then throw an error and abort the edit.
1119 smart Make point visible, and do insertion/deletion if it is
1120 adjacent to visible text and the change feels predictable.
1121 Never delete a previously invisible character or add in the
1122 middle or right after an invisible region. Basically, this
1123 allows insertion and backward-delete right before ellipses.
1124 FIXME: maybe in this case we should not even show?"
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not check" nil)
1129 (const :tag "Throw error when trying to edit" error)
1130 (const :tag "Unhide, but do not do the edit" show-and-error)
1131 (const :tag "Show invisible part and do the edit" show)
1132 (const :tag "Be smart and do the right thing" smart)))
1134 (defcustom org-yank-folded-subtrees t
1135 "Non-nil means when yanking subtrees, fold them.
1136 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1137 it starts with a heading and all other headings in it are either children
1138 or siblings, then fold all the subtrees. However, do this only if no
1139 text after the yank would be swallowed into a folded tree by this action."
1140 :group 'org-edit-structure
1141 :type 'boolean)
1143 (defcustom org-yank-adjusted-subtrees nil
1144 "Non-nil means when yanking subtrees, adjust the level.
1145 With this setting, `org-paste-subtree' is used to insert the subtree, see
1146 this function for details."
1147 :group 'org-edit-structure
1148 :type 'boolean)
1150 (defcustom org-M-RET-may-split-line '((default . t))
1151 "Non-nil means M-RET will split the line at the cursor position.
1152 When nil, it will go to the end of the line before making a
1153 new line.
1154 You may also set this option in a different way for different
1155 contexts. Valid contexts are:
1157 headline when creating a new headline
1158 item when creating a new item
1159 table in a table field
1160 default the value to be used for all contexts not explicitly
1161 customized"
1162 :group 'org-structure
1163 :group 'org-table
1164 :type '(choice
1165 (const :tag "Always" t)
1166 (const :tag "Never" nil)
1167 (repeat :greedy t :tag "Individual contexts"
1168 (cons
1169 (choice :tag "Context"
1170 (const headline)
1171 (const item)
1172 (const table)
1173 (const default))
1174 (boolean)))))
1177 (defcustom org-insert-heading-respect-content nil
1178 "Non-nil means insert new headings after the current subtree.
1179 When nil, the new heading is created directly after the current line.
1180 The commands \\[org-insert-heading-respect-content] and
1181 \\[org-insert-todo-heading-respect-content] turn this variable on
1182 for the duration of the command."
1183 :group 'org-structure
1184 :type 'boolean)
1186 (defcustom org-blank-before-new-entry '((heading . auto)
1187 (plain-list-item . auto))
1188 "Should `org-insert-heading' leave a blank line before new heading/item?
1189 The value is an alist, with `heading' and `plain-list-item' as CAR,
1190 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1191 which case Org will look at the surrounding headings/items and try to
1192 make an intelligent decision whether to insert a blank line or not.
1194 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1195 set, the setting here is ignored and no empty line is inserted, to avoid
1196 breaking the list structure."
1197 :group 'org-edit-structure
1198 :type '(list
1199 (cons (const heading)
1200 (choice (const :tag "Never" nil)
1201 (const :tag "Always" t)
1202 (const :tag "Auto" auto)))
1203 (cons (const plain-list-item)
1204 (choice (const :tag "Never" nil)
1205 (const :tag "Always" t)
1206 (const :tag "Auto" auto)))))
1208 (defcustom org-insert-heading-hook nil
1209 "Hook being run after inserting a new heading."
1210 :group 'org-edit-structure
1211 :type 'hook)
1213 (defcustom org-enable-fixed-width-editor t
1214 "Non-nil means lines starting with \":\" are treated as fixed-width.
1215 This currently only means they are never auto-wrapped.
1216 When nil, such lines will be treated like ordinary lines.
1217 See also the QUOTE keyword."
1218 :group 'org-edit-structure
1219 :type 'boolean)
1221 (defcustom org-goto-auto-isearch t
1222 "Non-nil means typing characters in `org-goto' starts incremental search."
1223 :group 'org-edit-structure
1224 :type 'boolean)
1226 (defgroup org-sparse-trees nil
1227 "Options concerning sparse trees in Org-mode."
1228 :tag "Org Sparse Trees"
1229 :group 'org-structure)
1231 (defcustom org-highlight-sparse-tree-matches t
1232 "Non-nil means highlight all matches that define a sparse tree.
1233 The highlights will automatically disappear the next time the buffer is
1234 changed by an edit command."
1235 :group 'org-sparse-trees
1236 :type 'boolean)
1238 (defcustom org-remove-highlights-with-change t
1239 "Non-nil means any change to the buffer will remove temporary highlights.
1240 Such highlights are created by `org-occur' and `org-clock-display'.
1241 When nil, `C-c C-c needs to be used to get rid of the highlights.
1242 The highlights created by `org-preview-latex-fragment' always need
1243 `C-c C-c' to be removed."
1244 :group 'org-sparse-trees
1245 :group 'org-time
1246 :type 'boolean)
1249 (defcustom org-occur-hook '(org-first-headline-recenter)
1250 "Hook that is run after `org-occur' has constructed a sparse tree.
1251 This can be used to recenter the window to show as much of the structure
1252 as possible."
1253 :group 'org-sparse-trees
1254 :type 'hook)
1256 (defgroup org-imenu-and-speedbar nil
1257 "Options concerning imenu and speedbar in Org-mode."
1258 :tag "Org Imenu and Speedbar"
1259 :group 'org-structure)
1261 (defcustom org-imenu-depth 2
1262 "The maximum level for Imenu access to Org-mode headlines.
1263 This also applied for speedbar access."
1264 :group 'org-imenu-and-speedbar
1265 :type 'integer)
1267 (defgroup org-table nil
1268 "Options concerning tables in Org-mode."
1269 :tag "Org Table"
1270 :group 'org)
1272 (defcustom org-enable-table-editor 'optimized
1273 "Non-nil means lines starting with \"|\" are handled by the table editor.
1274 When nil, such lines will be treated like ordinary lines.
1276 When equal to the symbol `optimized', the table editor will be optimized to
1277 do the following:
1278 - Automatic overwrite mode in front of whitespace in table fields.
1279 This makes the structure of the table stay in tact as long as the edited
1280 field does not exceed the column width.
1281 - Minimize the number of realigns. Normally, the table is aligned each time
1282 TAB or RET are pressed to move to another field. With optimization this
1283 happens only if changes to a field might have changed the column width.
1284 Optimization requires replacing the functions `self-insert-command',
1285 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1286 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1287 very good at guessing when a re-align will be necessary, but you can always
1288 force one with \\[org-ctrl-c-ctrl-c].
1290 If you would like to use the optimized version in Org-mode, but the
1291 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1293 This variable can be used to turn on and off the table editor during a session,
1294 but in order to toggle optimization, a restart is required.
1296 See also the variable `org-table-auto-blank-field'."
1297 :group 'org-table
1298 :type '(choice
1299 (const :tag "off" nil)
1300 (const :tag "on" t)
1301 (const :tag "on, optimized" optimized)))
1303 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1304 (version<= emacs-version "24.1"))
1305 "Non-nil means cluster self-insert commands for undo when possible.
1306 If this is set, then, like in the Emacs command loop, 20 consecutive
1307 characters will be undone together.
1308 This is configurable, because there is some impact on typing performance."
1309 :group 'org-table
1310 :type 'boolean)
1312 (defcustom org-table-tab-recognizes-table.el t
1313 "Non-nil means TAB will automatically notice a table.el table.
1314 When it sees such a table, it moves point into it and - if necessary -
1315 calls `table-recognize-table'."
1316 :group 'org-table-editing
1317 :type 'boolean)
1319 (defgroup org-link nil
1320 "Options concerning links in Org-mode."
1321 :tag "Org Link"
1322 :group 'org)
1324 (defvar org-link-abbrev-alist-local nil
1325 "Buffer-local version of `org-link-abbrev-alist', which see.
1326 The value of this is taken from the #+LINK lines.")
1327 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1329 (defcustom org-link-abbrev-alist nil
1330 "Alist of link abbreviations.
1331 The car of each element is a string, to be replaced at the start of a link.
1332 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1333 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1335 [[linkkey:tag][description]]
1337 The 'linkkey' must be a word word, starting with a letter, followed
1338 by letters, numbers, '-' or '_'.
1340 If REPLACE is a string, the tag will simply be appended to create the link.
1341 If the string contains \"%s\", the tag will be inserted there. If the string
1342 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1343 at that point (see the function `url-hexify-string'). If the string contains
1344 the specifier \"%(my-function)\", then the custom function `my-function' will
1345 be invoked: this function takes the tag as its only argument and must return
1346 a string.
1348 REPLACE may also be a function that will be called with the tag as the
1349 only argument to create the link, which should be returned as a string.
1351 See the manual for examples."
1352 :group 'org-link
1353 :type '(repeat
1354 (cons
1355 (string :tag "Protocol")
1356 (choice
1357 (string :tag "Format")
1358 (function)))))
1360 (defcustom org-descriptive-links t
1361 "Non-nil means Org will display descriptive links.
1362 E.g. [[http://orgmode.org][Org website]] will be displayed as
1363 \"Org Website\", hiding the link itself and just displaying its
1364 description. When set to `nil', Org will display the full links
1365 literally.
1367 You can interactively set the value of this variable by calling
1368 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1369 :group 'org-link
1370 :type 'boolean)
1372 (defcustom org-link-file-path-type 'adaptive
1373 "How the path name in file links should be stored.
1374 Valid values are:
1376 relative Relative to the current directory, i.e. the directory of the file
1377 into which the link is being inserted.
1378 absolute Absolute path, if possible with ~ for home directory.
1379 noabbrev Absolute path, no abbreviation of home directory.
1380 adaptive Use relative path for files in the current directory and sub-
1381 directories of it. For other files, use an absolute path."
1382 :group 'org-link
1383 :type '(choice
1384 (const relative)
1385 (const absolute)
1386 (const noabbrev)
1387 (const adaptive)))
1389 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1390 "Types of links that should be activated in Org-mode files.
1391 This is a list of symbols, each leading to the activation of a certain link
1392 type. In principle, it does not hurt to turn on most link types - there may
1393 be a small gain when turning off unused link types. The types are:
1395 bracket The recommended [[link][description]] or [[link]] links with hiding.
1396 angle Links in angular brackets that may contain whitespace like
1397 <bbdb:Carsten Dominik>.
1398 plain Plain links in normal text, no whitespace, like http://google.com.
1399 radio Text that is matched by a radio target, see manual for details.
1400 tag Tag settings in a headline (link to tag search).
1401 date Time stamps (link to calendar).
1402 footnote Footnote labels.
1404 Changing this variable requires a restart of Emacs to become effective."
1405 :group 'org-link
1406 :type '(set :greedy t
1407 (const :tag "Double bracket links" bracket)
1408 (const :tag "Angular bracket links" angle)
1409 (const :tag "Plain text links" plain)
1410 (const :tag "Radio target matches" radio)
1411 (const :tag "Tags" tag)
1412 (const :tag "Timestamps" date)
1413 (const :tag "Footnotes" footnote)))
1415 (defcustom org-make-link-description-function nil
1416 "Function to use for generating link descriptions from links.
1417 When nil, the link location will be used. This function must take
1418 two parameters: the first one is the link, the second one is the
1419 description generated by `org-insert-link'. The function should
1420 return the description to use."
1421 :group 'org-link
1422 :type 'function)
1424 (defgroup org-link-store nil
1425 "Options concerning storing links in Org-mode."
1426 :tag "Org Store Link"
1427 :group 'org-link)
1429 (defcustom org-url-hexify-p t
1430 "When non-nil, hexify URL when creating a link."
1431 :type 'boolean
1432 :version "24.3"
1433 :group 'org-link-store)
1435 (defcustom org-email-link-description-format "Email %c: %.30s"
1436 "Format of the description part of a link to an email or usenet message.
1437 The following %-escapes will be replaced by corresponding information:
1439 %F full \"From\" field
1440 %f name, taken from \"From\" field, address if no name
1441 %T full \"To\" field
1442 %t first name in \"To\" field, address if no name
1443 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1444 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1445 %s subject
1446 %d date
1447 %m message-id.
1449 You may use normal field width specification between the % and the letter.
1450 This is for example useful to limit the length of the subject.
1452 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1453 :group 'org-link-store
1454 :type 'string)
1456 (defcustom org-from-is-user-regexp
1457 (let (r1 r2)
1458 (when (and user-mail-address (not (string= user-mail-address "")))
1459 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1460 (when (and user-full-name (not (string= user-full-name "")))
1461 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1462 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1463 "Regexp matched against the \"From:\" header of an email or usenet message.
1464 It should match if the message is from the user him/herself."
1465 :group 'org-link-store
1466 :type 'regexp)
1468 (defcustom org-context-in-file-links t
1469 "Non-nil means file links from `org-store-link' contain context.
1470 A search string will be added to the file name with :: as separator and
1471 used to find the context when the link is activated by the command
1472 `org-open-at-point'. When this option is t, the entire active region
1473 will be placed in the search string of the file link. If set to a
1474 positive integer, only the first n lines of context will be stored.
1476 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1477 negates this setting for the duration of the command."
1478 :group 'org-link-store
1479 :type '(choice boolean integer))
1481 (defcustom org-keep-stored-link-after-insertion nil
1482 "Non-nil means keep link in list for entire session.
1484 The command `org-store-link' adds a link pointing to the current
1485 location to an internal list. These links accumulate during a session.
1486 The command `org-insert-link' can be used to insert links into any
1487 Org-mode file (offering completion for all stored links). When this
1488 option is nil, every link which has been inserted once using \\[org-insert-link]
1489 will be removed from the list, to make completing the unused links
1490 more efficient."
1491 :group 'org-link-store
1492 :type 'boolean)
1494 (defgroup org-link-follow nil
1495 "Options concerning following links in Org-mode."
1496 :tag "Org Follow Link"
1497 :group 'org-link)
1499 (defcustom org-link-translation-function nil
1500 "Function to translate links with different syntax to Org syntax.
1501 This can be used to translate links created for example by the Planner
1502 or emacs-wiki packages to Org syntax.
1503 The function must accept two parameters, a TYPE containing the link
1504 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1505 which is everything after the link protocol. It should return a cons
1506 with possibly modified values of type and path.
1507 Org contains a function for this, so if you set this variable to
1508 `org-translate-link-from-planner', you should be able follow many
1509 links created by planner."
1510 :group 'org-link-follow
1511 :type 'function)
1513 (defcustom org-follow-link-hook nil
1514 "Hook that is run after a link has been followed."
1515 :group 'org-link-follow
1516 :type 'hook)
1518 (defcustom org-tab-follows-link nil
1519 "Non-nil means on links TAB will follow the link.
1520 Needs to be set before org.el is loaded.
1521 This really should not be used, it does not make sense, and the
1522 implementation is bad."
1523 :group 'org-link-follow
1524 :type 'boolean)
1526 (defcustom org-return-follows-link nil
1527 "Non-nil means on links RET will follow the link."
1528 :group 'org-link-follow
1529 :type 'boolean)
1531 (defcustom org-mouse-1-follows-link
1532 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1533 "Non-nil means mouse-1 on a link will follow the link.
1534 A longer mouse click will still set point. Does not work on XEmacs.
1535 Needs to be set before org.el is loaded."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mark-ring-length 4
1540 "Number of different positions to be recorded in the ring.
1541 Changing this requires a restart of Emacs to work correctly."
1542 :group 'org-link-follow
1543 :type 'integer)
1545 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1546 "Non-nil means internal links in Org files must exactly match a headline.
1547 When nil, the link search tries to match a phrase with all words
1548 in the search text."
1549 :group 'org-link-follow
1550 :version "24.1"
1551 :type '(choice
1552 (const :tag "Use fuzzy text search" nil)
1553 (const :tag "Match only exact headline" t)
1554 (const :tag "Match exact headline or query to create it"
1555 query-to-create)))
1557 (defcustom org-link-frame-setup
1558 '((vm . vm-visit-folder-other-frame)
1559 (vm-imap . vm-visit-imap-folder-other-frame)
1560 (gnus . org-gnus-no-new-news)
1561 (file . find-file-other-window)
1562 (wl . wl-other-frame))
1563 "Setup the frame configuration for following links.
1564 When following a link with Emacs, it may often be useful to display
1565 this link in another window or frame. This variable can be used to
1566 set this up for the different types of links.
1567 For VM, use any of
1568 `vm-visit-folder'
1569 `vm-visit-folder-other-window'
1570 `vm-visit-folder-other-frame'
1571 For Gnus, use any of
1572 `gnus'
1573 `gnus-other-frame'
1574 `org-gnus-no-new-news'
1575 For FILE, use any of
1576 `find-file'
1577 `find-file-other-window'
1578 `find-file-other-frame'
1579 For Wanderlust use any of
1580 `wl'
1581 `wl-other-frame'
1582 For the calendar, use the variable `calendar-setup'.
1583 For BBDB, it is currently only possible to display the matches in
1584 another window."
1585 :group 'org-link-follow
1586 :type '(list
1587 (cons (const vm)
1588 (choice
1589 (const vm-visit-folder)
1590 (const vm-visit-folder-other-window)
1591 (const vm-visit-folder-other-frame)))
1592 (cons (const gnus)
1593 (choice
1594 (const gnus)
1595 (const gnus-other-frame)
1596 (const org-gnus-no-new-news)))
1597 (cons (const file)
1598 (choice
1599 (const find-file)
1600 (const find-file-other-window)
1601 (const find-file-other-frame)))
1602 (cons (const wl)
1603 (choice
1604 (const wl)
1605 (const wl-other-frame)))))
1607 (defcustom org-display-internal-link-with-indirect-buffer nil
1608 "Non-nil means use indirect buffer to display infile links.
1609 Activating internal links (from one location in a file to another location
1610 in the same file) normally just jumps to the location. When the link is
1611 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1612 is displayed in
1613 another window. When this option is set, the other window actually displays
1614 an indirect buffer clone of the current buffer, to avoid any visibility
1615 changes to the current buffer."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-open-non-existing-files nil
1620 "Non-nil means `org-open-file' will open non-existing files.
1621 When nil, an error will be generated.
1622 This variable applies only to external applications because they
1623 might choke on non-existing files. If the link is to a file that
1624 will be opened in Emacs, the variable is ignored."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-open-directory-means-index-dot-org nil
1629 "Non-nil means a link to a directory really means to index.org.
1630 When nil, following a directory link will run dired or open a finder/explorer
1631 window on that directory."
1632 :group 'org-link-follow
1633 :type 'boolean)
1635 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1636 "Function and arguments to call for following mailto links.
1637 This is a list with the first element being a Lisp function, and the
1638 remaining elements being arguments to the function. In string arguments,
1639 %a will be replaced by the address, and %s will be replaced by the subject
1640 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1641 :group 'org-link-follow
1642 :type '(choice
1643 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1644 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1645 (const :tag "message-mail" (message-mail "%a" "%s"))
1646 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1648 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1649 "Non-nil means ask for confirmation before executing shell links.
1650 Shell links can be dangerous: just think about a link
1652 [[shell:rm -rf ~/*][Google Search]]
1654 This link would show up in your Org-mode document as \"Google Search\",
1655 but really it would remove your entire home directory.
1656 Therefore we advise against setting this variable to nil.
1657 Just change it to `y-or-n-p' if you want to confirm with a
1658 single keystroke rather than having to type \"yes\"."
1659 :group 'org-link-follow
1660 :type '(choice
1661 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1662 (const :tag "with y-or-n (faster)" y-or-n-p)
1663 (const :tag "no confirmation (dangerous)" nil)))
1664 (put 'org-confirm-shell-link-function
1665 'safe-local-variable
1666 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1668 (defcustom org-confirm-shell-link-not-regexp ""
1669 "A regexp to skip confirmation for shell links."
1670 :group 'org-link-follow
1671 :version "24.1"
1672 :type 'regexp)
1674 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1675 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1676 Elisp links can be dangerous: just think about a link
1678 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1680 This link would show up in your Org-mode document as \"Google Search\",
1681 but really it would remove your entire home directory.
1682 Therefore we advise against setting this variable to nil.
1683 Just change it to `y-or-n-p' if you want to confirm with a
1684 single keystroke rather than having to type \"yes\"."
1685 :group 'org-link-follow
1686 :type '(choice
1687 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1688 (const :tag "with y-or-n (faster)" y-or-n-p)
1689 (const :tag "no confirmation (dangerous)" nil)))
1690 (put 'org-confirm-shell-link-function
1691 'safe-local-variable
1692 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1694 (defcustom org-confirm-elisp-link-not-regexp ""
1695 "A regexp to skip confirmation for Elisp links."
1696 :group 'org-link-follow
1697 :version "24.1"
1698 :type 'regexp)
1700 (defconst org-file-apps-defaults-gnu
1701 '((remote . emacs)
1702 (system . mailcap)
1703 (t . mailcap))
1704 "Default file applications on a UNIX or GNU/Linux system.
1705 See `org-file-apps'.")
1707 (defconst org-file-apps-defaults-macosx
1708 '((remote . emacs)
1709 (t . "open %s")
1710 (system . "open %s")
1711 ("ps.gz" . "gv %s")
1712 ("eps.gz" . "gv %s")
1713 ("dvi" . "xdvi %s")
1714 ("fig" . "xfig %s"))
1715 "Default file applications on a MacOS X system.
1716 The system \"open\" is known as a default, but we use X11 applications
1717 for some files for which the OS does not have a good default.
1718 See `org-file-apps'.")
1720 (defconst org-file-apps-defaults-windowsnt
1721 (list
1722 '(remote . emacs)
1723 (cons t
1724 (list (if (featurep 'xemacs)
1725 'mswindows-shell-execute
1726 'w32-shell-execute)
1727 "open" 'file))
1728 (cons 'system
1729 (list (if (featurep 'xemacs)
1730 'mswindows-shell-execute
1731 'w32-shell-execute)
1732 "open" 'file)))
1733 "Default file applications on a Windows NT system.
1734 The system \"open\" is used for most files.
1735 See `org-file-apps'.")
1737 (defcustom org-file-apps
1739 (auto-mode . emacs)
1740 ("\\.mm\\'" . default)
1741 ("\\.x?html?\\'" . default)
1742 ("\\.pdf\\'" . default)
1744 "External applications for opening `file:path' items in a document.
1745 Org-mode uses system defaults for different file types, but
1746 you can use this variable to set the application for a given file
1747 extension. The entries in this list are cons cells where the car identifies
1748 files and the cdr the corresponding command. Possible values for the
1749 file identifier are
1750 \"string\" A string as a file identifier can be interpreted in different
1751 ways, depending on its contents:
1753 - Alphanumeric characters only:
1754 Match links with this file extension.
1755 Example: (\"pdf\" . \"evince %s\")
1756 to open PDFs with evince.
1758 - Regular expression: Match links where the
1759 filename matches the regexp. If you want to
1760 use groups here, use shy groups.
1762 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1763 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1764 to open *.html and *.xhtml with firefox.
1766 - Regular expression which contains (non-shy) groups:
1767 Match links where the whole link, including \"::\", and
1768 anything after that, matches the regexp.
1769 In a custom command string, %1, %2, etc. are replaced with
1770 the parts of the link that were matched by the groups.
1771 For backwards compatibility, if a command string is given
1772 that does not use any of the group matches, this case is
1773 handled identically to the second one (i.e. match against
1774 file name only).
1775 In a custom lisp form, you can access the group matches with
1776 (match-string n link).
1778 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1779 to open [[file:document.pdf::5]] with evince at page 5.
1781 `directory' Matches a directory
1782 `remote' Matches a remote file, accessible through tramp or efs.
1783 Remote files most likely should be visited through Emacs
1784 because external applications cannot handle such paths.
1785 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1786 so all files Emacs knows how to handle. Using this with
1787 command `emacs' will open most files in Emacs. Beware that this
1788 will also open html files inside Emacs, unless you add
1789 (\"html\" . default) to the list as well.
1790 t Default for files not matched by any of the other options.
1791 `system' The system command to open files, like `open' on Windows
1792 and Mac OS X, and mailcap under GNU/Linux. This is the command
1793 that will be selected if you call `C-c C-o' with a double
1794 \\[universal-argument] \\[universal-argument] prefix.
1796 Possible values for the command are:
1797 `emacs' The file will be visited by the current Emacs process.
1798 `default' Use the default application for this file type, which is the
1799 association for t in the list, most likely in the system-specific
1800 part.
1801 This can be used to overrule an unwanted setting in the
1802 system-specific variable.
1803 `system' Use the system command for opening files, like \"open\".
1804 This command is specified by the entry whose car is `system'.
1805 Most likely, the system-specific version of this variable
1806 does define this command, but you can overrule/replace it
1807 here.
1808 string A command to be executed by a shell; %s will be replaced
1809 by the path to the file.
1810 sexp A Lisp form which will be evaluated. The file path will
1811 be available in the Lisp variable `file'.
1812 For more examples, see the system specific constants
1813 `org-file-apps-defaults-macosx'
1814 `org-file-apps-defaults-windowsnt'
1815 `org-file-apps-defaults-gnu'."
1816 :group 'org-link-follow
1817 :type '(repeat
1818 (cons (choice :value ""
1819 (string :tag "Extension")
1820 (const :tag "System command to open files" system)
1821 (const :tag "Default for unrecognized files" t)
1822 (const :tag "Remote file" remote)
1823 (const :tag "Links to a directory" directory)
1824 (const :tag "Any files that have Emacs modes"
1825 auto-mode))
1826 (choice :value ""
1827 (const :tag "Visit with Emacs" emacs)
1828 (const :tag "Use default" default)
1829 (const :tag "Use the system command" system)
1830 (string :tag "Command")
1831 (sexp :tag "Lisp form")))))
1833 (defcustom org-doi-server-url "http://dx.doi.org/"
1834 "The URL of the DOI server."
1835 :type 'string
1836 :version "24.3"
1837 :group 'org-link-follow)
1839 (defgroup org-refile nil
1840 "Options concerning refiling entries in Org-mode."
1841 :tag "Org Refile"
1842 :group 'org)
1844 (defcustom org-directory "~/org"
1845 "Directory with org files.
1846 This is just a default location to look for Org files. There is no need
1847 at all to put your files into this directory. It is only used in the
1848 following situations:
1850 1. When a capture template specifies a target file that is not an
1851 absolute path. The path will then be interpreted relative to
1852 `org-directory'
1853 2. When a capture note is filed away in an interactive way (when exiting the
1854 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1855 with `org-directory' as the default path."
1856 :group 'org-refile
1857 :group 'org-remember
1858 :group 'org-capture
1859 :type 'directory)
1861 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1862 "Default target for storing notes.
1863 Used as a fall back file for org-remember.el and org-capture.el, for
1864 templates that do not specify a target file."
1865 :group 'org-refile
1866 :group 'org-remember
1867 :group 'org-capture
1868 :type '(choice
1869 (const :tag "Default from remember-data-file" nil)
1870 file))
1872 (defcustom org-goto-interface 'outline
1873 "The default interface to be used for `org-goto'.
1874 Allowed values are:
1875 outline The interface shows an outline of the relevant file
1876 and the correct heading is found by moving through
1877 the outline or by searching with incremental search.
1878 outline-path-completion Headlines in the current buffer are offered via
1879 completion. This is the interface also used by
1880 the refile command."
1881 :group 'org-refile
1882 :type '(choice
1883 (const :tag "Outline" outline)
1884 (const :tag "Outline-path-completion" outline-path-completion)))
1886 (defcustom org-goto-max-level 5
1887 "Maximum target level when running `org-goto' with refile interface."
1888 :group 'org-refile
1889 :type 'integer)
1891 (defcustom org-reverse-note-order nil
1892 "Non-nil means store new notes at the beginning of a file or entry.
1893 When nil, new notes will be filed to the end of a file or entry.
1894 This can also be a list with cons cells of regular expressions that
1895 are matched against file names, and values."
1896 :group 'org-remember
1897 :group 'org-capture
1898 :group 'org-refile
1899 :type '(choice
1900 (const :tag "Reverse always" t)
1901 (const :tag "Reverse never" nil)
1902 (repeat :tag "By file name regexp"
1903 (cons regexp boolean))))
1905 (defcustom org-log-refile nil
1906 "Information to record when a task is refiled.
1908 Possible values are:
1910 nil Don't add anything
1911 time Add a time stamp to the task
1912 note Prompt for a note and add it with template `org-log-note-headings'
1914 This option can also be set with on a per-file-basis with
1916 #+STARTUP: nologrefile
1917 #+STARTUP: logrefile
1918 #+STARTUP: lognoterefile
1920 You can have local logging settings for a subtree by setting the LOGGING
1921 property to one or more of these keywords.
1923 When bulk-refiling from the agenda, the value `note' is forbidden and
1924 will temporarily be changed to `time'."
1925 :group 'org-refile
1926 :group 'org-progress
1927 :version "24.1"
1928 :type '(choice
1929 (const :tag "No logging" nil)
1930 (const :tag "Record timestamp" time)
1931 (const :tag "Record timestamp with note." note)))
1933 (defcustom org-refile-targets nil
1934 "Targets for refiling entries with \\[org-refile].
1935 This is a list of cons cells. Each cell contains:
1936 - a specification of the files to be considered, either a list of files,
1937 or a symbol whose function or variable value will be used to retrieve
1938 a file name or a list of file names. If you use `org-agenda-files' for
1939 that, all agenda files will be scanned for targets. Nil means consider
1940 headings in the current buffer.
1941 - A specification of how to find candidate refile targets. This may be
1942 any of:
1943 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1944 This tag has to be present in all target headlines, inheritance will
1945 not be considered.
1946 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1947 todo keyword.
1948 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1949 headlines that are refiling targets.
1950 - a cons cell (:level . N). Any headline of level N is considered a target.
1951 Note that, when `org-odd-levels-only' is set, level corresponds to
1952 order in hierarchy, not to the number of stars.
1953 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1954 Note that, when `org-odd-levels-only' is set, level corresponds to
1955 order in hierarchy, not to the number of stars.
1957 Each element of this list generates a set of possible targets.
1958 The union of these sets is presented (with completion) to
1959 the user by `org-refile'.
1961 You can set the variable `org-refile-target-verify-function' to a function
1962 to verify each headline found by the simple criteria above.
1964 When this variable is nil, all top-level headlines in the current buffer
1965 are used, equivalent to the value `((nil . (:level . 1))'."
1966 :group 'org-refile
1967 :type '(repeat
1968 (cons
1969 (choice :value org-agenda-files
1970 (const :tag "All agenda files" org-agenda-files)
1971 (const :tag "Current buffer" nil)
1972 (function) (variable) (file))
1973 (choice :tag "Identify target headline by"
1974 (cons :tag "Specific tag" (const :value :tag) (string))
1975 (cons :tag "TODO keyword" (const :value :todo) (string))
1976 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1977 (cons :tag "Level number" (const :value :level) (integer))
1978 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1980 (defcustom org-refile-target-verify-function nil
1981 "Function to verify if the headline at point should be a refile target.
1982 The function will be called without arguments, with point at the
1983 beginning of the headline. It should return t and leave point
1984 where it is if the headline is a valid target for refiling.
1986 If the target should not be selected, the function must return nil.
1987 In addition to this, it may move point to a place from where the search
1988 should be continued. For example, the function may decide that the entire
1989 subtree of the current entry should be excluded and move point to the end
1990 of the subtree."
1991 :group 'org-refile
1992 :type 'function)
1994 (defcustom org-refile-use-cache nil
1995 "Non-nil means cache refile targets to speed up the process.
1996 The cache for a particular file will be updated automatically when
1997 the buffer has been killed, or when any of the marker used for flagging
1998 refile targets no longer points at a live buffer.
1999 If you have added new entries to a buffer that might themselves be targets,
2000 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2001 find that easier, `C-u C-u C-u C-c C-w'."
2002 :group 'org-refile
2003 :version "24.1"
2004 :type 'boolean)
2006 (defcustom org-refile-use-outline-path nil
2007 "Non-nil means provide refile targets as paths.
2008 So a level 3 headline will be available as level1/level2/level3.
2010 When the value is `file', also include the file name (without directory)
2011 into the path. In this case, you can also stop the completion after
2012 the file name, to get entries inserted as top level in the file.
2014 When `full-file-path', include the full file path."
2015 :group 'org-refile
2016 :type '(choice
2017 (const :tag "Not" nil)
2018 (const :tag "Yes" t)
2019 (const :tag "Start with file name" file)
2020 (const :tag "Start with full file path" full-file-path)))
2022 (defcustom org-outline-path-complete-in-steps t
2023 "Non-nil means complete the outline path in hierarchical steps.
2024 When Org-mode uses the refile interface to select an outline path
2025 \(see variable `org-refile-use-outline-path'), the completion of
2026 the path can be done is a single go, or if can be done in steps down
2027 the headline hierarchy. Going in steps is probably the best if you
2028 do not use a special completion package like `ido' or `icicles'.
2029 However, when using these packages, going in one step can be very
2030 fast, while still showing the whole path to the entry."
2031 :group 'org-refile
2032 :type 'boolean)
2034 (defcustom org-refile-allow-creating-parent-nodes nil
2035 "Non-nil means allow to create new nodes as refile targets.
2036 New nodes are then created by adding \"/new node name\" to the completion
2037 of an existing node. When the value of this variable is `confirm',
2038 new node creation must be confirmed by the user (recommended)
2039 When nil, the completion must match an existing entry.
2041 Note that, if the new heading is not seen by the criteria
2042 listed in `org-refile-targets', multiple instances of the same
2043 heading would be created by trying again to file under the new
2044 heading."
2045 :group 'org-refile
2046 :type '(choice
2047 (const :tag "Never" nil)
2048 (const :tag "Always" t)
2049 (const :tag "Prompt for confirmation" confirm)))
2051 (defcustom org-refile-active-region-within-subtree nil
2052 "Non-nil means also refile active region within a subtree.
2054 By default `org-refile' doesn't allow refiling regions if they
2055 don't contain a set of subtrees, but it might be convenient to
2056 do so sometimes: in that case, the first line of the region is
2057 converted to a headline before refiling."
2058 :group 'org-refile
2059 :version "24.1"
2060 :type 'boolean)
2062 (defgroup org-todo nil
2063 "Options concerning TODO items in Org-mode."
2064 :tag "Org TODO"
2065 :group 'org)
2067 (defgroup org-progress nil
2068 "Options concerning Progress logging in Org-mode."
2069 :tag "Org Progress"
2070 :group 'org-time)
2072 (defvar org-todo-interpretation-widgets
2073 '((:tag "Sequence (cycling hits every state)" sequence)
2074 (:tag "Type (cycling directly to DONE)" type))
2075 "The available interpretation symbols for customizing `org-todo-keywords'.
2076 Interested libraries should add to this list.")
2078 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2079 "List of TODO entry keyword sequences and their interpretation.
2080 \\<org-mode-map>This is a list of sequences.
2082 Each sequence starts with a symbol, either `sequence' or `type',
2083 indicating if the keywords should be interpreted as a sequence of
2084 action steps, or as different types of TODO items. The first
2085 keywords are states requiring action - these states will select a headline
2086 for inclusion into the global TODO list Org-mode produces. If one of
2087 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2088 signify that no further action is necessary. If \"|\" is not found,
2089 the last keyword is treated as the only DONE state of the sequence.
2091 The command \\[org-todo] cycles an entry through these states, and one
2092 additional state where no keyword is present. For details about this
2093 cycling, see the manual.
2095 TODO keywords and interpretation can also be set on a per-file basis with
2096 the special #+SEQ_TODO and #+TYP_TODO lines.
2098 Each keyword can optionally specify a character for fast state selection
2099 \(in combination with the variable `org-use-fast-todo-selection')
2100 and specifiers for state change logging, using the same syntax that
2101 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2102 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2103 indicates to record a time stamp each time this state is selected.
2105 Each keyword may also specify if a timestamp or a note should be
2106 recorded when entering or leaving the state, by adding additional
2107 characters in the parenthesis after the keyword. This looks like this:
2108 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2109 record only the time of the state change. With X and Y being either
2110 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2111 Y when leaving the state if and only if the *target* state does not
2112 define X. You may omit any of the fast-selection key or X or /Y,
2113 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2115 For backward compatibility, this variable may also be just a list
2116 of keywords. In this case the interpretation (sequence or type) will be
2117 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2118 :group 'org-todo
2119 :group 'org-keywords
2120 :type '(choice
2121 (repeat :tag "Old syntax, just keywords"
2122 (string :tag "Keyword"))
2123 (repeat :tag "New syntax"
2124 (cons
2125 (choice
2126 :tag "Interpretation"
2127 ;;Quick and dirty way to see
2128 ;;`org-todo-interpretations'. This takes the
2129 ;;place of item arguments
2130 :convert-widget
2131 (lambda (widget)
2132 (widget-put widget
2133 :args (mapcar
2134 #'(lambda (x)
2135 (widget-convert
2136 (cons 'const x)))
2137 org-todo-interpretation-widgets))
2138 widget))
2139 (repeat
2140 (string :tag "Keyword"))))))
2142 (defvar org-todo-keywords-1 nil
2143 "All TODO and DONE keywords active in a buffer.")
2144 (make-variable-buffer-local 'org-todo-keywords-1)
2145 (defvar org-todo-keywords-for-agenda nil)
2146 (defvar org-done-keywords-for-agenda nil)
2147 (defvar org-drawers-for-agenda nil)
2148 (defvar org-todo-keyword-alist-for-agenda nil)
2149 (defvar org-tag-alist-for-agenda nil)
2150 (defvar org-agenda-contributing-files nil)
2151 (defvar org-not-done-keywords nil)
2152 (make-variable-buffer-local 'org-not-done-keywords)
2153 (defvar org-done-keywords nil)
2154 (make-variable-buffer-local 'org-done-keywords)
2155 (defvar org-todo-heads nil)
2156 (make-variable-buffer-local 'org-todo-heads)
2157 (defvar org-todo-sets nil)
2158 (make-variable-buffer-local 'org-todo-sets)
2159 (defvar org-todo-log-states nil)
2160 (make-variable-buffer-local 'org-todo-log-states)
2161 (defvar org-todo-kwd-alist nil)
2162 (make-variable-buffer-local 'org-todo-kwd-alist)
2163 (defvar org-todo-key-alist nil)
2164 (make-variable-buffer-local 'org-todo-key-alist)
2165 (defvar org-todo-key-trigger nil)
2166 (make-variable-buffer-local 'org-todo-key-trigger)
2168 (defcustom org-todo-interpretation 'sequence
2169 "Controls how TODO keywords are interpreted.
2170 This variable is in principle obsolete and is only used for
2171 backward compatibility, if the interpretation of todo keywords is
2172 not given already in `org-todo-keywords'. See that variable for
2173 more information."
2174 :group 'org-todo
2175 :group 'org-keywords
2176 :type '(choice (const sequence)
2177 (const type)))
2179 (defcustom org-use-fast-todo-selection t
2180 "Non-nil means use the fast todo selection scheme with C-c C-t.
2181 This variable describes if and under what circumstances the cycling
2182 mechanism for TODO keywords will be replaced by a single-key, direct
2183 selection scheme.
2185 When nil, fast selection is never used.
2187 When the symbol `prefix', it will be used when `org-todo' is called
2188 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2189 `C-u t' in an agenda buffer.
2191 When t, fast selection is used by default. In this case, the prefix
2192 argument forces cycling instead.
2194 In all cases, the special interface is only used if access keys have
2195 actually been assigned by the user, i.e. if keywords in the configuration
2196 are followed by a letter in parenthesis, like TODO(t)."
2197 :group 'org-todo
2198 :type '(choice
2199 (const :tag "Never" nil)
2200 (const :tag "By default" t)
2201 (const :tag "Only with C-u C-c C-t" prefix)))
2203 (defcustom org-provide-todo-statistics t
2204 "Non-nil means update todo statistics after insert and toggle.
2205 ALL-HEADLINES means update todo statistics by including headlines
2206 with no TODO keyword as well, counting them as not done.
2207 A list of TODO keywords means the same, but skip keywords that are
2208 not in this list.
2210 When this is set, todo statistics is updated in the parent of the
2211 current entry each time a todo state is changed."
2212 :group 'org-todo
2213 :type '(choice
2214 (const :tag "Yes, only for TODO entries" t)
2215 (const :tag "Yes, including all entries" 'all-headlines)
2216 (repeat :tag "Yes, for TODOs in this list"
2217 (string :tag "TODO keyword"))
2218 (other :tag "No TODO statistics" nil)))
2220 (defcustom org-hierarchical-todo-statistics t
2221 "Non-nil means TODO statistics covers just direct children.
2222 When nil, all entries in the subtree are considered.
2223 This has only an effect if `org-provide-todo-statistics' is set.
2224 To set this to nil for only a single subtree, use a COOKIE_DATA
2225 property and include the word \"recursive\" into the value."
2226 :group 'org-todo
2227 :type 'boolean)
2229 (defcustom org-after-todo-state-change-hook nil
2230 "Hook which is run after the state of a TODO item was changed.
2231 The new state (a string with a TODO keyword, or nil) is available in the
2232 Lisp variable `org-state'."
2233 :group 'org-todo
2234 :type 'hook)
2236 (defvar org-blocker-hook nil
2237 "Hook for functions that are allowed to block a state change.
2239 Functions in this hook should not modify the buffer.
2240 Each function gets as its single argument a property list,
2241 see `org-trigger-hook' for more information about this list.
2243 If any of the functions in this hook returns nil, the state change
2244 is blocked.")
2246 (defvar org-trigger-hook nil
2247 "Hook for functions that are triggered by a state change.
2249 Each function gets as its single argument a property list with at
2250 least the following elements:
2252 (:type type-of-change :position pos-at-entry-start
2253 :from old-state :to new-state)
2255 Depending on the type, more properties may be present.
2257 This mechanism is currently implemented for:
2259 TODO state changes
2260 ------------------
2261 :type todo-state-change
2262 :from previous state (keyword as a string), or nil, or a symbol
2263 'todo' or 'done', to indicate the general type of state.
2264 :to new state, like in :from")
2266 (defcustom org-enforce-todo-dependencies nil
2267 "Non-nil means undone TODO entries will block switching the parent to DONE.
2268 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2269 be blocked if any prior sibling is not yet done.
2270 Finally, if the parent is blocked because of ordered siblings of its own,
2271 the child will also be blocked."
2272 :set (lambda (var val)
2273 (set var val)
2274 (if val
2275 (add-hook 'org-blocker-hook
2276 'org-block-todo-from-children-or-siblings-or-parent)
2277 (remove-hook 'org-blocker-hook
2278 'org-block-todo-from-children-or-siblings-or-parent)))
2279 :group 'org-todo
2280 :type 'boolean)
2282 (defcustom org-enforce-todo-checkbox-dependencies nil
2283 "Non-nil means unchecked boxes will block switching the parent to DONE.
2284 When this is nil, checkboxes have no influence on switching TODO states.
2285 When non-nil, you first need to check off all check boxes before the TODO
2286 entry can be switched to DONE.
2287 This variable needs to be set before org.el is loaded, and you need to
2288 restart Emacs after a change to make the change effective. The only way
2289 to change is while Emacs is running is through the customize interface."
2290 :set (lambda (var val)
2291 (set var val)
2292 (if val
2293 (add-hook 'org-blocker-hook
2294 'org-block-todo-from-checkboxes)
2295 (remove-hook 'org-blocker-hook
2296 'org-block-todo-from-checkboxes)))
2297 :group 'org-todo
2298 :type 'boolean)
2300 (defcustom org-treat-insert-todo-heading-as-state-change nil
2301 "Non-nil means inserting a TODO heading is treated as state change.
2302 So when the command \\[org-insert-todo-heading] is used, state change
2303 logging will apply if appropriate. When nil, the new TODO item will
2304 be inserted directly, and no logging will take place."
2305 :group 'org-todo
2306 :type 'boolean)
2308 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2309 "Non-nil means switching TODO states with S-cursor counts as state change.
2310 This is the default behavior. However, setting this to nil allows a
2311 convenient way to select a TODO state and bypass any logging associated
2312 with that."
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-todo-state-tags-triggers nil
2317 "Tag changes that should be triggered by TODO state changes.
2318 This is a list. Each entry is
2320 (state-change (tag . flag) .......)
2322 State-change can be a string with a state, and empty string to indicate the
2323 state that has no TODO keyword, or it can be one of the symbols `todo'
2324 or `done', meaning any not-done or done state, respectively."
2325 :group 'org-todo
2326 :group 'org-tags
2327 :type '(repeat
2328 (cons (choice :tag "When changing to"
2329 (const :tag "Not-done state" todo)
2330 (const :tag "Done state" done)
2331 (string :tag "State"))
2332 (repeat
2333 (cons :tag "Tag action"
2334 (string :tag "Tag")
2335 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2337 (defcustom org-log-done nil
2338 "Information to record when a task moves to the DONE state.
2340 Possible values are:
2342 nil Don't add anything, just change the keyword
2343 time Add a time stamp to the task
2344 note Prompt for a note and add it with template `org-log-note-headings'
2346 This option can also be set with on a per-file-basis with
2348 #+STARTUP: nologdone
2349 #+STARTUP: logdone
2350 #+STARTUP: lognotedone
2352 You can have local logging settings for a subtree by setting the LOGGING
2353 property to one or more of these keywords."
2354 :group 'org-todo
2355 :group 'org-progress
2356 :type '(choice
2357 (const :tag "No logging" nil)
2358 (const :tag "Record CLOSED timestamp" time)
2359 (const :tag "Record CLOSED timestamp with note." note)))
2361 ;; Normalize old uses of org-log-done.
2362 (cond
2363 ((eq org-log-done t) (setq org-log-done 'time))
2364 ((and (listp org-log-done) (memq 'done org-log-done))
2365 (setq org-log-done 'note)))
2367 (defcustom org-log-reschedule nil
2368 "Information to record when the scheduling date of a tasks is modified.
2370 Possible values are:
2372 nil Don't add anything, just change the date
2373 time Add a time stamp to the task
2374 note Prompt for a note and add it with template `org-log-note-headings'
2376 This option can also be set with on a per-file-basis with
2378 #+STARTUP: nologreschedule
2379 #+STARTUP: logreschedule
2380 #+STARTUP: lognotereschedule"
2381 :group 'org-todo
2382 :group 'org-progress
2383 :type '(choice
2384 (const :tag "No logging" nil)
2385 (const :tag "Record timestamp" time)
2386 (const :tag "Record timestamp with note." note)))
2388 (defcustom org-log-redeadline nil
2389 "Information to record when the deadline date of a tasks is modified.
2391 Possible values are:
2393 nil Don't add anything, just change the date
2394 time Add a time stamp to the task
2395 note Prompt for a note and add it with template `org-log-note-headings'
2397 This option can also be set with on a per-file-basis with
2399 #+STARTUP: nologredeadline
2400 #+STARTUP: logredeadline
2401 #+STARTUP: lognoteredeadline
2403 You can have local logging settings for a subtree by setting the LOGGING
2404 property to one or more of these keywords."
2405 :group 'org-todo
2406 :group 'org-progress
2407 :type '(choice
2408 (const :tag "No logging" nil)
2409 (const :tag "Record timestamp" time)
2410 (const :tag "Record timestamp with note." note)))
2412 (defcustom org-log-note-clock-out nil
2413 "Non-nil means record a note when clocking out of an item.
2414 This can also be configured on a per-file basis by adding one of
2415 the following lines anywhere in the buffer:
2417 #+STARTUP: lognoteclock-out
2418 #+STARTUP: nolognoteclock-out"
2419 :group 'org-todo
2420 :group 'org-progress
2421 :type 'boolean)
2423 (defcustom org-log-done-with-time t
2424 "Non-nil means the CLOSED time stamp will contain date and time.
2425 When nil, only the date will be recorded."
2426 :group 'org-progress
2427 :type 'boolean)
2429 (defcustom org-log-note-headings
2430 '((done . "CLOSING NOTE %t")
2431 (state . "State %-12s from %-12S %t")
2432 (note . "Note taken on %t")
2433 (reschedule . "Rescheduled from %S on %t")
2434 (delschedule . "Not scheduled, was %S on %t")
2435 (redeadline . "New deadline from %S on %t")
2436 (deldeadline . "Removed deadline, was %S on %t")
2437 (refile . "Refiled on %t")
2438 (clock-out . ""))
2439 "Headings for notes added to entries.
2440 The value is an alist, with the car being a symbol indicating the note
2441 context, and the cdr is the heading to be used. The heading may also be the
2442 empty string.
2443 %t in the heading will be replaced by a time stamp.
2444 %T will be an active time stamp instead the default inactive one
2445 %d will be replaced by a short-format time stamp.
2446 %D will be replaced by an active short-format time stamp.
2447 %s will be replaced by the new TODO state, in double quotes.
2448 %S will be replaced by the old TODO state, in double quotes.
2449 %u will be replaced by the user name.
2450 %U will be replaced by the full user name.
2452 In fact, it is not a good idea to change the `state' entry, because
2453 agenda log mode depends on the format of these entries."
2454 :group 'org-todo
2455 :group 'org-progress
2456 :type '(list :greedy t
2457 (cons (const :tag "Heading when closing an item" done) string)
2458 (cons (const :tag
2459 "Heading when changing todo state (todo sequence only)"
2460 state) string)
2461 (cons (const :tag "Heading when just taking a note" note) string)
2462 (cons (const :tag "Heading when clocking out" clock-out) string)
2463 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2464 (cons (const :tag "Heading when rescheduling" reschedule) string)
2465 (cons (const :tag "Heading when changing deadline" redeadline) string)
2466 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2467 (cons (const :tag "Heading when refiling" refile) string)))
2469 (unless (assq 'note org-log-note-headings)
2470 (push '(note . "%t") org-log-note-headings))
2472 (defcustom org-log-into-drawer nil
2473 "Non-nil means insert state change notes and time stamps into a drawer.
2474 When nil, state changes notes will be inserted after the headline and
2475 any scheduling and clock lines, but not inside a drawer.
2477 The value of this variable should be the name of the drawer to use.
2478 LOGBOOK is proposed as the default drawer for this purpose, you can
2479 also set this to a string to define the drawer of your choice.
2481 A value of t is also allowed, representing \"LOGBOOK\".
2483 If this variable is set, `org-log-state-notes-insert-after-drawers'
2484 will be ignored.
2486 You can set the property LOG_INTO_DRAWER to overrule this setting for
2487 a subtree."
2488 :group 'org-todo
2489 :group 'org-progress
2490 :type '(choice
2491 (const :tag "Not into a drawer" nil)
2492 (const :tag "LOGBOOK" t)
2493 (string :tag "Other")))
2495 (if (fboundp 'defvaralias)
2496 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2498 (defun org-log-into-drawer ()
2499 "Return the value of `org-log-into-drawer', but let properties overrule.
2500 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2501 used instead of the default value."
2502 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2503 (cond
2504 ((not p) org-log-into-drawer)
2505 ((equal p "nil") nil)
2506 ((equal p "t") "LOGBOOK")
2507 (t p))))
2509 (defcustom org-log-state-notes-insert-after-drawers nil
2510 "Non-nil means insert state change notes after any drawers in entry.
2511 Only the drawers that *immediately* follow the headline and the
2512 deadline/scheduled line are skipped.
2513 When nil, insert notes right after the heading and perhaps the line
2514 with deadline/scheduling if present.
2516 This variable will have no effect if `org-log-into-drawer' is
2517 set."
2518 :group 'org-todo
2519 :group 'org-progress
2520 :type 'boolean)
2522 (defcustom org-log-states-order-reversed t
2523 "Non-nil means the latest state note will be directly after heading.
2524 When nil, the state change notes will be ordered according to time."
2525 :group 'org-todo
2526 :group 'org-progress
2527 :type 'boolean)
2529 (defcustom org-todo-repeat-to-state nil
2530 "The TODO state to which a repeater should return the repeating task.
2531 By default this is the first task in a TODO sequence, or the previous state
2532 in a TODO_TYP set. But you can specify another task here.
2533 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2534 :group 'org-todo
2535 :version "24.1"
2536 :type '(choice (const :tag "Head of sequence" nil)
2537 (string :tag "Specific state")))
2539 (defcustom org-log-repeat 'time
2540 "Non-nil means record moving through the DONE state when triggering repeat.
2541 An auto-repeating task is immediately switched back to TODO when
2542 marked DONE. If you are not logging state changes (by adding \"@\"
2543 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2544 record a closing note, there will be no record of the task moving
2545 through DONE. This variable forces taking a note anyway.
2547 nil Don't force a record
2548 time Record a time stamp
2549 note Prompt for a note and add it with template `org-log-note-headings'
2551 This option can also be set with on a per-file-basis with
2553 #+STARTUP: nologrepeat
2554 #+STARTUP: logrepeat
2555 #+STARTUP: lognoterepeat
2557 You can have local logging settings for a subtree by setting the LOGGING
2558 property to one or more of these keywords."
2559 :group 'org-todo
2560 :group 'org-progress
2561 :type '(choice
2562 (const :tag "Don't force a record" nil)
2563 (const :tag "Force recording the DONE state" time)
2564 (const :tag "Force recording a note with the DONE state" note)))
2567 (defgroup org-priorities nil
2568 "Priorities in Org-mode."
2569 :tag "Org Priorities"
2570 :group 'org-todo)
2572 (defcustom org-enable-priority-commands t
2573 "Non-nil means priority commands are active.
2574 When nil, these commands will be disabled, so that you never accidentally
2575 set a priority."
2576 :group 'org-priorities
2577 :type 'boolean)
2579 (defcustom org-highest-priority ?A
2580 "The highest priority of TODO items. A character like ?A, ?B etc.
2581 Must have a smaller ASCII number than `org-lowest-priority'."
2582 :group 'org-priorities
2583 :type 'character)
2585 (defcustom org-lowest-priority ?C
2586 "The lowest priority of TODO items. A character like ?A, ?B etc.
2587 Must have a larger ASCII number than `org-highest-priority'."
2588 :group 'org-priorities
2589 :type 'character)
2591 (defcustom org-default-priority ?B
2592 "The default priority of TODO items.
2593 This is the priority an item gets if no explicit priority is given.
2594 When starting to cycle on an empty priority the first step in the cycle
2595 depends on `org-priority-start-cycle-with-default'. The resulting first
2596 step priority must not exceed the range from `org-highest-priority' to
2597 `org-lowest-priority' which means that `org-default-priority' has to be
2598 in this range exclusive or inclusive the range boundaries. Else the
2599 first step refuses to set the default and the second will fall back
2600 to (depending on the command used) the highest or lowest priority."
2601 :group 'org-priorities
2602 :type 'character)
2604 (defcustom org-priority-start-cycle-with-default t
2605 "Non-nil means start with default priority when starting to cycle.
2606 When this is nil, the first step in the cycle will be (depending on the
2607 command used) one higher or lower than the default priority.
2608 See also `org-default-priority'."
2609 :group 'org-priorities
2610 :type 'boolean)
2612 (defcustom org-get-priority-function nil
2613 "Function to extract the priority from a string.
2614 The string is normally the headline. If this is nil Org computes the
2615 priority from the priority cookie like [#A] in the headline. It returns
2616 an integer, increasing by 1000 for each priority level.
2617 The user can set a different function here, which should take a string
2618 as an argument and return the numeric priority."
2619 :group 'org-priorities
2620 :version "24.1"
2621 :type 'function)
2623 (defgroup org-time nil
2624 "Options concerning time stamps and deadlines in Org-mode."
2625 :tag "Org Time"
2626 :group 'org)
2628 (defcustom org-insert-labeled-timestamps-at-point nil
2629 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2630 When nil, these labeled time stamps are forces into the second line of an
2631 entry, just after the headline. When scheduling from the global TODO list,
2632 the time stamp will always be forced into the second line."
2633 :group 'org-time
2634 :type 'boolean)
2636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2637 "Formats for `format-time-string' which are used for time stamps.
2638 It is not recommended to change this constant.")
2640 (defcustom org-time-stamp-rounding-minutes '(0 5)
2641 "Number of minutes to round time stamps to.
2642 These are two values, the first applies when first creating a time stamp.
2643 The second applies when changing it with the commands `S-up' and `S-down'.
2644 When changing the time stamp, this means that it will change in steps
2645 of N minutes, as given by the second value.
2647 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2648 numbers should be factors of 60, so for example 5, 10, 15.
2650 When this is larger than 1, you can still force an exact time stamp by using
2651 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2652 and by using a prefix arg to `S-up/down' to specify the exact number
2653 of minutes to shift."
2654 :group 'org-time
2655 :get #'(lambda (var) ; Make sure both elements are there
2656 (if (integerp (default-value var))
2657 (list (default-value var) 5)
2658 (default-value var)))
2659 :type '(list
2660 (integer :tag "when inserting times")
2661 (integer :tag "when modifying times")))
2663 ;; Normalize old customizations of this variable.
2664 (when (integerp org-time-stamp-rounding-minutes)
2665 (setq org-time-stamp-rounding-minutes
2666 (list org-time-stamp-rounding-minutes
2667 org-time-stamp-rounding-minutes)))
2669 (defcustom org-display-custom-times nil
2670 "Non-nil means overlay custom formats over all time stamps.
2671 The formats are defined through the variable `org-time-stamp-custom-formats'.
2672 To turn this on on a per-file basis, insert anywhere in the file:
2673 #+STARTUP: customtime"
2674 :group 'org-time
2675 :set 'set-default
2676 :type 'sexp)
2677 (make-variable-buffer-local 'org-display-custom-times)
2679 (defcustom org-time-stamp-custom-formats
2680 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2681 "Custom formats for time stamps. See `format-time-string' for the syntax.
2682 These are overlaid over the default ISO format if the variable
2683 `org-display-custom-times' is set. Time like %H:%M should be at the
2684 end of the second format. The custom formats are also honored by export
2685 commands, if custom time display is turned on at the time of export."
2686 :group 'org-time
2687 :type 'sexp)
2689 (defun org-time-stamp-format (&optional long inactive)
2690 "Get the right format for a time string."
2691 (let ((f (if long (cdr org-time-stamp-formats)
2692 (car org-time-stamp-formats))))
2693 (if inactive
2694 (concat "[" (substring f 1 -1) "]")
2695 f)))
2697 (defcustom org-time-clocksum-format "%d:%02d"
2698 "The format string used when creating CLOCKSUM lines.
2699 This is also used when org-mode generates a time duration."
2700 :group 'org-time
2701 :type 'string)
2703 (defcustom org-time-clocksum-use-fractional nil
2704 "If non-nil, \\[org-clock-display] uses fractional times.
2705 org-mode generates a time duration."
2706 :group 'org-time
2707 :type 'boolean)
2709 (defcustom org-time-clocksum-fractional-format "%.2f"
2710 "The format string used when creating CLOCKSUM lines, or when
2711 org-mode generates a time duration."
2712 :group 'org-time
2713 :type 'string)
2715 (defcustom org-deadline-warning-days 14
2716 "No. of days before expiration during which a deadline becomes active.
2717 This variable governs the display in sparse trees and in the agenda.
2718 When 0 or negative, it means use this number (the absolute value of it)
2719 even if a deadline has a different individual lead time specified.
2721 Custom commands can set this variable in the options section."
2722 :group 'org-time
2723 :group 'org-agenda-daily/weekly
2724 :type 'integer)
2726 (defcustom org-read-date-prefer-future t
2727 "Non-nil means assume future for incomplete date input from user.
2728 This affects the following situations:
2729 1. The user gives a month but not a year.
2730 For example, if it is April and you enter \"feb 2\", this will be read
2731 as Feb 2, *next* year. \"May 5\", however, will be this year.
2732 2. The user gives a day, but no month.
2733 For example, if today is the 15th, and you enter \"3\", Org-mode will
2734 read this as the third of *next* month. However, if you enter \"17\",
2735 it will be considered as *this* month.
2737 If you set this variable to the symbol `time', then also the following
2738 will work:
2740 3. If the user gives a time.
2741 If the time is before now, it will be interpreted as tomorrow.
2743 Currently none of this works for ISO week specifications.
2745 When this option is nil, the current day, month and year will always be
2746 used as defaults.
2748 See also `org-agenda-jump-prefer-future'."
2749 :group 'org-time
2750 :type '(choice
2751 (const :tag "Never" nil)
2752 (const :tag "Check month and day" t)
2753 (const :tag "Check month, day, and time" time)))
2755 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2756 "Should the agenda jump command prefer the future for incomplete dates?
2757 The default is to do the same as configured in `org-read-date-prefer-future'.
2758 But you can also set a deviating value here.
2759 This may t or nil, or the symbol `org-read-date-prefer-future'."
2760 :group 'org-agenda
2761 :group 'org-time
2762 :version "24.1"
2763 :type '(choice
2764 (const :tag "Use org-read-date-prefer-future"
2765 org-read-date-prefer-future)
2766 (const :tag "Never" nil)
2767 (const :tag "Always" t)))
2769 (defcustom org-read-date-force-compatible-dates t
2770 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2772 Depending on the system Emacs is running on, certain dates cannot
2773 be represented with the type used internally to represent time.
2774 Dates between 1970-1-1 and 2038-1-1 can always be represented
2775 correctly. Some systems allow for earlier dates, some for later,
2776 some for both. One way to find out it to insert any date into an
2777 Org buffer, putting the cursor on the year and hitting S-up and
2778 S-down to test the range.
2780 When this variable is set to t, the date/time prompt will not let
2781 you specify dates outside the 1970-2037 range, so it is certain that
2782 these dates will work in whatever version of Emacs you are
2783 running, and also that you can move a file from one Emacs implementation
2784 to another. WHenever Org is forcing the year for you, it will display
2785 a message and beep.
2787 When this variable is nil, Org will check if the date is
2788 representable in the specific Emacs implementation you are using.
2789 If not, it will force a year, usually the current year, and beep
2790 to remind you. Currently this setting is not recommended because
2791 the likelihood that you will open your Org files in an Emacs that
2792 has limited date range is not negligible.
2794 A workaround for this problem is to use diary sexp dates for time
2795 stamps outside of this range."
2796 :group 'org-time
2797 :version "24.1"
2798 :type 'boolean)
2800 (defcustom org-read-date-display-live t
2801 "Non-nil means display current interpretation of date prompt live.
2802 This display will be in an overlay, in the minibuffer."
2803 :group 'org-time
2804 :type 'boolean)
2806 (defcustom org-read-date-popup-calendar t
2807 "Non-nil means pop up a calendar when prompting for a date.
2808 In the calendar, the date can be selected with mouse-1. However, the
2809 minibuffer will also be active, and you can simply enter the date as well.
2810 When nil, only the minibuffer will be available."
2811 :group 'org-time
2812 :type 'boolean)
2813 (if (fboundp 'defvaralias)
2814 (defvaralias 'org-popup-calendar-for-date-prompt
2815 'org-read-date-popup-calendar))
2817 (defcustom org-read-date-minibuffer-setup-hook nil
2818 "Hook to be used to set up keys for the date/time interface.
2819 Add key definitions to `minibuffer-local-map', which will be a temporary
2820 copy."
2821 :group 'org-time
2822 :type 'hook)
2824 (defcustom org-extend-today-until 0
2825 "The hour when your day really ends. Must be an integer.
2826 This has influence for the following applications:
2827 - When switching the agenda to \"today\". It it is still earlier than
2828 the time given here, the day recognized as TODAY is actually yesterday.
2829 - When a date is read from the user and it is still before the time given
2830 here, the current date and time will be assumed to be yesterday, 23:59.
2831 Also, timestamps inserted in capture templates follow this rule.
2833 IMPORTANT: This is a feature whose implementation is and likely will
2834 remain incomplete. Really, it is only here because past midnight seems to
2835 be the favorite working time of John Wiegley :-)"
2836 :group 'org-time
2837 :type 'integer)
2839 (defcustom org-use-effective-time nil
2840 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2841 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2842 \"effective time\" of any timestamps between midnight and 8am will be
2843 23:59 of the previous day."
2844 :group 'org-time
2845 :version "24.1"
2846 :type 'boolean)
2848 (defcustom org-edit-timestamp-down-means-later nil
2849 "Non-nil means S-down will increase the time in a time stamp.
2850 When nil, S-up will increase."
2851 :group 'org-time
2852 :type 'boolean)
2854 (defcustom org-calendar-follow-timestamp-change t
2855 "Non-nil means make the calendar window follow timestamp changes.
2856 When a timestamp is modified and the calendar window is visible, it will be
2857 moved to the new date."
2858 :group 'org-time
2859 :type 'boolean)
2861 (defgroup org-tags nil
2862 "Options concerning tags in Org-mode."
2863 :tag "Org Tags"
2864 :group 'org)
2866 (defcustom org-tag-alist nil
2867 "List of tags allowed in Org-mode files.
2868 When this list is nil, Org-mode will base TAG input on what is already in the
2869 buffer.
2870 The value of this variable is an alist, the car of each entry must be a
2871 keyword as a string, the cdr may be a character that is used to select
2872 that tag through the fast-tag-selection interface.
2873 See the manual for details."
2874 :group 'org-tags
2875 :type '(repeat
2876 (choice
2877 (cons (string :tag "Tag name")
2878 (character :tag "Access char"))
2879 (list :tag "Start radio group"
2880 (const :startgroup)
2881 (option (string :tag "Group description")))
2882 (list :tag "End radio group"
2883 (const :endgroup)
2884 (option (string :tag "Group description")))
2885 (const :tag "New line" (:newline)))))
2887 (defcustom org-tag-persistent-alist nil
2888 "List of tags that will always appear in all Org-mode files.
2889 This is in addition to any in buffer settings or customizations
2890 of `org-tag-alist'.
2891 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2892 The value of this variable is an alist, the car of each entry must be a
2893 keyword as a string, the cdr may be a character that is used to select
2894 that tag through the fast-tag-selection interface.
2895 See the manual for details.
2896 To disable these tags on a per-file basis, insert anywhere in the file:
2897 #+STARTUP: noptag"
2898 :group 'org-tags
2899 :type '(repeat
2900 (choice
2901 (cons (string :tag "Tag name")
2902 (character :tag "Access char"))
2903 (const :tag "Start radio group" (:startgroup))
2904 (const :tag "End radio group" (:endgroup))
2905 (const :tag "New line" (:newline)))))
2907 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2908 "If non-nil, always offer completion for all tags of all agenda files.
2909 Instead of customizing this variable directly, you might want to
2910 set it locally for capture buffers, because there no list of
2911 tags in that file can be created dynamically (there are none).
2913 (add-hook 'org-capture-mode-hook
2914 (lambda ()
2915 (set (make-local-variable
2916 'org-complete-tags-always-offer-all-agenda-tags)
2917 t)))"
2918 :group 'org-tags
2919 :version "24.1"
2920 :type 'boolean)
2922 (defvar org-file-tags nil
2923 "List of tags that can be inherited by all entries in the file.
2924 The tags will be inherited if the variable `org-use-tag-inheritance'
2925 says they should be.
2926 This variable is populated from #+FILETAGS lines.")
2928 (defcustom org-use-fast-tag-selection 'auto
2929 "Non-nil means use fast tag selection scheme.
2930 This is a special interface to select and deselect tags with single keys.
2931 When nil, fast selection is never used.
2932 When the symbol `auto', fast selection is used if and only if selection
2933 characters for tags have been configured, either through the variable
2934 `org-tag-alist' or through a #+TAGS line in the buffer.
2935 When t, fast selection is always used and selection keys are assigned
2936 automatically if necessary."
2937 :group 'org-tags
2938 :type '(choice
2939 (const :tag "Always" t)
2940 (const :tag "Never" nil)
2941 (const :tag "When selection characters are configured" 'auto)))
2943 (defcustom org-fast-tag-selection-single-key nil
2944 "Non-nil means fast tag selection exits after first change.
2945 When nil, you have to press RET to exit it.
2946 During fast tag selection, you can toggle this flag with `C-c'.
2947 This variable can also have the value `expert'. In this case, the window
2948 displaying the tags menu is not even shown, until you press C-c again."
2949 :group 'org-tags
2950 :type '(choice
2951 (const :tag "No" nil)
2952 (const :tag "Yes" t)
2953 (const :tag "Expert" expert)))
2955 (defvar org-fast-tag-selection-include-todo nil
2956 "Non-nil means fast tags selection interface will also offer TODO states.
2957 This is an undocumented feature, you should not rely on it.")
2959 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2960 "The column to which tags should be indented in a headline.
2961 If this number is positive, it specifies the column. If it is negative,
2962 it means that the tags should be flushright to that column. For example,
2963 -80 works well for a normal 80 character screen.
2964 When 0, place tags directly after headline text, with only one space in
2965 between."
2966 :group 'org-tags
2967 :type 'integer)
2969 (defcustom org-auto-align-tags t
2970 "Non-nil keeps tags aligned when modifying headlines.
2971 Some operations (i.e. demoting) change the length of a headline and
2972 therefore shift the tags around. With this option turned on, after
2973 each such operation the tags are again aligned to `org-tags-column'."
2974 :group 'org-tags
2975 :type 'boolean)
2977 (defcustom org-use-tag-inheritance t
2978 "Non-nil means tags in levels apply also for sublevels.
2979 When nil, only the tags directly given in a specific line apply there.
2980 This may also be a list of tags that should be inherited, or a regexp that
2981 matches tags that should be inherited. Additional control is possible
2982 with the variable `org-tags-exclude-from-inheritance' which gives an
2983 explicit list of tags to be excluded from inheritance., even if the value of
2984 `org-use-tag-inheritance' would select it for inheritance.
2986 If this option is t, a match early-on in a tree can lead to a large
2987 number of matches in the subtree when constructing the agenda or creating
2988 a sparse tree. If you only want to see the first match in a tree during
2989 a search, check out the variable `org-tags-match-list-sublevels'."
2990 :group 'org-tags
2991 :type '(choice
2992 (const :tag "Not" nil)
2993 (const :tag "Always" t)
2994 (repeat :tag "Specific tags" (string :tag "Tag"))
2995 (regexp :tag "Tags matched by regexp")))
2997 (defcustom org-tags-exclude-from-inheritance nil
2998 "List of tags that should never be inherited.
2999 This is a way to exclude a few tags from inheritance. For way to do
3000 the opposite, to actively allow inheritance for selected tags,
3001 see the variable `org-use-tag-inheritance'."
3002 :group 'org-tags
3003 :type '(repeat (string :tag "Tag")))
3005 (defun org-tag-inherit-p (tag)
3006 "Check if TAG is one that should be inherited."
3007 (cond
3008 ((member tag org-tags-exclude-from-inheritance) nil)
3009 ((eq org-use-tag-inheritance t) t)
3010 ((not org-use-tag-inheritance) nil)
3011 ((stringp org-use-tag-inheritance)
3012 (string-match org-use-tag-inheritance tag))
3013 ((listp org-use-tag-inheritance)
3014 (member tag org-use-tag-inheritance))
3015 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3017 (defcustom org-tags-match-list-sublevels t
3018 "Non-nil means list also sublevels of headlines matching a search.
3019 This variable applies to tags/property searches, and also to stuck
3020 projects because this search is based on a tags match as well.
3022 When set to the symbol `indented', sublevels are indented with
3023 leading dots.
3025 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3026 the sublevels of a headline matching a tag search often also match
3027 the same search. Listing all of them can create very long lists.
3028 Setting this variable to nil causes subtrees of a match to be skipped.
3030 This variable is semi-obsolete and probably should always be true. It
3031 is better to limit inheritance to certain tags using the variables
3032 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3033 :group 'org-tags
3034 :type '(choice
3035 (const :tag "No, don't list them" nil)
3036 (const :tag "Yes, do list them" t)
3037 (const :tag "List them, indented with leading dots" indented)))
3039 (defcustom org-tags-sort-function nil
3040 "When set, tags are sorted using this function as a comparator."
3041 :group 'org-tags
3042 :type '(choice
3043 (const :tag "No sorting" nil)
3044 (const :tag "Alphabetical" string<)
3045 (const :tag "Reverse alphabetical" string>)
3046 (function :tag "Custom function" nil)))
3048 (defvar org-tags-history nil
3049 "History of minibuffer reads for tags.")
3050 (defvar org-last-tags-completion-table nil
3051 "The last used completion table for tags.")
3052 (defvar org-after-tags-change-hook nil
3053 "Hook that is run after the tags in a line have changed.")
3055 (defgroup org-properties nil
3056 "Options concerning properties in Org-mode."
3057 :tag "Org Properties"
3058 :group 'org)
3060 (defcustom org-property-format "%-10s %s"
3061 "How property key/value pairs should be formatted by `indent-line'.
3062 When `indent-line' hits a property definition, it will format the line
3063 according to this format, mainly to make sure that the values are
3064 lined-up with respect to each other."
3065 :group 'org-properties
3066 :type 'string)
3068 (defcustom org-properties-postprocess-alist nil
3069 "Alist of properties and functions to adjust inserted values.
3070 Elements of this alist must be of the form
3072 ([string] [function])
3074 where [string] must be a property name and [function] must be a
3075 lambda expression: this lambda expression must take one argument,
3076 the value to adjust, and return the new value as a string.
3078 For example, this element will allow the property \"Remaining\"
3079 to be updated wrt the relation between the \"Effort\" property
3080 and the clock summary:
3082 ((\"Remaining\" (lambda(value)
3083 (let ((clocksum (org-clock-sum-current-item))
3084 (effort (org-duration-string-to-minutes
3085 (org-entry-get (point) \"Effort\"))))
3086 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3087 :group 'org-properties
3088 :version "24.1"
3089 :type '(alist :key-type (string :tag "Property")
3090 :value-type (function :tag "Function")))
3092 (defcustom org-use-property-inheritance nil
3093 "Non-nil means properties apply also for sublevels.
3095 This setting is chiefly used during property searches. Turning it on can
3096 cause significant overhead when doing a search, which is why it is not
3097 on by default.
3099 When nil, only the properties directly given in the current entry count.
3100 When t, every property is inherited. The value may also be a list of
3101 properties that should have inheritance, or a regular expression matching
3102 properties that should be inherited.
3104 However, note that some special properties use inheritance under special
3105 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3106 and the properties ending in \"_ALL\" when they are used as descriptor
3107 for valid values of a property.
3109 Note for programmers:
3110 When querying an entry with `org-entry-get', you can control if inheritance
3111 should be used. By default, `org-entry-get' looks only at the local
3112 properties. You can request inheritance by setting the inherit argument
3113 to t (to force inheritance) or to `selective' (to respect the setting
3114 in this variable)."
3115 :group 'org-properties
3116 :type '(choice
3117 (const :tag "Not" nil)
3118 (const :tag "Always" t)
3119 (repeat :tag "Specific properties" (string :tag "Property"))
3120 (regexp :tag "Properties matched by regexp")))
3122 (defun org-property-inherit-p (property)
3123 "Check if PROPERTY is one that should be inherited."
3124 (cond
3125 ((eq org-use-property-inheritance t) t)
3126 ((not org-use-property-inheritance) nil)
3127 ((stringp org-use-property-inheritance)
3128 (string-match org-use-property-inheritance property))
3129 ((listp org-use-property-inheritance)
3130 (member property org-use-property-inheritance))
3131 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3133 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3134 "The default column format, if no other format has been defined.
3135 This variable can be set on the per-file basis by inserting a line
3137 #+COLUMNS: %25ITEM ....."
3138 :group 'org-properties
3139 :type 'string)
3141 (defcustom org-columns-ellipses ".."
3142 "The ellipses to be used when a field in column view is truncated.
3143 When this is the empty string, as many characters as possible are shown,
3144 but then there will be no visual indication that the field has been truncated.
3145 When this is a string of length N, the last N characters of a truncated
3146 field are replaced by this string. If the column is narrower than the
3147 ellipses string, only part of the ellipses string will be shown."
3148 :group 'org-properties
3149 :type 'string)
3151 (defcustom org-columns-modify-value-for-display-function nil
3152 "Function that modifies values for display in column view.
3153 For example, it can be used to cut out a certain part from a time stamp.
3154 The function must take 2 arguments:
3156 column-title The title of the column (*not* the property name)
3157 value The value that should be modified.
3159 The function should return the value that should be displayed,
3160 or nil if the normal value should be used."
3161 :group 'org-properties
3162 :type 'function)
3164 (defcustom org-effort-property "Effort"
3165 "The property that is being used to keep track of effort estimates.
3166 Effort estimates given in this property need to have the format H:MM."
3167 :group 'org-properties
3168 :group 'org-progress
3169 :type '(string :tag "Property"))
3171 (defconst org-global-properties-fixed
3172 '(("VISIBILITY_ALL" . "folded children content all")
3173 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3174 "List of property/value pairs that can be inherited by any entry.
3176 These are fixed values, for the preset properties. The user variable
3177 that can be used to add to this list is `org-global-properties'.
3179 The entries in this list are cons cells where the car is a property
3180 name and cdr is a string with the value. If the value represents
3181 multiple items like an \"_ALL\" property, separate the items by
3182 spaces.")
3184 (defcustom org-global-properties nil
3185 "List of property/value pairs that can be inherited by any entry.
3187 This list will be combined with the constant `org-global-properties-fixed'.
3189 The entries in this list are cons cells where the car is a property
3190 name and cdr is a string with the value.
3192 You can set buffer-local values for the same purpose in the variable
3193 `org-file-properties' this by adding lines like
3195 #+PROPERTY: NAME VALUE"
3196 :group 'org-properties
3197 :type '(repeat
3198 (cons (string :tag "Property")
3199 (string :tag "Value"))))
3201 (defvar org-file-properties nil
3202 "List of property/value pairs that can be inherited by any entry.
3203 Valid for the current buffer.
3204 This variable is populated from #+PROPERTY lines.")
3205 (make-variable-buffer-local 'org-file-properties)
3207 (defgroup org-agenda nil
3208 "Options concerning agenda views in Org-mode."
3209 :tag "Org Agenda"
3210 :group 'org)
3212 (defvar org-category nil
3213 "Variable used by org files to set a category for agenda display.
3214 Such files should use a file variable to set it, for example
3216 # -*- mode: org; org-category: \"ELisp\"
3218 or contain a special line
3220 #+CATEGORY: ELisp
3222 If the file does not specify a category, then file's base name
3223 is used instead.")
3224 (make-variable-buffer-local 'org-category)
3225 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3227 (defcustom org-agenda-files nil
3228 "The files to be used for agenda display.
3229 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3230 \\[org-remove-file]. You can also use customize to edit the list.
3232 If an entry is a directory, all files in that directory that are matched by
3233 `org-agenda-file-regexp' will be part of the file list.
3235 If the value of the variable is not a list but a single file name, then
3236 the list of agenda files is actually stored and maintained in that file, one
3237 agenda file per line. In this file paths can be given relative to
3238 `org-directory'. Tilde expansion and environment variable substitution
3239 are also made."
3240 :group 'org-agenda
3241 :type '(choice
3242 (repeat :tag "List of files and directories" file)
3243 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3245 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3246 "Regular expression to match files for `org-agenda-files'.
3247 If any element in the list in that variable contains a directory instead
3248 of a normal file, all files in that directory that are matched by this
3249 regular expression will be included."
3250 :group 'org-agenda
3251 :type 'regexp)
3253 (defcustom org-agenda-text-search-extra-files nil
3254 "List of extra files to be searched by text search commands.
3255 These files will be search in addition to the agenda files by the
3256 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3257 Note that these files will only be searched for text search commands,
3258 not for the other agenda views like todo lists, tag searches or the weekly
3259 agenda. This variable is intended to list notes and possibly archive files
3260 that should also be searched by these two commands.
3261 In fact, if the first element in the list is the symbol `agenda-archives',
3262 than all archive files of all agenda files will be added to the search
3263 scope."
3264 :group 'org-agenda
3265 :type '(set :greedy t
3266 (const :tag "Agenda Archives" agenda-archives)
3267 (repeat :inline t (file))))
3269 (if (fboundp 'defvaralias)
3270 (defvaralias 'org-agenda-multi-occur-extra-files
3271 'org-agenda-text-search-extra-files))
3273 (defcustom org-agenda-skip-unavailable-files nil
3274 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3275 A nil value means to remove them, after a query, from the list."
3276 :group 'org-agenda
3277 :type 'boolean)
3279 (defcustom org-calendar-to-agenda-key [?c]
3280 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3281 The command `org-calendar-goto-agenda' will be bound to this key. The
3282 default is the character `c' because then `c' can be used to switch back and
3283 forth between agenda and calendar."
3284 :group 'org-agenda
3285 :type 'sexp)
3287 (defcustom org-calendar-insert-diary-entry-key [?i]
3288 "The key to be installed in `calendar-mode-map' for adding diary entries.
3289 This option is irrelevant until `org-agenda-diary-file' has been configured
3290 to point to an Org-mode file. When that is the case, the command
3291 `org-agenda-diary-entry' will be bound to the key given here, by default
3292 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3293 if you want to continue doing this, you need to change this to a different
3294 key."
3295 :group 'org-agenda
3296 :type 'sexp)
3298 (defcustom org-agenda-diary-file 'diary-file
3299 "File to which to add new entries with the `i' key in agenda and calendar.
3300 When this is the symbol `diary-file', the functionality in the Emacs
3301 calendar will be used to add entries to the `diary-file'. But when this
3302 points to a file, `org-agenda-diary-entry' will be used instead."
3303 :group 'org-agenda
3304 :type '(choice
3305 (const :tag "The standard Emacs diary file" diary-file)
3306 (file :tag "Special Org file diary entries")))
3308 (eval-after-load "calendar"
3309 '(progn
3310 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3311 'org-calendar-goto-agenda)
3312 (add-hook 'calendar-mode-hook
3313 (lambda ()
3314 (unless (eq org-agenda-diary-file 'diary-file)
3315 (define-key calendar-mode-map
3316 org-calendar-insert-diary-entry-key
3317 'org-agenda-diary-entry))))))
3319 (defgroup org-latex nil
3320 "Options for embedding LaTeX code into Org-mode."
3321 :tag "Org LaTeX"
3322 :group 'org)
3324 (defcustom org-format-latex-options
3325 '(:foreground default :background default :scale 1.0
3326 :html-foreground "Black" :html-background "Transparent"
3327 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3328 "Options for creating images from LaTeX fragments.
3329 This is a property list with the following properties:
3330 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3331 `default' means use the foreground of the default face.
3332 :background the background color, or \"Transparent\".
3333 `default' means use the background of the default face.
3334 :scale a scaling factor for the size of the images, to get more pixels
3335 :html-foreground, :html-background, :html-scale
3336 the same numbers for HTML export.
3337 :matchers a list indicating which matchers should be used to
3338 find LaTeX fragments. Valid members of this list are:
3339 \"begin\" find environments
3340 \"$1\" find single characters surrounded by $.$
3341 \"$\" find math expressions surrounded by $...$
3342 \"$$\" find math expressions surrounded by $$....$$
3343 \"\\(\" find math expressions surrounded by \\(...\\)
3344 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3345 :group 'org-latex
3346 :type 'plist)
3348 (defcustom org-format-latex-signal-error t
3349 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3350 When nil, just push out a message."
3351 :group 'org-latex
3352 :version "24.1"
3353 :type 'boolean)
3355 (defcustom org-latex-to-mathml-jar-file nil
3356 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3357 Use this to specify additional executable file say a jar file.
3359 When using MathToWeb as the converter, specify the full-path to
3360 your mathtoweb.jar file."
3361 :group 'org-latex
3362 :version "24.1"
3363 :type '(choice
3364 (const :tag "None" nil)
3365 (file :tag "JAR file" :must-match t)))
3367 (defcustom org-latex-to-mathml-convert-command nil
3368 "Command to convert LaTeX fragments to MathML.
3369 Replace format-specifiers in the command as noted below and use
3370 `shell-command' to convert LaTeX to MathML.
3371 %j: Executable file in fully expanded form as specified by
3372 `org-latex-to-mathml-jar-file'.
3373 %I: Input LaTeX file in fully expanded form
3374 %o: Output MathML file
3375 This command is used by `org-create-math-formula'.
3377 When using MathToWeb as the converter, set this to
3378 \"java -jar %j -unicode -force -df %o %I\"."
3379 :group 'org-latex
3380 :version "24.1"
3381 :type '(choice
3382 (const :tag "None" nil)
3383 (string :tag "\nShell command")))
3385 (defcustom org-latex-create-formula-image-program 'dvipng
3386 "Program to convert LaTeX fragments with.
3388 dvipng Process the LaTeX fragments to dvi file, then convert
3389 dvi files to png files using dvipng.
3390 This will also include processing of non-math environments.
3391 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3392 to convert pdf files to png files"
3393 :group 'org-latex
3394 :version "24.1"
3395 :type '(choice
3396 (const :tag "dvipng" dvipng)
3397 (const :tag "imagemagick" imagemagick)))
3399 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3400 "Path to store latex preview images. A relative path here creates many
3401 directories relative to the processed org files paths. An absolute path
3402 puts all preview images at the same place."
3403 :group 'org-latex
3404 :version "24.3"
3405 :type 'string)
3407 (defun org-format-latex-mathml-available-p ()
3408 "Return t if `org-latex-to-mathml-convert-command' is usable."
3409 (save-match-data
3410 (when (and (boundp 'org-latex-to-mathml-convert-command)
3411 org-latex-to-mathml-convert-command)
3412 (let ((executable (car (split-string
3413 org-latex-to-mathml-convert-command))))
3414 (when (executable-find executable)
3415 (if (string-match
3416 "%j" org-latex-to-mathml-convert-command)
3417 (file-readable-p org-latex-to-mathml-jar-file)
3418 t))))))
3420 (defcustom org-format-latex-header "\\documentclass{article}
3421 \\usepackage[usenames]{color}
3422 \\usepackage{amsmath}
3423 \\usepackage[mathscr]{eucal}
3424 \\pagestyle{empty} % do not remove
3425 \[PACKAGES]
3426 \[DEFAULT-PACKAGES]
3427 % The settings below are copied from fullpage.sty
3428 \\setlength{\\textwidth}{\\paperwidth}
3429 \\addtolength{\\textwidth}{-3cm}
3430 \\setlength{\\oddsidemargin}{1.5cm}
3431 \\addtolength{\\oddsidemargin}{-2.54cm}
3432 \\setlength{\\evensidemargin}{\\oddsidemargin}
3433 \\setlength{\\textheight}{\\paperheight}
3434 \\addtolength{\\textheight}{-\\headheight}
3435 \\addtolength{\\textheight}{-\\headsep}
3436 \\addtolength{\\textheight}{-\\footskip}
3437 \\addtolength{\\textheight}{-3cm}
3438 \\setlength{\\topmargin}{1.5cm}
3439 \\addtolength{\\topmargin}{-2.54cm}"
3440 "The document header used for processing LaTeX fragments.
3441 It is imperative that this header make sure that no page number
3442 appears on the page. The package defined in the variables
3443 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3444 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3445 will be appended."
3446 :group 'org-latex
3447 :type 'string)
3449 (defvar org-format-latex-header-extra nil)
3451 (defun org-set-packages-alist (var val)
3452 "Set the packages alist and make sure it has 3 elements per entry."
3453 (set var (mapcar (lambda (x)
3454 (if (and (consp x) (= (length x) 2))
3455 (list (car x) (nth 1 x) t)
3457 val)))
3459 (defun org-get-packages-alist (var)
3461 "Get the packages alist and make sure it has 3 elements per entry."
3462 (mapcar (lambda (x)
3463 (if (and (consp x) (= (length x) 2))
3464 (list (car x) (nth 1 x) t)
3466 (default-value var)))
3468 ;; The following variables are defined here because is it also used
3469 ;; when formatting latex fragments. Originally it was part of the
3470 ;; LaTeX exporter, which is why the name includes "export".
3471 (defcustom org-export-latex-default-packages-alist
3472 '(("AUTO" "inputenc" t)
3473 ("T1" "fontenc" t)
3474 ("" "fixltx2e" nil)
3475 ("" "graphicx" t)
3476 ("" "longtable" nil)
3477 ("" "float" nil)
3478 ("" "wrapfig" nil)
3479 ("" "soul" t)
3480 ("" "textcomp" t)
3481 ("" "marvosym" t)
3482 ("" "wasysym" t)
3483 ("" "latexsym" t)
3484 ("" "amssymb" t)
3485 ("" "hyperref" nil)
3486 "\\tolerance=1000"
3488 "Alist of default packages to be inserted in the header.
3489 Change this only if one of the packages here causes an incompatibility
3490 with another package you are using.
3491 The packages in this list are needed by one part or another of Org-mode
3492 to function properly.
3494 - inputenc, fontenc: for basic font and character selection
3495 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3496 for interpreting the entities in `org-entities'. You can skip some of these
3497 packages if you don't use any of the symbols in it.
3498 - graphicx: for including images
3499 - float, wrapfig: for figure placement
3500 - longtable: for long tables
3501 - hyperref: for cross references
3503 Therefore you should not modify this variable unless you know what you
3504 are doing. The one reason to change it anyway is that you might be loading
3505 some other package that conflicts with one of the default packages.
3506 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3507 If SNIPPET-FLAG is t, the package also needs to be included when
3508 compiling LaTeX snippets into images for inclusion into HTML."
3509 :group 'org-export-latex
3510 :set 'org-set-packages-alist
3511 :get 'org-get-packages-alist
3512 :version "24.1"
3513 :type '(repeat
3514 (choice
3515 (list :tag "options/package pair"
3516 (string :tag "options")
3517 (string :tag "package")
3518 (boolean :tag "Snippet"))
3519 (string :tag "A line of LaTeX"))))
3521 (defcustom org-export-latex-packages-alist nil
3522 "Alist of packages to be inserted in every LaTeX header.
3523 These will be inserted after `org-export-latex-default-packages-alist'.
3524 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3525 SNIPPET-FLAG, when t, indicates that this package is also needed when
3526 turning LaTeX snippets into images for inclusion into HTML.
3527 Make sure that you only list packages here which:
3528 - you want in every file
3529 - do not conflict with the default packages in
3530 `org-export-latex-default-packages-alist'
3531 - do not conflict with the setup in `org-format-latex-header'."
3532 :group 'org-export-latex
3533 :set 'org-set-packages-alist
3534 :get 'org-get-packages-alist
3535 :type '(repeat
3536 (choice
3537 (list :tag "options/package pair"
3538 (string :tag "options")
3539 (string :tag "package")
3540 (boolean :tag "Snippet"))
3541 (string :tag "A line of LaTeX"))))
3544 (defgroup org-appearance nil
3545 "Settings for Org-mode appearance."
3546 :tag "Org Appearance"
3547 :group 'org)
3549 (defcustom org-level-color-stars-only nil
3550 "Non-nil means fontify only the stars in each headline.
3551 When nil, the entire headline is fontified.
3552 Changing it requires restart of `font-lock-mode' to become effective
3553 also in regions already fontified."
3554 :group 'org-appearance
3555 :type 'boolean)
3557 (defcustom org-hide-leading-stars nil
3558 "Non-nil means hide the first N-1 stars in a headline.
3559 This works by using the face `org-hide' for these stars. This
3560 face is white for a light background, and black for a dark
3561 background. You may have to customize the face `org-hide' to
3562 make this work.
3563 Changing it requires restart of `font-lock-mode' to become effective
3564 also in regions already fontified.
3565 You may also set this on a per-file basis by adding one of the following
3566 lines to the buffer:
3568 #+STARTUP: hidestars
3569 #+STARTUP: showstars"
3570 :group 'org-appearance
3571 :type 'boolean)
3573 (defcustom org-hidden-keywords nil
3574 "List of symbols corresponding to keywords to be hidden the org buffer.
3575 For example, a value '(title) for this list will make the document's title
3576 appear in the buffer without the initial #+TITLE: keyword."
3577 :group 'org-appearance
3578 :version "24.1"
3579 :type '(set (const :tag "#+AUTHOR" author)
3580 (const :tag "#+DATE" date)
3581 (const :tag "#+EMAIL" email)
3582 (const :tag "#+TITLE" title)))
3584 (defcustom org-custom-properties nil
3585 "List of properties (as strings) with a special meaning.
3586 The default use of these custom properties is to let the user
3587 hide them with `org-toggle-custom-properties-visibility'."
3588 :group 'org-properties
3589 :group 'org-appearance
3590 :version "24.3"
3591 :type '(repeat (string :tag "Property Name")))
3593 (defcustom org-fontify-done-headline nil
3594 "Non-nil means change the face of a headline if it is marked DONE.
3595 Normally, only the TODO/DONE keyword indicates the state of a headline.
3596 When this is non-nil, the headline after the keyword is set to the
3597 `org-headline-done' as an additional indication."
3598 :group 'org-appearance
3599 :type 'boolean)
3601 (defcustom org-fontify-emphasized-text t
3602 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3603 Changing this variable requires a restart of Emacs to take effect."
3604 :group 'org-appearance
3605 :type 'boolean)
3607 (defcustom org-fontify-whole-heading-line nil
3608 "Non-nil means fontify the whole line for headings.
3609 This is useful when setting a background color for the
3610 org-level-* faces."
3611 :group 'org-appearance
3612 :type 'boolean)
3614 (defcustom org-highlight-latex-fragments-and-specials nil
3615 "Non-nil means fontify what is treated specially by the exporters."
3616 :group 'org-appearance
3617 :type 'boolean)
3619 (defcustom org-hide-emphasis-markers nil
3620 "Non-nil mean font-lock should hide the emphasis marker characters."
3621 :group 'org-appearance
3622 :type 'boolean)
3624 (defcustom org-pretty-entities nil
3625 "Non-nil means show entities as UTF8 characters.
3626 When nil, the \\name form remains in the buffer."
3627 :group 'org-appearance
3628 :version "24.1"
3629 :type 'boolean)
3631 (defcustom org-pretty-entities-include-sub-superscripts t
3632 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3633 :group 'org-appearance
3634 :version "24.1"
3635 :type 'boolean)
3637 (defvar org-emph-re nil
3638 "Regular expression for matching emphasis.
3639 After a match, the match groups contain these elements:
3640 0 The match of the full regular expression, including the characters
3641 before and after the proper match
3642 1 The character before the proper match, or empty at beginning of line
3643 2 The proper match, including the leading and trailing markers
3644 3 The leading marker like * or /, indicating the type of highlighting
3645 4 The text between the emphasis markers, not including the markers
3646 5 The character after the match, empty at the end of a line")
3647 (defvar org-verbatim-re nil
3648 "Regular expression for matching verbatim text.")
3649 (defvar org-emphasis-regexp-components) ; defined just below
3650 (defvar org-emphasis-alist) ; defined just below
3651 (defun org-set-emph-re (var val)
3652 "Set variable and compute the emphasis regular expression."
3653 (set var val)
3654 (when (and (boundp 'org-emphasis-alist)
3655 (boundp 'org-emphasis-regexp-components)
3656 org-emphasis-alist org-emphasis-regexp-components)
3657 (let* ((e org-emphasis-regexp-components)
3658 (pre (car e))
3659 (post (nth 1 e))
3660 (border (nth 2 e))
3661 (body (nth 3 e))
3662 (nl (nth 4 e))
3663 (body1 (concat body "*?"))
3664 (markers (mapconcat 'car org-emphasis-alist ""))
3665 (vmarkers (mapconcat
3666 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3667 org-emphasis-alist "")))
3668 ;; make sure special characters appear at the right position in the class
3669 (if (string-match "\\^" markers)
3670 (setq markers (concat (replace-match "" t t markers) "^")))
3671 (if (string-match "-" markers)
3672 (setq markers (concat (replace-match "" t t markers) "-")))
3673 (if (string-match "\\^" vmarkers)
3674 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3675 (if (string-match "-" vmarkers)
3676 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3677 (if (> nl 0)
3678 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3679 (int-to-string nl) "\\}")))
3680 ;; Make the regexp
3681 (setq org-emph-re
3682 (concat "\\([" pre "]\\|^\\)"
3683 "\\("
3684 "\\([" markers "]\\)"
3685 "\\("
3686 "[^" border "]\\|"
3687 "[^" border "]"
3688 body1
3689 "[^" border "]"
3690 "\\)"
3691 "\\3\\)"
3692 "\\([" post "]\\|$\\)"))
3693 (setq org-verbatim-re
3694 (concat "\\([" pre "]\\|^\\)"
3695 "\\("
3696 "\\([" vmarkers "]\\)"
3697 "\\("
3698 "[^" border "]\\|"
3699 "[^" border "]"
3700 body1
3701 "[^" border "]"
3702 "\\)"
3703 "\\3\\)"
3704 "\\([" post "]\\|$\\)")))))
3706 (defcustom org-emphasis-regexp-components
3707 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3708 "Components used to build the regular expression for emphasis.
3709 This is a list with five entries. Terminology: In an emphasis string
3710 like \" *strong word* \", we call the initial space PREMATCH, the final
3711 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3712 and \"trong wor\" is the body. The different components in this variable
3713 specify what is allowed/forbidden in each part:
3715 pre Chars allowed as prematch. Beginning of line will be allowed too.
3716 post Chars allowed as postmatch. End of line will be allowed too.
3717 border The chars *forbidden* as border characters.
3718 body-regexp A regexp like \".\" to match a body character. Don't use
3719 non-shy groups here, and don't allow newline here.
3720 newline The maximum number of newlines allowed in an emphasis exp.
3722 Use customize to modify this, or restart Emacs after changing it."
3723 :group 'org-appearance
3724 :set 'org-set-emph-re
3725 :type '(list
3726 (sexp :tag "Allowed chars in pre ")
3727 (sexp :tag "Allowed chars in post ")
3728 (sexp :tag "Forbidden chars in border ")
3729 (sexp :tag "Regexp for body ")
3730 (integer :tag "number of newlines allowed")
3731 (option (boolean :tag "Please ignore this button"))))
3733 (defcustom org-emphasis-alist
3734 `(("*" bold "<b>" "</b>")
3735 ("/" italic "<i>" "</i>")
3736 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3737 ("=" org-code "<code>" "</code>" verbatim)
3738 ("~" org-verbatim "<code>" "</code>" verbatim)
3739 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3740 "<del>" "</del>")
3742 "Special syntax for emphasized text.
3743 Text starting and ending with a special character will be emphasized, for
3744 example *bold*, _underlined_ and /italic/. This variable sets the marker
3745 characters, the face to be used by font-lock for highlighting in Org-mode
3746 Emacs buffers, and the HTML tags to be used for this.
3747 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3748 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3749 Use customize to modify this, or restart Emacs after changing it."
3750 :group 'org-appearance
3751 :set 'org-set-emph-re
3752 :type '(repeat
3753 (list
3754 (string :tag "Marker character")
3755 (choice
3756 (face :tag "Font-lock-face")
3757 (plist :tag "Face property list"))
3758 (string :tag "HTML start tag")
3759 (string :tag "HTML end tag")
3760 (option (const verbatim)))))
3762 (defvar org-protecting-blocks
3763 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3764 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3765 This is needed for font-lock setup.")
3767 ;;; Miscellaneous options
3769 (defgroup org-completion nil
3770 "Completion in Org-mode."
3771 :tag "Org Completion"
3772 :group 'org)
3774 (defcustom org-completion-use-ido nil
3775 "Non-nil means use ido completion wherever possible.
3776 Note that `ido-mode' must be active for this variable to be relevant.
3777 If you decide to turn this variable on, you might well want to turn off
3778 `org-outline-path-complete-in-steps'.
3779 See also `org-completion-use-iswitchb'."
3780 :group 'org-completion
3781 :type 'boolean)
3783 (defcustom org-completion-use-iswitchb nil
3784 "Non-nil means use iswitchb completion wherever possible.
3785 Note that `iswitchb-mode' must be active for this variable to be relevant.
3786 If you decide to turn this variable on, you might well want to turn off
3787 `org-outline-path-complete-in-steps'.
3788 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3789 :group 'org-completion
3790 :type 'boolean)
3792 (defcustom org-completion-fallback-command 'hippie-expand
3793 "The expansion command called by \\[pcomplete] in normal context.
3794 Normal means, no org-mode-specific context."
3795 :group 'org-completion
3796 :type 'function)
3798 ;;; Functions and variables from their packages
3799 ;; Declared here to avoid compiler warnings
3801 ;; XEmacs only
3802 (defvar outline-mode-menu-heading)
3803 (defvar outline-mode-menu-show)
3804 (defvar outline-mode-menu-hide)
3805 (defvar zmacs-regions) ; XEmacs regions
3807 ;; Emacs only
3808 (defvar mark-active)
3810 ;; Various packages
3811 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3812 (declare-function calendar-forward-day "cal-move" (arg))
3813 (declare-function calendar-goto-date "cal-move" (date))
3814 (declare-function calendar-goto-today "cal-move" ())
3815 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3816 (defvar calc-embedded-close-formula)
3817 (defvar calc-embedded-open-formula)
3818 (declare-function cdlatex-tab "ext:cdlatex" ())
3819 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3820 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3821 (defvar font-lock-unfontify-region-function)
3822 (declare-function iswitchb-read-buffer "iswitchb"
3823 (prompt &optional default require-match start matches-set))
3824 (defvar iswitchb-temp-buflist)
3825 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3826 (defvar org-agenda-tags-todo-honor-ignore-options)
3827 (declare-function org-agenda-skip "org-agenda" ())
3828 (declare-function
3829 org-agenda-format-item "org-agenda"
3830 (extra txt &optional category tags dotime noprefix remove-re habitp))
3831 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3832 (declare-function org-agenda-change-all-lines "org-agenda"
3833 (newhead hdmarker &optional fixface just-this))
3834 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3835 (declare-function org-agenda-maybe-redo "org-agenda" ())
3836 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3837 (beg end))
3838 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3839 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3840 "org-agenda" (&optional end))
3841 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3842 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3843 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3844 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3845 (declare-function org-indent-mode "org-indent" (&optional arg))
3846 (declare-function parse-time-string "parse-time" (string))
3847 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3848 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3849 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3850 (defvar remember-data-file)
3851 (defvar texmathp-why)
3852 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3853 (declare-function table--at-cell-p "table" (position &optional object at-column))
3855 (defvar w3m-current-url)
3856 (defvar w3m-current-title)
3858 (defvar org-latex-regexps)
3860 ;;; Autoload and prepare some org modules
3862 ;; Some table stuff that needs to be defined here, because it is used
3863 ;; by the functions setting up org-mode or checking for table context.
3865 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3866 "Detect an org-type or table-type table.")
3867 (defconst org-table-line-regexp "^[ \t]*|"
3868 "Detect an org-type table line.")
3869 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3870 "Detect an org-type table line.")
3871 (defconst org-table-hline-regexp "^[ \t]*|-"
3872 "Detect an org-type table hline.")
3873 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3874 "Detect a table-type table hline.")
3875 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3876 "Detect the first line outside a table when searching from within it.
3877 This works for both table types.")
3879 ;; Autoload the functions in org-table.el that are needed by functions here.
3881 (eval-and-compile
3882 (org-autoload "org-table"
3883 '(org-table-begin org-table-blank-field org-table-end)))
3885 ;;;###autoload
3886 (defun turn-on-orgtbl ()
3887 "Unconditionally turn on `orgtbl-mode'."
3888 (require 'org-table)
3889 (orgtbl-mode 1))
3891 (defun org-at-table-p (&optional table-type)
3892 "Return t if the cursor is inside an org-type table.
3893 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3894 (if org-enable-table-editor
3895 (save-excursion
3896 (beginning-of-line 1)
3897 (looking-at (if table-type org-table-any-line-regexp
3898 org-table-line-regexp)))
3899 nil))
3900 (defsubst org-table-p () (org-at-table-p))
3902 (defun org-at-table.el-p ()
3903 "Return t if and only if we are at a table.el table."
3904 (and (org-at-table-p 'any)
3905 (save-excursion
3906 (goto-char (org-table-begin 'any))
3907 (looking-at org-table1-hline-regexp))))
3908 (defun org-table-recognize-table.el ()
3909 "If there is a table.el table nearby, recognize it and move into it."
3910 (if org-table-tab-recognizes-table.el
3911 (if (org-at-table.el-p)
3912 (progn
3913 (beginning-of-line 1)
3914 (if (looking-at org-table-dataline-regexp)
3916 (if (looking-at org-table1-hline-regexp)
3917 (progn
3918 (beginning-of-line 2)
3919 (if (looking-at org-table-any-border-regexp)
3920 (beginning-of-line -1)))))
3921 (if (re-search-forward "|" (org-table-end t) t)
3922 (progn
3923 (require 'table)
3924 (if (table--at-cell-p (point))
3926 (message "recognizing table.el table...")
3927 (table-recognize-table)
3928 (message "recognizing table.el table...done")))
3929 (error "This should not happen"))
3931 nil)
3932 nil))
3934 (defun org-at-table-hline-p ()
3935 "Return t if the cursor is inside a hline in a table."
3936 (if org-enable-table-editor
3937 (save-excursion
3938 (beginning-of-line 1)
3939 (looking-at org-table-hline-regexp))
3940 nil))
3942 (defvar org-table-clean-did-remove-column nil)
3944 (defun org-table-map-tables (function &optional quietly)
3945 "Apply FUNCTION to the start of all tables in the buffer."
3946 (save-excursion
3947 (save-restriction
3948 (widen)
3949 (goto-char (point-min))
3950 (while (re-search-forward org-table-any-line-regexp nil t)
3951 (unless quietly
3952 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3953 (beginning-of-line 1)
3954 (when (and (looking-at org-table-line-regexp)
3955 ;; Exclude tables in src/example/verbatim/clocktable blocks
3956 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
3957 (save-excursion (funcall function))
3958 (or (looking-at org-table-line-regexp)
3959 (forward-char 1)))
3960 (re-search-forward org-table-any-border-regexp nil 1))))
3961 (unless quietly (message "Mapping tables: done")))
3963 ;; Declare and autoload functions from org-exp.el & Co
3965 (declare-function org-default-export-plist "org-exp")
3966 (declare-function org-infile-export-plist "org-exp")
3967 (declare-function org-get-current-options "org-exp")
3969 ;; Declare and autoload functions from org-agenda.el
3971 (eval-and-compile
3972 (org-autoload "org-agenda"
3973 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3975 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3976 (declare-function org-clock-update-mode-line "org-clock" ())
3977 (declare-function org-resolve-clocks "org-clock"
3978 (&optional also-non-dangling-p prompt last-valid))
3979 (defvar org-clock-start-time)
3980 (defvar org-clock-marker (make-marker)
3981 "Marker recording the last clock-in.")
3982 (defvar org-clock-hd-marker (make-marker)
3983 "Marker recording the last clock-in, but the headline position.")
3984 (defvar org-clock-heading ""
3985 "The heading of the current clock entry.")
3986 (defun org-clock-is-active ()
3987 "Return non-nil if clock is currently running.
3988 The return value is actually the clock marker."
3989 (marker-buffer org-clock-marker))
3991 (eval-and-compile
3992 (org-autoload "org-clock" '(org-clock-remove-overlays
3993 org-clock-update-time-maybe
3994 org-clocktable-shift)))
3996 (defun org-check-running-clock ()
3997 "Check if the current buffer contains the running clock.
3998 If yes, offer to stop it and to save the buffer with the changes."
3999 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4000 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4001 (buffer-name))))
4002 (org-clock-out)
4003 (when (y-or-n-p "Save changed buffer?")
4004 (save-buffer))))
4006 (defun org-clocktable-try-shift (dir n)
4007 "Check if this line starts a clock table, if yes, shift the time block."
4008 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4009 (org-clocktable-shift dir n)))
4011 ;;;###autoload
4012 (defun org-clock-persistence-insinuate ()
4013 "Set up hooks for clock persistence."
4014 (require 'org-clock)
4015 (add-hook 'org-mode-hook 'org-clock-load)
4016 (add-hook 'kill-emacs-hook 'org-clock-save))
4018 ;; Define the variable already here, to make sure we have it.
4019 (defvar org-indent-mode nil
4020 "Non-nil if Org-Indent mode is enabled.
4021 Use the command `org-indent-mode' to change this variable.")
4023 ;; Autoload archiving code
4024 ;; The stuff that is needed for cycling and tags has to be defined here.
4026 (defgroup org-archive nil
4027 "Options concerning archiving in Org-mode."
4028 :tag "Org Archive"
4029 :group 'org-structure)
4031 (defcustom org-archive-location "%s_archive::"
4032 "The location where subtrees should be archived.
4034 The value of this variable is a string, consisting of two parts,
4035 separated by a double-colon. The first part is a filename and
4036 the second part is a headline.
4038 When the filename is omitted, archiving happens in the same file.
4039 %s in the filename will be replaced by the current file
4040 name (without the directory part). Archiving to a different file
4041 is useful to keep archived entries from contributing to the
4042 Org-mode Agenda.
4044 The archived entries will be filed as subtrees of the specified
4045 headline. When the headline is omitted, the subtrees are simply
4046 filed away at the end of the file, as top-level entries. Also in
4047 the heading you can use %s to represent the file name, this can be
4048 useful when using the same archive for a number of different files.
4050 Here are a few examples:
4051 \"%s_archive::\"
4052 If the current file is Projects.org, archive in file
4053 Projects.org_archive, as top-level trees. This is the default.
4055 \"::* Archived Tasks\"
4056 Archive in the current file, under the top-level headline
4057 \"* Archived Tasks\".
4059 \"~/org/archive.org::\"
4060 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4062 \"~/org/archive.org::* From %s\"
4063 Archive in file ~/org/archive.org (absolute path), under headlines
4064 \"From FILENAME\" where file name is the current file name.
4066 \"~/org/datetree.org::datetree/* Finished Tasks\"
4067 The \"datetree/\" string is special, signifying to archive
4068 items to the datetree. Items are placed in either the CLOSED
4069 date of the item, or the current date if there is no CLOSED date.
4070 The heading will be a subentry to the current date. There doesn't
4071 need to be a heading, but there always needs to be a slash after
4072 datetree. For example, to store archived items directly in the
4073 datetree, use \"~/org/datetree.org::datetree/\".
4075 \"basement::** Finished Tasks\"
4076 Archive in file ./basement (relative path), as level 3 trees
4077 below the level 2 heading \"** Finished Tasks\".
4079 You may set this option on a per-file basis by adding to the buffer a
4080 line like
4082 #+ARCHIVE: basement::** Finished Tasks
4084 You may also define it locally for a subtree by setting an ARCHIVE property
4085 in the entry. If such a property is found in an entry, or anywhere up
4086 the hierarchy, it will be used."
4087 :group 'org-archive
4088 :type 'string)
4090 (defcustom org-archive-tag "ARCHIVE"
4091 "The tag that marks a subtree as archived.
4092 An archived subtree does not open during visibility cycling, and does
4093 not contribute to the agenda listings.
4094 After changing this, font-lock must be restarted in the relevant buffers to
4095 get the proper fontification."
4096 :group 'org-archive
4097 :group 'org-keywords
4098 :type 'string)
4100 (defcustom org-agenda-skip-archived-trees t
4101 "Non-nil means the agenda will skip any items located in archived trees.
4102 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4103 variable is no longer recommended, you should leave it at the value t.
4104 Instead, use the key `v' to cycle the archives-mode in the agenda."
4105 :group 'org-archive
4106 :group 'org-agenda-skip
4107 :type 'boolean)
4109 (defcustom org-columns-skip-archived-trees t
4110 "Non-nil means ignore archived trees when creating column view."
4111 :group 'org-archive
4112 :group 'org-properties
4113 :type 'boolean)
4115 (defcustom org-cycle-open-archived-trees nil
4116 "Non-nil means `org-cycle' will open archived trees.
4117 An archived tree is a tree marked with the tag ARCHIVE.
4118 When nil, archived trees will stay folded. You can still open them with
4119 normal outline commands like `show-all', but not with the cycling commands."
4120 :group 'org-archive
4121 :group 'org-cycle
4122 :type 'boolean)
4124 (defcustom org-sparse-tree-open-archived-trees nil
4125 "Non-nil means sparse tree construction shows matches in archived trees.
4126 When nil, matches in these trees are highlighted, but the trees are kept in
4127 collapsed state."
4128 :group 'org-archive
4129 :group 'org-sparse-trees
4130 :type 'boolean)
4132 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4133 "The default date type when building a sparse tree.
4134 When this is nil, a date is a scheduled or a deadline timestamp.
4135 Otherwise, these types are allowed:
4137 all: all timestamps
4138 active: only active timestamps (<...>)
4139 inactive: only inactive timestamps (<...)
4140 scheduled: only scheduled timestamps
4141 deadline: only deadline timestamps"
4142 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4143 (const :tag "All timestamps" all)
4144 (const :tag "Only active timestamps" active)
4145 (const :tag "Only inactive timestamps" inactive)
4146 (const :tag "Only scheduled timestamps" scheduled)
4147 (const :tag "Only deadline timestamps" deadline))
4148 :version "24.3"
4149 :group 'org-sparse-trees)
4151 (defun org-cycle-hide-archived-subtrees (state)
4152 "Re-hide all archived subtrees after a visibility state change."
4153 (when (and (not org-cycle-open-archived-trees)
4154 (not (memq state '(overview folded))))
4155 (save-excursion
4156 (let* ((globalp (memq state '(contents all)))
4157 (beg (if globalp (point-min) (point)))
4158 (end (if globalp (point-max) (org-end-of-subtree t))))
4159 (org-hide-archived-subtrees beg end)
4160 (goto-char beg)
4161 (if (looking-at (concat ".*:" org-archive-tag ":"))
4162 (message "%s" (substitute-command-keys
4163 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4165 (defun org-force-cycle-archived ()
4166 "Cycle subtree even if it is archived."
4167 (interactive)
4168 (setq this-command 'org-cycle)
4169 (let ((org-cycle-open-archived-trees t))
4170 (call-interactively 'org-cycle)))
4172 (defun org-hide-archived-subtrees (beg end)
4173 "Re-hide all archived subtrees after a visibility state change."
4174 (save-excursion
4175 (let* ((re (concat ":" org-archive-tag ":")))
4176 (goto-char beg)
4177 (while (re-search-forward re end t)
4178 (when (org-at-heading-p)
4179 (org-flag-subtree t)
4180 (org-end-of-subtree t))))))
4182 (declare-function outline-end-of-heading "outline" ())
4183 (declare-function outline-flag-region "outline" (from to flag))
4184 (defun org-flag-subtree (flag)
4185 (save-excursion
4186 (org-back-to-heading t)
4187 (outline-end-of-heading)
4188 (outline-flag-region (point)
4189 (progn (org-end-of-subtree t) (point))
4190 flag)))
4192 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4194 (eval-and-compile
4195 (org-autoload "org-archive"
4196 '(org-add-archive-files)))
4198 ;; Autoload Column View Code
4200 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4201 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4202 (declare-function org-columns-compute "org-colview" (property))
4204 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4205 '(org-columns-number-to-string
4206 org-columns-get-format-and-top-level
4207 org-columns-compute
4208 org-columns-remove-overlays))
4210 ;; Autoload ID code
4212 (declare-function org-id-store-link "org-id")
4213 (declare-function org-id-locations-load "org-id")
4214 (declare-function org-id-locations-save "org-id")
4215 (defvar org-id-track-globally)
4216 (org-autoload "org-id"
4217 '(org-id-new
4218 org-id-copy
4219 org-id-get-with-outline-path-completion
4220 org-id-get-with-outline-drilling))
4222 ;;; Variables for pre-computed regular expressions, all buffer local
4224 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4225 "Matches first line of a hidden block.")
4226 (make-variable-buffer-local 'org-drawer-regexp)
4227 (defvar org-todo-regexp nil
4228 "Matches any of the TODO state keywords.")
4229 (make-variable-buffer-local 'org-todo-regexp)
4230 (defvar org-not-done-regexp nil
4231 "Matches any of the TODO state keywords except the last one.")
4232 (make-variable-buffer-local 'org-not-done-regexp)
4233 (defvar org-not-done-heading-regexp nil
4234 "Matches a TODO headline that is not done.")
4235 (make-variable-buffer-local 'org-not-done-regexp)
4236 (defvar org-todo-line-regexp nil
4237 "Matches a headline and puts TODO state into group 2 if present.")
4238 (make-variable-buffer-local 'org-todo-line-regexp)
4239 (defvar org-complex-heading-regexp nil
4240 "Matches a headline and puts everything into groups:
4241 group 1: the stars
4242 group 2: The todo keyword, maybe
4243 group 3: Priority cookie
4244 group 4: True headline
4245 group 5: Tags")
4246 (make-variable-buffer-local 'org-complex-heading-regexp)
4247 (defvar org-complex-heading-regexp-format nil
4248 "Printf format to make regexp to match an exact headline.
4249 This regexp will match the headline of any node which has the
4250 exact headline text that is put into the format, but may have any
4251 TODO state, priority and tags.")
4252 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4253 (defvar org-todo-line-tags-regexp nil
4254 "Matches a headline and puts TODO state into group 2 if present.
4255 Also put tags into group 4 if tags are present.")
4256 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4257 (defvar org-ds-keyword-length 12
4258 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4259 (make-variable-buffer-local 'org-ds-keyword-length)
4260 (defvar org-deadline-regexp nil
4261 "Matches the DEADLINE keyword.")
4262 (make-variable-buffer-local 'org-deadline-regexp)
4263 (defvar org-deadline-time-regexp nil
4264 "Matches the DEADLINE keyword together with a time stamp.")
4265 (make-variable-buffer-local 'org-deadline-time-regexp)
4266 (defvar org-deadline-line-regexp nil
4267 "Matches the DEADLINE keyword and the rest of the line.")
4268 (make-variable-buffer-local 'org-deadline-line-regexp)
4269 (defvar org-scheduled-regexp nil
4270 "Matches the SCHEDULED keyword.")
4271 (make-variable-buffer-local 'org-scheduled-regexp)
4272 (defvar org-scheduled-time-regexp nil
4273 "Matches the SCHEDULED keyword together with a time stamp.")
4274 (make-variable-buffer-local 'org-scheduled-time-regexp)
4275 (defvar org-closed-time-regexp nil
4276 "Matches the CLOSED keyword together with a time stamp.")
4277 (make-variable-buffer-local 'org-closed-time-regexp)
4279 (defvar org-keyword-time-regexp nil
4280 "Matches any of the 4 keywords, together with the time stamp.")
4281 (make-variable-buffer-local 'org-keyword-time-regexp)
4282 (defvar org-keyword-time-not-clock-regexp nil
4283 "Matches any of the 3 keywords, together with the time stamp.")
4284 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4285 (defvar org-maybe-keyword-time-regexp nil
4286 "Matches a timestamp, possibly preceded by a keyword.")
4287 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4288 (defvar org-all-time-keywords nil
4289 "List of time keywords.")
4290 (make-variable-buffer-local 'org-all-time-keywords)
4292 (defconst org-plain-time-of-day-regexp
4293 (concat
4294 "\\(\\<[012]?[0-9]"
4295 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4296 "\\(--?"
4297 "\\(\\<[012]?[0-9]"
4298 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4299 "\\)?")
4300 "Regular expression to match a plain time or time range.
4301 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4302 groups carry important information:
4303 0 the full match
4304 1 the first time, range or not
4305 8 the second time, if it is a range.")
4307 (defconst org-plain-time-extension-regexp
4308 (concat
4309 "\\(\\<[012]?[0-9]"
4310 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4311 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4312 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4313 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4314 groups carry important information:
4315 0 the full match
4316 7 hours of duration
4317 9 minutes of duration")
4319 (defconst org-stamp-time-of-day-regexp
4320 (concat
4321 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4322 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4323 "\\(--?"
4324 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4325 "Regular expression to match a timestamp time or time range.
4326 After a match, the following groups carry important information:
4327 0 the full match
4328 1 date plus weekday, for back referencing to make sure both times are on the same day
4329 2 the first time, range or not
4330 4 the second time, if it is a range.")
4332 (defconst org-startup-options
4333 '(("fold" org-startup-folded t)
4334 ("overview" org-startup-folded t)
4335 ("nofold" org-startup-folded nil)
4336 ("showall" org-startup-folded nil)
4337 ("showeverything" org-startup-folded showeverything)
4338 ("content" org-startup-folded content)
4339 ("indent" org-startup-indented t)
4340 ("noindent" org-startup-indented nil)
4341 ("hidestars" org-hide-leading-stars t)
4342 ("showstars" org-hide-leading-stars nil)
4343 ("odd" org-odd-levels-only t)
4344 ("oddeven" org-odd-levels-only nil)
4345 ("align" org-startup-align-all-tables t)
4346 ("noalign" org-startup-align-all-tables nil)
4347 ("inlineimages" org-startup-with-inline-images t)
4348 ("noinlineimages" org-startup-with-inline-images nil)
4349 ("customtime" org-display-custom-times t)
4350 ("logdone" org-log-done time)
4351 ("lognotedone" org-log-done note)
4352 ("nologdone" org-log-done nil)
4353 ("lognoteclock-out" org-log-note-clock-out t)
4354 ("nolognoteclock-out" org-log-note-clock-out nil)
4355 ("logrepeat" org-log-repeat state)
4356 ("lognoterepeat" org-log-repeat note)
4357 ("nologrepeat" org-log-repeat nil)
4358 ("logreschedule" org-log-reschedule time)
4359 ("lognotereschedule" org-log-reschedule note)
4360 ("nologreschedule" org-log-reschedule nil)
4361 ("logredeadline" org-log-redeadline time)
4362 ("lognoteredeadline" org-log-redeadline note)
4363 ("nologredeadline" org-log-redeadline nil)
4364 ("logrefile" org-log-refile time)
4365 ("lognoterefile" org-log-refile note)
4366 ("nologrefile" org-log-refile nil)
4367 ("fninline" org-footnote-define-inline t)
4368 ("nofninline" org-footnote-define-inline nil)
4369 ("fnlocal" org-footnote-section nil)
4370 ("fnauto" org-footnote-auto-label t)
4371 ("fnprompt" org-footnote-auto-label nil)
4372 ("fnconfirm" org-footnote-auto-label confirm)
4373 ("fnplain" org-footnote-auto-label plain)
4374 ("fnadjust" org-footnote-auto-adjust t)
4375 ("nofnadjust" org-footnote-auto-adjust nil)
4376 ("constcgs" constants-unit-system cgs)
4377 ("constSI" constants-unit-system SI)
4378 ("noptag" org-tag-persistent-alist nil)
4379 ("hideblocks" org-hide-block-startup t)
4380 ("nohideblocks" org-hide-block-startup nil)
4381 ("beamer" org-startup-with-beamer-mode t)
4382 ("entitiespretty" org-pretty-entities t)
4383 ("entitiesplain" org-pretty-entities nil))
4384 "Variable associated with STARTUP options for org-mode.
4385 Each element is a list of three items: the startup options (as written
4386 in the #+STARTUP line), the corresponding variable, and the value to set
4387 this variable to if the option is found. An optional forth element PUSH
4388 means to push this value onto the list in the variable.")
4390 (defun org-update-property-plist (key val props)
4391 "Update PROPS with KEY and VAL."
4392 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4393 (key (if appending (substring key 0 (- (length key) 1)) key))
4394 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4395 (previous (cdr (assoc key props))))
4396 (if appending
4397 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4398 (cons (cons key val) remainder))))
4400 (defconst org-block-regexp
4401 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4402 "Regular expression for hiding blocks.")
4403 (defconst org-heading-keyword-regexp-format
4404 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4405 "Printf format for a regexp matching an headline with some keyword.
4406 This regexp will match the headline of any node which has the
4407 exact keyword that is put into the format. The keyword isn't in
4408 any group by default, but the stars and the body are.")
4409 (defconst org-heading-keyword-maybe-regexp-format
4410 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4411 "Printf format for a regexp matching an headline, possibly with some keyword.
4412 This regexp can match any headline with the specified keyword, or
4413 without a keyword. The keyword isn't in any group by default,
4414 but the stars and the body are.")
4416 (defun org-set-regexps-and-options ()
4417 "Precompute regular expressions for current buffer."
4418 (when (derived-mode-p 'org-mode)
4419 (org-set-local 'org-todo-kwd-alist nil)
4420 (org-set-local 'org-todo-key-alist nil)
4421 (org-set-local 'org-todo-key-trigger nil)
4422 (org-set-local 'org-todo-keywords-1 nil)
4423 (org-set-local 'org-done-keywords nil)
4424 (org-set-local 'org-todo-heads nil)
4425 (org-set-local 'org-todo-sets nil)
4426 (org-set-local 'org-todo-log-states nil)
4427 (org-set-local 'org-file-properties nil)
4428 (org-set-local 'org-file-tags nil)
4429 (let ((re (org-make-options-regexp
4430 '("CATEGORY" "TODO" "COLUMNS"
4431 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4432 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4433 "OPTIONS")
4434 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4435 (splitre "[ \t]+")
4436 (scripts org-use-sub-superscripts)
4437 kwds kws0 kwsa key log value cat arch tags const links hw dws
4438 tail sep kws1 prio props ftags drawers beamer-p
4439 ext-setup-or-nil setup-contents (start 0))
4440 (save-excursion
4441 (save-restriction
4442 (widen)
4443 (goto-char (point-min))
4444 (while (or (and ext-setup-or-nil
4445 (string-match re ext-setup-or-nil start)
4446 (setq start (match-end 0)))
4447 (and (setq ext-setup-or-nil nil start 0)
4448 (re-search-forward re nil t)))
4449 (setq key (upcase (match-string 1 ext-setup-or-nil))
4450 value (org-match-string-no-properties 2 ext-setup-or-nil))
4451 (if (stringp value) (setq value (org-trim value)))
4452 (cond
4453 ((equal key "CATEGORY")
4454 (setq cat value))
4455 ((member key '("SEQ_TODO" "TODO"))
4456 (push (cons 'sequence (org-split-string value splitre)) kwds))
4457 ((equal key "TYP_TODO")
4458 (push (cons 'type (org-split-string value splitre)) kwds))
4459 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4460 ;; general TODO-like setup
4461 (push (cons (intern (downcase (match-string 1 key)))
4462 (org-split-string value splitre)) kwds))
4463 ((equal key "TAGS")
4464 (setq tags (append tags (if tags '("\\n") nil)
4465 (org-split-string value splitre))))
4466 ((equal key "COLUMNS")
4467 (org-set-local 'org-columns-default-format value))
4468 ((equal key "LINK")
4469 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4470 (push (cons (match-string 1 value)
4471 (org-trim (match-string 2 value)))
4472 links)))
4473 ((equal key "PRIORITIES")
4474 (setq prio (org-split-string value " +")))
4475 ((equal key "PROPERTY")
4476 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4477 (setq props (org-update-property-plist (match-string 1 value)
4478 (match-string 2 value)
4479 props))))
4480 ((equal key "FILETAGS")
4481 (when (string-match "\\S-" value)
4482 (setq ftags
4483 (append
4484 ftags
4485 (apply 'append
4486 (mapcar (lambda (x) (org-split-string x ":"))
4487 (org-split-string value)))))))
4488 ((equal key "DRAWERS")
4489 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4490 ((equal key "CONSTANTS")
4491 (setq const (append const (org-split-string value splitre))))
4492 ((equal key "STARTUP")
4493 (let ((opts (org-split-string value splitre))
4494 l var val)
4495 (while (setq l (pop opts))
4496 (when (setq l (assoc l org-startup-options))
4497 (setq var (nth 1 l) val (nth 2 l))
4498 (if (not (nth 3 l))
4499 (set (make-local-variable var) val)
4500 (if (not (listp (symbol-value var)))
4501 (set (make-local-variable var) nil))
4502 (set (make-local-variable var) (symbol-value var))
4503 (add-to-list var val))))))
4504 ((equal key "ARCHIVE")
4505 (setq arch value)
4506 (remove-text-properties 0 (length arch)
4507 '(face t fontified t) arch))
4508 ((equal key "LATEX_CLASS")
4509 (setq beamer-p (equal value "beamer")))
4510 ((equal key "OPTIONS")
4511 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4512 (setq scripts (read (match-string 2 value)))))
4513 ((equal key "SETUPFILE")
4514 (setq setup-contents (org-file-contents
4515 (expand-file-name
4516 (org-remove-double-quotes value))
4517 'noerror))
4518 (if (not ext-setup-or-nil)
4519 (setq ext-setup-or-nil setup-contents start 0)
4520 (setq ext-setup-or-nil
4521 (concat (substring ext-setup-or-nil 0 start)
4522 "\n" setup-contents "\n"
4523 (substring ext-setup-or-nil start)))))))
4524 ;; search for property blocks
4525 (goto-char (point-min))
4526 (while (re-search-forward org-block-regexp nil t)
4527 (when (equal "PROPERTY" (upcase (match-string 1)))
4528 (setq value (replace-regexp-in-string
4529 "[\n\r]" " " (match-string 4)))
4530 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4531 (setq props (org-update-property-plist (match-string 1 value)
4532 (match-string 2 value)
4533 props)))))))
4534 (org-set-local 'org-use-sub-superscripts scripts)
4535 (when cat
4536 (org-set-local 'org-category (intern cat))
4537 (push (cons "CATEGORY" cat) props))
4538 (when prio
4539 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4540 (setq prio (mapcar 'string-to-char prio))
4541 (org-set-local 'org-highest-priority (nth 0 prio))
4542 (org-set-local 'org-lowest-priority (nth 1 prio))
4543 (org-set-local 'org-default-priority (nth 2 prio)))
4544 (and props (org-set-local 'org-file-properties (nreverse props)))
4545 (and ftags (org-set-local 'org-file-tags
4546 (mapcar 'org-add-prop-inherited ftags)))
4547 (and drawers (org-set-local 'org-drawers drawers))
4548 (and arch (org-set-local 'org-archive-location arch))
4549 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4550 ;; Process the TODO keywords
4551 (unless kwds
4552 ;; Use the global values as if they had been given locally.
4553 (setq kwds (default-value 'org-todo-keywords))
4554 (if (stringp (car kwds))
4555 (setq kwds (list (cons org-todo-interpretation
4556 (default-value 'org-todo-keywords)))))
4557 (setq kwds (reverse kwds)))
4558 (setq kwds (nreverse kwds))
4559 (let (inter kws kw)
4560 (while (setq kws (pop kwds))
4561 (let ((kws (or
4562 (run-hook-with-args-until-success
4563 'org-todo-setup-filter-hook kws)
4564 kws)))
4565 (setq inter (pop kws) sep (member "|" kws)
4566 kws0 (delete "|" (copy-sequence kws))
4567 kwsa nil
4568 kws1 (mapcar
4569 (lambda (x)
4570 ;; 1 2
4571 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4572 (progn
4573 (setq kw (match-string 1 x)
4574 key (and (match-end 2) (match-string 2 x))
4575 log (org-extract-log-state-settings x))
4576 (push (cons kw (and key (string-to-char key))) kwsa)
4577 (and log (push log org-todo-log-states))
4579 (error "Invalid TODO keyword %s" x)))
4580 kws0)
4581 kwsa (if kwsa (append '((:startgroup))
4582 (nreverse kwsa)
4583 '((:endgroup))))
4584 hw (car kws1)
4585 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4586 tail (list inter hw (car dws) (org-last dws))))
4587 (add-to-list 'org-todo-heads hw 'append)
4588 (push kws1 org-todo-sets)
4589 (setq org-done-keywords (append org-done-keywords dws nil))
4590 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4591 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4592 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4593 (setq org-todo-sets (nreverse org-todo-sets)
4594 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4595 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4596 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4597 ;; Process the constants
4598 (when const
4599 (let (e cst)
4600 (while (setq e (pop const))
4601 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4602 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4603 (setq org-table-formula-constants-local cst)))
4605 ;; Process the tags.
4606 (when tags
4607 (let (e tgs)
4608 (while (setq e (pop tags))
4609 (cond
4610 ((equal e "{") (push '(:startgroup) tgs))
4611 ((equal e "}") (push '(:endgroup) tgs))
4612 ((equal e "\\n") (push '(:newline) tgs))
4613 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4614 (push (cons (match-string 1 e)
4615 (string-to-char (match-string 2 e)))
4616 tgs))
4617 (t (push (list e) tgs))))
4618 (org-set-local 'org-tag-alist nil)
4619 (while (setq e (pop tgs))
4620 (or (and (stringp (car e))
4621 (assoc (car e) org-tag-alist))
4622 (push e org-tag-alist)))))
4624 ;; Compute the regular expressions and other local variables.
4625 ;; Using `org-outline-regexp-bol' would complicate them much,
4626 ;; because of the fixed white space at the end of that string.
4627 (if (not org-done-keywords)
4628 (setq org-done-keywords (and org-todo-keywords-1
4629 (list (org-last org-todo-keywords-1)))))
4630 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4631 (length org-scheduled-string)
4632 (length org-clock-string)
4633 (length org-closed-string)))
4634 org-drawer-regexp
4635 (concat "^[ \t]*:\\("
4636 (mapconcat 'regexp-quote org-drawers "\\|")
4637 "\\):[ \t]*$")
4638 org-not-done-keywords
4639 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4640 org-todo-regexp
4641 (concat "\\("
4642 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4643 "\\)")
4644 org-not-done-regexp
4645 (concat "\\("
4646 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4647 "\\)")
4648 org-not-done-heading-regexp
4649 (format org-heading-keyword-regexp-format org-not-done-regexp)
4650 org-todo-line-regexp
4651 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4652 org-complex-heading-regexp
4653 (concat "^\\(\\*+\\)"
4654 "\\(?: +" org-todo-regexp "\\)?"
4655 "\\(?: +\\(\\[#.\\]\\)\\)?"
4656 "\\(?: +\\(.*?\\)\\)??"
4657 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4658 "[ \t]*$")
4659 org-complex-heading-regexp-format
4660 (concat "^\\(\\*+\\)"
4661 "\\(?: +" org-todo-regexp "\\)?"
4662 "\\(?: +\\(\\[#.\\]\\)\\)?"
4663 "\\(?: +"
4664 ;; Stats cookies can be stuck to body.
4665 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4666 "\\(%s\\)"
4667 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4668 "\\)"
4669 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4670 "[ \t]*$")
4671 org-todo-line-tags-regexp
4672 (concat "^\\(\\*+\\)"
4673 "\\(?: +" org-todo-regexp "\\)?"
4674 "\\(?: +\\(.*?\\)\\)??"
4675 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4676 "[ \t]*$")
4677 org-deadline-regexp (concat "\\<" org-deadline-string)
4678 org-deadline-time-regexp
4679 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4680 org-deadline-line-regexp
4681 (concat "\\<\\(" org-deadline-string "\\).*")
4682 org-scheduled-regexp
4683 (concat "\\<" org-scheduled-string)
4684 org-scheduled-time-regexp
4685 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4686 org-closed-time-regexp
4687 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4688 org-keyword-time-regexp
4689 (concat "\\<\\(" org-scheduled-string
4690 "\\|" org-deadline-string
4691 "\\|" org-closed-string
4692 "\\|" org-clock-string "\\)"
4693 " *[[<]\\([^]>]+\\)[]>]")
4694 org-keyword-time-not-clock-regexp
4695 (concat "\\<\\(" org-scheduled-string
4696 "\\|" org-deadline-string
4697 "\\|" org-closed-string
4698 "\\)"
4699 " *[[<]\\([^]>]+\\)[]>]")
4700 org-maybe-keyword-time-regexp
4701 (concat "\\(\\<\\(" org-scheduled-string
4702 "\\|" org-deadline-string
4703 "\\|" org-closed-string
4704 "\\|" org-clock-string "\\)\\)?"
4705 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4706 org-all-time-keywords
4707 (mapcar (lambda (w) (substring w 0 -1))
4708 (list org-scheduled-string org-deadline-string
4709 org-clock-string org-closed-string))
4711 (org-compute-latex-and-specials-regexp)
4712 (org-set-font-lock-defaults))))
4714 (defun org-file-contents (file &optional noerror)
4715 "Return the contents of FILE, as a string."
4716 (if (or (not file)
4717 (not (file-readable-p file)))
4718 (if noerror
4719 (progn
4720 (message "Cannot read file \"%s\"" file)
4721 (ding) (sit-for 2)
4723 (error "Cannot read file \"%s\"" file))
4724 (with-temp-buffer
4725 (insert-file-contents file)
4726 (buffer-string))))
4728 (defun org-extract-log-state-settings (x)
4729 "Extract the log state setting from a TODO keyword string.
4730 This will extract info from a string like \"WAIT(w@/!)\"."
4731 (let (kw key log1 log2)
4732 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4733 (setq kw (match-string 1 x)
4734 key (and (match-end 2) (match-string 2 x))
4735 log1 (and (match-end 3) (match-string 3 x))
4736 log2 (and (match-end 4) (match-string 4 x)))
4737 (and (or log1 log2)
4738 (list kw
4739 (and log1 (if (equal log1 "!") 'time 'note))
4740 (and log2 (if (equal log2 "!") 'time 'note)))))))
4742 (defun org-remove-keyword-keys (list)
4743 "Remove a pair of parenthesis at the end of each string in LIST."
4744 (mapcar (lambda (x)
4745 (if (string-match "(.*)$" x)
4746 (substring x 0 (match-beginning 0))
4748 list))
4750 (defun org-assign-fast-keys (alist)
4751 "Assign fast keys to a keyword-key alist.
4752 Respect keys that are already there."
4753 (let (new e (alt ?0))
4754 (while (setq e (pop alist))
4755 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4756 (cdr e)) ;; Key already assigned.
4757 (push e new)
4758 (let ((clist (string-to-list (downcase (car e))))
4759 (used (append new alist)))
4760 (when (= (car clist) ?@)
4761 (pop clist))
4762 (while (and clist (rassoc (car clist) used))
4763 (pop clist))
4764 (unless clist
4765 (while (rassoc alt used)
4766 (incf alt)))
4767 (push (cons (car e) (or (car clist) alt)) new))))
4768 (nreverse new)))
4770 ;;; Some variables used in various places
4772 (defvar org-window-configuration nil
4773 "Used in various places to store a window configuration.")
4774 (defvar org-selected-window nil
4775 "Used in various places to store a window configuration.")
4776 (defvar org-finish-function nil
4777 "Function to be called when `C-c C-c' is used.
4778 This is for getting out of special buffers like capture.")
4781 ;; FIXME: Occasionally check by commenting these, to make sure
4782 ;; no other functions uses these, forgetting to let-bind them.
4783 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4784 (defvar org-last-state)
4785 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4787 ;; Defined somewhere in this file, but used before definition.
4788 (defvar org-entities) ;; defined in org-entities.el
4789 (defvar org-struct-menu)
4790 (defvar org-org-menu)
4791 (defvar org-tbl-menu)
4793 ;;;; Define the Org-mode
4795 ;; We use a before-change function to check if a table might need
4796 ;; an update.
4797 (defvar org-table-may-need-update t
4798 "Indicates that a table might need an update.
4799 This variable is set by `org-before-change-function'.
4800 `org-table-align' sets it back to nil.")
4801 (defun org-before-change-function (beg end)
4802 "Every change indicates that a table might need an update."
4803 (setq org-table-may-need-update t))
4804 (defvar org-mode-map)
4805 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4806 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4807 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4808 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4809 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4810 (defvar org-table-buffer-is-an nil)
4812 (defvar bidi-paragraph-direction)
4813 (defvar buffer-face-mode-face)
4815 (require 'outline)
4816 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4817 (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"))
4818 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4820 ;; Other stuff we need.
4821 (require 'time-date)
4822 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4823 (require 'easymenu)
4824 (require 'overlay)
4826 (require 'org-macs)
4827 (require 'org-entities)
4828 ;; (require 'org-compat) moved higher up in the file before it is first used
4829 (require 'org-faces)
4830 (require 'org-list)
4831 (require 'org-pcomplete)
4832 (require 'org-src)
4833 (require 'org-footnote)
4835 ;; babel
4836 (require 'ob)
4837 (require 'ob-table)
4838 (require 'ob-lob)
4839 (require 'ob-ref)
4840 (require 'ob-tangle)
4841 (require 'ob-comint)
4842 (require 'ob-keys)
4844 ;;;###autoload
4845 (define-derived-mode org-mode outline-mode "Org"
4846 "Outline-based notes management and organizer, alias
4847 \"Carsten's outline-mode for keeping track of everything.\"
4849 Org-mode develops organizational tasks around a NOTES file which
4850 contains information about projects as plain text. Org-mode is
4851 implemented on top of outline-mode, which is ideal to keep the content
4852 of large files well structured. It supports ToDo items, deadlines and
4853 time stamps, which magically appear in the diary listing of the Emacs
4854 calendar. Tables are easily created with a built-in table editor.
4855 Plain text URL-like links connect to websites, emails (VM), Usenet
4856 messages (Gnus), BBDB entries, and any files related to the project.
4857 For printing and sharing of notes, an Org-mode file (or a part of it)
4858 can be exported as a structured ASCII or HTML file.
4860 The following commands are available:
4862 \\{org-mode-map}"
4864 ;; Get rid of Outline menus, they are not needed
4865 ;; Need to do this here because define-derived-mode sets up
4866 ;; the keymap so late. Still, it is a waste to call this each time
4867 ;; we switch another buffer into org-mode.
4868 (if (featurep 'xemacs)
4869 (when (boundp 'outline-mode-menu-heading)
4870 ;; Assume this is Greg's port, it uses easymenu
4871 (easy-menu-remove outline-mode-menu-heading)
4872 (easy-menu-remove outline-mode-menu-show)
4873 (easy-menu-remove outline-mode-menu-hide))
4874 (define-key org-mode-map [menu-bar headings] 'undefined)
4875 (define-key org-mode-map [menu-bar hide] 'undefined)
4876 (define-key org-mode-map [menu-bar show] 'undefined))
4878 (org-load-modules-maybe)
4879 (easy-menu-add org-org-menu)
4880 (easy-menu-add org-tbl-menu)
4881 (org-install-agenda-files-menu)
4882 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4883 (add-to-invisibility-spec '(org-cwidth))
4884 (add-to-invisibility-spec '(org-hide-block . t))
4885 (when (featurep 'xemacs)
4886 (org-set-local 'line-move-ignore-invisible t))
4887 (org-set-local 'outline-regexp org-outline-regexp)
4888 (org-set-local 'outline-level 'org-outline-level)
4889 (setq bidi-paragraph-direction 'left-to-right)
4890 (when (and org-ellipsis
4891 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4892 (fboundp 'make-glyph-code))
4893 (unless org-display-table
4894 (setq org-display-table (make-display-table)))
4895 (set-display-table-slot
4896 org-display-table 4
4897 (vconcat (mapcar
4898 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4899 org-ellipsis)))
4900 (if (stringp org-ellipsis) org-ellipsis "..."))))
4901 (setq buffer-display-table org-display-table))
4902 (org-set-regexps-and-options)
4903 (when (and org-tag-faces (not org-tags-special-faces-re))
4904 ;; tag faces set outside customize.... force initialization.
4905 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4906 ;; Calc embedded
4907 (org-set-local 'calc-embedded-open-mode "# ")
4908 (modify-syntax-entry ?@ "w")
4909 (if org-startup-truncated (setq truncate-lines t))
4910 (org-set-local 'font-lock-unfontify-region-function
4911 'org-unfontify-region)
4912 ;; Activate before-change-function
4913 (org-set-local 'org-table-may-need-update t)
4914 (org-add-hook 'before-change-functions 'org-before-change-function nil
4915 'local)
4916 ;; Check for running clock before killing a buffer
4917 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4918 ;; Indentation.
4919 (org-set-local 'indent-line-function 'org-indent-line)
4920 (org-set-local 'indent-region-function 'org-indent-region)
4921 ;; Initialize radio targets.
4922 (org-update-radio-target-regexp)
4923 ;; Filling and auto-filling.
4924 (org-setup-filling)
4925 ;; Comments.
4926 (org-setup-comments-handling)
4927 ;; Beginning/end of defun
4928 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4929 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4930 ;; Next error for sparse trees
4931 (org-set-local 'next-error-function 'org-occur-next-match)
4932 ;; Make sure dependence stuff works reliably, even for users who set it
4933 ;; too late :-(
4934 (if org-enforce-todo-dependencies
4935 (add-hook 'org-blocker-hook
4936 'org-block-todo-from-children-or-siblings-or-parent)
4937 (remove-hook 'org-blocker-hook
4938 'org-block-todo-from-children-or-siblings-or-parent))
4939 (if org-enforce-todo-checkbox-dependencies
4940 (add-hook 'org-blocker-hook
4941 'org-block-todo-from-checkboxes)
4942 (remove-hook 'org-blocker-hook
4943 'org-block-todo-from-checkboxes))
4945 ;; Align options lines
4946 (org-set-local
4947 'align-mode-rules-list
4948 '((org-in-buffer-settings
4949 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4950 (modes . '(org-mode)))))
4952 ;; Imenu
4953 (org-set-local 'imenu-create-index-function
4954 'org-imenu-get-tree)
4956 ;; Make isearch reveal context
4957 (if (or (featurep 'xemacs)
4958 (not (boundp 'outline-isearch-open-invisible-function)))
4959 ;; Emacs 21 and XEmacs make use of the hook
4960 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4961 ;; Emacs 22 deals with this through a special variable
4962 (org-set-local 'outline-isearch-open-invisible-function
4963 (lambda (&rest ignore) (org-show-context 'isearch))))
4965 ;; Turn on org-beamer-mode?
4966 (and org-startup-with-beamer-mode (org-beamer-mode))
4968 ;; Setup the pcomplete hooks
4969 (set (make-local-variable 'pcomplete-command-completion-function)
4970 'org-pcomplete-initial)
4971 (set (make-local-variable 'pcomplete-command-name-function)
4972 'org-command-at-point)
4973 (set (make-local-variable 'pcomplete-default-completion-function)
4974 'ignore)
4975 (set (make-local-variable 'pcomplete-parse-arguments-function)
4976 'org-parse-arguments)
4977 (set (make-local-variable 'pcomplete-termination-string) "")
4978 (when (>= emacs-major-version 23)
4979 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4981 ;; If empty file that did not turn on org-mode automatically, make it to.
4982 (if (and org-insert-mode-line-in-empty-file
4983 (org-called-interactively-p 'any)
4984 (= (point-min) (point-max)))
4985 (insert "# -*- mode: org -*-\n\n"))
4986 (unless org-inhibit-startup
4987 (when org-startup-align-all-tables
4988 (let ((bmp (buffer-modified-p)))
4989 (org-table-map-tables 'org-table-align 'quietly)
4990 (set-buffer-modified-p bmp)))
4991 (when org-startup-with-inline-images
4992 (org-display-inline-images))
4993 (when org-startup-indented
4994 (require 'org-indent)
4995 (org-indent-mode 1))
4996 (unless org-inhibit-startup-visibility-stuff
4997 (org-set-startup-visibility)))
4998 ;; Try to set org-hide correctly
4999 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5001 (when (fboundp 'abbrev-table-put)
5002 (abbrev-table-put org-mode-abbrev-table
5003 :parents (list text-mode-abbrev-table)))
5005 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5008 (defun org-find-invisible-foreground ()
5009 (let ((candidates (remove
5010 "unspecified-bg"
5011 (nconc
5012 (list (face-background 'default)
5013 (face-background 'org-default))
5014 (mapcar
5015 (lambda (alist)
5016 (when (boundp alist)
5017 (cdr (assoc 'background-color (symbol-value alist)))))
5018 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5019 (list (face-foreground 'org-hide))))))
5020 (car (remove nil candidates))))
5022 (defun org-current-time ()
5023 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5024 (if (> (car org-time-stamp-rounding-minutes) 1)
5025 (let ((r (car org-time-stamp-rounding-minutes))
5026 (time (decode-time)))
5027 (apply 'encode-time
5028 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5029 (nthcdr 2 time))))
5030 (current-time)))
5032 (defun org-today ()
5033 "Return today date, considering `org-extend-today-until'."
5034 (time-to-days
5035 (time-subtract (current-time)
5036 (list 0 (* 3600 org-extend-today-until) 0))))
5038 ;;;; Font-Lock stuff, including the activators
5040 (defvar org-mouse-map (make-sparse-keymap))
5041 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5042 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5043 (when org-mouse-1-follows-link
5044 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5045 (when org-tab-follows-link
5046 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5047 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5049 (require 'font-lock)
5051 (defconst org-non-link-chars "]\t\n\r<>")
5052 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5053 "shell" "elisp" "doi" "message"))
5054 (defvar org-link-types-re nil
5055 "Matches a link that has a url-like prefix like \"http:\"")
5056 (defvar org-link-re-with-space nil
5057 "Matches a link with spaces, optional angular brackets around it.")
5058 (defvar org-link-re-with-space2 nil
5059 "Matches a link with spaces, optional angular brackets around it.")
5060 (defvar org-link-re-with-space3 nil
5061 "Matches a link with spaces, only for internal part in bracket links.")
5062 (defvar org-angle-link-re nil
5063 "Matches link with angular brackets, spaces are allowed.")
5064 (defvar org-plain-link-re nil
5065 "Matches plain link, without spaces.")
5066 (defvar org-bracket-link-regexp nil
5067 "Matches a link in double brackets.")
5068 (defvar org-bracket-link-analytic-regexp nil
5069 "Regular expression used to analyze links.
5070 Here is what the match groups contain after a match:
5071 1: http:
5072 2: http
5073 3: path
5074 4: [desc]
5075 5: desc")
5076 (defvar org-bracket-link-analytic-regexp++ nil
5077 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5078 (defvar org-any-link-re nil
5079 "Regular expression matching any link.")
5081 (defcustom org-match-sexp-depth 3
5082 "Number of stacked braces for sub/superscript matching.
5083 This has to be set before loading org.el to be effective."
5084 :group 'org-export-translation ; ??????????????????????????/
5085 :type 'integer)
5087 (defun org-create-multibrace-regexp (left right n)
5088 "Create a regular expression which will match a balanced sexp.
5089 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5090 as single character strings.
5091 The regexp returned will match the entire expression including the
5092 delimiters. It will also define a single group which contains the
5093 match except for the outermost delimiters. The maximum depth of
5094 stacked delimiters is N. Escaping delimiters is not possible."
5095 (let* ((nothing (concat "[^" left right "]*?"))
5096 (or "\\|")
5097 (re nothing)
5098 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5099 (while (> n 1)
5100 (setq n (1- n)
5101 re (concat re or next)
5102 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5103 (concat left "\\(" re "\\)" right)))
5105 (defvar org-match-substring-regexp
5106 (concat
5107 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5108 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5109 "\\|"
5110 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5111 "\\|"
5112 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5113 "The regular expression matching a sub- or superscript.")
5115 (defvar org-match-substring-with-braces-regexp
5116 (concat
5117 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5118 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5119 "\\)")
5120 "The regular expression matching a sub- or superscript, forcing braces.")
5122 (defun org-make-link-regexps ()
5123 "Update the link regular expressions.
5124 This should be called after the variable `org-link-types' has changed."
5125 (setq org-link-types-re
5126 (concat
5127 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5128 org-link-re-with-space
5129 (concat
5130 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5131 "\\([^" org-non-link-chars " ]"
5132 "[^" org-non-link-chars "]*"
5133 "[^" org-non-link-chars " ]\\)>?")
5134 org-link-re-with-space2
5135 (concat
5136 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5137 "\\([^" org-non-link-chars " ]"
5138 "[^\t\n\r]*"
5139 "[^" org-non-link-chars " ]\\)>?")
5140 org-link-re-with-space3
5141 (concat
5142 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5143 "\\([^" org-non-link-chars " ]"
5144 "[^\t\n\r]*\\)")
5145 org-angle-link-re
5146 (concat
5147 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5148 "\\([^" org-non-link-chars " ]"
5149 "[^" org-non-link-chars "]*"
5150 "\\)>")
5151 org-plain-link-re
5152 (concat
5153 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5154 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5155 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5156 org-bracket-link-regexp
5157 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5158 org-bracket-link-analytic-regexp
5159 (concat
5160 "\\[\\["
5161 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5162 "\\([^]]+\\)"
5163 "\\]"
5164 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5165 "\\]")
5166 org-bracket-link-analytic-regexp++
5167 (concat
5168 "\\[\\["
5169 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5170 "\\([^]]+\\)"
5171 "\\]"
5172 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5173 "\\]")
5174 org-any-link-re
5175 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5176 org-angle-link-re "\\)\\|\\("
5177 org-plain-link-re "\\)")))
5179 (org-make-link-regexps)
5181 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5182 "Regular expression for fast time stamp matching.")
5183 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5184 "Regular expression for fast time stamp matching.")
5185 (defconst org-ts-regexp0
5186 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5187 "Regular expression matching time strings for analysis.
5188 This one does not require the space after the date, so it can be used
5189 on a string that terminates immediately after the date.")
5190 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5191 "Regular expression matching time strings for analysis.")
5192 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5193 "Regular expression matching time stamps, with groups.")
5194 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5195 "Regular expression matching time stamps (also [..]), with groups.")
5196 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5197 "Regular expression matching a time stamp range.")
5198 (defconst org-tr-regexp-both
5199 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5200 "Regular expression matching a time stamp range.")
5201 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5202 org-ts-regexp "\\)?")
5203 "Regular expression matching a time stamp or time stamp range.")
5204 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5205 org-ts-regexp-both "\\)?")
5206 "Regular expression matching a time stamp or time stamp range.
5207 The time stamps may be either active or inactive.")
5209 (defvar org-emph-face nil)
5211 (defun org-do-emphasis-faces (limit)
5212 "Run through the buffer and add overlays to emphasized strings."
5213 (let (rtn a)
5214 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5215 (if (not (= (char-after (match-beginning 3))
5216 (char-after (match-beginning 4))))
5217 (progn
5218 (setq rtn t)
5219 (setq a (assoc (match-string 3) org-emphasis-alist))
5220 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5221 'face
5222 (nth 1 a))
5223 (and (nth 4 a)
5224 (org-remove-flyspell-overlays-in
5225 (match-beginning 0) (match-end 0)))
5226 (add-text-properties (match-beginning 2) (match-end 2)
5227 '(font-lock-multiline t org-emphasis t))
5228 (when org-hide-emphasis-markers
5229 (add-text-properties (match-end 4) (match-beginning 5)
5230 '(invisible org-link))
5231 (add-text-properties (match-beginning 3) (match-end 3)
5232 '(invisible org-link)))))
5233 (backward-char 1))
5234 rtn))
5236 (defun org-emphasize (&optional char)
5237 "Insert or change an emphasis, i.e. a font like bold or italic.
5238 If there is an active region, change that region to a new emphasis.
5239 If there is no region, just insert the marker characters and position
5240 the cursor between them.
5241 CHAR should be either the marker character, or the first character of the
5242 HTML tag associated with that emphasis. If CHAR is a space, the means
5243 to remove the emphasis of the selected region.
5244 If char is not given (for example in an interactive call) it
5245 will be prompted for."
5246 (interactive)
5247 (let ((eal org-emphasis-alist) e det
5248 (erc org-emphasis-regexp-components)
5249 (prompt "")
5250 (string "") beg end move tag c s)
5251 (if (org-region-active-p)
5252 (setq beg (region-beginning) end (region-end)
5253 string (buffer-substring beg end))
5254 (setq move t))
5256 (while (setq e (pop eal))
5257 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5258 c (aref tag 0))
5259 (push (cons c (string-to-char (car e))) det)
5260 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5261 (substring tag 1)))))
5262 (setq det (nreverse det))
5263 (unless char
5264 (message "%s" (concat "Emphasis marker or tag:" prompt))
5265 (setq char (read-char-exclusive)))
5266 (setq char (or (cdr (assoc char det)) char))
5267 (if (equal char ?\ )
5268 (setq s "" move nil)
5269 (unless (assoc (char-to-string char) org-emphasis-alist)
5270 (error "No such emphasis marker: \"%c\"" char))
5271 (setq s (char-to-string char)))
5272 (while (and (> (length string) 1)
5273 (equal (substring string 0 1) (substring string -1))
5274 (assoc (substring string 0 1) org-emphasis-alist))
5275 (setq string (substring string 1 -1)))
5276 (setq string (concat s string s))
5277 (if beg (delete-region beg end))
5278 (unless (or (bolp)
5279 (string-match (concat "[" (nth 0 erc) "\n]")
5280 (char-to-string (char-before (point)))))
5281 (insert " "))
5282 (unless (or (eobp)
5283 (string-match (concat "[" (nth 1 erc) "\n]")
5284 (char-to-string (char-after (point)))))
5285 (insert " ") (backward-char 1))
5286 (insert string)
5287 (and move (backward-char 1))))
5289 (defconst org-nonsticky-props
5290 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5292 (defsubst org-rear-nonsticky-at (pos)
5293 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5295 (defun org-activate-plain-links (limit)
5296 "Run through the buffer and add overlays to links."
5297 (catch 'exit
5298 (let (f)
5299 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5300 (not (org-in-src-block-p)))
5301 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5302 (setq f (get-text-property (match-beginning 0) 'face))
5303 (unless (or (org-in-src-block-p)
5304 (eq f 'org-tag)
5305 (and (listp f) (memq 'org-tag f)))
5306 (add-text-properties (match-beginning 0) (match-end 0)
5307 (list 'mouse-face 'highlight
5308 'face 'org-link
5309 'keymap org-mouse-map))
5310 (org-rear-nonsticky-at (match-end 0)))
5311 t))))
5313 (defun org-activate-code (limit)
5314 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5315 (progn
5316 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5317 (remove-text-properties (match-beginning 0) (match-end 0)
5318 '(display t invisible t intangible t))
5319 t)))
5321 (defcustom org-src-fontify-natively nil
5322 "When non-nil, fontify code in code blocks."
5323 :type 'boolean
5324 :version "24.1"
5325 :group 'org-appearance
5326 :group 'org-babel)
5328 (defcustom org-allow-promoting-top-level-subtree nil
5329 "When non-nil, allow promoting a top level subtree.
5330 The leading star of the top level headline will be replaced
5331 by a #."
5332 :type 'boolean
5333 :version "24.1"
5334 :group 'org-appearance)
5336 (defun org-fontify-meta-lines-and-blocks (limit)
5337 (condition-case nil
5338 (org-fontify-meta-lines-and-blocks-1 limit)
5339 (error (message "org-mode fontification error"))))
5341 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5342 "Fontify #+ lines and blocks, in the correct ways."
5343 (let ((case-fold-search t))
5344 (if (re-search-forward
5345 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5346 limit t)
5347 (let ((beg (match-beginning 0))
5348 (block-start (match-end 0))
5349 (block-end nil)
5350 (lang (match-string 7))
5351 (beg1 (line-beginning-position 2))
5352 (dc1 (downcase (match-string 2)))
5353 (dc3 (downcase (match-string 3)))
5354 end end1 quoting block-type ovl)
5355 (cond
5356 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5357 ;; a single line of backend-specific content
5358 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5359 (remove-text-properties (match-beginning 0) (match-end 0)
5360 '(display t invisible t intangible t))
5361 (add-text-properties (match-beginning 1) (match-end 3)
5362 '(font-lock-fontified t face org-meta-line))
5363 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5364 '(font-lock-fontified t face org-block))
5365 ; for backend-specific code
5367 ((and (match-end 4) (equal dc3 "+begin"))
5368 ;; Truly a block
5369 (setq block-type (downcase (match-string 5))
5370 quoting (member block-type org-protecting-blocks))
5371 (when (re-search-forward
5372 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5373 nil t) ;; on purpose, we look further than LIMIT
5374 (setq end (min (point-max) (match-end 0))
5375 end1 (min (point-max) (1- (match-beginning 0))))
5376 (setq block-end (match-beginning 0))
5377 (when quoting
5378 (remove-text-properties beg end
5379 '(display t invisible t intangible t)))
5380 (add-text-properties
5381 beg end
5382 '(font-lock-fontified t font-lock-multiline t))
5383 (add-text-properties beg beg1 '(face org-meta-line))
5384 (add-text-properties end1 (min (point-max) (1+ end))
5385 '(face org-meta-line)) ; for end_src
5386 (cond
5387 ((and lang (not (string= lang "")) org-src-fontify-natively)
5388 (org-src-font-lock-fontify-block lang block-start block-end)
5389 ;; remove old background overlays
5390 (mapc (lambda (ov)
5391 (if (eq (overlay-get ov 'face) 'org-block-background)
5392 (delete-overlay ov)))
5393 (overlays-at (/ (+ beg1 block-end) 2)))
5394 ;; add a background overlay
5395 (setq ovl (make-overlay beg1 block-end))
5396 (overlay-put ovl 'face 'org-block-background)
5397 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5398 (quoting
5399 (add-text-properties beg1 (min (point-max) (1+ end1))
5400 '(face org-block))) ; end of source block
5401 ((not org-fontify-quote-and-verse-blocks))
5402 ((string= block-type "quote")
5403 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5404 ((string= block-type "verse")
5405 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5406 (add-text-properties beg beg1 '(face org-block-begin-line))
5407 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5408 '(face org-block-end-line))
5410 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5411 (add-text-properties
5412 beg (match-end 3)
5413 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5414 '(font-lock-fontified t invisible t)
5415 '(font-lock-fontified t face org-document-info-keyword)))
5416 (add-text-properties
5417 (match-beginning 6) (match-end 6)
5418 (if (string-equal dc1 "+title:")
5419 '(font-lock-fontified t face org-document-title)
5420 '(font-lock-fontified t face org-document-info))))
5421 ((or (equal dc1 "+results")
5422 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5423 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5424 "+call:" "+header:" "+headers:" "+name:"))
5425 (and (match-end 4) (equal dc3 "+attr")))
5426 (add-text-properties
5427 beg (match-end 0)
5428 '(font-lock-fontified t face org-meta-line))
5430 ((member dc3 '(" " ""))
5431 (add-text-properties
5432 beg (match-end 0)
5433 '(font-lock-fontified t face font-lock-comment-face)))
5434 ((not (member (char-after beg) '(?\ ?\t)))
5435 ;; just any other in-buffer setting, but not indented
5436 (add-text-properties
5437 beg (match-end 0)
5438 '(font-lock-fontified t face org-meta-line))
5440 (t nil))))))
5442 (defun org-activate-angle-links (limit)
5443 "Run through the buffer and add overlays to links."
5444 (if (and (re-search-forward org-angle-link-re limit t)
5445 (not (org-in-src-block-p)))
5446 (progn
5447 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5448 (add-text-properties (match-beginning 0) (match-end 0)
5449 (list 'mouse-face 'highlight
5450 'keymap org-mouse-map))
5451 (org-rear-nonsticky-at (match-end 0))
5452 t)))
5454 (defun org-activate-footnote-links (limit)
5455 "Run through the buffer and add overlays to footnotes."
5456 (let ((fn (org-footnote-next-reference-or-definition limit)))
5457 (when fn
5458 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5459 (org-remove-flyspell-overlays-in beg end)
5460 (add-text-properties beg end
5461 (list 'mouse-face 'highlight
5462 'keymap org-mouse-map
5463 'help-echo
5464 (if (= (point-at-bol) beg)
5465 "Footnote definition"
5466 "Footnote reference")
5467 'font-lock-fontified t
5468 'font-lock-multiline t
5469 'face 'org-footnote))))))
5471 (defun org-activate-bracket-links (limit)
5472 "Run through the buffer and add overlays to bracketed links."
5473 (if (and (re-search-forward org-bracket-link-regexp limit t)
5474 (not (org-in-src-block-p)))
5475 (let* ((help (concat "LINK: "
5476 (org-match-string-no-properties 1)))
5477 ;; FIXME: above we should remove the escapes.
5478 ;; but that requires another match, protecting match data,
5479 ;; a lot of overhead for font-lock.
5480 (ip (org-maybe-intangible
5481 (list 'invisible 'org-link
5482 'keymap org-mouse-map 'mouse-face 'highlight
5483 'font-lock-multiline t 'help-echo help)))
5484 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5485 'font-lock-multiline t 'help-echo help)))
5486 ;; We need to remove the invisible property here. Table narrowing
5487 ;; may have made some of this invisible.
5488 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5489 (remove-text-properties (match-beginning 0) (match-end 0)
5490 '(invisible nil))
5491 (if (match-end 3)
5492 (progn
5493 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5494 (org-rear-nonsticky-at (match-beginning 3))
5495 (add-text-properties (match-beginning 3) (match-end 3) vp)
5496 (org-rear-nonsticky-at (match-end 3))
5497 (add-text-properties (match-end 3) (match-end 0) ip)
5498 (org-rear-nonsticky-at (match-end 0)))
5499 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5500 (org-rear-nonsticky-at (match-beginning 1))
5501 (add-text-properties (match-beginning 1) (match-end 1) vp)
5502 (org-rear-nonsticky-at (match-end 1))
5503 (add-text-properties (match-end 1) (match-end 0) ip)
5504 (org-rear-nonsticky-at (match-end 0)))
5505 t)))
5507 (defun org-activate-dates (limit)
5508 "Run through the buffer and add overlays to dates."
5509 (if (re-search-forward org-tsr-regexp-both limit t)
5510 (progn
5511 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5512 (add-text-properties (match-beginning 0) (match-end 0)
5513 (list 'mouse-face 'highlight
5514 'keymap org-mouse-map))
5515 (org-rear-nonsticky-at (match-end 0))
5516 (when org-display-custom-times
5517 (if (match-end 3)
5518 (org-display-custom-time (match-beginning 3) (match-end 3)))
5519 (org-display-custom-time (match-beginning 1) (match-end 1)))
5520 t)))
5522 (defvar org-target-link-regexp nil
5523 "Regular expression matching radio targets in plain text.")
5524 (make-variable-buffer-local 'org-target-link-regexp)
5525 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5526 "Regular expression matching a link target.")
5527 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5528 "Regular expression matching a radio target.")
5529 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5530 "Regular expression matching any target.")
5532 (defun org-activate-target-links (limit)
5533 "Run through the buffer and add overlays to target matches."
5534 (when org-target-link-regexp
5535 (let ((case-fold-search t))
5536 (if (re-search-forward org-target-link-regexp limit t)
5537 (progn
5538 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5539 (add-text-properties (match-beginning 0) (match-end 0)
5540 (list 'mouse-face 'highlight
5541 'keymap org-mouse-map
5542 'help-echo "Radio target link"
5543 'org-linked-text t))
5544 (org-rear-nonsticky-at (match-end 0))
5545 t)))))
5547 (defun org-update-radio-target-regexp ()
5548 "Find all radio targets in this file and update the regular expression."
5549 (interactive)
5550 (when (memq 'radio org-activate-links)
5551 (setq org-target-link-regexp
5552 (org-make-target-link-regexp (org-all-targets 'radio)))
5553 (org-restart-font-lock)))
5555 (defun org-hide-wide-columns (limit)
5556 (let (s e)
5557 (setq s (text-property-any (point) (or limit (point-max))
5558 'org-cwidth t))
5559 (when s
5560 (setq e (next-single-property-change s 'org-cwidth))
5561 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5562 (goto-char e)
5563 t)))
5565 (defvar org-latex-and-specials-regexp nil
5566 "Regular expression for highlighting export special stuff.")
5567 (defvar org-match-substring-regexp)
5568 (defvar org-match-substring-with-braces-regexp)
5570 ;; This should be with the exporter code, but we also use if for font-locking
5571 (defconst org-export-html-special-string-regexps
5572 '(("\\\\-" . "&shy;")
5573 ("---\\([^-]\\)" . "&mdash;\\1")
5574 ("--\\([^-]\\)" . "&ndash;\\1")
5575 ("\\.\\.\\." . "&hellip;"))
5576 "Regular expressions for special string conversion.")
5579 (defun org-compute-latex-and-specials-regexp ()
5580 "Compute regular expression for stuff treated specially by exporters."
5581 (if (not org-highlight-latex-fragments-and-specials)
5582 (org-set-local 'org-latex-and-specials-regexp nil)
5583 (require 'org-exp)
5584 (let*
5585 ((matchers (plist-get org-format-latex-options :matchers))
5586 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5587 org-latex-regexps)))
5588 (org-export-allow-BIND nil)
5589 (options (org-combine-plists (org-default-export-plist)
5590 (org-infile-export-plist)))
5591 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5592 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5593 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5594 (org-export-html-expand (plist-get options :expand-quoted-html))
5595 (org-export-with-special-strings (plist-get options :special-strings))
5596 (re-sub
5597 (cond
5598 ((equal org-export-with-sub-superscripts '{})
5599 (list org-match-substring-with-braces-regexp))
5600 (org-export-with-sub-superscripts
5601 (list org-match-substring-regexp))))
5602 (re-latex
5603 (if org-export-with-LaTeX-fragments
5604 (mapcar (lambda (x) (nth 1 x)) latexs)))
5605 (re-macros
5606 (if org-export-with-TeX-macros
5607 (list (concat "\\\\"
5608 (regexp-opt
5609 (append
5611 (delq nil
5612 (mapcar 'car-safe
5613 (append org-entities-user
5614 org-entities)))
5615 (if (boundp 'org-latex-entities)
5616 (mapcar (lambda (x)
5617 (or (car-safe x) x))
5618 org-latex-entities)
5619 nil))
5620 'words))) ; FIXME
5622 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5623 (re-special (if org-export-with-special-strings
5624 (mapcar (lambda (x) (car x))
5625 org-export-html-special-string-regexps)))
5626 (re-rest
5627 (delq nil
5628 (list
5629 (if org-export-html-expand "@<[^>\n]+>")
5630 ))))
5631 (org-set-local
5632 'org-latex-and-specials-regexp
5633 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5634 re-rest) "\\|")))))
5636 (defun org-do-latex-and-special-faces (limit)
5637 "Run through the buffer and add overlays to links."
5638 (when org-latex-and-specials-regexp
5639 (let (rtn d)
5640 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5641 limit t))
5642 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5643 'face))
5644 '(org-code org-verbatim underline)))
5645 (progn
5646 (setq rtn t
5647 d (cond ((member (char-after (1+ (match-beginning 0)))
5648 '(?_ ?^)) 1)
5649 (t 0)))
5650 (font-lock-prepend-text-property
5651 (+ d (match-beginning 0)) (match-end 0)
5652 'face 'org-latex-and-export-specials)
5653 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5654 '(font-lock-multiline t)))))
5655 rtn)))
5657 (defun org-restart-font-lock ()
5658 "Restart `font-lock-mode', to force refontification."
5659 (when (and (boundp 'font-lock-mode) font-lock-mode)
5660 (font-lock-mode -1)
5661 (font-lock-mode 1)))
5663 (defun org-all-targets (&optional radio)
5664 "Return a list of all targets in this file.
5665 With optional argument RADIO, only find radio targets."
5666 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5667 rtn)
5668 (save-excursion
5669 (goto-char (point-min))
5670 (while (re-search-forward re nil t)
5671 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5672 rtn)))
5674 (defun org-make-target-link-regexp (targets)
5675 "Make regular expression matching all strings in TARGETS.
5676 The regular expression finds the targets also if there is a line break
5677 between words."
5678 (and targets
5679 (concat
5680 "\\<\\("
5681 (mapconcat
5682 (lambda (x)
5683 (setq x (regexp-quote x))
5684 (while (string-match " +" x)
5685 (setq x (replace-match "\\s-+" t t x)))
5687 targets
5688 "\\|")
5689 "\\)\\>")))
5691 (defun org-activate-tags (limit)
5692 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5693 (progn
5694 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5695 (add-text-properties (match-beginning 1) (match-end 1)
5696 (list 'mouse-face 'highlight
5697 'keymap org-mouse-map))
5698 (org-rear-nonsticky-at (match-end 1))
5699 t)))
5701 (defun org-outline-level ()
5702 "Compute the outline level of the heading at point.
5703 This function assumes that the cursor is at the beginning of a line matched
5704 by `outline-regexp'. Otherwise it returns garbage.
5705 If this is called at a normal headline, the level is the number of stars.
5706 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5707 (save-excursion
5708 (looking-at org-outline-regexp)
5709 (1- (- (match-end 0) (match-beginning 0)))))
5711 (defvar org-font-lock-keywords nil)
5713 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5714 "Regular expression matching a property line.")
5716 (defvar org-font-lock-hook nil
5717 "Functions to be called for special font lock stuff.")
5719 (defvar org-font-lock-set-keywords-hook nil
5720 "Functions that can manipulate `org-font-lock-extra-keywords'.
5721 This is called after `org-font-lock-extra-keywords' is defined, but before
5722 it is installed to be used by font lock. This can be useful if something
5723 needs to be inserted at a specific position in the font-lock sequence.")
5725 (defun org-font-lock-hook (limit)
5726 "Run `org-font-lock-hook' within LIMIT."
5727 (run-hook-with-args 'org-font-lock-hook limit))
5729 (defun org-set-font-lock-defaults ()
5730 "Set font lock defaults for the current buffer."
5731 (let* ((em org-fontify-emphasized-text)
5732 (lk org-activate-links)
5733 (org-font-lock-extra-keywords
5734 (list
5735 ;; Call the hook
5736 '(org-font-lock-hook)
5737 ;; Headlines
5738 `(,(if org-fontify-whole-heading-line
5739 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5740 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5741 (1 (org-get-level-face 1))
5742 (2 (org-get-level-face 2))
5743 (3 (org-get-level-face 3)))
5744 ;; Table lines
5745 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5746 (1 'org-table t))
5747 ;; Table internals
5748 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5749 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5750 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5751 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5752 ;; Drawers
5753 (list org-drawer-regexp '(0 'org-special-keyword t))
5754 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5755 ;; Properties
5756 (list org-property-re
5757 '(1 'org-special-keyword t)
5758 '(3 'org-property-value t))
5759 ;; Links
5760 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5761 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5762 (if (memq 'plain lk) '(org-activate-plain-links))
5763 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5764 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5765 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5766 (if (memq 'footnote lk) '(org-activate-footnote-links))
5767 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5768 '(org-hide-wide-columns (0 nil append))
5769 ;; TODO keyword
5770 (list (format org-heading-keyword-regexp-format
5771 org-todo-regexp)
5772 '(2 (org-get-todo-face 2) t))
5773 ;; DONE
5774 (if org-fontify-done-headline
5775 (list (format org-heading-keyword-regexp-format
5776 (concat
5777 "\\(?:"
5778 (mapconcat 'regexp-quote org-done-keywords "\\|")
5779 "\\)"))
5780 '(2 'org-headline-done t))
5781 nil)
5782 ;; Priorities
5783 '(org-font-lock-add-priority-faces)
5784 ;; Tags
5785 '(org-font-lock-add-tag-faces)
5786 ;; Special keywords
5787 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5788 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5789 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5790 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5791 ;; Emphasis
5792 (if em
5793 (if (featurep 'xemacs)
5794 '(org-do-emphasis-faces (0 nil append))
5795 '(org-do-emphasis-faces)))
5796 ;; Checkboxes
5797 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5798 1 'org-checkbox prepend)
5799 (if (cdr (assq 'checkbox org-list-automatic-rules))
5800 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5801 (0 (org-get-checkbox-statistics-face) t)))
5802 ;; Description list items
5803 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5804 1 'org-list-dt prepend)
5805 ;; ARCHIVEd headings
5806 (list (concat
5807 org-outline-regexp-bol
5808 "\\(.*:" org-archive-tag ":.*\\)")
5809 '(1 'org-archived prepend))
5810 ;; Specials
5811 '(org-do-latex-and-special-faces)
5812 '(org-fontify-entities)
5813 '(org-raise-scripts)
5814 ;; Code
5815 '(org-activate-code (1 'org-code t))
5816 ;; COMMENT
5817 (list (format org-heading-keyword-regexp-format
5818 (concat "\\("
5819 org-comment-string "\\|" org-quote-string
5820 "\\)"))
5821 '(2 'org-special-keyword t))
5822 ;; Blocks and meta lines
5823 '(org-fontify-meta-lines-and-blocks)
5825 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5826 (run-hooks 'org-font-lock-set-keywords-hook)
5827 ;; Now set the full font-lock-keywords
5828 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5829 (org-set-local 'font-lock-defaults
5830 '(org-font-lock-keywords t nil nil backward-paragraph))
5831 (kill-local-variable 'font-lock-keywords) nil))
5833 (defun org-toggle-pretty-entities ()
5834 "Toggle the composition display of entities as UTF8 characters."
5835 (interactive)
5836 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5837 (org-restart-font-lock)
5838 (if org-pretty-entities
5839 (message "Entities are displayed as UTF8 characters")
5840 (save-restriction
5841 (widen)
5842 (org-decompose-region (point-min) (point-max))
5843 (message "Entities are displayed plain"))))
5845 (defvar org-custom-properties-overlays nil
5846 "List of overlays used for custom properties.")
5847 (make-variable-buffer-local 'org-custom-properties-overlays)
5849 (defun org-toggle-custom-properties-visibility ()
5850 "Display or hide properties in `org-custom-properties'."
5851 (interactive)
5852 (if org-custom-properties-overlays
5853 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5854 (setq org-custom-properties-overlays nil))
5855 (unless (not org-custom-properties)
5856 (save-excursion
5857 (save-restriction
5858 (widen)
5859 (goto-char (point-min))
5860 (while (re-search-forward org-property-re nil t)
5861 (mapc (lambda(p)
5862 (when (equal p (substring (match-string 1) 1 -1))
5863 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5864 (overlay-put o 'invisible t)
5865 (overlay-put o 'org-custom-property t)
5866 (push o org-custom-properties-overlays))))
5867 org-custom-properties)))))))
5869 (defun org-fontify-entities (limit)
5870 "Find an entity to fontify."
5871 (let (ee)
5872 (when org-pretty-entities
5873 (catch 'match
5874 (while (re-search-forward
5875 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5876 limit t)
5877 (if (and (not (org-in-indented-comment-line))
5878 (setq ee (org-entity-get (match-string 1)))
5879 (= (length (nth 6 ee)) 1))
5880 (let*
5881 ((end (if (equal (match-string 2) "{}")
5882 (match-end 2)
5883 (match-end 1))))
5884 (add-text-properties
5885 (match-beginning 0) end
5886 (list 'font-lock-fontified t))
5887 (compose-region (match-beginning 0) end
5888 (nth 6 ee) nil)
5889 (backward-char 1)
5890 (throw 'match t))))
5891 nil))))
5893 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5894 "Fontify string S like in Org-mode."
5895 (with-temp-buffer
5896 (insert s)
5897 (let ((org-odd-levels-only odd-levels))
5898 (org-mode)
5899 (font-lock-fontify-buffer)
5900 (buffer-string))))
5902 (defvar org-m nil)
5903 (defvar org-l nil)
5904 (defvar org-f nil)
5905 (defun org-get-level-face (n)
5906 "Get the right face for match N in font-lock matching of headlines."
5907 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5908 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5909 (if org-cycle-level-faces
5910 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5911 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5912 (cond
5913 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5914 ((eq n 2) org-f)
5915 (t (if org-level-color-stars-only nil org-f))))
5918 (defun org-get-todo-face (kwd)
5919 "Get the right face for a TODO keyword KWD.
5920 If KWD is a number, get the corresponding match group."
5921 (if (numberp kwd) (setq kwd (match-string kwd)))
5922 (or (org-face-from-face-or-color
5923 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5924 (and (member kwd org-done-keywords) 'org-done)
5925 'org-todo))
5927 (defun org-face-from-face-or-color (context inherit face-or-color)
5928 "Create a face list that inherits INHERIT, but sets the foreground color.
5929 When FACE-OR-COLOR is not a string, just return it."
5930 (if (stringp face-or-color)
5931 (list :inherit inherit
5932 (cdr (assoc context org-faces-easy-properties))
5933 face-or-color)
5934 face-or-color))
5936 (defun org-font-lock-add-tag-faces (limit)
5937 "Add the special tag faces."
5938 (when (and org-tag-faces org-tags-special-faces-re)
5939 (while (re-search-forward org-tags-special-faces-re limit t)
5940 (add-text-properties (match-beginning 1) (match-end 1)
5941 (list 'face (org-get-tag-face 1)
5942 'font-lock-fontified t))
5943 (backward-char 1))))
5945 (defun org-font-lock-add-priority-faces (limit)
5946 "Add the special priority faces."
5947 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5948 (when (save-match-data (org-at-heading-p))
5949 (add-text-properties
5950 (match-beginning 0) (match-end 0)
5951 (list 'face (or (org-face-from-face-or-color
5952 'priority 'org-special-keyword
5953 (cdr (assoc (char-after (match-beginning 1))
5954 org-priority-faces)))
5955 'org-special-keyword)
5956 'font-lock-fontified t)))))
5958 (defun org-get-tag-face (kwd)
5959 "Get the right face for a TODO keyword KWD.
5960 If KWD is a number, get the corresponding match group."
5961 (if (numberp kwd) (setq kwd (match-string kwd)))
5962 (or (org-face-from-face-or-color
5963 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5964 'org-tag))
5966 (defun org-unfontify-region (beg end &optional maybe_loudly)
5967 "Remove fontification and activation overlays from links."
5968 (font-lock-default-unfontify-region beg end)
5969 (let* ((buffer-undo-list t)
5970 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5971 (inhibit-modification-hooks t)
5972 deactivate-mark buffer-file-name buffer-file-truename)
5973 (org-decompose-region beg end)
5974 (remove-text-properties beg end
5975 '(mouse-face t keymap t org-linked-text t
5976 invisible t intangible t
5977 org-no-flyspell t org-emphasis t))
5978 (org-remove-font-lock-display-properties beg end)))
5980 (defconst org-script-display '(((raise -0.3) (height 0.7))
5981 ((raise 0.3) (height 0.7))
5982 ((raise -0.5))
5983 ((raise 0.5)))
5984 "Display properties for showing superscripts and subscripts.")
5986 (defun org-remove-font-lock-display-properties (beg end)
5987 "Remove specific display properties that have been added by font lock.
5988 The will remove the raise properties that are used to show superscripts
5989 and subscripts."
5990 (let (next prop)
5991 (while (< beg end)
5992 (setq next (next-single-property-change beg 'display nil end)
5993 prop (get-text-property beg 'display))
5994 (if (member prop org-script-display)
5995 (put-text-property beg next 'display nil))
5996 (setq beg next))))
5998 (defun org-raise-scripts (limit)
5999 "Add raise properties to sub/superscripts."
6000 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6001 (if (re-search-forward
6002 (if (eq org-use-sub-superscripts t)
6003 org-match-substring-regexp
6004 org-match-substring-with-braces-regexp)
6005 limit t)
6006 (let* ((pos (point)) table-p comment-p
6007 (mpos (match-beginning 3))
6008 (emph-p (get-text-property mpos 'org-emphasis))
6009 (link-p (get-text-property mpos 'mouse-face))
6010 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6011 (goto-char (point-at-bol))
6012 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6013 comment-p (org-looking-at-p "[ \t]*#"))
6014 (goto-char pos)
6015 ;; FIXME: Should we go back one character here, for a_b^c
6016 ;; (goto-char (1- pos)) ;????????????????????
6017 (if (or comment-p emph-p link-p keyw-p)
6019 (put-text-property (match-beginning 3) (match-end 0)
6020 'display
6021 (if (equal (char-after (match-beginning 2)) ?^)
6022 (nth (if table-p 3 1) org-script-display)
6023 (nth (if table-p 2 0) org-script-display)))
6024 (add-text-properties (match-beginning 2) (match-end 2)
6025 (list 'invisible t
6026 'org-dwidth t 'org-dwidth-n 1))
6027 (if (and (eq (char-after (match-beginning 3)) ?{)
6028 (eq (char-before (match-end 3)) ?}))
6029 (progn
6030 (add-text-properties
6031 (match-beginning 3) (1+ (match-beginning 3))
6032 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6033 (add-text-properties
6034 (1- (match-end 3)) (match-end 3)
6035 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6036 t)))))
6038 ;;;; Visibility cycling, including org-goto and indirect buffer
6040 ;;; Cycling
6042 (defvar org-cycle-global-status nil)
6043 (make-variable-buffer-local 'org-cycle-global-status)
6044 (defvar org-cycle-subtree-status nil)
6045 (make-variable-buffer-local 'org-cycle-subtree-status)
6047 (defvar org-inlinetask-min-level)
6049 ;;;###autoload
6050 (defun org-cycle (&optional arg)
6051 "TAB-action and visibility cycling for Org-mode.
6053 This is the command invoked in Org-mode by the TAB key. Its main purpose
6054 is outline visibility cycling, but it also invokes other actions
6055 in special contexts.
6057 - When this function is called with a prefix argument, rotate the entire
6058 buffer through 3 states (global cycling)
6059 1. OVERVIEW: Show only top-level headlines.
6060 2. CONTENTS: Show all headlines of all levels, but no body text.
6061 3. SHOW ALL: Show everything.
6062 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6063 determined by the variable `org-startup-folded', and by any VISIBILITY
6064 properties in the buffer.
6065 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6066 including any drawers.
6068 - When inside a table, re-align the table and move to the next field.
6070 - When point is at the beginning of a headline, rotate the subtree started
6071 by this line through 3 different states (local cycling)
6072 1. FOLDED: Only the main headline is shown.
6073 2. CHILDREN: The main headline and the direct children are shown.
6074 From this state, you can move to one of the children
6075 and zoom in further.
6076 3. SUBTREE: Show the entire subtree, including body text.
6077 If there is no subtree, switch directly from CHILDREN to FOLDED.
6079 - When point is at the beginning of an empty headline and the variable
6080 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6081 of the headline by demoting and promoting it to likely levels. This
6082 speeds up creation document structure by pressing TAB once or several
6083 times right after creating a new headline.
6085 - When there is a numeric prefix, go up to a heading with level ARG, do
6086 a `show-subtree' and return to the previous cursor position. If ARG
6087 is negative, go up that many levels.
6089 - When point is not at the beginning of a headline, execute the global
6090 binding for TAB, which is re-indenting the line. See the option
6091 `org-cycle-emulate-tab' for details.
6093 - Special case: if point is at the beginning of the buffer and there is
6094 no headline in line 1, this function will act as if called with prefix arg
6095 (C-u TAB, same as S-TAB) also when called without prefix arg.
6096 But only if also the variable `org-cycle-global-at-bob' is t."
6097 (interactive "P")
6098 (org-load-modules-maybe)
6099 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6100 (and org-cycle-level-after-item/entry-creation
6101 (or (org-cycle-level)
6102 (org-cycle-item-indentation))))
6103 (let* ((limit-level
6104 (or org-cycle-max-level
6105 (and (boundp 'org-inlinetask-min-level)
6106 org-inlinetask-min-level
6107 (1- org-inlinetask-min-level))))
6108 (nstars (and limit-level
6109 (if org-odd-levels-only
6110 (and limit-level (1- (* limit-level 2)))
6111 limit-level)))
6112 (org-outline-regexp
6113 (if (not (derived-mode-p 'org-mode))
6114 outline-regexp
6115 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6116 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6117 (not (looking-at org-outline-regexp))))
6118 (org-cycle-hook
6119 (if bob-special
6120 (delq 'org-optimize-window-after-visibility-change
6121 (copy-sequence org-cycle-hook))
6122 org-cycle-hook))
6123 (pos (point)))
6125 (if (or bob-special (equal arg '(4)))
6126 ;; special case: use global cycling
6127 (setq arg t))
6129 (cond
6131 ((equal arg '(16))
6132 (setq last-command 'dummy)
6133 (org-set-startup-visibility)
6134 (message "Startup visibility, plus VISIBILITY properties"))
6136 ((equal arg '(64))
6137 (show-all)
6138 (message "Entire buffer visible, including drawers"))
6140 ;; Table: enter it or move to the next field.
6141 ((org-at-table-p 'any)
6142 (if (org-at-table.el-p)
6143 (message "Use C-c ' to edit table.el tables")
6144 (if arg (org-table-edit-field t)
6145 (org-table-justify-field-maybe)
6146 (call-interactively 'org-table-next-field))))
6148 ((run-hook-with-args-until-success
6149 'org-tab-after-check-for-table-hook))
6151 ;; Global cycling: delegate to `org-cycle-internal-global'.
6152 ((eq arg t) (org-cycle-internal-global))
6154 ;; Drawers: delegate to `org-flag-drawer'.
6155 ((and org-drawers org-drawer-regexp
6156 (save-excursion
6157 (beginning-of-line 1)
6158 (looking-at org-drawer-regexp)))
6159 (org-flag-drawer ; toggle block visibility
6160 (not (get-char-property (match-end 0) 'invisible))))
6162 ;; Show-subtree, ARG levels up from here.
6163 ((integerp arg)
6164 (save-excursion
6165 (org-back-to-heading)
6166 (outline-up-heading (if (< arg 0) (- arg)
6167 (- (funcall outline-level) arg)))
6168 (org-show-subtree)))
6170 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6171 ((and (featurep 'org-inlinetask)
6172 (org-inlinetask-at-task-p)
6173 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6174 (org-inlinetask-toggle-visibility))
6176 ((org-try-cdlatex-tab))
6178 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6179 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6180 (save-excursion (beginning-of-line 1)
6181 (looking-at org-outline-regexp)))
6182 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6183 (org-cycle-internal-local))
6185 ;; From there: TAB emulation and template completion.
6186 (buffer-read-only (org-back-to-heading))
6188 ((run-hook-with-args-until-success
6189 'org-tab-after-check-for-cycling-hook))
6191 ((org-try-structure-completion))
6193 ((run-hook-with-args-until-success
6194 'org-tab-before-tab-emulation-hook))
6196 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6197 (or (not (bolp))
6198 (not (looking-at org-outline-regexp))))
6199 (call-interactively (global-key-binding "\t")))
6201 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6202 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6203 (or (and (eq org-cycle-emulate-tab 'white)
6204 (= (match-end 0) (point-at-eol)))
6205 (and (eq org-cycle-emulate-tab 'whitestart)
6206 (>= (match-end 0) pos))))
6208 (eq org-cycle-emulate-tab t))
6209 (call-interactively (global-key-binding "\t")))
6211 (t (save-excursion
6212 (org-back-to-heading)
6213 (org-cycle)))))))
6215 (defun org-cycle-internal-global ()
6216 "Do the global cycling action."
6217 ;; Hack to avoid display of messages for .org attachments in Gnus
6218 (let ((ga (string-match "\\*fontification" (buffer-name))))
6219 (cond
6220 ((and (eq last-command this-command)
6221 (eq org-cycle-global-status 'overview))
6222 ;; We just created the overview - now do table of contents
6223 ;; This can be slow in very large buffers, so indicate action
6224 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6225 (unless ga (message "CONTENTS..."))
6226 (org-content)
6227 (unless ga (message "CONTENTS...done"))
6228 (setq org-cycle-global-status 'contents)
6229 (run-hook-with-args 'org-cycle-hook 'contents))
6231 ((and (eq last-command this-command)
6232 (eq org-cycle-global-status 'contents))
6233 ;; We just showed the table of contents - now show everything
6234 (run-hook-with-args 'org-pre-cycle-hook 'all)
6235 (show-all)
6236 (unless ga (message "SHOW ALL"))
6237 (setq org-cycle-global-status 'all)
6238 (run-hook-with-args 'org-cycle-hook 'all))
6241 ;; Default action: go to overview
6242 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6243 (org-overview)
6244 (unless ga (message "OVERVIEW"))
6245 (setq org-cycle-global-status 'overview)
6246 (run-hook-with-args 'org-cycle-hook 'overview)))))
6248 (defun org-cycle-internal-local ()
6249 "Do the local cycling action."
6250 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6251 ;; First, determine end of headline (EOH), end of subtree or item
6252 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6253 (save-excursion
6254 (if (org-at-item-p)
6255 (progn
6256 (beginning-of-line)
6257 (setq struct (org-list-struct))
6258 (setq eoh (point-at-eol))
6259 (setq eos (org-list-get-item-end-before-blank (point) struct))
6260 (setq has-children (org-list-has-child-p (point) struct)))
6261 (org-back-to-heading)
6262 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6263 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6264 (setq has-children
6265 (or (save-excursion
6266 (let ((level (funcall outline-level)))
6267 (outline-next-heading)
6268 (and (org-at-heading-p t)
6269 (> (funcall outline-level) level))))
6270 (save-excursion
6271 (org-list-search-forward (org-item-beginning-re) eos t)))))
6272 ;; Determine end invisible part of buffer (EOL)
6273 (beginning-of-line 2)
6274 ;; XEmacs doesn't have `next-single-char-property-change'
6275 (if (featurep 'xemacs)
6276 (while (and (not (eobp)) ;; this is like `next-line'
6277 (get-char-property (1- (point)) 'invisible))
6278 (beginning-of-line 2))
6279 (while (and (not (eobp)) ;; this is like `next-line'
6280 (get-char-property (1- (point)) 'invisible))
6281 (goto-char (next-single-char-property-change (point) 'invisible))
6282 (and (eolp) (beginning-of-line 2))))
6283 (setq eol (point)))
6284 ;; Find out what to do next and set `this-command'
6285 (cond
6286 ((= eos eoh)
6287 ;; Nothing is hidden behind this heading
6288 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6289 (message "EMPTY ENTRY")
6290 (setq org-cycle-subtree-status nil)
6291 (save-excursion
6292 (goto-char eos)
6293 (outline-next-heading)
6294 (if (outline-invisible-p) (org-flag-heading nil))))
6295 ((and (or (>= eol eos)
6296 (not (string-match "\\S-" (buffer-substring eol eos))))
6297 (or has-children
6298 (not (setq children-skipped
6299 org-cycle-skip-children-state-if-no-children))))
6300 ;; Entire subtree is hidden in one line: children view
6301 (run-hook-with-args 'org-pre-cycle-hook 'children)
6302 (if (org-at-item-p)
6303 (org-list-set-item-visibility (point-at-bol) struct 'children)
6304 (org-show-entry)
6305 (org-with-limited-levels (show-children))
6306 ;; FIXME: This slows down the func way too much.
6307 ;; How keep drawers hidden in subtree anyway?
6308 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6309 ;; (org-cycle-hide-drawers 'subtree))
6311 ;; Fold every list in subtree to top-level items.
6312 (when (eq org-cycle-include-plain-lists 'integrate)
6313 (save-excursion
6314 (org-back-to-heading)
6315 (while (org-list-search-forward (org-item-beginning-re) eos t)
6316 (beginning-of-line 1)
6317 (let* ((struct (org-list-struct))
6318 (prevs (org-list-prevs-alist struct))
6319 (end (org-list-get-bottom-point struct)))
6320 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6321 (org-list-get-all-items (point) struct prevs))
6322 (goto-char end))))))
6323 (message "CHILDREN")
6324 (save-excursion
6325 (goto-char eos)
6326 (outline-next-heading)
6327 (if (outline-invisible-p) (org-flag-heading nil)))
6328 (setq org-cycle-subtree-status 'children)
6329 (run-hook-with-args 'org-cycle-hook 'children))
6330 ((or children-skipped
6331 (and (eq last-command this-command)
6332 (eq org-cycle-subtree-status 'children)))
6333 ;; We just showed the children, or no children are there,
6334 ;; now show everything.
6335 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6336 (outline-flag-region eoh eos nil)
6337 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6338 (setq org-cycle-subtree-status 'subtree)
6339 (run-hook-with-args 'org-cycle-hook 'subtree))
6341 ;; Default action: hide the subtree.
6342 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6343 (outline-flag-region eoh eos t)
6344 (message "FOLDED")
6345 (setq org-cycle-subtree-status 'folded)
6346 (run-hook-with-args 'org-cycle-hook 'folded)))))
6348 ;;;###autoload
6349 (defun org-global-cycle (&optional arg)
6350 "Cycle the global visibility. For details see `org-cycle'.
6351 With \\[universal-argument] prefix arg, switch to startup visibility.
6352 With a numeric prefix, show all headlines up to that level."
6353 (interactive "P")
6354 (let ((org-cycle-include-plain-lists
6355 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6356 (cond
6357 ((integerp arg)
6358 (show-all)
6359 (hide-sublevels arg)
6360 (setq org-cycle-global-status 'contents))
6361 ((equal arg '(4))
6362 (org-set-startup-visibility)
6363 (message "Startup visibility, plus VISIBILITY properties."))
6365 (org-cycle '(4))))))
6367 (defun org-set-startup-visibility ()
6368 "Set the visibility required by startup options and properties."
6369 (cond
6370 ((eq org-startup-folded t)
6371 (org-cycle '(4)))
6372 ((eq org-startup-folded 'content)
6373 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6374 (org-cycle '(4)) (org-cycle '(4)))))
6375 (unless (eq org-startup-folded 'showeverything)
6376 (if org-hide-block-startup (org-hide-block-all))
6377 (org-set-visibility-according-to-property 'no-cleanup)
6378 (org-cycle-hide-archived-subtrees 'all)
6379 (org-cycle-hide-drawers 'all)
6380 (org-cycle-show-empty-lines t)))
6382 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6383 "Switch subtree visibilities according to :VISIBILITY: property."
6384 (interactive)
6385 (let (org-show-entry-below state)
6386 (save-excursion
6387 (goto-char (point-min))
6388 (while (re-search-forward
6389 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6390 nil t)
6391 (setq state (match-string 1))
6392 (save-excursion
6393 (org-back-to-heading t)
6394 (hide-subtree)
6395 (org-reveal)
6396 (cond
6397 ((equal state '("fold" "folded"))
6398 (hide-subtree))
6399 ((equal state "children")
6400 (org-show-hidden-entry)
6401 (show-children))
6402 ((equal state "content")
6403 (save-excursion
6404 (save-restriction
6405 (org-narrow-to-subtree)
6406 (org-content))))
6407 ((member state '("all" "showall"))
6408 (show-subtree)))))
6409 (unless no-cleanup
6410 (org-cycle-hide-archived-subtrees 'all)
6411 (org-cycle-hide-drawers 'all)
6412 (org-cycle-show-empty-lines 'all)))))
6414 ;; This function uses outline-regexp instead of the more fundamental
6415 ;; org-outline-regexp so that org-cycle-global works outside of Org
6416 ;; buffers, where outline-regexp is needed.
6417 (defun org-overview ()
6418 "Switch to overview mode, showing only top-level headlines.
6419 Really, this shows all headlines with level equal or greater than the level
6420 of the first headline in the buffer. This is important, because if the
6421 first headline is not level one, then (hide-sublevels 1) gives confusing
6422 results."
6423 (interactive)
6424 (let ((level (save-excursion
6425 (goto-char (point-min))
6426 (if (re-search-forward (concat "^" outline-regexp) nil t)
6427 (progn
6428 (goto-char (match-beginning 0))
6429 (funcall outline-level))))))
6430 (and level (hide-sublevels level))))
6432 (defun org-content (&optional arg)
6433 "Show all headlines in the buffer, like a table of contents.
6434 With numerical argument N, show content up to level N."
6435 (interactive "P")
6436 (save-excursion
6437 ;; Visit all headings and show their offspring
6438 (and (integerp arg) (org-overview))
6439 (goto-char (point-max))
6440 (catch 'exit
6441 (while (and (progn (condition-case nil
6442 (outline-previous-visible-heading 1)
6443 (error (goto-char (point-min))))
6445 (looking-at org-outline-regexp))
6446 (if (integerp arg)
6447 (show-children (1- arg))
6448 (show-branches))
6449 (if (bobp) (throw 'exit nil))))))
6452 (defun org-optimize-window-after-visibility-change (state)
6453 "Adjust the window after a change in outline visibility.
6454 This function is the default value of the hook `org-cycle-hook'."
6455 (when (get-buffer-window (current-buffer))
6456 (cond
6457 ((eq state 'content) nil)
6458 ((eq state 'all) nil)
6459 ((eq state 'folded) nil)
6460 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6461 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6463 (defun org-remove-empty-overlays-at (pos)
6464 "Remove outline overlays that do not contain non-white stuff."
6465 (mapc
6466 (lambda (o)
6467 (and (eq 'outline (overlay-get o 'invisible))
6468 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6469 (overlay-end o))))
6470 (delete-overlay o)))
6471 (overlays-at pos)))
6473 (defun org-clean-visibility-after-subtree-move ()
6474 "Fix visibility issues after moving a subtree."
6475 ;; First, find a reasonable region to look at:
6476 ;; Start two siblings above, end three below
6477 (let* ((beg (save-excursion
6478 (and (org-get-last-sibling)
6479 (org-get-last-sibling))
6480 (point)))
6481 (end (save-excursion
6482 (and (org-get-next-sibling)
6483 (org-get-next-sibling)
6484 (org-get-next-sibling))
6485 (if (org-at-heading-p)
6486 (point-at-eol)
6487 (point))))
6488 (level (looking-at "\\*+"))
6489 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6490 (save-excursion
6491 (save-restriction
6492 (narrow-to-region beg end)
6493 (when re
6494 ;; Properly fold already folded siblings
6495 (goto-char (point-min))
6496 (while (re-search-forward re nil t)
6497 (if (and (not (outline-invisible-p))
6498 (save-excursion
6499 (goto-char (point-at-eol)) (outline-invisible-p)))
6500 (hide-entry))))
6501 (org-cycle-show-empty-lines 'overview)
6502 (org-cycle-hide-drawers 'overview)))))
6504 (defun org-cycle-show-empty-lines (state)
6505 "Show empty lines above all visible headlines.
6506 The region to be covered depends on STATE when called through
6507 `org-cycle-hook'. Lisp program can use t for STATE to get the
6508 entire buffer covered. Note that an empty line is only shown if there
6509 are at least `org-cycle-separator-lines' empty lines before the headline."
6510 (when (not (= org-cycle-separator-lines 0))
6511 (save-excursion
6512 (let* ((n (abs org-cycle-separator-lines))
6513 (re (cond
6514 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6515 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6516 (t (let ((ns (number-to-string (- n 2))))
6517 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6518 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6519 beg end b e)
6520 (cond
6521 ((memq state '(overview contents t))
6522 (setq beg (point-min) end (point-max)))
6523 ((memq state '(children folded))
6524 (setq beg (point) end (progn (org-end-of-subtree t t)
6525 (beginning-of-line 2)
6526 (point)))))
6527 (when beg
6528 (goto-char beg)
6529 (while (re-search-forward re end t)
6530 (unless (get-char-property (match-end 1) 'invisible)
6531 (setq e (match-end 1))
6532 (if (< org-cycle-separator-lines 0)
6533 (setq b (save-excursion
6534 (goto-char (match-beginning 0))
6535 (org-back-over-empty-lines)
6536 (if (save-excursion
6537 (goto-char (max (point-min) (1- (point))))
6538 (org-at-heading-p))
6539 (1- (point))
6540 (point))))
6541 (setq b (match-beginning 1)))
6542 (outline-flag-region b e nil)))))))
6543 ;; Never hide empty lines at the end of the file.
6544 (save-excursion
6545 (goto-char (point-max))
6546 (outline-previous-heading)
6547 (outline-end-of-heading)
6548 (if (and (looking-at "[ \t\n]+")
6549 (= (match-end 0) (point-max)))
6550 (outline-flag-region (point) (match-end 0) nil))))
6552 (defun org-show-empty-lines-in-parent ()
6553 "Move to the parent and re-show empty lines before visible headlines."
6554 (save-excursion
6555 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6556 (org-cycle-show-empty-lines context))))
6558 (defun org-files-list ()
6559 "Return `org-agenda-files' list, plus all open org-mode files.
6560 This is useful for operations that need to scan all of a user's
6561 open and agenda-wise Org files."
6562 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6563 (dolist (buf (buffer-list))
6564 (with-current-buffer buf
6565 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6566 (let ((file (expand-file-name (buffer-file-name))))
6567 (unless (member file files)
6568 (push file files))))))
6569 files))
6571 (defsubst org-entry-beginning-position ()
6572 "Return the beginning position of the current entry."
6573 (save-excursion (outline-back-to-heading t) (point)))
6575 (defsubst org-entry-end-position ()
6576 "Return the end position of the current entry."
6577 (save-excursion (outline-next-heading) (point)))
6579 (defun org-cycle-hide-drawers (state)
6580 "Re-hide all drawers after a visibility state change."
6581 (when (and (derived-mode-p 'org-mode)
6582 (not (memq state '(overview folded contents))))
6583 (save-excursion
6584 (let* ((globalp (memq state '(contents all)))
6585 (beg (if globalp (point-min) (point)))
6586 (end (if globalp (point-max)
6587 (if (eq state 'children)
6588 (save-excursion (outline-next-heading) (point))
6589 (org-end-of-subtree t)))))
6590 (goto-char beg)
6591 (while (re-search-forward org-drawer-regexp end t)
6592 (org-flag-drawer t))))))
6594 (defun org-flag-drawer (flag)
6595 "When FLAG is non-nil, hide the drawer we are within.
6596 Otherwise make it visible."
6597 (save-excursion
6598 (beginning-of-line 1)
6599 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6600 (let ((b (match-end 0)))
6601 (if (re-search-forward
6602 "^[ \t]*:END:"
6603 (save-excursion (outline-next-heading) (point)) t)
6604 (outline-flag-region b (point-at-eol) flag)
6605 (error ":END: line missing at position %s" b))))))
6607 (defun org-subtree-end-visible-p ()
6608 "Is the end of the current subtree visible?"
6609 (pos-visible-in-window-p
6610 (save-excursion (org-end-of-subtree t) (point))))
6612 (defun org-first-headline-recenter (&optional N)
6613 "Move cursor to the first headline and recenter the headline.
6614 Optional argument N means put the headline into the Nth line of the window."
6615 (goto-char (point-min))
6616 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6617 (beginning-of-line)
6618 (recenter (prefix-numeric-value N))))
6620 ;;; Saving and restoring visibility
6622 (defun org-outline-overlay-data (&optional use-markers)
6623 "Return a list of the locations of all outline overlays.
6624 These are overlays with the `invisible' property value `outline'.
6625 The return value is a list of cons cells, with start and stop
6626 positions for each overlay.
6627 If USE-MARKERS is set, return the positions as markers."
6628 (let (beg end)
6629 (save-excursion
6630 (save-restriction
6631 (widen)
6632 (delq nil
6633 (mapcar (lambda (o)
6634 (when (eq (overlay-get o 'invisible) 'outline)
6635 (setq beg (overlay-start o)
6636 end (overlay-end o))
6637 (and beg end (> end beg)
6638 (if use-markers
6639 (cons (move-marker (make-marker) beg)
6640 (move-marker (make-marker) end))
6641 (cons beg end)))))
6642 (overlays-in (point-min) (point-max))))))))
6644 (defun org-set-outline-overlay-data (data)
6645 "Create visibility overlays for all positions in DATA.
6646 DATA should have been made by `org-outline-overlay-data'."
6647 (let (o)
6648 (save-excursion
6649 (save-restriction
6650 (widen)
6651 (show-all)
6652 (mapc (lambda (c)
6653 (outline-flag-region (car c) (cdr c) t))
6654 data)))))
6656 ;;; Folding of blocks
6658 (defvar org-hide-block-overlays nil
6659 "Overlays hiding blocks.")
6660 (make-variable-buffer-local 'org-hide-block-overlays)
6662 (defun org-block-map (function &optional start end)
6663 "Call FUNCTION at the head of all source blocks in the current buffer.
6664 Optional arguments START and END can be used to limit the range."
6665 (let ((start (or start (point-min)))
6666 (end (or end (point-max))))
6667 (save-excursion
6668 (goto-char start)
6669 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6670 (save-excursion
6671 (save-match-data
6672 (goto-char (match-beginning 0))
6673 (funcall function)))))))
6675 (defun org-hide-block-toggle-all ()
6676 "Toggle the visibility of all blocks in the current buffer."
6677 (org-block-map #'org-hide-block-toggle))
6679 (defun org-hide-block-all ()
6680 "Fold all blocks in the current buffer."
6681 (interactive)
6682 (org-show-block-all)
6683 (org-block-map #'org-hide-block-toggle-maybe))
6685 (defun org-show-block-all ()
6686 "Unfold all blocks in the current buffer."
6687 (interactive)
6688 (mapc 'delete-overlay org-hide-block-overlays)
6689 (setq org-hide-block-overlays nil))
6691 (defun org-hide-block-toggle-maybe ()
6692 "Toggle visibility of block at point."
6693 (interactive)
6694 (let ((case-fold-search t))
6695 (if (save-excursion
6696 (beginning-of-line 1)
6697 (looking-at org-block-regexp))
6698 (progn (org-hide-block-toggle)
6699 t) ;; to signal that we took action
6700 nil))) ;; to signal that we did not
6702 (defun org-hide-block-toggle (&optional force)
6703 "Toggle the visibility of the current block."
6704 (interactive)
6705 (save-excursion
6706 (beginning-of-line)
6707 (if (re-search-forward org-block-regexp nil t)
6708 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6709 (end (match-end 0)) ;; end of entire body
6711 (if (memq t (mapcar (lambda (overlay)
6712 (eq (overlay-get overlay 'invisible)
6713 'org-hide-block))
6714 (overlays-at start)))
6715 (if (or (not force) (eq force 'off))
6716 (mapc (lambda (ov)
6717 (when (member ov org-hide-block-overlays)
6718 (setq org-hide-block-overlays
6719 (delq ov org-hide-block-overlays)))
6720 (when (eq (overlay-get ov 'invisible)
6721 'org-hide-block)
6722 (delete-overlay ov)))
6723 (overlays-at start)))
6724 (setq ov (make-overlay start end))
6725 (overlay-put ov 'invisible 'org-hide-block)
6726 ;; make the block accessible to isearch
6727 (overlay-put
6728 ov 'isearch-open-invisible
6729 (lambda (ov)
6730 (when (member ov org-hide-block-overlays)
6731 (setq org-hide-block-overlays
6732 (delq ov org-hide-block-overlays)))
6733 (when (eq (overlay-get ov 'invisible)
6734 'org-hide-block)
6735 (delete-overlay ov))))
6736 (push ov org-hide-block-overlays)))
6737 (error "Not looking at a source block"))))
6739 ;; org-tab-after-check-for-cycling-hook
6740 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6741 ;; Remove overlays when changing major mode
6742 (add-hook 'org-mode-hook
6743 (lambda () (org-add-hook 'change-major-mode-hook
6744 'org-show-block-all 'append 'local)))
6746 ;;; Org-goto
6748 (defvar org-goto-window-configuration nil)
6749 (defvar org-goto-marker nil)
6750 (defvar org-goto-map
6751 (let ((map (make-sparse-keymap)))
6752 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6753 (while (setq cmd (pop cmds))
6754 (substitute-key-definition cmd cmd map global-map)))
6755 (suppress-keymap map)
6756 (org-defkey map "\C-m" 'org-goto-ret)
6757 (org-defkey map [(return)] 'org-goto-ret)
6758 (org-defkey map [(left)] 'org-goto-left)
6759 (org-defkey map [(right)] 'org-goto-right)
6760 (org-defkey map [(control ?g)] 'org-goto-quit)
6761 (org-defkey map "\C-i" 'org-cycle)
6762 (org-defkey map [(tab)] 'org-cycle)
6763 (org-defkey map [(down)] 'outline-next-visible-heading)
6764 (org-defkey map [(up)] 'outline-previous-visible-heading)
6765 (if org-goto-auto-isearch
6766 (if (fboundp 'define-key-after)
6767 (define-key-after map [t] 'org-goto-local-auto-isearch)
6768 nil)
6769 (org-defkey map "q" 'org-goto-quit)
6770 (org-defkey map "n" 'outline-next-visible-heading)
6771 (org-defkey map "p" 'outline-previous-visible-heading)
6772 (org-defkey map "f" 'outline-forward-same-level)
6773 (org-defkey map "b" 'outline-backward-same-level)
6774 (org-defkey map "u" 'outline-up-heading))
6775 (org-defkey map "/" 'org-occur)
6776 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6777 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6778 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6779 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6780 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6781 map))
6783 (defconst org-goto-help
6784 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6785 RET=jump to location [Q]uit and return to previous location
6786 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6788 (defvar org-goto-start-pos) ; dynamically scoped parameter
6790 ;; FIXME: Docstring does not mention both interfaces
6791 (defun org-goto (&optional alternative-interface)
6792 "Look up a different location in the current file, keeping current visibility.
6794 When you want look-up or go to a different location in a
6795 document, the fastest way is often to fold the entire buffer and
6796 then dive into the tree. This method has the disadvantage, that
6797 the previous location will be folded, which may not be what you
6798 want.
6800 This command works around this by showing a copy of the current
6801 buffer in an indirect buffer, in overview mode. You can dive
6802 into the tree in that copy, use org-occur and incremental search
6803 to find a location. When pressing RET or `Q', the command
6804 returns to the original buffer in which the visibility is still
6805 unchanged. After RET it will also jump to the location selected
6806 in the indirect buffer and expose the headline hierarchy above.
6808 With a prefix argument, use the alternative interface: e.g. if
6809 `org-goto-interface' is 'outline use 'outline-path-completion."
6810 (interactive "P")
6811 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6812 (org-refile-use-outline-path t)
6813 (org-refile-target-verify-function nil)
6814 (interface
6815 (if (not alternative-interface)
6816 org-goto-interface
6817 (if (eq org-goto-interface 'outline)
6818 'outline-path-completion
6819 'outline)))
6820 (org-goto-start-pos (point))
6821 (selected-point
6822 (if (eq interface 'outline)
6823 (car (org-get-location (current-buffer) org-goto-help))
6824 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6825 (org-refile-check-position pa)
6826 (nth 3 pa)))))
6827 (if selected-point
6828 (progn
6829 (org-mark-ring-push org-goto-start-pos)
6830 (goto-char selected-point)
6831 (if (or (outline-invisible-p) (org-invisible-p2))
6832 (org-show-context 'org-goto)))
6833 (message "Quit"))))
6835 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6836 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6837 (defvar org-goto-local-auto-isearch-map) ; defined below
6839 (defun org-get-location (buf help)
6840 "Let the user select a location in the Org-mode buffer BUF.
6841 This function uses a recursive edit. It returns the selected position
6842 or nil."
6843 (org-no-popups
6844 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6845 (isearch-hide-immediately nil)
6846 (isearch-search-fun-function
6847 (lambda () 'org-goto-local-search-headings))
6848 (org-goto-selected-point org-goto-exit-command))
6849 (save-excursion
6850 (save-window-excursion
6851 (delete-other-windows)
6852 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6853 (org-pop-to-buffer-same-window
6854 (condition-case nil
6855 (make-indirect-buffer (current-buffer) "*org-goto*")
6856 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6857 (with-output-to-temp-buffer "*Help*"
6858 (princ help))
6859 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6860 (setq buffer-read-only nil)
6861 (let ((org-startup-truncated t)
6862 (org-startup-folded nil)
6863 (org-startup-align-all-tables nil))
6864 (org-mode)
6865 (org-overview))
6866 (setq buffer-read-only t)
6867 (if (and (boundp 'org-goto-start-pos)
6868 (integer-or-marker-p org-goto-start-pos))
6869 (let ((org-show-hierarchy-above t)
6870 (org-show-siblings t)
6871 (org-show-following-heading t))
6872 (goto-char org-goto-start-pos)
6873 (and (outline-invisible-p) (org-show-context)))
6874 (goto-char (point-min)))
6875 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6876 (message "Select location and press RET")
6877 (use-local-map org-goto-map)
6878 (recursive-edit)
6880 (kill-buffer "*org-goto*")
6881 (cons org-goto-selected-point org-goto-exit-command))))
6883 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6884 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6885 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6886 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6888 (defun org-goto-local-search-headings (string bound noerror)
6889 "Search and make sure that any matches are in headlines."
6890 (catch 'return
6891 (while (if isearch-forward
6892 (search-forward string bound noerror)
6893 (search-backward string bound noerror))
6894 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6895 (and (member :headline context)
6896 (not (member :tags context))))
6897 (throw 'return (point))))))
6899 (defun org-goto-local-auto-isearch ()
6900 "Start isearch."
6901 (interactive)
6902 (goto-char (point-min))
6903 (let ((keys (this-command-keys)))
6904 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6905 (isearch-mode t)
6906 (isearch-process-search-char (string-to-char keys)))))
6908 (defun org-goto-ret (&optional arg)
6909 "Finish `org-goto' by going to the new location."
6910 (interactive "P")
6911 (setq org-goto-selected-point (point)
6912 org-goto-exit-command 'return)
6913 (throw 'exit nil))
6915 (defun org-goto-left ()
6916 "Finish `org-goto' by going to the new location."
6917 (interactive)
6918 (if (org-at-heading-p)
6919 (progn
6920 (beginning-of-line 1)
6921 (setq org-goto-selected-point (point)
6922 org-goto-exit-command 'left)
6923 (throw 'exit nil))
6924 (error "Not on a heading")))
6926 (defun org-goto-right ()
6927 "Finish `org-goto' by going to the new location."
6928 (interactive)
6929 (if (org-at-heading-p)
6930 (progn
6931 (setq org-goto-selected-point (point)
6932 org-goto-exit-command 'right)
6933 (throw 'exit nil))
6934 (error "Not on a heading")))
6936 (defun org-goto-quit ()
6937 "Finish `org-goto' without cursor motion."
6938 (interactive)
6939 (setq org-goto-selected-point nil)
6940 (setq org-goto-exit-command 'quit)
6941 (throw 'exit nil))
6943 ;;; Indirect buffer display of subtrees
6945 (defvar org-indirect-dedicated-frame nil
6946 "This is the frame being used for indirect tree display.")
6947 (defvar org-last-indirect-buffer nil)
6949 (defun org-tree-to-indirect-buffer (&optional arg)
6950 "Create indirect buffer and narrow it to current subtree.
6951 With a numerical prefix ARG, go up to this level and then take that tree.
6952 If ARG is negative, go up that many levels.
6954 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6955 indirect buffer previously made with this command, to avoid proliferation of
6956 indirect buffers. However, when you call the command with a \
6957 \\[universal-argument] prefix, or
6958 when `org-indirect-buffer-display' is `new-frame', the last buffer
6959 is kept so that you can work with several indirect buffers at the same time.
6960 If `org-indirect-buffer-display' is `dedicated-frame', the \
6961 \\[universal-argument] prefix also
6962 requests that a new frame be made for the new buffer, so that the dedicated
6963 frame is not changed."
6964 (interactive "P")
6965 (let ((cbuf (current-buffer))
6966 (cwin (selected-window))
6967 (pos (point))
6968 beg end level heading ibuf)
6969 (save-excursion
6970 (org-back-to-heading t)
6971 (when (numberp arg)
6972 (setq level (org-outline-level))
6973 (if (< arg 0) (setq arg (+ level arg)))
6974 (while (> (setq level (org-outline-level)) arg)
6975 (org-up-heading-safe)))
6976 (setq beg (point)
6977 heading (org-get-heading))
6978 (org-end-of-subtree t t)
6979 (if (org-at-heading-p) (backward-char 1))
6980 (setq end (point)))
6981 (if (and (buffer-live-p org-last-indirect-buffer)
6982 (not (eq org-indirect-buffer-display 'new-frame))
6983 (not arg))
6984 (kill-buffer org-last-indirect-buffer))
6985 (setq ibuf (org-get-indirect-buffer cbuf)
6986 org-last-indirect-buffer ibuf)
6987 (cond
6988 ((or (eq org-indirect-buffer-display 'new-frame)
6989 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6990 (select-frame (make-frame))
6991 (delete-other-windows)
6992 (org-pop-to-buffer-same-window ibuf)
6993 (org-set-frame-title heading))
6994 ((eq org-indirect-buffer-display 'dedicated-frame)
6995 (raise-frame
6996 (select-frame (or (and org-indirect-dedicated-frame
6997 (frame-live-p org-indirect-dedicated-frame)
6998 org-indirect-dedicated-frame)
6999 (setq org-indirect-dedicated-frame (make-frame)))))
7000 (delete-other-windows)
7001 (org-pop-to-buffer-same-window ibuf)
7002 (org-set-frame-title (concat "Indirect: " heading)))
7003 ((eq org-indirect-buffer-display 'current-window)
7004 (org-pop-to-buffer-same-window ibuf))
7005 ((eq org-indirect-buffer-display 'other-window)
7006 (pop-to-buffer ibuf))
7007 (t (error "Invalid value")))
7008 (if (featurep 'xemacs)
7009 (save-excursion (org-mode) (turn-on-font-lock)))
7010 (narrow-to-region beg end)
7011 (show-all)
7012 (goto-char pos)
7013 (run-hook-with-args 'org-cycle-hook 'all)
7014 (and (window-live-p cwin) (select-window cwin))))
7016 (defun org-get-indirect-buffer (&optional buffer)
7017 (setq buffer (or buffer (current-buffer)))
7018 (let ((n 1) (base (buffer-name buffer)) bname)
7019 (while (buffer-live-p
7020 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7021 (setq n (1+ n)))
7022 (condition-case nil
7023 (make-indirect-buffer buffer bname 'clone)
7024 (error (make-indirect-buffer buffer bname)))))
7026 (defun org-set-frame-title (title)
7027 "Set the title of the current frame to the string TITLE."
7028 ;; FIXME: how to name a single frame in XEmacs???
7029 (unless (featurep 'xemacs)
7030 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7032 ;;;; Structure editing
7034 ;;; Inserting headlines
7036 (defun org-previous-line-empty-p ()
7037 (save-excursion
7038 (and (not (bobp))
7039 (or (beginning-of-line 0) t)
7040 (save-match-data
7041 (looking-at "[ \t]*$")))))
7043 (defun org-insert-heading (&optional force-heading invisible-ok)
7044 "Insert a new heading or item with same depth at point.
7045 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7046 If point is at the beginning of a headline, insert a sibling before the
7047 current headline. If point is not at the beginning, split the line,
7048 create the new headline with the text in the current line after point
7049 \(but see also the variable `org-M-RET-may-split-line').
7051 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7052 This is important for non-interactive uses of the command."
7053 (interactive "P")
7054 (if (or (= (buffer-size) 0)
7055 (and (not (save-excursion
7056 (and (ignore-errors (org-back-to-heading invisible-ok))
7057 (org-at-heading-p))))
7058 (or force-heading (not (org-in-item-p)))))
7059 (progn
7060 (insert "\n* ")
7061 (run-hooks 'org-insert-heading-hook))
7062 (when (or force-heading (not (org-insert-item)))
7063 (let* ((empty-line-p nil)
7064 (level nil)
7065 (on-heading (org-at-heading-p))
7066 (head (save-excursion
7067 (condition-case nil
7068 (progn
7069 (org-back-to-heading invisible-ok)
7070 (when (and (not on-heading)
7071 (featurep 'org-inlinetask)
7072 (integerp org-inlinetask-min-level)
7073 (>= (length (match-string 0))
7074 org-inlinetask-min-level))
7075 ;; Find a heading level before the inline task
7076 (while (and (setq level (org-up-heading-safe))
7077 (>= level org-inlinetask-min-level)))
7078 (if (org-at-heading-p)
7079 (org-back-to-heading invisible-ok)
7080 (error "This should not happen")))
7081 (setq empty-line-p (org-previous-line-empty-p))
7082 (match-string 0))
7083 (error "*"))))
7084 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7085 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7086 pos hide-previous previous-pos)
7087 (cond
7088 ((and (org-at-heading-p) (bolp)
7089 (or (bobp)
7090 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7091 ;; insert before the current line
7092 (open-line (if blank 2 1)))
7093 ((and (bolp)
7094 (not org-insert-heading-respect-content)
7095 (or (bobp)
7096 (save-excursion
7097 (backward-char 1) (not (outline-invisible-p)))))
7098 ;; insert right here
7099 nil)
7101 ;; somewhere in the line
7102 (save-excursion
7103 (setq previous-pos (point-at-bol))
7104 (end-of-line)
7105 (setq hide-previous (outline-invisible-p)))
7106 (and org-insert-heading-respect-content (org-show-subtree))
7107 (let ((split
7108 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7109 (save-excursion
7110 (let ((p (point)))
7111 (goto-char (point-at-bol))
7112 (and (looking-at org-complex-heading-regexp)
7113 (match-beginning 4)
7114 (> p (match-beginning 4)))))))
7115 tags pos)
7116 (cond
7117 (org-insert-heading-respect-content
7118 (org-end-of-subtree nil t)
7119 (when (featurep 'org-inlinetask)
7120 (while (and (not (eobp))
7121 (looking-at "\\(\\*+\\)[ \t]+")
7122 (>= (length (match-string 1))
7123 org-inlinetask-min-level))
7124 (org-end-of-subtree nil t)))
7125 (or (bolp) (newline))
7126 (or (org-previous-line-empty-p)
7127 (and blank (newline)))
7128 (open-line 1))
7129 ((org-at-heading-p)
7130 (when hide-previous
7131 (show-children)
7132 (org-show-entry))
7133 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7134 (setq tags (and (match-end 2) (match-string 2)))
7135 (and (match-end 1)
7136 (delete-region (match-beginning 1) (match-end 1)))
7137 (setq pos (point-at-bol))
7138 (or split (end-of-line 1))
7139 (delete-horizontal-space)
7140 (if (string-match "\\`\\*+\\'"
7141 (buffer-substring (point-at-bol) (point)))
7142 (insert " "))
7143 (newline (if blank 2 1))
7144 (when tags
7145 (save-excursion
7146 (goto-char pos)
7147 (end-of-line 1)
7148 (insert " " tags)
7149 (org-set-tags nil 'align))))
7151 (or split (end-of-line 1))
7152 (newline (if blank 2 1)))))))
7153 (insert head) (just-one-space)
7154 (setq pos (point))
7155 (end-of-line 1)
7156 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7157 (when (and org-insert-heading-respect-content hide-previous)
7158 (save-excursion
7159 (goto-char previous-pos)
7160 (hide-subtree)))
7161 (run-hooks 'org-insert-heading-hook)))))
7163 (defun org-get-heading (&optional no-tags no-todo)
7164 "Return the heading of the current entry, without the stars.
7165 When NO-TAGS is non-nil, don't include tags.
7166 When NO-TODO is non-nil, don't include TODO keywords."
7167 (save-excursion
7168 (org-back-to-heading t)
7169 (cond
7170 ((and no-tags no-todo)
7171 (looking-at org-complex-heading-regexp)
7172 (match-string 4))
7173 (no-tags
7174 (looking-at (concat org-outline-regexp
7175 "\\(.*?\\)"
7176 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7177 (match-string 1))
7178 (no-todo
7179 (looking-at org-todo-line-regexp)
7180 (match-string 3))
7181 (t (looking-at org-heading-regexp)
7182 (match-string 2)))))
7184 (defun org-heading-components ()
7185 "Return the components of the current heading.
7186 This is a list with the following elements:
7187 - the level as an integer
7188 - the reduced level, different if `org-odd-levels-only' is set.
7189 - the TODO keyword, or nil
7190 - the priority character, like ?A, or nil if no priority is given
7191 - the headline text itself, or the tags string if no headline text
7192 - the tags string, or nil."
7193 (save-excursion
7194 (org-back-to-heading t)
7195 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7196 (list (length (match-string 1))
7197 (org-reduced-level (length (match-string 1)))
7198 (org-match-string-no-properties 2)
7199 (and (match-end 3) (aref (match-string 3) 2))
7200 (org-match-string-no-properties 4)
7201 (org-match-string-no-properties 5)))))
7203 (defun org-get-entry ()
7204 "Get the entry text, after heading, entire subtree."
7205 (save-excursion
7206 (org-back-to-heading t)
7207 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7209 (defun org-insert-heading-after-current ()
7210 "Insert a new heading with same level as current, after current subtree."
7211 (interactive)
7212 (org-back-to-heading)
7213 (org-insert-heading)
7214 (org-move-subtree-down)
7215 (end-of-line 1))
7217 (defun org-insert-heading-respect-content ()
7218 (interactive)
7219 (let ((org-insert-heading-respect-content t))
7220 (org-insert-heading t)))
7222 (defun org-insert-todo-heading-respect-content (&optional force-state)
7223 (interactive "P")
7224 (let ((org-insert-heading-respect-content t))
7225 (org-insert-todo-heading force-state t)))
7227 (defun org-insert-todo-heading (arg &optional force-heading)
7228 "Insert a new heading with the same level and TODO state as current heading.
7229 If the heading has no TODO state, or if the state is DONE, use the first
7230 state (TODO by default). Also with prefix arg, force first state."
7231 (interactive "P")
7232 (when (or force-heading (not (org-insert-item 'checkbox)))
7233 (org-insert-heading force-heading)
7234 (save-excursion
7235 (org-back-to-heading)
7236 (outline-previous-heading)
7237 (looking-at org-todo-line-regexp))
7238 (let*
7239 ((new-mark-x
7240 (if (or arg
7241 (not (match-beginning 2))
7242 (member (match-string 2) org-done-keywords))
7243 (car org-todo-keywords-1)
7244 (match-string 2)))
7245 (new-mark
7247 (run-hook-with-args-until-success
7248 'org-todo-get-default-hook new-mark-x nil)
7249 new-mark-x)))
7250 (beginning-of-line 1)
7251 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7252 (if org-treat-insert-todo-heading-as-state-change
7253 (org-todo new-mark)
7254 (insert new-mark " "))))
7255 (when org-provide-todo-statistics
7256 (org-update-parent-todo-statistics))))
7258 (defun org-insert-subheading (arg)
7259 "Insert a new subheading and demote it.
7260 Works for outline headings and for plain lists alike."
7261 (interactive "P")
7262 (org-insert-heading arg)
7263 (cond
7264 ((org-at-heading-p) (org-do-demote))
7265 ((org-at-item-p) (org-indent-item))))
7267 (defun org-insert-todo-subheading (arg)
7268 "Insert a new subheading with TODO keyword or checkbox and demote it.
7269 Works for outline headings and for plain lists alike."
7270 (interactive "P")
7271 (org-insert-todo-heading arg)
7272 (cond
7273 ((org-at-heading-p) (org-do-demote))
7274 ((org-at-item-p) (org-indent-item))))
7276 ;;; Promotion and Demotion
7278 (defvar org-after-demote-entry-hook nil
7279 "Hook run after an entry has been demoted.
7280 The cursor will be at the beginning of the entry.
7281 When a subtree is being demoted, the hook will be called for each node.")
7283 (defvar org-after-promote-entry-hook nil
7284 "Hook run after an entry has been promoted.
7285 The cursor will be at the beginning of the entry.
7286 When a subtree is being promoted, the hook will be called for each node.")
7288 (defun org-promote-subtree ()
7289 "Promote the entire subtree.
7290 See also `org-promote'."
7291 (interactive)
7292 (save-excursion
7293 (org-with-limited-levels (org-map-tree 'org-promote)))
7294 (org-fix-position-after-promote))
7296 (defun org-demote-subtree ()
7297 "Demote the entire subtree. See `org-demote'.
7298 See also `org-promote'."
7299 (interactive)
7300 (save-excursion
7301 (org-with-limited-levels (org-map-tree 'org-demote)))
7302 (org-fix-position-after-promote))
7305 (defun org-do-promote ()
7306 "Promote the current heading higher up the tree.
7307 If the region is active in `transient-mark-mode', promote all headings
7308 in the region."
7309 (interactive)
7310 (save-excursion
7311 (if (org-region-active-p)
7312 (org-map-region 'org-promote (region-beginning) (region-end))
7313 (org-promote)))
7314 (org-fix-position-after-promote))
7316 (defun org-do-demote ()
7317 "Demote the current heading lower down the tree.
7318 If the region is active in `transient-mark-mode', demote all headings
7319 in the region."
7320 (interactive)
7321 (save-excursion
7322 (if (org-region-active-p)
7323 (org-map-region 'org-demote (region-beginning) (region-end))
7324 (org-demote)))
7325 (org-fix-position-after-promote))
7327 (defun org-fix-position-after-promote ()
7328 "Make sure that after pro/demotion cursor position is right."
7329 (let ((pos (point)))
7330 (when (save-excursion
7331 (beginning-of-line 1)
7332 (looking-at org-todo-line-regexp)
7333 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7334 (cond ((eobp) (insert " "))
7335 ((eolp) (insert " "))
7336 ((equal (char-after) ?\ ) (forward-char 1))))))
7338 (defun org-current-level ()
7339 "Return the level of the current entry, or nil if before the first headline.
7340 The level is the number of stars at the beginning of the headline."
7341 (save-excursion
7342 (org-with-limited-levels
7343 (if (ignore-errors (org-back-to-heading t))
7344 (funcall outline-level)))))
7346 (defun org-get-previous-line-level ()
7347 "Return the outline depth of the last headline before the current line.
7348 Returns 0 for the first headline in the buffer, and nil if before the
7349 first headline."
7350 (let ((current-level (org-current-level))
7351 (prev-level (when (> (line-number-at-pos) 1)
7352 (save-excursion
7353 (beginning-of-line 0)
7354 (org-current-level)))))
7355 (cond ((null current-level) nil) ; Before first headline
7356 ((null prev-level) 0) ; At first headline
7357 (prev-level))))
7359 (defun org-reduced-level (l)
7360 "Compute the effective level of a heading.
7361 This takes into account the setting of `org-odd-levels-only'."
7362 (cond
7363 ((zerop l) 0)
7364 (org-odd-levels-only (1+ (floor (/ l 2))))
7365 (t l)))
7367 (defun org-level-increment ()
7368 "Return the number of stars that will be added or removed at a
7369 time to headlines when structure editing, based on the value of
7370 `org-odd-levels-only'."
7371 (if org-odd-levels-only 2 1))
7373 (defun org-get-valid-level (level &optional change)
7374 "Rectify a level change under the influence of `org-odd-levels-only'
7375 LEVEL is a current level, CHANGE is by how much the level should be
7376 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7377 even level numbers will become the next higher odd number."
7378 (if org-odd-levels-only
7379 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7380 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7381 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7382 (max 1 (+ level (or change 0)))))
7384 (if (boundp 'define-obsolete-function-alias)
7385 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7386 (define-obsolete-function-alias 'org-get-legal-level
7387 'org-get-valid-level)
7388 (define-obsolete-function-alias 'org-get-legal-level
7389 'org-get-valid-level "23.1")))
7391 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7392 ;; ̀org-with-limited-levels'
7393 (defun org-promote ()
7394 "Promote the current heading higher up the tree.
7395 If the region is active in `transient-mark-mode', promote all headings
7396 in the region."
7397 (org-back-to-heading t)
7398 (let* ((level (save-match-data (funcall outline-level)))
7399 (after-change-functions (remove 'flyspell-after-change-function
7400 after-change-functions))
7401 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7402 (diff (abs (- level (length up-head) -1))))
7403 (cond ((and (= level 1) org-called-with-limited-levels
7404 org-allow-promoting-top-level-subtree)
7405 (replace-match "# " nil t))
7406 ((= level 1)
7407 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7408 (t (replace-match up-head nil t)))
7409 ;; Fixup tag positioning
7410 (unless (= level 1)
7411 (and org-auto-align-tags (org-set-tags nil t))
7412 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7413 (run-hooks 'org-after-promote-entry-hook)))
7415 (defun org-demote ()
7416 "Demote the current heading lower down the tree.
7417 If the region is active in `transient-mark-mode', demote all headings
7418 in the region."
7419 (org-back-to-heading t)
7420 (let* ((level (save-match-data (funcall outline-level)))
7421 (after-change-functions (remove 'flyspell-after-change-function
7422 after-change-functions))
7423 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7424 (diff (abs (- level (length down-head) -1))))
7425 (replace-match down-head nil t)
7426 ;; Fixup tag positioning
7427 (and org-auto-align-tags (org-set-tags nil t))
7428 (if org-adapt-indentation (org-fixup-indentation diff))
7429 (run-hooks 'org-after-demote-entry-hook)))
7431 (defun org-cycle-level ()
7432 "Cycle the level of an empty headline through possible states.
7433 This goes first to child, then to parent, level, then up the hierarchy.
7434 After top level, it switches back to sibling level."
7435 (interactive)
7436 (let ((org-adapt-indentation nil))
7437 (when (org-point-at-end-of-empty-headline)
7438 (setq this-command 'org-cycle-level) ; Only needed for caching
7439 (let ((cur-level (org-current-level))
7440 (prev-level (org-get-previous-line-level)))
7441 (cond
7442 ;; If first headline in file, promote to top-level.
7443 ((= prev-level 0)
7444 (loop repeat (/ (- cur-level 1) (org-level-increment))
7445 do (org-do-promote)))
7446 ;; If same level as prev, demote one.
7447 ((= prev-level cur-level)
7448 (org-do-demote))
7449 ;; If parent is top-level, promote to top level if not already.
7450 ((= prev-level 1)
7451 (loop repeat (/ (- cur-level 1) (org-level-increment))
7452 do (org-do-promote)))
7453 ;; If top-level, return to prev-level.
7454 ((= cur-level 1)
7455 (loop repeat (/ (- prev-level 1) (org-level-increment))
7456 do (org-do-demote)))
7457 ;; If less than prev-level, promote one.
7458 ((< cur-level prev-level)
7459 (org-do-promote))
7460 ;; If deeper than prev-level, promote until higher than
7461 ;; prev-level.
7462 ((> cur-level prev-level)
7463 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7464 do (org-do-promote))))
7465 t))))
7467 (defun org-map-tree (fun)
7468 "Call FUN for every heading underneath the current one."
7469 (org-back-to-heading)
7470 (let ((level (funcall outline-level)))
7471 (save-excursion
7472 (funcall fun)
7473 (while (and (progn
7474 (outline-next-heading)
7475 (> (funcall outline-level) level))
7476 (not (eobp)))
7477 (funcall fun)))))
7479 (defun org-map-region (fun beg end)
7480 "Call FUN for every heading between BEG and END."
7481 (let ((org-ignore-region t))
7482 (save-excursion
7483 (setq end (copy-marker end))
7484 (goto-char beg)
7485 (if (and (re-search-forward org-outline-regexp-bol nil t)
7486 (< (point) end))
7487 (funcall fun))
7488 (while (and (progn
7489 (outline-next-heading)
7490 (< (point) end))
7491 (not (eobp)))
7492 (funcall fun)))))
7494 (defvar org-property-end-re) ; silence byte-compiler
7495 (defun org-fixup-indentation (diff)
7496 "Change the indentation in the current entry by DIFF.
7497 However, if any line in the current entry has no indentation, or if it
7498 would end up with no indentation after the change, nothing at all is done."
7499 (save-excursion
7500 (let ((end (save-excursion (outline-next-heading)
7501 (point-marker)))
7502 (prohibit (if (> diff 0)
7503 "^\\S-"
7504 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7505 col)
7506 (unless (save-excursion (end-of-line 1)
7507 (re-search-forward prohibit end t))
7508 (while (and (< (point) end)
7509 (re-search-forward "^[ \t]+" end t))
7510 (goto-char (match-end 0))
7511 (setq col (current-column))
7512 (if (< diff 0) (replace-match ""))
7513 (org-indent-to-column (+ diff col))))
7514 (move-marker end nil))))
7516 (defun org-convert-to-odd-levels ()
7517 "Convert an org-mode file with all levels allowed to one with odd levels.
7518 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7519 level 5 etc."
7520 (interactive)
7521 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7522 (let ((outline-level 'org-outline-level)
7523 (org-odd-levels-only nil) n)
7524 (save-excursion
7525 (goto-char (point-min))
7526 (while (re-search-forward "^\\*\\*+ " nil t)
7527 (setq n (- (length (match-string 0)) 2))
7528 (while (>= (setq n (1- n)) 0)
7529 (org-demote))
7530 (end-of-line 1))))))
7532 (defun org-convert-to-oddeven-levels ()
7533 "Convert an org-mode file with only odd levels to one with odd/even levels.
7534 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7535 file contains a section with an even level, conversion would
7536 destroy the structure of the file. An error is signaled in this
7537 case."
7538 (interactive)
7539 (goto-char (point-min))
7540 ;; First check if there are no even levels
7541 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7542 (org-show-context t)
7543 (error "Not all levels are odd in this file. Conversion not possible"))
7544 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7545 (let ((outline-regexp org-outline-regexp)
7546 (outline-level 'org-outline-level)
7547 (org-odd-levels-only nil) n)
7548 (save-excursion
7549 (goto-char (point-min))
7550 (while (re-search-forward "^\\*\\*+ " nil t)
7551 (setq n (/ (1- (length (match-string 0))) 2))
7552 (while (>= (setq n (1- n)) 0)
7553 (org-promote))
7554 (end-of-line 1))))))
7556 (defun org-tr-level (n)
7557 "Make N odd if required."
7558 (if org-odd-levels-only (1+ (/ n 2)) n))
7560 ;;; Vertical tree motion, cutting and pasting of subtrees
7562 (defun org-move-subtree-up (&optional arg)
7563 "Move the current subtree up past ARG headlines of the same level."
7564 (interactive "p")
7565 (org-move-subtree-down (- (prefix-numeric-value arg))))
7567 (defun org-move-subtree-down (&optional arg)
7568 "Move the current subtree down past ARG headlines of the same level."
7569 (interactive "p")
7570 (setq arg (prefix-numeric-value arg))
7571 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7572 'org-get-last-sibling))
7573 (ins-point (make-marker))
7574 (cnt (abs arg))
7575 (col (current-column))
7576 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7577 ;; Select the tree
7578 (org-back-to-heading)
7579 (setq beg0 (point))
7580 (save-excursion
7581 (setq ne-beg (org-back-over-empty-lines))
7582 (setq beg (point)))
7583 (save-match-data
7584 (save-excursion (outline-end-of-heading)
7585 (setq folded (outline-invisible-p)))
7586 (outline-end-of-subtree))
7587 (outline-next-heading)
7588 (setq ne-end (org-back-over-empty-lines))
7589 (setq end (point))
7590 (goto-char beg0)
7591 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7592 ;; include less whitespace
7593 (save-excursion
7594 (goto-char beg)
7595 (forward-line (- ne-beg ne-end))
7596 (setq beg (point))))
7597 ;; Find insertion point, with error handling
7598 (while (> cnt 0)
7599 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7600 (progn (goto-char beg0)
7601 (error "Cannot move past superior level or buffer limit")))
7602 (setq cnt (1- cnt)))
7603 (if (> arg 0)
7604 ;; Moving forward - still need to move over subtree
7605 (progn (org-end-of-subtree t t)
7606 (save-excursion
7607 (org-back-over-empty-lines)
7608 (or (bolp) (newline)))))
7609 (setq ne-ins (org-back-over-empty-lines))
7610 (move-marker ins-point (point))
7611 (setq txt (buffer-substring beg end))
7612 (org-save-markers-in-region beg end)
7613 (delete-region beg end)
7614 (org-remove-empty-overlays-at beg)
7615 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7616 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7617 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7618 (let ((bbb (point)))
7619 (insert-before-markers txt)
7620 (org-reinstall-markers-in-region bbb)
7621 (move-marker ins-point bbb))
7622 (or (bolp) (insert "\n"))
7623 (setq ins-end (point))
7624 (goto-char ins-point)
7625 (org-skip-whitespace)
7626 (when (and (< arg 0)
7627 (org-first-sibling-p)
7628 (> ne-ins ne-beg))
7629 ;; Move whitespace back to beginning
7630 (save-excursion
7631 (goto-char ins-end)
7632 (let ((kill-whole-line t))
7633 (kill-line (- ne-ins ne-beg)) (point)))
7634 (insert (make-string (- ne-ins ne-beg) ?\n)))
7635 (move-marker ins-point nil)
7636 (if folded
7637 (hide-subtree)
7638 (org-show-entry)
7639 (show-children)
7640 (org-cycle-hide-drawers 'children))
7641 (org-clean-visibility-after-subtree-move)
7642 ;; move back to the initial column we were at
7643 (move-to-column col)))
7645 (defvar org-subtree-clip ""
7646 "Clipboard for cut and paste of subtrees.
7647 This is actually only a copy of the kill, because we use the normal kill
7648 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7650 (defvar org-subtree-clip-folded nil
7651 "Was the last copied subtree folded?
7652 This is used to fold the tree back after pasting.")
7654 (defun org-cut-subtree (&optional n)
7655 "Cut the current subtree into the clipboard.
7656 With prefix arg N, cut this many sequential subtrees.
7657 This is a short-hand for marking the subtree and then cutting it."
7658 (interactive "p")
7659 (org-copy-subtree n 'cut))
7661 (defun org-copy-subtree (&optional n cut force-store-markers)
7662 "Cut the current subtree into the clipboard.
7663 With prefix arg N, cut this many sequential subtrees.
7664 This is a short-hand for marking the subtree and then copying it.
7665 If CUT is non-nil, actually cut the subtree.
7666 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7667 of some markers in the region, even if CUT is non-nil. This is
7668 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7669 (interactive "p")
7670 (let (beg end folded (beg0 (point)))
7671 (if (org-called-interactively-p 'any)
7672 (org-back-to-heading nil) ; take what looks like a subtree
7673 (org-back-to-heading t)) ; take what is really there
7674 (setq beg (point))
7675 (skip-chars-forward " \t\r\n")
7676 (save-match-data
7677 (save-excursion (outline-end-of-heading)
7678 (setq folded (outline-invisible-p)))
7679 (condition-case nil
7680 (org-forward-heading-same-level (1- n) t)
7681 (error nil))
7682 (org-end-of-subtree t t))
7683 (setq end (point))
7684 (goto-char beg0)
7685 (when (> end beg)
7686 (setq org-subtree-clip-folded folded)
7687 (when (or cut force-store-markers)
7688 (org-save-markers-in-region beg end))
7689 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7690 (setq org-subtree-clip (current-kill 0))
7691 (message "%s: Subtree(s) with %d characters"
7692 (if cut "Cut" "Copied")
7693 (length org-subtree-clip)))))
7695 (defun org-paste-subtree (&optional level tree for-yank)
7696 "Paste the clipboard as a subtree, with modification of headline level.
7697 The entire subtree is promoted or demoted in order to match a new headline
7698 level.
7700 If the cursor is at the beginning of a headline, the same level as
7701 that headline is used to paste the tree
7703 If not, the new level is derived from the *visible* headings
7704 before and after the insertion point, and taken to be the inferior headline
7705 level of the two. So if the previous visible heading is level 3 and the
7706 next is level 4 (or vice versa), level 4 will be used for insertion.
7707 This makes sure that the subtree remains an independent subtree and does
7708 not swallow low level entries.
7710 You can also force a different level, either by using a numeric prefix
7711 argument, or by inserting the heading marker by hand. For example, if the
7712 cursor is after \"*****\", then the tree will be shifted to level 5.
7714 If optional TREE is given, use this text instead of the kill ring.
7716 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7717 move back over whitespace before inserting, and move point to the end of
7718 the inserted text when done."
7719 (interactive "P")
7720 (setq tree (or tree (and kill-ring (current-kill 0))))
7721 (unless (org-kill-is-subtree-p tree)
7722 (error "%s"
7723 (substitute-command-keys
7724 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7725 (org-with-limited-levels
7726 (let* ((visp (not (outline-invisible-p)))
7727 (txt tree)
7728 (^re_ "\\(\\*+\\)[ \t]*")
7729 (old-level (if (string-match org-outline-regexp-bol txt)
7730 (- (match-end 0) (match-beginning 0) 1)
7731 -1))
7732 (force-level (cond (level (prefix-numeric-value level))
7733 ((and (looking-at "[ \t]*$")
7734 (string-match
7735 "^\\*+$" (buffer-substring
7736 (point-at-bol) (point))))
7737 (- (match-end 1) (match-beginning 1)))
7738 ((and (bolp)
7739 (looking-at org-outline-regexp))
7740 (- (match-end 0) (point) 1))))
7741 (previous-level (save-excursion
7742 (condition-case nil
7743 (progn
7744 (outline-previous-visible-heading 1)
7745 (if (looking-at ^re_)
7746 (- (match-end 0) (match-beginning 0) 1)
7748 (error 1))))
7749 (next-level (save-excursion
7750 (condition-case nil
7751 (progn
7752 (or (looking-at org-outline-regexp)
7753 (outline-next-visible-heading 1))
7754 (if (looking-at ^re_)
7755 (- (match-end 0) (match-beginning 0) 1)
7757 (error 1))))
7758 (new-level (or force-level (max previous-level next-level)))
7759 (shift (if (or (= old-level -1)
7760 (= new-level -1)
7761 (= old-level new-level))
7763 (- new-level old-level)))
7764 (delta (if (> shift 0) -1 1))
7765 (func (if (> shift 0) 'org-demote 'org-promote))
7766 (org-odd-levels-only nil)
7767 beg end newend)
7768 ;; Remove the forced level indicator
7769 (if force-level
7770 (delete-region (point-at-bol) (point)))
7771 ;; Paste
7772 (beginning-of-line (if (bolp) 1 2))
7773 (setq beg (point))
7774 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7775 (insert-before-markers txt)
7776 (unless (string-match "\n\\'" txt) (insert "\n"))
7777 (setq newend (point))
7778 (org-reinstall-markers-in-region beg)
7779 (setq end (point))
7780 (goto-char beg)
7781 (skip-chars-forward " \t\n\r")
7782 (setq beg (point))
7783 (if (and (outline-invisible-p) visp)
7784 (save-excursion (outline-show-heading)))
7785 ;; Shift if necessary
7786 (unless (= shift 0)
7787 (save-restriction
7788 (narrow-to-region beg end)
7789 (while (not (= shift 0))
7790 (org-map-region func (point-min) (point-max))
7791 (setq shift (+ delta shift)))
7792 (goto-char (point-min))
7793 (setq newend (point-max))))
7794 (when (or (org-called-interactively-p 'interactive) for-yank)
7795 (message "Clipboard pasted as level %d subtree" new-level))
7796 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7797 kill-ring
7798 (eq org-subtree-clip (current-kill 0))
7799 org-subtree-clip-folded)
7800 ;; The tree was folded before it was killed/copied
7801 (hide-subtree))
7802 (and for-yank (goto-char newend)))))
7804 (defun org-kill-is-subtree-p (&optional txt)
7805 "Check if the current kill is an outline subtree, or a set of trees.
7806 Returns nil if kill does not start with a headline, or if the first
7807 headline level is not the largest headline level in the tree.
7808 So this will actually accept several entries of equal levels as well,
7809 which is OK for `org-paste-subtree'.
7810 If optional TXT is given, check this string instead of the current kill."
7811 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7812 (re (org-get-limited-outline-regexp))
7813 (^re (concat "^" re))
7814 (start-level (and kill
7815 (string-match
7816 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7817 kill)
7818 (- (match-end 2) (match-beginning 2) 1)))
7819 (start (1+ (or (match-beginning 2) -1))))
7820 (if (not start-level)
7821 (progn
7822 nil) ;; does not even start with a heading
7823 (catch 'exit
7824 (while (setq start (string-match ^re kill (1+ start)))
7825 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7826 (throw 'exit nil)))
7827 t))))
7829 (defvar org-markers-to-move nil
7830 "Markers that should be moved with a cut-and-paste operation.
7831 Those markers are stored together with their positions relative to
7832 the start of the region.")
7834 (defun org-save-markers-in-region (beg end)
7835 "Check markers in region.
7836 If these markers are between BEG and END, record their position relative
7837 to BEG, so that after moving the block of text, we can put the markers back
7838 into place.
7839 This function gets called just before an entry or tree gets cut from the
7840 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7841 called immediately, to move the markers with the entries."
7842 (setq org-markers-to-move nil)
7843 (when (featurep 'org-clock)
7844 (org-clock-save-markers-for-cut-and-paste beg end))
7845 (when (featurep 'org-agenda)
7846 (org-agenda-save-markers-for-cut-and-paste beg end)))
7848 (defun org-check-and-save-marker (marker beg end)
7849 "Check if MARKER is between BEG and END.
7850 If yes, remember the marker and the distance to BEG."
7851 (when (and (marker-buffer marker)
7852 (equal (marker-buffer marker) (current-buffer)))
7853 (if (and (>= marker beg) (< marker end))
7854 (push (cons marker (- marker beg)) org-markers-to-move))))
7856 (defun org-reinstall-markers-in-region (beg)
7857 "Move all remembered markers to their position relative to BEG."
7858 (mapc (lambda (x)
7859 (move-marker (car x) (+ beg (cdr x))))
7860 org-markers-to-move)
7861 (setq org-markers-to-move nil))
7863 (defun org-narrow-to-subtree ()
7864 "Narrow buffer to the current subtree."
7865 (interactive)
7866 (save-excursion
7867 (save-match-data
7868 (org-with-limited-levels
7869 (narrow-to-region
7870 (progn (org-back-to-heading t) (point))
7871 (progn (org-end-of-subtree t t)
7872 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7873 (point)))))))
7875 (defun org-narrow-to-block ()
7876 "Narrow buffer to the current block."
7877 (interactive)
7878 (let* ((case-fold-search t)
7879 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7880 "^[ \t]*#\\+end_.*")))
7881 (if blockp
7882 (narrow-to-region (car blockp) (cdr blockp))
7883 (error "Not in a block"))))
7885 (eval-when-compile
7886 (defvar org-property-drawer-re))
7888 (defvar org-property-start-re) ;; defined below
7889 (defun org-clone-subtree-with-time-shift (n &optional shift)
7890 "Clone the task (subtree) at point N times.
7891 The clones will be inserted as siblings.
7893 In interactive use, the user will be prompted for the number of
7894 clones to be produced, and for a time SHIFT, which may be a
7895 repeater as used in time stamps, for example `+3d'.
7897 When a valid repeater is given and the entry contains any time
7898 stamps, the clones will become a sequence in time, with time
7899 stamps in the subtree shifted for each clone produced. If SHIFT
7900 is nil or the empty string, time stamps will be left alone. The
7901 ID property of the original subtree is removed.
7903 If the original subtree did contain time stamps with a repeater,
7904 the following will happen:
7905 - the repeater will be removed in each clone
7906 - an additional clone will be produced, with the current, unshifted
7907 date(s) in the entry.
7908 - the original entry will be placed *after* all the clones, with
7909 repeater intact.
7910 - the start days in the repeater in the original entry will be shifted
7911 to past the last clone.
7912 In this way you can spell out a number of instances of a repeating task,
7913 and still retain the repeater to cover future instances of the task."
7914 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7915 (let (beg end template task idprop
7916 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7917 (drawer-re org-drawer-regexp))
7918 (if (not (and (integerp n) (> n 0)))
7919 (error "Invalid number of replications %s" n))
7920 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7921 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7922 shift)))
7923 (error "Invalid shift specification %s" shift))
7924 (when doshift
7925 (setq shift-n (string-to-number (match-string 1 shift))
7926 shift-what (cdr (assoc (match-string 2 shift)
7927 '(("d" . day) ("w" . week)
7928 ("m" . month) ("y" . year))))))
7929 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7930 (setq nmin 1 nmax n)
7931 (org-back-to-heading t)
7932 (setq beg (point))
7933 (setq idprop (org-entry-get nil "ID"))
7934 (org-end-of-subtree t t)
7935 (or (bolp) (insert "\n"))
7936 (setq end (point))
7937 (setq template (buffer-substring beg end))
7938 (when (and doshift
7939 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7940 (delete-region beg end)
7941 (setq end beg)
7942 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7943 (goto-char end)
7944 (loop for n from nmin to nmax do
7945 ;; prepare clone
7946 (with-temp-buffer
7947 (insert template)
7948 (org-mode)
7949 (goto-char (point-min))
7950 (org-show-subtree)
7951 (and idprop (if org-clone-delete-id
7952 (org-entry-delete nil "ID")
7953 (org-id-get-create t)))
7954 (unless (= n 0)
7955 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7956 (kill-whole-line))
7957 (goto-char (point-min))
7958 (while (re-search-forward drawer-re nil t)
7959 (mapc (lambda (d)
7960 (org-remove-empty-drawer-at d (point))) org-drawers)))
7961 (goto-char (point-min))
7962 (when doshift
7963 (while (re-search-forward org-ts-regexp-both nil t)
7964 (org-timestamp-change (* n shift-n) shift-what))
7965 (unless (= n n-no-remove)
7966 (goto-char (point-min))
7967 (while (re-search-forward org-ts-regexp nil t)
7968 (save-excursion
7969 (goto-char (match-beginning 0))
7970 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7971 (delete-region (match-beginning 1) (match-end 1)))))))
7972 (setq task (buffer-string)))
7973 (insert task))
7974 (goto-char beg)))
7976 ;;; Outline Sorting
7978 (defun org-sort (with-case)
7979 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7980 Optional argument WITH-CASE means sort case-sensitively."
7981 (interactive "P")
7982 (cond
7983 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7984 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7986 (org-call-with-arg 'org-sort-entries with-case))))
7988 (defun org-sort-remove-invisible (s)
7989 (remove-text-properties 0 (length s) org-rm-props s)
7990 (while (string-match org-bracket-link-regexp s)
7991 (setq s (replace-match (if (match-end 2)
7992 (match-string 3 s)
7993 (match-string 1 s)) t t s)))
7996 (defvar org-priority-regexp) ; defined later in the file
7998 (defvar org-after-sorting-entries-or-items-hook nil
7999 "Hook that is run after a bunch of entries or items have been sorted.
8000 When children are sorted, the cursor is in the parent line when this
8001 hook gets called. When a region or a plain list is sorted, the cursor
8002 will be in the first entry of the sorted region/list.")
8004 (defun org-sort-entries
8005 (&optional with-case sorting-type getkey-func compare-func property)
8006 "Sort entries on a certain level of an outline tree.
8007 If there is an active region, the entries in the region are sorted.
8008 Else, if the cursor is before the first entry, sort the top-level items.
8009 Else, the children of the entry at point are sorted.
8011 Sorting can be alphabetically, numerically, by date/time as given by
8012 a time stamp, by a property or by priority.
8014 The command prompts for the sorting type unless it has been given to the
8015 function through the SORTING-TYPE argument, which needs to be a character,
8016 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8017 precise meaning of each character:
8019 n Numerically, by converting the beginning of the entry/item to a number.
8020 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8021 o By order of TODO keywords.
8022 t By date/time, either the first active time stamp in the entry, or, if
8023 none exist, by the first inactive one.
8024 s By the scheduled date/time.
8025 d By deadline date/time.
8026 c By creation time, which is assumed to be the first inactive time stamp
8027 at the beginning of a line.
8028 p By priority according to the cookie.
8029 r By the value of a property.
8031 Capital letters will reverse the sort order.
8033 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8034 called with point at the beginning of the record. It must return either
8035 a string or a number that should serve as the sorting key for that record.
8037 Comparing entries ignores case by default. However, with an optional argument
8038 WITH-CASE, the sorting considers case as well."
8039 (interactive "P")
8040 (let ((case-func (if with-case 'identity 'downcase))
8041 (cmstr
8042 ;; The clock marker is lost when using `sort-subr', let's
8043 ;; store the clocking string.
8044 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8045 (save-excursion
8046 (goto-char org-clock-marker)
8047 (looking-back "^.*") (match-string-no-properties 0))))
8048 start beg end stars re re2
8049 txt what tmp)
8050 ;; Find beginning and end of region to sort
8051 (cond
8052 ((org-region-active-p)
8053 ;; we will sort the region
8054 (setq end (region-end)
8055 what "region")
8056 (goto-char (region-beginning))
8057 (if (not (org-at-heading-p)) (outline-next-heading))
8058 (setq start (point)))
8059 ((or (org-at-heading-p)
8060 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8061 ;; we will sort the children of the current headline
8062 (org-back-to-heading)
8063 (setq start (point)
8064 end (progn (org-end-of-subtree t t)
8065 (or (bolp) (insert "\n"))
8066 (org-back-over-empty-lines)
8067 (point))
8068 what "children")
8069 (goto-char start)
8070 (show-subtree)
8071 (outline-next-heading))
8073 ;; we will sort the top-level entries in this file
8074 (goto-char (point-min))
8075 (or (org-at-heading-p) (outline-next-heading))
8076 (setq start (point))
8077 (goto-char (point-max))
8078 (beginning-of-line 1)
8079 (when (looking-at ".*?\\S-")
8080 ;; File ends in a non-white line
8081 (end-of-line 1)
8082 (insert "\n"))
8083 (setq end (point-max))
8084 (setq what "top-level")
8085 (goto-char start)
8086 (show-all)))
8088 (setq beg (point))
8089 (if (>= beg end) (error "Nothing to sort"))
8091 (looking-at "\\(\\*+\\)")
8092 (setq stars (match-string 1)
8093 re (concat "^" (regexp-quote stars) " +")
8094 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8095 txt (buffer-substring beg end))
8096 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8097 (if (and (not (equal stars "*")) (string-match re2 txt))
8098 (error "Region to sort contains a level above the first entry"))
8100 (unless sorting-type
8101 (message
8102 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8103 [t]ime [s]cheduled [d]eadline [c]reated
8104 A/N/P/R/O/F/T/S/D/C means reversed:"
8105 what)
8106 (setq sorting-type (read-char-exclusive))
8108 (and (= (downcase sorting-type) ?f)
8109 (setq getkey-func
8110 (org-icompleting-read "Sort using function: "
8111 obarray 'fboundp t nil nil))
8112 (setq getkey-func (intern getkey-func)))
8114 (and (= (downcase sorting-type) ?r)
8115 (setq property
8116 (org-icompleting-read "Property: "
8117 (mapcar 'list (org-buffer-property-keys t))
8118 nil t))))
8120 (message "Sorting entries...")
8122 (save-restriction
8123 (narrow-to-region start end)
8124 (let ((dcst (downcase sorting-type))
8125 (case-fold-search nil)
8126 (now (current-time)))
8127 (sort-subr
8128 (/= dcst sorting-type)
8129 ;; This function moves to the beginning character of the "record" to
8130 ;; be sorted.
8131 (lambda nil
8132 (if (re-search-forward re nil t)
8133 (goto-char (match-beginning 0))
8134 (goto-char (point-max))))
8135 ;; This function moves to the last character of the "record" being
8136 ;; sorted.
8137 (lambda nil
8138 (save-match-data
8139 (condition-case nil
8140 (outline-forward-same-level 1)
8141 (error
8142 (goto-char (point-max))))))
8143 ;; This function returns the value that gets sorted against.
8144 (lambda nil
8145 (cond
8146 ((= dcst ?n)
8147 (if (looking-at org-complex-heading-regexp)
8148 (string-to-number (match-string 4))
8149 nil))
8150 ((= dcst ?a)
8151 (if (looking-at org-complex-heading-regexp)
8152 (funcall case-func (match-string 4))
8153 nil))
8154 ((= dcst ?t)
8155 (let ((end (save-excursion (outline-next-heading) (point))))
8156 (if (or (re-search-forward org-ts-regexp end t)
8157 (re-search-forward org-ts-regexp-both end t))
8158 (org-time-string-to-seconds (match-string 0))
8159 (org-float-time now))))
8160 ((= dcst ?c)
8161 (let ((end (save-excursion (outline-next-heading) (point))))
8162 (if (re-search-forward
8163 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8164 end t)
8165 (org-time-string-to-seconds (match-string 0))
8166 (org-float-time now))))
8167 ((= dcst ?s)
8168 (let ((end (save-excursion (outline-next-heading) (point))))
8169 (if (re-search-forward org-scheduled-time-regexp end t)
8170 (org-time-string-to-seconds (match-string 1))
8171 (org-float-time now))))
8172 ((= dcst ?d)
8173 (let ((end (save-excursion (outline-next-heading) (point))))
8174 (if (re-search-forward org-deadline-time-regexp end t)
8175 (org-time-string-to-seconds (match-string 1))
8176 (org-float-time now))))
8177 ((= dcst ?p)
8178 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8179 (string-to-char (match-string 2))
8180 org-default-priority))
8181 ((= dcst ?r)
8182 (or (org-entry-get nil property) ""))
8183 ((= dcst ?o)
8184 (if (looking-at org-complex-heading-regexp)
8185 (- 9999 (length (member (match-string 2)
8186 org-todo-keywords-1)))))
8187 ((= dcst ?f)
8188 (if getkey-func
8189 (progn
8190 (setq tmp (funcall getkey-func))
8191 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8192 tmp)
8193 (error "Invalid key function `%s'" getkey-func)))
8194 (t (error "Invalid sorting type `%c'" sorting-type))))
8196 (cond
8197 ((= dcst ?a) 'string<)
8198 ((= dcst ?f) compare-func)
8199 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8200 (run-hooks 'org-after-sorting-entries-or-items-hook)
8201 ;; Reset the clock marker if needed
8202 (when cmstr
8203 (save-excursion
8204 (goto-char start)
8205 (search-forward cmstr nil t)
8206 (move-marker org-clock-marker (point))))
8207 (message "Sorting entries...done")))
8209 (defun org-do-sort (table what &optional with-case sorting-type)
8210 "Sort TABLE of WHAT according to SORTING-TYPE.
8211 The user will be prompted for the SORTING-TYPE if the call to this
8212 function does not specify it. WHAT is only for the prompt, to indicate
8213 what is being sorted. The sorting key will be extracted from
8214 the car of the elements of the table.
8215 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8216 (unless sorting-type
8217 (message
8218 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8219 what)
8220 (setq sorting-type (read-char-exclusive)))
8221 (let ((dcst (downcase sorting-type))
8222 extractfun comparefun)
8223 ;; Define the appropriate functions
8224 (cond
8225 ((= dcst ?n)
8226 (setq extractfun 'string-to-number
8227 comparefun (if (= dcst sorting-type) '< '>)))
8228 ((= dcst ?a)
8229 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8230 (lambda(x) (downcase (org-sort-remove-invisible x))))
8231 comparefun (if (= dcst sorting-type)
8232 'string<
8233 (lambda (a b) (and (not (string< a b))
8234 (not (string= a b)))))))
8235 ((= dcst ?t)
8236 (setq extractfun
8237 (lambda (x)
8238 (if (or (string-match org-ts-regexp x)
8239 (string-match org-ts-regexp-both x))
8240 (org-float-time
8241 (org-time-string-to-time (match-string 0 x)))
8243 comparefun (if (= dcst sorting-type) '< '>)))
8244 (t (error "Invalid sorting type `%c'" sorting-type)))
8246 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8247 table)
8248 (lambda (a b) (funcall comparefun (car a) (car b))))))
8251 ;;; The orgstruct minor mode
8253 ;; Define a minor mode which can be used in other modes in order to
8254 ;; integrate the org-mode structure editing commands.
8256 ;; This is really a hack, because the org-mode structure commands use
8257 ;; keys which normally belong to the major mode. Here is how it
8258 ;; works: The minor mode defines all the keys necessary to operate the
8259 ;; structure commands, but wraps the commands into a function which
8260 ;; tests if the cursor is currently at a headline or a plain list
8261 ;; item. If that is the case, the structure command is used,
8262 ;; temporarily setting many Org-mode variables like regular
8263 ;; expressions for filling etc. However, when any of those keys is
8264 ;; used at a different location, function uses `key-binding' to look
8265 ;; up if the key has an associated command in another currently active
8266 ;; keymap (minor modes, major mode, global), and executes that
8267 ;; command. There might be problems if any of the keys is otherwise
8268 ;; used as a prefix key.
8270 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8271 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8272 ;; addresses this by checking explicitly for both bindings.
8274 (defvar orgstruct-mode-map (make-sparse-keymap)
8275 "Keymap for the minor `orgstruct-mode'.")
8277 (defvar org-local-vars nil
8278 "List of local variables, for use by `orgstruct-mode'.")
8280 ;;;###autoload
8281 (define-minor-mode orgstruct-mode
8282 "Toggle the minor mode `orgstruct-mode'.
8283 This mode is for using Org-mode structure commands in other
8284 modes. The following keys behave as if Org-mode were active, if
8285 the cursor is on a headline, or on a plain list item (both as
8286 defined by Org-mode).
8288 M-up Move entry/item up
8289 M-down Move entry/item down
8290 M-left Promote
8291 M-right Demote
8292 M-S-up Move entry/item up
8293 M-S-down Move entry/item down
8294 M-S-left Promote subtree
8295 M-S-right Demote subtree
8296 M-q Fill paragraph and items like in Org-mode
8297 C-c ^ Sort entries
8298 C-c - Cycle list bullet
8299 TAB Cycle item visibility
8300 M-RET Insert new heading/item
8301 S-M-RET Insert new TODO heading / Checkbox item
8302 C-c C-c Set tags / toggle checkbox"
8303 nil " OrgStruct" nil
8304 (org-load-modules-maybe)
8305 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8307 ;;;###autoload
8308 (defun turn-on-orgstruct ()
8309 "Unconditionally turn on `orgstruct-mode'."
8310 (orgstruct-mode 1))
8312 (defvar org-fb-vars nil)
8313 (make-variable-buffer-local 'org-fb-vars)
8314 (defun orgstruct++-mode (&optional arg)
8315 "Toggle `orgstruct-mode', the enhanced version of it.
8316 In addition to setting orgstruct-mode, this also exports all
8317 indentation and autofilling variables from org-mode into the
8318 buffer. It will also recognize item context in multiline items."
8319 (interactive "P")
8320 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8321 (if (< arg 1)
8322 (progn (orgstruct-mode -1)
8323 (mapc (lambda(v)
8324 (org-set-local (car v)
8325 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8326 org-fb-vars))
8327 (orgstruct-mode 1)
8328 (setq org-fb-vars nil)
8329 (let (var val)
8330 (mapc
8331 (lambda (x)
8332 (when (string-match
8333 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8334 (symbol-name (car x)))
8335 (setq var (car x) val (nth 1 x))
8336 (push (list var `(quote ,(eval var))) org-fb-vars)
8337 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8338 org-local-vars)
8339 (org-set-local 'orgstruct-is-++ t))))
8341 (defvar orgstruct-is-++ nil
8342 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8343 (make-variable-buffer-local 'orgstruct-is-++)
8345 ;;;###autoload
8346 (defun turn-on-orgstruct++ ()
8347 "Unconditionally turn on `orgstruct++-mode'."
8348 (orgstruct++-mode 1))
8350 (defun orgstruct-error ()
8351 "Error when there is no default binding for a structure key."
8352 (interactive)
8353 (error "This key has no function outside structure elements"))
8355 (defun orgstruct-setup ()
8356 "Setup orgstruct keymaps."
8357 (let ((nfunc 0)
8358 (bindings
8359 (list
8360 '([(meta up)] org-metaup)
8361 '([(meta down)] org-metadown)
8362 '([(meta left)] org-metaleft)
8363 '([(meta right)] org-metaright)
8364 '([(meta shift up)] org-shiftmetaup)
8365 '([(meta shift down)] org-shiftmetadown)
8366 '([(meta shift left)] org-shiftmetaleft)
8367 '([(meta shift right)] org-shiftmetaright)
8368 '([?\e (up)] org-metaup)
8369 '([?\e (down)] org-metadown)
8370 '([?\e (left)] org-metaleft)
8371 '([?\e (right)] org-metaright)
8372 '([?\e (shift up)] org-shiftmetaup)
8373 '([?\e (shift down)] org-shiftmetadown)
8374 '([?\e (shift left)] org-shiftmetaleft)
8375 '([?\e (shift right)] org-shiftmetaright)
8376 '([(shift up)] org-shiftup)
8377 '([(shift down)] org-shiftdown)
8378 '([(shift left)] org-shiftleft)
8379 '([(shift right)] org-shiftright)
8380 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8381 '("\M-q" fill-paragraph)
8382 '("\C-c^" org-sort)
8383 '("\C-c-" org-cycle-list-bullet)))
8384 elt key fun cmd)
8385 (while (setq elt (pop bindings))
8386 (setq nfunc (1+ nfunc))
8387 (setq key (org-key (car elt))
8388 fun (nth 1 elt)
8389 cmd (orgstruct-make-binding fun nfunc key))
8390 (org-defkey orgstruct-mode-map key cmd))
8392 ;; Prevent an error for users who forgot to make autoloads
8393 (require 'org-element)
8395 ;; Special treatment needed for TAB and RET
8396 (org-defkey orgstruct-mode-map [(tab)]
8397 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8398 (org-defkey orgstruct-mode-map "\C-i"
8399 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8401 (org-defkey orgstruct-mode-map "\M-\C-m"
8402 (orgstruct-make-binding 'org-insert-heading 105
8403 "\M-\C-m" [(meta return)]))
8404 (org-defkey orgstruct-mode-map [(meta return)]
8405 (orgstruct-make-binding 'org-insert-heading 106
8406 [(meta return)] "\M-\C-m"))
8408 (org-defkey orgstruct-mode-map [(shift meta return)]
8409 (orgstruct-make-binding 'org-insert-todo-heading 107
8410 [(meta return)] "\M-\C-m"))
8412 (org-defkey orgstruct-mode-map "\e\C-m"
8413 (orgstruct-make-binding 'org-insert-heading 108
8414 "\e\C-m" [?\e (return)]))
8415 (org-defkey orgstruct-mode-map [?\e (return)]
8416 (orgstruct-make-binding 'org-insert-heading 109
8417 [?\e (return)] "\e\C-m"))
8418 (org-defkey orgstruct-mode-map [?\e (shift return)]
8419 (orgstruct-make-binding 'org-insert-todo-heading 110
8420 [?\e (return)] "\e\C-m"))
8422 (unless org-local-vars
8423 (setq org-local-vars (org-get-local-variables)))
8427 (defun orgstruct-make-binding (fun n &rest keys)
8428 "Create a function for binding in the structure minor mode.
8429 FUN is the command to call inside a table. N is used to create a unique
8430 command name. KEYS are keys that should be checked in for a command
8431 to execute outside of tables."
8432 (eval
8433 (list 'defun
8434 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8435 '(arg)
8436 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8437 "Outside of structure, run the binding of `"
8438 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8439 "'.")
8440 '(interactive "p")
8441 (list 'if
8442 `(org-context-p 'headline 'item
8443 (and orgstruct-is-++
8444 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8445 'item-body))
8446 (list 'org-run-like-in-org-mode (list 'quote fun))
8447 (list 'let '(orgstruct-mode)
8448 (list 'call-interactively
8449 (append '(or)
8450 (mapcar (lambda (k)
8451 (list 'key-binding k))
8452 keys)
8453 '('orgstruct-error))))))))
8455 (defun org-contextualize-keys (alist contexts)
8456 "Return valid elements in ALIST depending on CONTEXTS.
8458 `org-agenda-custom-commands' or `org-capture-templates' are the
8459 values used for ALIST, and `org-agenda-custom-commands-contexts'
8460 or `org-capture-templates-contexts' are the associated contexts
8461 definitions."
8462 (let ((contexts
8463 ;; normalize contexts
8464 (mapcar
8465 (lambda(c) (cond ((listp (cadr c))
8466 (list (car c) (car c) (cadr c)))
8467 ((string= "" (cadr c))
8468 (list (car c) (car c) (caddr c)))
8469 (t c))) contexts))
8470 (a alist) c r s)
8471 ;; loop over all commands or templates
8472 (while (setq c (pop a))
8473 (let (vrules repl)
8474 (cond
8475 ((not (assoc (car c) contexts))
8476 (push c r))
8477 ((and (assoc (car c) contexts)
8478 (setq vrules (org-contextualize-validate-key
8479 (car c) contexts)))
8480 (mapc (lambda (vr)
8481 (when (not (equal (car vr) (cadr vr)))
8482 (setq repl vr))) vrules)
8483 (if (not repl) (push c r)
8484 (push (cadr repl) s)
8485 (push
8486 (cons (car c)
8487 (cdr (or (assoc (cadr repl) alist)
8488 (error "Undefined key `%s' as contextual replacement for `%s'"
8489 (cadr repl) (car c)))))
8490 r))))))
8491 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8492 (delq
8494 (delete-dups
8495 (mapcar (lambda (x)
8496 (let ((tpl (car x)))
8497 (when (not (delq
8499 (mapcar (lambda(y)
8500 (equal y tpl)) s))) x)))
8501 (reverse r))))))
8503 (defun org-contextualize-validate-key (key contexts)
8504 "Check CONTEXTS for agenda or capture KEY."
8505 (let (r rr res)
8506 (while (setq r (pop contexts))
8507 (mapc
8508 (lambda (rr)
8509 (when
8510 (and (equal key (car r))
8511 (if (functionp rr) (funcall rr)
8512 (or (and (eq (car rr) 'in-file)
8513 (buffer-file-name)
8514 (string-match (cdr rr) (buffer-file-name)))
8515 (and (eq (car rr) 'in-mode)
8516 (string-match (cdr rr) (symbol-name major-mode)))
8517 (when (and (eq (car rr) 'not-in-file)
8518 (buffer-file-name))
8519 (not (string-match (cdr rr) (buffer-file-name))))
8520 (when (eq (car rr) 'not-in-mode)
8521 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8522 (push r res)))
8523 (car (last r))))
8524 (delete-dups (delq nil res))))
8526 (defun org-context-p (&rest contexts)
8527 "Check if local context is any of CONTEXTS.
8528 Possible values in the list of contexts are `table', `headline', and `item'."
8529 (let ((pos (point)))
8530 (goto-char (point-at-bol))
8531 (prog1 (or (and (memq 'table contexts)
8532 (looking-at "[ \t]*|"))
8533 (and (memq 'headline contexts)
8534 (looking-at org-outline-regexp))
8535 (and (memq 'item contexts)
8536 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8537 (and (memq 'item-body contexts)
8538 (org-in-item-p)))
8539 (goto-char pos))))
8541 (defun org-get-local-variables ()
8542 "Return a list of all local variables in an Org mode buffer."
8543 (let (varlist)
8544 (with-current-buffer (get-buffer-create "*Org tmp*")
8545 (erase-buffer)
8546 (org-mode)
8547 (setq varlist (buffer-local-variables)))
8548 (kill-buffer "*Org tmp*")
8549 (delq nil
8550 (mapcar
8551 (lambda (x)
8552 (setq x
8553 (if (symbolp x)
8554 (list x)
8555 (list (car x) (list 'quote (cdr x)))))
8556 (if (string-match
8557 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8558 (symbol-name (car x)))
8559 x nil))
8560 varlist))))
8562 (defun org-clone-local-variables (from-buffer &optional regexp)
8563 "Clone local variables from FROM-BUFFER.
8564 Optional argument REGEXP selects variables to clone."
8565 (mapc
8566 (lambda (pair)
8567 (and (symbolp (car pair))
8568 (or (null regexp)
8569 (string-match regexp (symbol-name (car pair))))
8570 (set (make-local-variable (car pair))
8571 (cdr pair))))
8572 (buffer-local-variables from-buffer)))
8574 ;;;###autoload
8575 (defun org-run-like-in-org-mode (cmd)
8576 "Run a command, pretending that the current buffer is in Org-mode.
8577 This will temporarily bind local variables that are typically bound in
8578 Org-mode to the values they have in Org-mode, and then interactively
8579 call CMD."
8580 (org-load-modules-maybe)
8581 (unless org-local-vars
8582 (setq org-local-vars (org-get-local-variables)))
8583 (eval (list 'let org-local-vars
8584 (list 'call-interactively (list 'quote cmd)))))
8586 ;;;; Archiving
8588 (defun org-get-category (&optional pos force-refresh)
8589 "Get the category applying to position POS."
8590 (save-match-data
8591 (if force-refresh (org-refresh-category-properties))
8592 (let ((pos (or pos (point))))
8593 (or (get-text-property pos 'org-category)
8594 (progn (org-refresh-category-properties)
8595 (get-text-property pos 'org-category))))))
8597 (defun org-refresh-category-properties ()
8598 "Refresh category text properties in the buffer."
8599 (let ((case-fold-search t)
8600 (inhibit-read-only t)
8601 (def-cat (cond
8602 ((null org-category)
8603 (if buffer-file-name
8604 (file-name-sans-extension
8605 (file-name-nondirectory buffer-file-name))
8606 "???"))
8607 ((symbolp org-category) (symbol-name org-category))
8608 (t org-category)))
8609 beg end cat pos optionp)
8610 (org-unmodified
8611 (save-excursion
8612 (save-restriction
8613 (widen)
8614 (goto-char (point-min))
8615 (put-text-property (point) (point-max) 'org-category def-cat)
8616 (while (re-search-forward
8617 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8618 (setq pos (match-end 0)
8619 optionp (equal (char-after (match-beginning 0)) ?#)
8620 cat (org-trim (match-string 2)))
8621 (if optionp
8622 (setq beg (point-at-bol) end (point-max))
8623 (org-back-to-heading t)
8624 (setq beg (point) end (org-end-of-subtree t t)))
8625 (put-text-property beg end 'org-category cat)
8626 (put-text-property beg end 'org-category-position beg)
8627 (goto-char pos)))))))
8630 ;;;; Link Stuff
8632 ;;; Link abbreviations
8634 (defun org-link-expand-abbrev (link)
8635 "Apply replacements as defined in `org-link-abbrev-alist'."
8636 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8637 (let* ((key (match-string 1 link))
8638 (as (or (assoc key org-link-abbrev-alist-local)
8639 (assoc key org-link-abbrev-alist)))
8640 (tag (and (match-end 2) (match-string 3 link)))
8641 rpl)
8642 (if (not as)
8643 link
8644 (setq rpl (cdr as))
8645 (cond
8646 ((symbolp rpl) (funcall rpl tag))
8647 ((string-match "%(\\([^)]+\\))" rpl)
8648 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8649 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8650 ((string-match "%h" rpl)
8651 (replace-match (url-hexify-string (or tag "")) t t rpl))
8652 (t (concat rpl tag)))))
8653 link))
8655 ;;; Storing and inserting links
8657 (defvar org-insert-link-history nil
8658 "Minibuffer history for links inserted with `org-insert-link'.")
8660 (defvar org-stored-links nil
8661 "Contains the links stored with `org-store-link'.")
8663 (defvar org-store-link-plist nil
8664 "Plist with info about the most recently link created with `org-store-link'.")
8666 (defvar org-link-protocols nil
8667 "Link protocols added to Org-mode using `org-add-link-type'.")
8669 (defvar org-store-link-functions nil
8670 "List of functions that are called to create and store a link.
8671 Each function will be called in turn until one returns a non-nil
8672 value. Each function should check if it is responsible for creating
8673 this link (for example by looking at the major mode).
8674 If not, it must exit and return nil.
8675 If yes, it should return a non-nil value after a calling
8676 `org-store-link-props' with a list of properties and values.
8677 Special properties are:
8679 :type The link prefix, like \"http\". This must be given.
8680 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8681 This is obligatory as well.
8682 :description Optional default description for the second pair
8683 of brackets in an Org-mode link. The user can still change
8684 this when inserting this link into an Org-mode buffer.
8686 In addition to these, any additional properties can be specified
8687 and then used in capture templates.")
8689 (defun org-add-link-type (type &optional follow export)
8690 "Add TYPE to the list of `org-link-types'.
8691 Re-compute all regular expressions depending on `org-link-types'
8693 FOLLOW and EXPORT are two functions.
8695 FOLLOW should take the link path as the single argument and do whatever
8696 is necessary to follow the link, for example find a file or display
8697 a mail message.
8699 EXPORT should format the link path for export to one of the export formats.
8700 It should be a function accepting three arguments:
8702 path the path of the link, the text after the prefix (like \"http:\")
8703 desc the description of the link, if any, or a description added by
8704 org-export-normalize-links if there is none
8705 format the export format, a symbol like `html' or `latex' or `ascii'..
8707 The function may use the FORMAT information to return different values
8708 depending on the format. The return value will be put literally into
8709 the exported file. If the return value is nil, this means Org should
8710 do what it normally does with links which do not have EXPORT defined.
8712 Org-mode has a built-in default for exporting links. If you are happy with
8713 this default, there is no need to define an export function for the link
8714 type. For a simple example of an export function, see `org-bbdb.el'."
8715 (add-to-list 'org-link-types type t)
8716 (org-make-link-regexps)
8717 (if (assoc type org-link-protocols)
8718 (setcdr (assoc type org-link-protocols) (list follow export))
8719 (push (list type follow export) org-link-protocols)))
8721 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8722 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8724 ;;;###autoload
8725 (defun org-store-link (arg)
8726 "\\<org-mode-map>Store an org-link to the current location.
8727 This link is added to `org-stored-links' and can later be inserted
8728 into an org-buffer with \\[org-insert-link].
8730 For some link types, a prefix arg is interpreted:
8731 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8732 For file links, arg negates `org-context-in-file-links'."
8733 (interactive "P")
8734 (org-load-modules-maybe)
8735 (setq org-store-link-plist nil) ; reset
8736 (org-with-limited-levels
8737 (let (link cpltxt desc description search txt custom-id agenda-link)
8738 (cond
8740 ((run-hook-with-args-until-success 'org-store-link-functions)
8741 (setq link (plist-get org-store-link-plist :link)
8742 desc (or (plist-get org-store-link-plist :description) link)))
8744 ((org-src-edit-buffer-p)
8745 (let (label gc)
8746 (while (or (not label)
8747 (save-excursion
8748 (save-restriction
8749 (widen)
8750 (goto-char (point-min))
8751 (re-search-forward
8752 (regexp-quote (format org-coderef-label-format label))
8753 nil t))))
8754 (when label (message "Label exists already") (sit-for 2))
8755 (setq label (read-string "Code line label: " label)))
8756 (end-of-line 1)
8757 (setq link (format org-coderef-label-format label))
8758 (setq gc (- 79 (length link)))
8759 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8760 (insert link)
8761 (setq link (concat "(" label ")") desc nil)))
8763 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8764 ;; We are in the agenda, link to referenced location
8765 (let ((m (or (get-text-property (point) 'org-hd-marker)
8766 (get-text-property (point) 'org-marker))))
8767 (when m
8768 (org-with-point-at m
8769 (setq agenda-link
8770 (if (org-called-interactively-p 'any)
8771 (call-interactively 'org-store-link)
8772 (org-store-link nil)))))))
8774 ((eq major-mode 'calendar-mode)
8775 (let ((cd (calendar-cursor-to-date)))
8776 (setq link
8777 (format-time-string
8778 (car org-time-stamp-formats)
8779 (apply 'encode-time
8780 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8781 nil nil nil))))
8782 (org-store-link-props :type "calendar" :date cd)))
8784 ((eq major-mode 'help-mode)
8785 (setq link (concat "help:" (save-excursion
8786 (goto-char (point-min))
8787 (looking-at "^[^ ]+")
8788 (match-string 0))))
8789 (org-store-link-props :type "help"))
8791 ((eq major-mode 'w3-mode)
8792 (setq cpltxt (if (and (buffer-name)
8793 (not (string-match "Untitled" (buffer-name))))
8794 (buffer-name)
8795 (url-view-url t))
8796 link (url-view-url t))
8797 (org-store-link-props :type "w3" :url (url-view-url t)))
8799 ((eq major-mode 'w3m-mode)
8800 (setq cpltxt (or w3m-current-title w3m-current-url)
8801 link w3m-current-url)
8802 (org-store-link-props :type "w3m" :url (url-view-url t)))
8804 ((setq search (run-hook-with-args-until-success
8805 'org-create-file-search-functions))
8806 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8807 "::" search))
8808 (setq cpltxt (or description link)))
8810 ((eq major-mode 'image-mode)
8811 (setq cpltxt (concat "file:"
8812 (abbreviate-file-name buffer-file-name))
8813 link cpltxt)
8814 (org-store-link-props :type "image" :file buffer-file-name))
8816 ((eq major-mode 'dired-mode)
8817 ;; link to the file in the current line
8818 (let ((file (dired-get-filename nil t)))
8819 (setq file (if file
8820 (abbreviate-file-name
8821 (expand-file-name (dired-get-filename nil t)))
8822 ;; otherwise, no file so use current directory.
8823 default-directory))
8824 (setq cpltxt (concat "file:" file)
8825 link cpltxt)))
8827 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8828 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8829 (cond
8830 ((org-in-regexp "<<\\(.*?\\)>>")
8831 (setq cpltxt
8832 (concat "file:"
8833 (abbreviate-file-name
8834 (buffer-file-name (buffer-base-buffer)))
8835 "::" (match-string 1))
8836 link cpltxt))
8837 ((and (featurep 'org-id)
8838 (or (eq org-link-to-org-use-id t)
8839 (and (org-called-interactively-p 'any)
8840 (or (eq org-link-to-org-use-id 'create-if-interactive)
8841 (and (eq org-link-to-org-use-id
8842 'create-if-interactive-and-no-custom-id)
8843 (not custom-id))))
8844 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8845 ;; We can make a link using the ID.
8846 (setq link (condition-case nil
8847 (prog1 (org-id-store-link)
8848 (setq desc (plist-get org-store-link-plist :description)))
8849 (error
8850 ;; probably before first headline, link to file only
8851 (concat "file:"
8852 (abbreviate-file-name
8853 (buffer-file-name (buffer-base-buffer))))))))
8855 ;; Just link to current headline
8856 (setq cpltxt (concat "file:"
8857 (abbreviate-file-name
8858 (buffer-file-name (buffer-base-buffer)))))
8859 ;; Add a context search string
8860 (when (org-xor org-context-in-file-links arg)
8861 (setq txt (cond
8862 ((org-at-heading-p) nil)
8863 ((org-region-active-p)
8864 (buffer-substring (region-beginning) (region-end)))))
8865 (when (or (null txt) (string-match "\\S-" txt))
8866 (setq cpltxt
8867 (concat cpltxt "::"
8868 (condition-case nil
8869 (org-make-org-heading-search-string txt)
8870 (error "")))
8871 desc (or (nth 4 (ignore-errors
8872 (org-heading-components))) "NONE"))))
8873 (if (string-match "::\\'" cpltxt)
8874 (setq cpltxt (substring cpltxt 0 -2)))
8875 (setq link cpltxt))))
8877 ((buffer-file-name (buffer-base-buffer))
8878 ;; Just link to this file here.
8879 (setq cpltxt (concat "file:"
8880 (abbreviate-file-name
8881 (buffer-file-name (buffer-base-buffer)))))
8882 ;; Add a context string
8883 (when (org-xor org-context-in-file-links arg)
8884 (setq txt (if (org-region-active-p)
8885 (buffer-substring (region-beginning) (region-end))
8886 (buffer-substring (point-at-bol) (point-at-eol))))
8887 ;; Only use search option if there is some text.
8888 (when (string-match "\\S-" txt)
8889 (setq cpltxt
8890 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8891 desc "NONE")))
8892 (setq link cpltxt))
8894 ((org-called-interactively-p 'interactive)
8895 (error "Cannot link to a buffer which is not visiting a file"))
8897 (t (setq link nil)))
8899 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8900 (setq link (or link cpltxt)
8901 desc (or desc cpltxt))
8902 (if (equal desc "NONE") (setq desc nil))
8904 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8905 (progn
8906 (setq org-stored-links
8907 (cons (list link desc) org-stored-links))
8908 (message "Stored: %s" (or desc link))
8909 (when custom-id
8910 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8911 "::#" custom-id))
8912 (setq org-stored-links
8913 (cons (list link desc) org-stored-links))))
8914 (or agenda-link (and link (org-make-link-string link desc)))))))
8916 (defun org-store-link-props (&rest plist)
8917 "Store link properties, extract names and addresses."
8918 (let (x adr)
8919 (when (setq x (plist-get plist :from))
8920 (setq adr (mail-extract-address-components x))
8921 (setq plist (plist-put plist :fromname (car adr)))
8922 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8923 (when (setq x (plist-get plist :to))
8924 (setq adr (mail-extract-address-components x))
8925 (setq plist (plist-put plist :toname (car adr)))
8926 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8927 (let ((from (plist-get plist :from))
8928 (to (plist-get plist :to)))
8929 (when (and from to org-from-is-user-regexp)
8930 (setq plist
8931 (plist-put plist :fromto
8932 (if (string-match org-from-is-user-regexp from)
8933 (concat "to %t")
8934 (concat "from %f"))))))
8935 (setq org-store-link-plist plist))
8937 (defun org-add-link-props (&rest plist)
8938 "Add these properties to the link property list."
8939 (let (key value)
8940 (while plist
8941 (setq key (pop plist) value (pop plist))
8942 (setq org-store-link-plist
8943 (plist-put org-store-link-plist key value)))))
8945 (defun org-email-link-description (&optional fmt)
8946 "Return the description part of an email link.
8947 This takes information from `org-store-link-plist' and formats it
8948 according to FMT (default from `org-email-link-description-format')."
8949 (setq fmt (or fmt org-email-link-description-format))
8950 (let* ((p org-store-link-plist)
8951 (to (plist-get p :toaddress))
8952 (from (plist-get p :fromaddress))
8953 (table
8954 (list
8955 (cons "%c" (plist-get p :fromto))
8956 (cons "%F" (plist-get p :from))
8957 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8958 (cons "%T" (plist-get p :to))
8959 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8960 (cons "%s" (plist-get p :subject))
8961 (cons "%d" (plist-get p :date))
8962 (cons "%m" (plist-get p :message-id)))))
8963 (when (string-match "%c" fmt)
8964 ;; Check if the user wrote this message
8965 (if (and org-from-is-user-regexp from to
8966 (save-match-data (string-match org-from-is-user-regexp from)))
8967 (setq fmt (replace-match "to %t" t t fmt))
8968 (setq fmt (replace-match "from %f" t t fmt))))
8969 (org-replace-escapes fmt table)))
8971 (defun org-make-org-heading-search-string (&optional string heading)
8972 "Make search string for STRING or current headline."
8973 (interactive)
8974 (let ((s (or string (org-get-heading)))
8975 (lines org-context-in-file-links))
8976 (unless (and string (not heading))
8977 ;; We are using a headline, clean up garbage in there.
8978 (if (string-match org-todo-regexp s)
8979 (setq s (replace-match "" t t s)))
8980 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8981 (setq s (replace-match "" t t s)))
8982 (setq s (org-trim s))
8983 (if (string-match (concat "^\\(" org-quote-string "\\|"
8984 org-comment-string "\\)") s)
8985 (setq s (replace-match "" t t s)))
8986 (while (string-match org-ts-regexp s)
8987 (setq s (replace-match "" t t s))))
8988 (or string (setq s (concat "*" s))) ; Add * for headlines
8989 (when (and string (integerp lines) (> lines 0))
8990 (let ((slines (org-split-string s "\n")))
8991 (when (< lines (length slines))
8992 (setq s (mapconcat
8993 'identity
8994 (reverse (nthcdr (- (length slines) lines)
8995 (reverse slines))) "\n")))))
8996 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8998 (defun org-make-link-string (link &optional description)
8999 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9000 (unless (string-match "\\S-" link)
9001 (error "Empty link"))
9002 (when (and description
9003 (stringp description)
9004 (not (string-match "\\S-" description)))
9005 (setq description nil))
9006 (when (stringp description)
9007 ;; Remove brackets from the description, they are fatal.
9008 (while (string-match "\\[" description)
9009 (setq description (replace-match "{" t t description)))
9010 (while (string-match "\\]" description)
9011 (setq description (replace-match "}" t t description))))
9012 (when (equal link description)
9013 ;; No description needed, it is identical
9014 (setq description nil))
9015 (when (and (not description)
9016 (not (string-match (org-image-file-name-regexp) link))
9017 (not (equal link (org-link-escape link))))
9018 (setq description (org-extract-attributes link)))
9019 (setq link
9020 (cond ((string-match (org-image-file-name-regexp) link) link)
9021 ((string-match org-link-types-re link)
9022 (concat (match-string 1 link)
9023 (org-link-escape (substring link (match-end 1)))))
9024 (t (org-link-escape link))))
9025 (concat "[[" link "]"
9026 (if description (concat "[" description "]") "")
9027 "]"))
9029 (defconst org-link-escape-chars
9030 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9031 "List of characters that should be escaped in link.
9032 This is the list that is used for internal purposes.")
9034 (defconst org-link-escape-chars-browser
9035 '(?\ )
9036 "List of escapes for characters that are problematic in links.
9037 This is the list that is used before handing over to the browser.")
9039 (defun org-link-escape (text &optional table merge)
9040 "Return percent escaped representation of TEXT.
9041 TEXT is a string with the text to escape.
9042 Optional argument TABLE is a list with characters that should be
9043 escaped. When nil, `org-link-escape-chars' is used.
9044 If optional argument MERGE is set, merge TABLE into
9045 `org-link-escape-chars'."
9046 (cond
9047 ((and table merge)
9048 (mapc (lambda (defchr)
9049 (unless (member defchr table)
9050 (setq table (cons defchr table)))) org-link-escape-chars))
9051 ((null table)
9052 (setq table org-link-escape-chars)))
9053 (mapconcat
9054 (lambda (char)
9055 (if (or (member char table)
9056 (and (or (< char 32) (= char 37) (> char 126))
9057 org-url-hexify-p))
9058 (mapconcat (lambda (sequence-element)
9059 (format "%%%.2X" sequence-element))
9060 (or (encode-coding-char char 'utf-8)
9061 (error "Unable to percent escape character: %s"
9062 (char-to-string char))) "")
9063 (char-to-string char))) text ""))
9065 (defun org-link-unescape (str)
9066 "Unhex hexified Unicode strings as returned from the JavaScript function
9067 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9068 (unless (and (null str) (string= "" str))
9069 (let ((pos 0) (case-fold-search t) unhexed)
9070 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9071 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9072 (setq str (replace-match unhexed t t str))
9073 (setq pos (+ pos (length unhexed))))))
9074 str)
9076 (defun org-link-unescape-compound (hex)
9077 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9078 Note: this function also decodes single byte encodings like
9079 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9080 (save-match-data
9081 (let* ((bytes (cdr (split-string hex "%")))
9082 (ret "")
9083 (eat 0)
9084 (sum 0))
9085 (while bytes
9086 (let* ((val (string-to-number (pop bytes) 16))
9087 (shift-xor
9088 (if (= 0 eat)
9089 (cond
9090 ((>= val 252) (cons 6 252))
9091 ((>= val 248) (cons 5 248))
9092 ((>= val 240) (cons 4 240))
9093 ((>= val 224) (cons 3 224))
9094 ((>= val 192) (cons 2 192))
9095 (t (cons 0 0)))
9096 (cons 6 128))))
9097 (if (>= val 192) (setq eat (car shift-xor)))
9098 (setq val (logxor val (cdr shift-xor)))
9099 (setq sum (+ (lsh sum (car shift-xor)) val))
9100 (if (> eat 0) (setq eat (- eat 1)))
9101 (cond
9102 ((= 0 eat) ;multi byte
9103 (setq ret (concat ret (org-char-to-string sum)))
9104 (setq sum 0))
9105 ((not bytes) ; single byte(s)
9106 (setq ret (org-link-unescape-single-byte-sequence hex))))
9107 )) ;; end (while bytes
9108 ret )))
9110 (defun org-link-unescape-single-byte-sequence (hex)
9111 "Unhexify hex-encoded single byte character sequences."
9112 (mapconcat (lambda (byte)
9113 (char-to-string (string-to-number byte 16)))
9114 (cdr (split-string hex "%")) ""))
9116 (defun org-xor (a b)
9117 "Exclusive or."
9118 (if a (not b) b))
9120 (defun org-fixup-message-id-for-http (s)
9121 "Replace special characters in a message id, so it can be used in an http query."
9122 (when (string-match "%" s)
9123 (setq s (mapconcat (lambda (c)
9124 (if (eq c ?%)
9125 "%25"
9126 (char-to-string c)))
9127 s "")))
9128 (while (string-match "<" s)
9129 (setq s (replace-match "%3C" t t s)))
9130 (while (string-match ">" s)
9131 (setq s (replace-match "%3E" t t s)))
9132 (while (string-match "@" s)
9133 (setq s (replace-match "%40" t t s)))
9136 (defun org-link-prettify (link)
9137 "Return a human-readable representation of LINK.
9138 The car of LINK must be a raw link the cdr of LINK must be either
9139 a link description or nil."
9140 (let ((desc (or (cadr link) "<no description>")))
9141 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9142 "<" (car link) ">")))
9144 ;;;###autoload
9145 (defun org-insert-link-global ()
9146 "Insert a link like Org-mode does.
9147 This command can be called in any mode to insert a link in Org-mode syntax."
9148 (interactive)
9149 (org-load-modules-maybe)
9150 (org-run-like-in-org-mode 'org-insert-link))
9152 (defun org-insert-all-links (&optional keep)
9153 "Insert all links in `org-stored-links'."
9154 (interactive "P")
9155 (let ((links (copy-sequence org-stored-links)) l)
9156 (while (setq l (if keep (pop links) (pop org-stored-links)))
9157 (insert "- ")
9158 (org-insert-link nil (car l) (cadr l))
9159 (insert "\n"))))
9161 (defun org-link-fontify-links-to-this-file ()
9162 "Fontify links to the current file in `org-stored-links'."
9163 (let ((f (buffer-file-name)) a b)
9164 (setq a (mapcar (lambda(l)
9165 (let ((ll (car l)))
9166 (when (and (string-match "^file:\\(.+\\)::" ll)
9167 (equal f (expand-file-name (match-string 1 ll))))
9168 ll)))
9169 org-stored-links))
9170 (when (featurep 'org-id)
9171 (setq b (mapcar (lambda(l)
9172 (let ((ll (car l)))
9173 (when (and (string-match "^id:\\(.+\\)$" ll)
9174 (equal f (expand-file-name
9175 (or (org-id-find-id-file
9176 (match-string 1 ll)) ""))))
9177 ll)))
9178 org-stored-links)))
9179 (mapcar (lambda(l)
9180 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9181 (delq nil (append a b)))))
9183 (defvar org-link-links-in-this-file nil)
9184 (defun org-insert-link (&optional complete-file link-location default-description)
9185 "Insert a link. At the prompt, enter the link.
9187 Completion can be used to insert any of the link protocol prefixes like
9188 http or ftp in use.
9190 The history can be used to select a link previously stored with
9191 `org-store-link'. When the empty string is entered (i.e. if you just
9192 press RET at the prompt), the link defaults to the most recently
9193 stored link. As SPC triggers completion in the minibuffer, you need to
9194 use M-SPC or C-q SPC to force the insertion of a space character.
9196 You will also be prompted for a description, and if one is given, it will
9197 be displayed in the buffer instead of the link.
9199 If there is already a link at point, this command will allow you to edit link
9200 and description parts.
9202 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9203 be selected using completion. The path to the file will be relative to the
9204 current directory if the file is in the current directory or a subdirectory.
9205 Otherwise, the link will be the absolute path as completed in the minibuffer
9206 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9207 option `org-link-file-path-type'.
9209 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9210 the current directory or below.
9212 With three \\[universal-argument] prefixes, negate the meaning of
9213 `org-keep-stored-link-after-insertion'.
9215 If `org-make-link-description-function' is non-nil, this function will be
9216 called with the link target, and the result will be the default
9217 link description.
9219 If the LINK-LOCATION parameter is non-nil, this value will be
9220 used as the link location instead of reading one interactively.
9222 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9223 be used as the default description."
9224 (interactive "P")
9225 (let* ((wcf (current-window-configuration))
9226 (region (if (org-region-active-p)
9227 (buffer-substring (region-beginning) (region-end))))
9228 (remove (and region (list (region-beginning) (region-end))))
9229 (desc region)
9230 tmphist ; byte-compile incorrectly complains about this
9231 (link link-location)
9232 (abbrevs org-link-abbrev-alist-local)
9233 entry file all-prefixes auto-desc)
9234 (cond
9235 (link-location) ; specified by arg, just use it.
9236 ((org-in-regexp org-bracket-link-regexp 1)
9237 ;; We do have a link at point, and we are going to edit it.
9238 (setq remove (list (match-beginning 0) (match-end 0)))
9239 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9240 (setq link (read-string "Link: "
9241 (org-link-unescape
9242 (org-match-string-no-properties 1)))))
9243 ((or (org-in-regexp org-angle-link-re)
9244 (org-in-regexp org-plain-link-re))
9245 ;; Convert to bracket link
9246 (setq remove (list (match-beginning 0) (match-end 0))
9247 link (read-string "Link: "
9248 (org-remove-angle-brackets (match-string 0)))))
9249 ((member complete-file '((4) (16)))
9250 ;; Completing read for file names.
9251 (setq link (org-file-complete-link complete-file)))
9253 ;; Read link, with completion for stored links.
9254 (org-link-fontify-links-to-this-file)
9255 (org-switch-to-buffer-other-window "*Org Links*")
9256 (with-current-buffer "*Org Links*"
9257 (erase-buffer)
9258 (insert "Insert a link.
9259 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9260 (when org-stored-links
9261 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9262 (insert (mapconcat 'org-link-prettify
9263 (reverse org-stored-links) "\n")))
9264 (goto-char (point-min)))
9265 (let ((cw (selected-window)))
9266 (select-window (get-buffer-window "*Org Links*" 'visible))
9267 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9268 (unless (pos-visible-in-window-p (point-max))
9269 (org-fit-window-to-buffer))
9270 (and (window-live-p cw) (select-window cw)))
9271 ;; Fake a link history, containing the stored links.
9272 (setq tmphist (append (mapcar 'car org-stored-links)
9273 org-insert-link-history))
9274 (setq all-prefixes (append (mapcar 'car abbrevs)
9275 (mapcar 'car org-link-abbrev-alist)
9276 org-link-types))
9277 (unwind-protect
9278 (progn
9279 (setq link
9280 (let ((org-completion-use-ido nil)
9281 (org-completion-use-iswitchb nil))
9282 (org-completing-read
9283 "Link: "
9284 (append
9285 (mapcar (lambda (x) (list (concat x ":")))
9286 all-prefixes)
9287 (mapcar 'car org-stored-links)
9288 (mapcar 'cadr org-stored-links))
9289 nil nil nil
9290 'tmphist
9291 (caar org-stored-links))))
9292 (if (not (string-match "\\S-" link))
9293 (error "No link selected"))
9294 (mapc (lambda(l)
9295 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9296 org-stored-links)
9297 (if (or (member link all-prefixes)
9298 (and (equal ":" (substring link -1))
9299 (member (substring link 0 -1) all-prefixes)
9300 (setq link (substring link 0 -1))))
9301 (setq link (org-link-try-special-completion link))))
9302 (set-window-configuration wcf)
9303 (kill-buffer "*Org Links*"))
9304 (setq entry (assoc link org-stored-links))
9305 (or entry (push link org-insert-link-history))
9306 (setq desc (or desc (nth 1 entry)))))
9308 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9309 (not org-keep-stored-link-after-insertion))
9310 (setq org-stored-links (delq (assoc link org-stored-links)
9311 org-stored-links)))
9313 (if (string-match org-plain-link-re link)
9314 ;; URL-like link, normalize the use of angular brackets.
9315 (setq link (org-remove-angle-brackets link)))
9317 ;; Check if we are linking to the current file with a search
9318 ;; option If yes, simplify the link by using only the search
9319 ;; option.
9320 (when (and buffer-file-name
9321 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9322 (let* ((path (match-string 1 link))
9323 (case-fold-search nil)
9324 (search (match-string 2 link)))
9325 (save-match-data
9326 (if (equal (file-truename buffer-file-name) (file-truename path))
9327 ;; We are linking to this same file, with a search option
9328 (setq link search)))))
9330 ;; Check if we can/should use a relative path. If yes, simplify the link
9331 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9332 (let* ((type (match-string 1 link))
9333 (path (match-string 2 link))
9334 (origpath path)
9335 (case-fold-search nil))
9336 (cond
9337 ((or (eq org-link-file-path-type 'absolute)
9338 (equal complete-file '(16)))
9339 (setq path (abbreviate-file-name (expand-file-name path))))
9340 ((eq org-link-file-path-type 'noabbrev)
9341 (setq path (expand-file-name path)))
9342 ((eq org-link-file-path-type 'relative)
9343 (setq path (file-relative-name path)))
9345 (save-match-data
9346 (if (string-match (concat "^" (regexp-quote
9347 (expand-file-name
9348 (file-name-as-directory
9349 default-directory))))
9350 (expand-file-name path))
9351 ;; We are linking a file with relative path name.
9352 (setq path (substring (expand-file-name path)
9353 (match-end 0)))
9354 (setq path (abbreviate-file-name (expand-file-name path)))))))
9355 (setq link (concat type path))
9356 (if (equal desc origpath)
9357 (setq desc path))))
9359 (if org-make-link-description-function
9360 (setq desc
9361 (or (condition-case nil
9362 (funcall org-make-link-description-function link desc)
9363 (error (progn (message "Can't get link description from `%s'"
9364 (symbol-name org-make-link-description-function))
9365 (sit-for 2) nil)))
9366 (read-string "Description: " default-description)))
9367 (if default-description (setq desc default-description)
9368 (setq desc (or (and auto-desc desc)
9369 (read-string "Description: " desc)))))
9371 (unless (string-match "\\S-" desc) (setq desc nil))
9372 (if remove (apply 'delete-region remove))
9373 (insert (org-make-link-string link desc))))
9375 (defun org-link-try-special-completion (type)
9376 "If there is completion support for link type TYPE, offer it."
9377 (let ((fun (intern (concat "org-" type "-complete-link"))))
9378 (if (functionp fun)
9379 (funcall fun)
9380 (read-string "Link (no completion support): " (concat type ":")))))
9382 (defun org-file-complete-link (&optional arg)
9383 "Create a file link using completion."
9384 (let (file link)
9385 (setq file (read-file-name "File: "))
9386 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9387 (pwd1 (file-name-as-directory (abbreviate-file-name
9388 (expand-file-name ".")))))
9389 (cond
9390 ((equal arg '(16))
9391 (setq link (concat
9392 "file:"
9393 (abbreviate-file-name (expand-file-name file)))))
9394 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9395 (setq link (concat "file:" (match-string 1 file))))
9396 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9397 (expand-file-name file))
9398 (setq link (concat
9399 "file:" (match-string 1 (expand-file-name file)))))
9400 (t (setq link (concat "file:" file)))))
9401 link))
9403 (defun org-completing-read (&rest args)
9404 "Completing-read with SPACE being a normal character."
9405 (let ((enable-recursive-minibuffers t)
9406 (minibuffer-local-completion-map
9407 (copy-keymap minibuffer-local-completion-map)))
9408 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9409 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9410 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9411 (apply 'org-icompleting-read args)))
9413 (defun org-completing-read-no-i (&rest args)
9414 (let (org-completion-use-ido org-completion-use-iswitchb)
9415 (apply 'org-completing-read args)))
9417 (defun org-iswitchb-completing-read (prompt choices &rest args)
9418 "Use iswitch as a completing-read replacement to choose from choices.
9419 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9420 from."
9421 (let* ((iswitchb-use-virtual-buffers nil)
9422 (iswitchb-make-buflist-hook
9423 (lambda ()
9424 (setq iswitchb-temp-buflist choices))))
9425 (iswitchb-read-buffer prompt)))
9427 (defun org-icompleting-read (&rest args)
9428 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9429 (org-without-partial-completion
9430 (if (and org-completion-use-ido
9431 (fboundp 'ido-completing-read)
9432 (boundp 'ido-mode) ido-mode
9433 (listp (second args)))
9434 (let ((ido-enter-matching-directory nil))
9435 (apply 'ido-completing-read (concat (car args))
9436 (if (consp (car (nth 1 args)))
9437 (mapcar 'car (nth 1 args))
9438 (nth 1 args))
9439 (cddr args)))
9440 (if (and org-completion-use-iswitchb
9441 (boundp 'iswitchb-mode) iswitchb-mode
9442 (listp (second args)))
9443 (apply 'org-iswitchb-completing-read (concat (car args))
9444 (if (consp (car (nth 1 args)))
9445 (mapcar 'car (nth 1 args))
9446 (nth 1 args))
9447 (cddr args))
9448 (apply 'completing-read args)))))
9450 (defun org-extract-attributes (s)
9451 "Extract the attributes cookie from a string and set as text property."
9452 (let (a attr (start 0) key value)
9453 (save-match-data
9454 (when (string-match "{{\\([^}]+\\)}}$" s)
9455 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9456 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9457 (setq key (match-string 1 a) value (match-string 2 a)
9458 start (match-end 0)
9459 attr (plist-put attr (intern key) value))))
9460 (org-add-props s nil 'org-attr attr))
9463 (defun org-extract-attributes-from-string (tag)
9464 (let (key value attr)
9465 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9466 (setq key (match-string 1 tag) value (match-string 2 tag)
9467 tag (replace-match "" t t tag)
9468 attr (plist-put attr (intern key) value)))
9469 (cons tag attr)))
9471 (defun org-attributes-to-string (plist)
9472 "Format a property list into an HTML attribute list."
9473 (let ((s "") key value)
9474 (while plist
9475 (setq key (pop plist) value (pop plist))
9476 (and value
9477 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9480 ;;; Opening/following a link
9482 (defvar org-link-search-failed nil)
9484 (defvar org-open-link-functions nil
9485 "Hook for functions finding a plain text link.
9486 These functions must take a single argument, the link content.
9487 They will be called for links that look like [[link text][description]]
9488 when LINK TEXT does not have a protocol like \"http:\" and does not look
9489 like a filename (e.g. \"./blue.png\").
9491 These functions will be called *before* Org attempts to resolve the
9492 link by doing text searches in the current buffer - so if you want a
9493 link \"[[target]]\" to still find \"<<target>>\", your function should
9494 handle this as a special case.
9496 When the function does handle the link, it must return a non-nil value.
9497 If it decides that it is not responsible for this link, it must return
9498 nil to indicate that that Org-mode can continue with other options
9499 like exact and fuzzy text search.")
9501 (defun org-next-link ()
9502 "Move forward to the next link.
9503 If the link is in hidden text, expose it."
9504 (interactive)
9505 (when (and org-link-search-failed (eq this-command last-command))
9506 (goto-char (point-min))
9507 (message "Link search wrapped back to beginning of buffer"))
9508 (setq org-link-search-failed nil)
9509 (let* ((pos (point))
9510 (ct (org-context))
9511 (a (assoc :link ct)))
9512 (if a (goto-char (nth 2 a)))
9513 (if (re-search-forward org-any-link-re nil t)
9514 (progn
9515 (goto-char (match-beginning 0))
9516 (if (outline-invisible-p) (org-show-context)))
9517 (goto-char pos)
9518 (setq org-link-search-failed t)
9519 (error "No further link found"))))
9521 (defun org-previous-link ()
9522 "Move backward to the previous link.
9523 If the link is in hidden text, expose it."
9524 (interactive)
9525 (when (and org-link-search-failed (eq this-command last-command))
9526 (goto-char (point-max))
9527 (message "Link search wrapped back to end of buffer"))
9528 (setq org-link-search-failed nil)
9529 (let* ((pos (point))
9530 (ct (org-context))
9531 (a (assoc :link ct)))
9532 (if a (goto-char (nth 1 a)))
9533 (if (re-search-backward org-any-link-re nil t)
9534 (progn
9535 (goto-char (match-beginning 0))
9536 (if (outline-invisible-p) (org-show-context)))
9537 (goto-char pos)
9538 (setq org-link-search-failed t)
9539 (error "No further link found"))))
9541 (defun org-translate-link (s)
9542 "Translate a link string if a translation function has been defined."
9543 (if (and org-link-translation-function
9544 (fboundp org-link-translation-function)
9545 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9546 (progn
9547 (setq s (funcall org-link-translation-function
9548 (match-string 1 s) (match-string 2 s)))
9549 (concat (car s) ":" (cdr s)))
9552 (defun org-translate-link-from-planner (type path)
9553 "Translate a link from Emacs Planner syntax so that Org can follow it.
9554 This is still an experimental function, your mileage may vary."
9555 (cond
9556 ((member type '("http" "https" "news" "ftp"))
9557 ;; standard Internet links are the same.
9558 nil)
9559 ((and (equal type "irc") (string-match "^//" path))
9560 ;; Planner has two / at the beginning of an irc link, we have 1.
9561 ;; We should have zero, actually....
9562 (setq path (substring path 1)))
9563 ((and (equal type "lisp") (string-match "^/" path))
9564 ;; Planner has a slash, we do not.
9565 (setq type "elisp" path (substring path 1)))
9566 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9567 ;; A typical message link. Planner has the id after the final slash,
9568 ;; we separate it with a hash mark
9569 (setq path (concat (match-string 1 path) "#"
9570 (org-remove-angle-brackets (match-string 2 path)))))
9572 (cons type path))
9574 (defun org-find-file-at-mouse (ev)
9575 "Open file link or URL at mouse."
9576 (interactive "e")
9577 (mouse-set-point ev)
9578 (org-open-at-point 'in-emacs))
9580 (defun org-open-at-mouse (ev)
9581 "Open file link or URL at mouse.
9582 See the docstring of `org-open-file' for details."
9583 (interactive "e")
9584 (mouse-set-point ev)
9585 (if (eq major-mode 'org-agenda-mode)
9586 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9587 (org-open-at-point))
9589 (defvar org-window-config-before-follow-link nil
9590 "The window configuration before following a link.
9591 This is saved in case the need arises to restore it.")
9593 (defvar org-open-link-marker (make-marker)
9594 "Marker pointing to the location where `org-open-at-point; was called.")
9596 ;;;###autoload
9597 (defun org-open-at-point-global ()
9598 "Follow a link like Org-mode does.
9599 This command can be called in any mode to follow a link that has
9600 Org-mode syntax."
9601 (interactive)
9602 (org-run-like-in-org-mode 'org-open-at-point))
9604 ;;;###autoload
9605 (defun org-open-link-from-string (s &optional arg reference-buffer)
9606 "Open a link in the string S, as if it was in Org-mode."
9607 (interactive "sLink: \nP")
9608 (let ((reference-buffer (or reference-buffer (current-buffer))))
9609 (with-temp-buffer
9610 (let ((org-inhibit-startup (not reference-buffer)))
9611 (org-mode)
9612 (insert s)
9613 (goto-char (point-min))
9614 (when reference-buffer
9615 (setq org-link-abbrev-alist-local
9616 (with-current-buffer reference-buffer
9617 org-link-abbrev-alist-local)))
9618 (org-open-at-point arg reference-buffer)))))
9620 (defvar org-open-at-point-functions nil
9621 "Hook that is run when following a link at point.
9623 Functions in this hook must return t if they identify and follow
9624 a link at point. If they don't find anything interesting at point,
9625 they must return nil.")
9627 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9628 (defun org-open-at-point (&optional arg reference-buffer)
9629 "Open link at or after point.
9630 If there is no link at point, this function will search forward up to
9631 the end of the current line.
9632 Normally, files will be opened by an appropriate application. If the
9633 optional prefix argument ARG is non-nil, Emacs will visit the file.
9634 With a double prefix argument, try to open outside of Emacs, in the
9635 application the system uses for this file type."
9636 (interactive "P")
9637 ;; if in a code block, then open the block's results
9638 (unless (call-interactively #'org-babel-open-src-block-result)
9639 (org-load-modules-maybe)
9640 (move-marker org-open-link-marker (point))
9641 (setq org-window-config-before-follow-link (current-window-configuration))
9642 (org-remove-occur-highlights nil nil t)
9643 (cond
9644 ((and (org-at-heading-p)
9645 (not (org-at-timestamp-p t))
9646 (not (org-in-regexp
9647 (concat org-plain-link-re "\\|"
9648 org-bracket-link-regexp "\\|"
9649 org-angle-link-re "\\|"
9650 "[ \t]:[^ \t\n]+:[ \t]*$")))
9651 (not (get-text-property (point) 'org-linked-text)))
9652 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9653 (lk (car lkall))
9654 (lkend (cdr lkall)))
9655 (when lk
9656 (prog1 (search-forward lk nil lkend)
9657 (goto-char (match-beginning 0))
9658 (org-open-at-point))))
9659 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9660 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9661 ((and (org-at-timestamp-p t)
9662 (not (org-in-regexp org-bracket-link-regexp)))
9663 (org-follow-timestamp-link))
9664 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9665 (not (org-in-regexp org-any-link-re)))
9666 (org-footnote-action))
9668 (let (type path link line search (pos (point)))
9669 (catch 'match
9670 (save-excursion
9671 (skip-chars-forward "^]\n\r")
9672 (when (org-in-regexp org-bracket-link-regexp 1)
9673 (setq link (org-extract-attributes
9674 (org-link-unescape (org-match-string-no-properties 1))))
9675 (while (string-match " *\n *" link)
9676 (setq link (replace-match " " t t link)))
9677 (setq link (org-link-expand-abbrev link))
9678 (cond
9679 ((or (file-name-absolute-p link)
9680 (string-match "^\\.\\.?/" link))
9681 (setq type "file" path link))
9682 ((string-match org-link-re-with-space3 link)
9683 (setq type (match-string 1 link) path (match-string 2 link)))
9684 ((string-match "^help:+\\(.+\\)" link)
9685 (setq type "help" path (match-string 1 link)))
9686 (t (setq type "thisfile" path link)))
9687 (throw 'match t)))
9689 (when (get-text-property (point) 'org-linked-text)
9690 (setq type "thisfile"
9691 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9692 (1+ (point)) (point))
9693 path (buffer-substring
9694 (or (previous-single-property-change pos 'org-linked-text)
9695 (point-min))
9696 (or (next-single-property-change pos 'org-linked-text)
9697 (point-max))))
9698 (throw 'match t))
9700 (save-excursion
9701 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9702 (when (or (org-in-regexp org-angle-link-re)
9703 (and plinkpos (goto-char (car plinkpos))
9704 (save-match-data (not (looking-back "\\[\\[")))))
9705 (setq type (match-string 1)
9706 path (org-link-unescape (match-string 2)))
9707 (throw 'match t))))
9708 (save-excursion
9709 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9710 (setq type "tags"
9711 path (match-string 1))
9712 (while (string-match ":" path)
9713 (setq path (replace-match "+" t t path)))
9714 (throw 'match t)))
9715 (when (org-in-regexp "<\\([^><\n]+\\)>")
9716 (setq type "tree-match"
9717 path (match-string 1))
9718 (throw 'match t)))
9719 (unless path
9720 (user-error "No link found"))
9722 ;; switch back to reference buffer
9723 ;; needed when if called in a temporary buffer through
9724 ;; org-open-link-from-string
9725 (with-current-buffer (or reference-buffer (current-buffer))
9727 ;; Remove any trailing spaces in path
9728 (if (string-match " +\\'" path)
9729 (setq path (replace-match "" t t path)))
9730 (if (and org-link-translation-function
9731 (fboundp org-link-translation-function))
9732 ;; Check if we need to translate the link
9733 (let ((tmp (funcall org-link-translation-function type path)))
9734 (setq type (car tmp) path (cdr tmp))))
9736 (cond
9738 ((assoc type org-link-protocols)
9739 (funcall (nth 1 (assoc type org-link-protocols)) path))
9741 ((equal type "help")
9742 (let ((f-or-v (intern path)))
9743 (cond ((fboundp f-or-v)
9744 (describe-function f-or-v))
9745 ((boundp f-or-v)
9746 (describe-variable f-or-v))
9747 (t (error "Not a known function or variable")))))
9749 ((equal type "mailto")
9750 (let ((cmd (car org-link-mailto-program))
9751 (args (cdr org-link-mailto-program)) args1
9752 (address path) (subject "") a)
9753 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9754 (setq address (match-string 1 path)
9755 subject (org-link-escape (match-string 2 path))))
9756 (while args
9757 (cond
9758 ((not (stringp (car args))) (push (pop args) args1))
9759 (t (setq a (pop args))
9760 (if (string-match "%a" a)
9761 (setq a (replace-match address t t a)))
9762 (if (string-match "%s" a)
9763 (setq a (replace-match subject t t a)))
9764 (push a args1))))
9765 (apply cmd (nreverse args1))))
9767 ((member type '("http" "https" "ftp" "news"))
9768 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9769 (org-link-escape
9770 path org-link-escape-chars-browser)
9771 path))))
9773 ((string= type "doi")
9774 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9775 (org-link-escape
9776 path org-link-escape-chars-browser)
9777 path))))
9779 ((member type '("message"))
9780 (browse-url (concat type ":" path)))
9782 ((string= type "tags")
9783 (org-tags-view arg path))
9785 ((string= type "tree-match")
9786 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9788 ((string= type "file")
9789 (if (string-match "::\\([0-9]+\\)\\'" path)
9790 (setq line (string-to-number (match-string 1 path))
9791 path (substring path 0 (match-beginning 0)))
9792 (if (string-match "::\\(.+\\)\\'" path)
9793 (setq search (match-string 1 path)
9794 path (substring path 0 (match-beginning 0)))))
9795 (if (string-match "[*?{]" (file-name-nondirectory path))
9796 (dired path)
9797 (org-open-file path arg line search)))
9799 ((string= type "shell")
9800 (let ((buf (generate-new-buffer "*Org Shell Output"))
9801 (cmd path))
9802 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9803 (string-match org-confirm-shell-link-not-regexp cmd))
9804 (not org-confirm-shell-link-function)
9805 (funcall org-confirm-shell-link-function
9806 (format "Execute \"%s\" in shell? "
9807 (org-add-props cmd nil
9808 'face 'org-warning))))
9809 (progn
9810 (message "Executing %s" cmd)
9811 (shell-command cmd buf)
9812 (if (featurep 'midnight)
9813 (setq clean-buffer-list-kill-buffer-names
9814 (cons buf clean-buffer-list-kill-buffer-names))))
9815 (error "Abort"))))
9817 ((string= type "elisp")
9818 (let ((cmd path))
9819 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9820 (string-match org-confirm-elisp-link-not-regexp cmd))
9821 (not org-confirm-elisp-link-function)
9822 (funcall org-confirm-elisp-link-function
9823 (format "Execute \"%s\" as elisp? "
9824 (org-add-props cmd nil
9825 'face 'org-warning))))
9826 (message "%s => %s" cmd
9827 (if (equal (string-to-char cmd) ?\()
9828 (eval (read cmd))
9829 (call-interactively (read cmd))))
9830 (error "Abort"))))
9832 ((and (string= type "thisfile")
9833 (run-hook-with-args-until-success
9834 'org-open-link-functions path)))
9836 ((string= type "thisfile")
9837 (if arg
9838 (switch-to-buffer-other-window
9839 (org-get-buffer-for-internal-link (current-buffer)))
9840 (org-mark-ring-push))
9841 (let ((cmd `(org-link-search
9842 ,path
9843 ,(cond ((equal arg '(4)) ''occur)
9844 ((equal arg '(16)) ''org-occur))
9845 ,pos)))
9846 (condition-case nil (let ((org-link-search-inhibit-query t))
9847 (eval cmd))
9848 (error (progn (widen) (eval cmd))))))
9850 (t (browse-url-at-point)))))))
9851 (move-marker org-open-link-marker nil)
9852 (run-hook-with-args 'org-follow-link-hook)))
9854 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9855 "Offer links in the current entry and return the selected link.
9856 If there is only one link, return it.
9857 If NTH is an integer, return the NTH link found.
9858 If ZERO is a string, check also this string for a link, and if
9859 there is one, return it."
9860 (with-current-buffer buffer
9861 (save-excursion
9862 (save-restriction
9863 (widen)
9864 (goto-char marker)
9865 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9866 "\\(" org-angle-link-re "\\)\\|"
9867 "\\(" org-plain-link-re "\\)"))
9868 (cnt ?0)
9869 (in-emacs (if (integerp nth) nil nth))
9870 have-zero end links link c)
9871 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9872 (push (match-string 0 zero) links)
9873 (setq cnt (1- cnt) have-zero t))
9874 (save-excursion
9875 (org-back-to-heading t)
9876 (setq end (save-excursion (outline-next-heading) (point)))
9877 (while (re-search-forward re end t)
9878 (push (match-string 0) links))
9879 (setq links (org-uniquify (reverse links))))
9880 (cond
9881 ((null links)
9882 (message "No links"))
9883 ((equal (length links) 1)
9884 (setq link (car links)))
9885 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9886 (setq link (nth (if have-zero nth (1- nth)) links)))
9887 (t ; we have to select a link
9888 (save-excursion
9889 (save-window-excursion
9890 (delete-other-windows)
9891 (with-output-to-temp-buffer "*Select Link*"
9892 (mapc (lambda (l)
9893 (if (not (string-match org-bracket-link-regexp l))
9894 (princ (format "[%c] %s\n" (incf cnt)
9895 (org-remove-angle-brackets l)))
9896 (if (match-end 3)
9897 (princ (format "[%c] %s (%s)\n" (incf cnt)
9898 (match-string 3 l) (match-string 1 l)))
9899 (princ (format "[%c] %s\n" (incf cnt)
9900 (match-string 1 l))))))
9901 links))
9902 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9903 (message "Select link to open, RET to open all:")
9904 (setq c (read-char-exclusive))
9905 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9906 (when (equal c ?q) (error "Abort"))
9907 (if (equal c ?\C-m)
9908 (setq link links)
9909 (setq nth (- c ?0))
9910 (if have-zero (setq nth (1+ nth)))
9911 (unless (and (integerp nth) (>= (length links) nth))
9912 (error "Invalid link selection"))
9913 (setq link (nth (1- nth) links)))))
9914 (cons link end))))))
9916 ;; Add special file links that specify the way of opening
9918 (org-add-link-type "file+sys" 'org-open-file-with-system)
9919 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9920 (defun org-open-file-with-system (path)
9921 "Open file at PATH using the system way of opening it."
9922 (org-open-file path 'system))
9923 (defun org-open-file-with-emacs (path)
9924 "Open file at PATH in Emacs."
9925 (org-open-file path 'emacs))
9926 (defun org-remove-file-link-modifiers ()
9927 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9928 (goto-char (point-min))
9929 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9930 (org-if-unprotected
9931 (replace-match "file:" t t))))
9932 (eval-after-load "org-exp"
9933 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9934 'org-remove-file-link-modifiers))
9936 ;;;; Time estimates
9938 (defun org-get-effort (&optional pom)
9939 "Get the effort estimate for the current entry."
9940 (org-entry-get pom org-effort-property))
9942 ;;; File search
9944 (defvar org-create-file-search-functions nil
9945 "List of functions to construct the right search string for a file link.
9946 These functions are called in turn with point at the location to
9947 which the link should point.
9949 A function in the hook should first test if it would like to
9950 handle this file type, for example by checking the `major-mode'
9951 or the file extension. If it decides not to handle this file, it
9952 should just return nil to give other functions a chance. If it
9953 does handle the file, it must return the search string to be used
9954 when following the link. The search string will be part of the
9955 file link, given after a double colon, and `org-open-at-point'
9956 will automatically search for it. If special measures must be
9957 taken to make the search successful, another function should be
9958 added to the companion hook `org-execute-file-search-functions',
9959 which see.
9961 A function in this hook may also use `setq' to set the variable
9962 `description' to provide a suggestion for the descriptive text to
9963 be used for this link when it gets inserted into an Org-mode
9964 buffer with \\[org-insert-link].")
9966 (defvar org-execute-file-search-functions nil
9967 "List of functions to execute a file search triggered by a link.
9969 Functions added to this hook must accept a single argument, the
9970 search string that was part of the file link, the part after the
9971 double colon. The function must first check if it would like to
9972 handle this search, for example by checking the `major-mode' or
9973 the file extension. If it decides not to handle this search, it
9974 should just return nil to give other functions a chance. If it
9975 does handle the search, it must return a non-nil value to keep
9976 other functions from trying.
9978 Each function can access the current prefix argument through the
9979 variable `current-prefix-argument'. Note that a single prefix is
9980 used to force opening a link in Emacs, so it may be good to only
9981 use a numeric or double prefix to guide the search function.
9983 In case this is needed, a function in this hook can also restore
9984 the window configuration before `org-open-at-point' was called using:
9986 (set-window-configuration org-window-config-before-follow-link)")
9988 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9989 (defun org-link-search (s &optional type avoid-pos stealth)
9990 "Search for a link search option.
9991 If S is surrounded by forward slashes, it is interpreted as a
9992 regular expression. In org-mode files, this will create an `org-occur'
9993 sparse tree. In ordinary files, `occur' will be used to list matches.
9994 If the current buffer is in `dired-mode', grep will be used to search
9995 in all files. If AVOID-POS is given, ignore matches near that position.
9997 When optional argument STEALTH is non-nil, do not modify
9998 visibility around point, thus ignoring
9999 `org-show-hierarchy-above', `org-show-following-heading' and
10000 `org-show-siblings' variables."
10001 (let ((case-fold-search t)
10002 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10003 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10004 (append '(("") (" ") ("\t") ("\n"))
10005 org-emphasis-alist)
10006 "\\|") "\\)"))
10007 (pos (point))
10008 (pre nil) (post nil)
10009 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10010 (cond
10011 ;; First check if there are any special search functions
10012 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10013 ;; Now try the builtin stuff
10014 ((and (equal (string-to-char s0) ?#)
10015 (> (length s0) 1)
10016 (save-excursion
10017 (goto-char (point-min))
10018 (and
10019 (re-search-forward
10020 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10021 (setq type 'dedicated
10022 pos (match-beginning 0))))
10023 ;; There is an exact target for this
10024 (goto-char pos)
10025 (org-back-to-heading t)))
10026 ((save-excursion
10027 (goto-char (point-min))
10028 (and
10029 (re-search-forward
10030 (concat "<<" (regexp-quote s0) ">>") nil t)
10031 (setq type 'dedicated
10032 pos (match-beginning 0))))
10033 ;; There is an exact target for this
10034 (goto-char pos))
10035 ((save-excursion
10036 (goto-char (point-min))
10037 (and
10038 (re-search-forward
10039 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10040 (setq type 'dedicated pos (match-beginning 0))))
10041 ;; Found an invisible target.
10042 (goto-char pos))
10043 ((save-excursion
10044 (goto-char (point-min))
10045 (and
10046 (re-search-forward
10047 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10048 (setq type 'dedicated pos (match-beginning 0))))
10049 ;; Found an element with a matching #+name affiliated keyword.
10050 (goto-char pos))
10051 ((and (string-match "^(\\(.*\\))$" s0)
10052 (save-excursion
10053 (goto-char (point-min))
10054 (and
10055 (re-search-forward
10056 (concat "[^[]" (regexp-quote
10057 (format org-coderef-label-format
10058 (match-string 1 s0))))
10059 nil t)
10060 (setq type 'dedicated
10061 pos (1+ (match-beginning 0))))))
10062 ;; There is a coderef target for this
10063 (goto-char pos))
10064 ((string-match "^/\\(.*\\)/$" s)
10065 ;; A regular expression
10066 (cond
10067 ((derived-mode-p 'org-mode)
10068 (org-occur (match-string 1 s)))
10069 ;;((eq major-mode 'dired-mode)
10070 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10071 (t (org-do-occur (match-string 1 s)))))
10072 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10073 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10074 (goto-char (point-min))
10075 (cond
10076 ((let (case-fold-search)
10077 (re-search-forward (format org-complex-heading-regexp-format
10078 (regexp-quote s))
10079 nil t))
10080 ;; OK, found a match
10081 (setq type 'dedicated)
10082 (goto-char (match-beginning 0)))
10083 ((and (not org-link-search-inhibit-query)
10084 (eq org-link-search-must-match-exact-headline 'query-to-create)
10085 (y-or-n-p "No match - create this as a new heading? "))
10086 (goto-char (point-max))
10087 (or (bolp) (newline))
10088 (insert "* " s "\n")
10089 (beginning-of-line 0))
10091 (goto-char pos)
10092 (error "No match"))))
10094 ;; A normal search string
10095 (when (equal (string-to-char s) ?*)
10096 ;; Anchor on headlines, post may include tags.
10097 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10098 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10099 s (substring s 1)))
10100 (remove-text-properties
10101 0 (length s)
10102 '(face nil mouse-face nil keymap nil fontified nil) s)
10103 ;; Make a series of regular expressions to find a match
10104 (setq words (org-split-string s "[ \n\r\t]+")
10106 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10107 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10108 "\\)" markers)
10109 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10110 re2a (concat "[ \t\r\n]" re2a_)
10111 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10112 re4 (concat "[^a-zA-Z_]" re4_)
10114 re1 (concat pre re2 post)
10115 re3 (concat pre (if pre re4_ re4) post)
10116 re5 (concat pre ".*" re4)
10117 re2 (concat pre re2)
10118 re2a (concat pre (if pre re2a_ re2a))
10119 re4 (concat pre (if pre re4_ re4))
10120 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10121 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10122 re5 "\\)"
10124 (cond
10125 ((eq type 'org-occur) (org-occur reall))
10126 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10127 (t (goto-char (point-min))
10128 (setq type 'fuzzy)
10129 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10130 (org-search-not-self 1 re1 nil t)
10131 (org-search-not-self 1 re2 nil t)
10132 (org-search-not-self 1 re2a nil t)
10133 (org-search-not-self 1 re3 nil t)
10134 (org-search-not-self 1 re4 nil t)
10135 (org-search-not-self 1 re5 nil t)
10137 (goto-char (match-beginning 1))
10138 (goto-char pos)
10139 (error "No match"))))))
10140 (and (derived-mode-p 'org-mode)
10141 (not stealth)
10142 (org-show-context 'link-search))
10143 type))
10145 (defun org-search-not-self (group &rest args)
10146 "Execute `re-search-forward', but only accept matches that do not
10147 enclose the position of `org-open-link-marker'."
10148 (let ((m org-open-link-marker))
10149 (catch 'exit
10150 (while (apply 're-search-forward args)
10151 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10152 (goto-char (match-end group))
10153 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10154 (> (match-beginning 0) (marker-position m))
10155 (< (match-end 0) (marker-position m)))
10156 (save-match-data
10157 (or (not (org-in-regexp
10158 org-bracket-link-analytic-regexp 1))
10159 (not (match-end 4)) ; no description
10160 (and (<= (match-beginning 4) (point))
10161 (>= (match-end 4) (point))))))
10162 (throw 'exit (point))))))))
10164 (defun org-get-buffer-for-internal-link (buffer)
10165 "Return a buffer to be used for displaying the link target of internal links."
10166 (cond
10167 ((not org-display-internal-link-with-indirect-buffer)
10168 buffer)
10169 ((string-match "(Clone)$" (buffer-name buffer))
10170 (message "Buffer is already a clone, not making another one")
10171 ;; we also do not modify visibility in this case
10172 buffer)
10173 (t ; make a new indirect buffer for displaying the link
10174 (let* ((bn (buffer-name buffer))
10175 (ibn (concat bn "(Clone)"))
10176 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10177 (with-current-buffer ib (org-overview))
10178 ib))))
10180 (defun org-do-occur (regexp &optional cleanup)
10181 "Call the Emacs command `occur'.
10182 If CLEANUP is non-nil, remove the printout of the regular expression
10183 in the *Occur* buffer. This is useful if the regex is long and not useful
10184 to read."
10185 (occur regexp)
10186 (when cleanup
10187 (let ((cwin (selected-window)) win beg end)
10188 (when (setq win (get-buffer-window "*Occur*"))
10189 (select-window win))
10190 (goto-char (point-min))
10191 (when (re-search-forward "match[a-z]+" nil t)
10192 (setq beg (match-end 0))
10193 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10194 (setq end (1- (match-beginning 0)))))
10195 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10196 (goto-char (point-min))
10197 (select-window cwin))))
10199 ;;; The mark ring for links jumps
10201 (defvar org-mark-ring nil
10202 "Mark ring for positions before jumps in Org-mode.")
10203 (defvar org-mark-ring-last-goto nil
10204 "Last position in the mark ring used to go back.")
10205 ;; Fill and close the ring
10206 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10207 (loop for i from 1 to org-mark-ring-length do
10208 (push (make-marker) org-mark-ring))
10209 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10210 org-mark-ring)
10212 (defun org-mark-ring-push (&optional pos buffer)
10213 "Put the current position or POS into the mark ring and rotate it."
10214 (interactive)
10215 (setq pos (or pos (point)))
10216 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10217 (move-marker (car org-mark-ring)
10218 (or pos (point))
10219 (or buffer (current-buffer)))
10220 (message "%s"
10221 (substitute-command-keys
10222 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10224 (defun org-mark-ring-goto (&optional n)
10225 "Jump to the previous position in the mark ring.
10226 With prefix arg N, jump back that many stored positions. When
10227 called several times in succession, walk through the entire ring.
10228 Org-mode commands jumping to a different position in the current file,
10229 or to another Org-mode file, automatically push the old position
10230 onto the ring."
10231 (interactive "p")
10232 (let (p m)
10233 (if (eq last-command this-command)
10234 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10235 (setq p org-mark-ring))
10236 (setq org-mark-ring-last-goto p)
10237 (setq m (car p))
10238 (org-pop-to-buffer-same-window (marker-buffer m))
10239 (goto-char m)
10240 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10242 (defun org-remove-angle-brackets (s)
10243 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10244 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10246 (defun org-add-angle-brackets (s)
10247 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10248 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10250 (defun org-remove-double-quotes (s)
10251 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10252 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10255 ;;; Following specific links
10257 (defun org-follow-timestamp-link ()
10258 "Open an agenda view for the time-stamp date/range at point."
10259 (cond
10260 ((org-at-date-range-p t)
10261 (let ((org-agenda-start-on-weekday)
10262 (t1 (match-string 1))
10263 (t2 (match-string 2)) tt1 tt2)
10264 (setq tt1 (time-to-days (org-time-string-to-time t1))
10265 tt2 (time-to-days (org-time-string-to-time t2)))
10266 (let ((org-agenda-buffer-tmp-name
10267 (format "*Org Agenda(a:%s)"
10268 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10269 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10270 ((org-at-timestamp-p t)
10271 (let ((org-agenda-buffer-tmp-name
10272 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10273 (org-agenda-list nil (time-to-days (org-time-string-to-time
10274 (substring (match-string 1) 0 10)))
10275 1)))
10276 (t (error "This should not happen"))))
10279 ;;; Following file links
10280 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10281 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10282 (declare-function mailcap-mime-info
10283 "mailcap" (string &optional request no-decode))
10284 (defvar org-wait nil)
10285 (defun org-open-file (path &optional in-emacs line search)
10286 "Open the file at PATH.
10287 First, this expands any special file name abbreviations. Then the
10288 configuration variable `org-file-apps' is checked if it contains an
10289 entry for this file type, and if yes, the corresponding command is launched.
10291 If no application is found, Emacs simply visits the file.
10293 With optional prefix argument IN-EMACS, Emacs will visit the file.
10294 With a double \\[universal-argument] \\[universal-argument] \
10295 prefix arg, Org tries to avoid opening in Emacs
10296 and to use an external application to visit the file.
10298 Optional LINE specifies a line to go to, optional SEARCH a string
10299 to search for. If LINE or SEARCH is given, the file will be
10300 opened in Emacs, unless an entry from org-file-apps that makes
10301 use of groups in a regexp matches.
10303 If you want to change the way frames are used when following a
10304 link, please customize `org-link-frame-setup'.
10306 If the file does not exist, an error is thrown."
10307 (let* ((file (if (equal path "")
10308 buffer-file-name
10309 (substitute-in-file-name (expand-file-name path))))
10310 (file-apps (append org-file-apps (org-default-apps)))
10311 (apps (org-remove-if
10312 'org-file-apps-entry-match-against-dlink-p file-apps))
10313 (apps-dlink (org-remove-if-not
10314 'org-file-apps-entry-match-against-dlink-p file-apps))
10315 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10316 (dirp (if remp nil (file-directory-p file)))
10317 (file (if (and dirp org-open-directory-means-index-dot-org)
10318 (concat (file-name-as-directory file) "index.org")
10319 file))
10320 (a-m-a-p (assq 'auto-mode apps))
10321 (dfile (downcase file))
10322 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10323 (link (cond ((and (eq line nil)
10324 (eq search nil))
10325 file)
10326 (line
10327 (concat file "::" (number-to-string line)))
10328 (search
10329 (concat file "::" search))))
10330 (dlink (downcase link))
10331 (old-buffer (current-buffer))
10332 (old-pos (point))
10333 (old-mode major-mode)
10334 ext cmd link-match-data)
10335 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10336 (setq ext (match-string 1 dfile))
10337 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10338 (setq ext (match-string 1 dfile))))
10339 (cond
10340 ((member in-emacs '((16) system))
10341 (setq cmd (cdr (assoc 'system apps))))
10342 (in-emacs (setq cmd 'emacs))
10344 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10345 (and dirp (cdr (assoc 'directory apps)))
10346 ; first, try matching against apps-dlink
10347 ; if we get a match here, store the match data for later
10348 (let ((match (assoc-default dlink apps-dlink
10349 'string-match)))
10350 (if match
10351 (progn (setq link-match-data (match-data))
10352 match)
10353 (progn (setq in-emacs (or in-emacs line search))
10354 nil))) ; if we have no match in apps-dlink,
10355 ; always open the file in emacs if line or search
10356 ; is given (for backwards compatibility)
10357 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10358 'string-match)
10359 (cdr (assoc ext apps))
10360 (cdr (assoc t apps))))))
10361 (when (eq cmd 'system)
10362 (setq cmd (cdr (assoc 'system apps))))
10363 (when (eq cmd 'default)
10364 (setq cmd (cdr (assoc t apps))))
10365 (when (eq cmd 'mailcap)
10366 (require 'mailcap)
10367 (mailcap-parse-mailcaps)
10368 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10369 (command (mailcap-mime-info mime-type)))
10370 (if (stringp command)
10371 (setq cmd command)
10372 (setq cmd 'emacs))))
10373 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10374 (not (file-exists-p file))
10375 (not org-open-non-existing-files))
10376 (error "No such file: %s" file))
10377 (cond
10378 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10379 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10380 (while (string-match "['\"]%s['\"]" cmd)
10381 (setq cmd (replace-match "%s" t t cmd)))
10382 (while (string-match "%s" cmd)
10383 (setq cmd (replace-match
10384 (save-match-data
10385 (shell-quote-argument
10386 (convert-standard-filename file)))
10387 t t cmd)))
10389 ;; Replace "%1", "%2" etc. in command with group matches from regex
10390 (save-match-data
10391 (let ((match-index 1)
10392 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10393 (set-match-data link-match-data)
10394 (while (<= match-index number-of-groups)
10395 (let ((regex (concat "%" (number-to-string match-index)))
10396 (replace-with (match-string match-index dlink)))
10397 (while (string-match regex cmd)
10398 (setq cmd (replace-match replace-with t t cmd))))
10399 (setq match-index (+ match-index 1)))))
10401 (save-window-excursion
10402 (start-process-shell-command cmd nil cmd)
10403 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10405 ((or (stringp cmd)
10406 (eq cmd 'emacs))
10407 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10408 (widen)
10409 (if line (org-goto-line line)
10410 (if search (org-link-search search))))
10411 ((consp cmd)
10412 (let ((file (convert-standard-filename file)))
10413 (save-match-data
10414 (set-match-data link-match-data)
10415 (eval cmd))))
10416 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10417 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10418 (or (not (equal old-buffer (current-buffer)))
10419 (not (equal old-pos (point))))
10420 (org-mark-ring-push old-pos old-buffer))))
10422 (defun org-file-apps-entry-match-against-dlink-p (entry)
10423 "This function returns non-nil if `entry' uses a regular
10424 expression which should be matched against the whole link by
10425 org-open-file.
10427 It assumes that is the case when the entry uses a regular
10428 expression which has at least one grouping construct and the
10429 action is either a lisp form or a command string containing
10430 '%1', i.e. using at least one subexpression match as a
10431 parameter."
10432 (let ((selector (car entry))
10433 (action (cdr entry)))
10434 (if (stringp selector)
10435 (and (> (regexp-opt-depth selector) 0)
10436 (or (and (stringp action)
10437 (string-match "%[0-9]" action))
10438 (consp action)))
10439 nil)))
10441 (defun org-default-apps ()
10442 "Return the default applications for this operating system."
10443 (cond
10444 ((eq system-type 'darwin)
10445 org-file-apps-defaults-macosx)
10446 ((eq system-type 'windows-nt)
10447 org-file-apps-defaults-windowsnt)
10448 (t org-file-apps-defaults-gnu)))
10450 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10451 "Convert extensions to regular expressions in the cars of LIST.
10452 Also, weed out any non-string entries, because the return value is used
10453 only for regexp matching.
10454 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10455 point to the symbol `emacs', indicating that the file should
10456 be opened in Emacs."
10457 (append
10458 (delq nil
10459 (mapcar (lambda (x)
10460 (if (not (stringp (car x)))
10462 (if (string-match "\\W" (car x))
10464 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10465 list))
10466 (if add-auto-mode
10467 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10469 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10470 (defun org-file-remote-p (file)
10471 "Test whether FILE specifies a location on a remote system.
10472 Return non-nil if the location is indeed remote.
10474 For example, the filename \"/user@host:/foo\" specifies a location
10475 on the system \"/user@host:\"."
10476 (cond ((fboundp 'file-remote-p)
10477 (file-remote-p file))
10478 ((fboundp 'tramp-handle-file-remote-p)
10479 (tramp-handle-file-remote-p file))
10480 ((and (boundp 'ange-ftp-name-format)
10481 (string-match (car ange-ftp-name-format) file))
10482 t)))
10485 ;;;; Refiling
10487 (defun org-get-org-file ()
10488 "Read a filename, with default directory `org-directory'."
10489 (let ((default (or org-default-notes-file remember-data-file)))
10490 (read-file-name (format "File name [%s]: " default)
10491 (file-name-as-directory org-directory)
10492 default)))
10494 (defun org-notes-order-reversed-p ()
10495 "Check if the current file should receive notes in reversed order."
10496 (cond
10497 ((not org-reverse-note-order) nil)
10498 ((eq t org-reverse-note-order) t)
10499 ((not (listp org-reverse-note-order)) nil)
10500 (t (catch 'exit
10501 (let ((all org-reverse-note-order)
10502 entry)
10503 (while (setq entry (pop all))
10504 (if (string-match (car entry) buffer-file-name)
10505 (throw 'exit (cdr entry))))
10506 nil)))))
10508 (defvar org-refile-target-table nil
10509 "The list of refile targets, created by `org-refile'.")
10511 (defvar org-agenda-new-buffers nil
10512 "Buffers created to visit agenda files.")
10514 (defvar org-refile-cache nil
10515 "Cache for refile targets.")
10517 (defvar org-refile-markers nil
10518 "All the markers used for caching refile locations.")
10520 (defun org-refile-marker (pos)
10521 "Get a new refile marker, but only if caching is in use."
10522 (if (not org-refile-use-cache)
10524 (let ((m (make-marker)))
10525 (move-marker m pos)
10526 (push m org-refile-markers)
10527 m)))
10529 (defun org-refile-cache-clear ()
10530 "Clear the refile cache and disable all the markers."
10531 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10532 (setq org-refile-markers nil)
10533 (setq org-refile-cache nil)
10534 (message "Refile cache has been cleared"))
10536 (defun org-refile-cache-check-set (set)
10537 "Check if all the markers in the cache still have live buffers."
10538 (let (marker)
10539 (catch 'exit
10540 (while (and set (setq marker (nth 3 (pop set))))
10541 ;; if org-refile-use-outline-path is 'file, marker may be nil
10542 (when (and marker (null (marker-buffer marker)))
10543 (message "not found") (sit-for 3)
10544 (throw 'exit nil)))
10545 t)))
10547 (defun org-refile-cache-put (set &rest identifiers)
10548 "Push the refile targets SET into the cache, under IDENTIFIERS."
10549 (let* ((key (sha1 (prin1-to-string identifiers)))
10550 (entry (assoc key org-refile-cache)))
10551 (if entry
10552 (setcdr entry set)
10553 (push (cons key set) org-refile-cache))))
10555 (defun org-refile-cache-get (&rest identifiers)
10556 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10557 (cond
10558 ((not org-refile-cache) nil)
10559 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10561 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10562 org-refile-cache))))
10563 (and set (org-refile-cache-check-set set) set)))))
10565 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10566 "Produce a table with refile targets."
10567 (let ((case-fold-search nil)
10568 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10569 (entries (or org-refile-targets '((nil . (:level . 1)))))
10570 targets tgs txt re files f desc descre fast-path-p level pos0)
10571 (message "Getting targets...")
10572 (with-current-buffer (or default-buffer (current-buffer))
10573 (while (setq entry (pop entries))
10574 (setq files (car entry) desc (cdr entry))
10575 (setq fast-path-p nil)
10576 (cond
10577 ((null files) (setq files (list (current-buffer))))
10578 ((eq files 'org-agenda-files)
10579 (setq files (org-agenda-files 'unrestricted)))
10580 ((and (symbolp files) (fboundp files))
10581 (setq files (funcall files)))
10582 ((and (symbolp files) (boundp files))
10583 (setq files (symbol-value files))))
10584 (if (stringp files) (setq files (list files)))
10585 (cond
10586 ((eq (car desc) :tag)
10587 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10588 ((eq (car desc) :todo)
10589 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10590 ((eq (car desc) :regexp)
10591 (setq descre (cdr desc)))
10592 ((eq (car desc) :level)
10593 (setq descre (concat "^\\*\\{" (number-to-string
10594 (if org-odd-levels-only
10595 (1- (* 2 (cdr desc)))
10596 (cdr desc)))
10597 "\\}[ \t]")))
10598 ((eq (car desc) :maxlevel)
10599 (setq fast-path-p t)
10600 (setq descre (concat "^\\*\\{1," (number-to-string
10601 (if org-odd-levels-only
10602 (1- (* 2 (cdr desc)))
10603 (cdr desc)))
10604 "\\}[ \t]")))
10605 (t (error "Bad refiling target description %s" desc)))
10606 (while (setq f (pop files))
10607 (with-current-buffer
10608 (if (bufferp f) f (org-get-agenda-file-buffer f))
10610 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10611 (progn
10612 (if (bufferp f) (setq f (buffer-file-name
10613 (buffer-base-buffer f))))
10614 (setq f (and f (expand-file-name f)))
10615 (if (eq org-refile-use-outline-path 'file)
10616 (push (list (file-name-nondirectory f) f nil nil) tgs))
10617 (save-excursion
10618 (save-restriction
10619 (widen)
10620 (goto-char (point-min))
10621 (while (re-search-forward descre nil t)
10622 (goto-char (setq pos0 (point-at-bol)))
10623 (catch 'next
10624 (when org-refile-target-verify-function
10625 (save-match-data
10626 (or (funcall org-refile-target-verify-function)
10627 (throw 'next t))))
10628 (when (and (looking-at org-complex-heading-regexp)
10629 (not (member (match-string 4) excluded-entries))
10630 (match-string 4))
10631 (setq level (org-reduced-level
10632 (- (match-end 1) (match-beginning 1)))
10633 txt (org-link-display-format (match-string 4))
10634 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10635 re (format org-complex-heading-regexp-format
10636 (regexp-quote (match-string 4))))
10637 (when org-refile-use-outline-path
10638 (setq txt (mapconcat
10639 'org-protect-slash
10640 (append
10641 (if (eq org-refile-use-outline-path
10642 'file)
10643 (list (file-name-nondirectory
10644 (buffer-file-name
10645 (buffer-base-buffer))))
10646 (if (eq org-refile-use-outline-path
10647 'full-file-path)
10648 (list (buffer-file-name
10649 (buffer-base-buffer)))))
10650 (org-get-outline-path fast-path-p
10651 level txt)
10652 (list txt))
10653 "/")))
10654 (push (list txt f re (org-refile-marker (point)))
10655 tgs)))
10656 (when (= (point) pos0)
10657 ;; verification function has not moved point
10658 (goto-char (point-at-eol))))))))
10659 (when org-refile-use-cache
10660 (org-refile-cache-put tgs (buffer-file-name) descre))
10661 (setq targets (append tgs targets))
10662 ))))
10663 (message "Getting targets...done")
10664 (nreverse targets)))
10666 (defun org-protect-slash (s)
10667 (while (string-match "/" s)
10668 (setq s (replace-match "\\" t t s)))
10671 (defvar org-olpa (make-vector 20 nil))
10673 (defun org-get-outline-path (&optional fastp level heading)
10674 "Return the outline path to the current entry, as a list.
10676 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10677 routine which makes outline path derivations for an entire file,
10678 avoiding backtracing. Refile target collection makes use of that."
10679 (if fastp
10680 (progn
10681 (if (> level 19)
10682 (error "Outline path failure, more than 19 levels"))
10683 (loop for i from level upto 19 do
10684 (aset org-olpa i nil))
10685 (prog1
10686 (delq nil (append org-olpa nil))
10687 (aset org-olpa level heading)))
10688 (let (rtn case-fold-search)
10689 (save-excursion
10690 (save-restriction
10691 (widen)
10692 (while (org-up-heading-safe)
10693 (when (looking-at org-complex-heading-regexp)
10694 (push (org-match-string-no-properties 4) rtn)))
10695 rtn)))))
10697 (defun org-format-outline-path (path &optional width prefix)
10698 "Format the outline path PATH for display.
10699 Width is the maximum number of characters that is available.
10700 Prefix is a prefix to be included in the returned string,
10701 such as the file name."
10702 (setq width (or width 79))
10703 (if prefix (setq width (- width (length prefix))))
10704 (if (not path)
10705 (or prefix "")
10706 (let* ((nsteps (length path))
10707 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10708 (maxwidth (if (<= total-width width)
10709 10000 ;; everything fits
10710 ;; we need to shorten the level headings
10711 (/ (- width nsteps) nsteps)))
10712 (org-odd-levels-only nil)
10713 (n 0)
10714 (total (1+ (length prefix))))
10715 (setq maxwidth (max maxwidth 10))
10716 (concat prefix
10717 (mapconcat
10718 (lambda (h)
10719 (setq n (1+ n))
10720 (if (and (= n nsteps) (< maxwidth 10000))
10721 (setq maxwidth (- total-width total)))
10722 (if (< (length h) maxwidth)
10723 (progn (setq total (+ total (length h) 1)) h)
10724 (setq h (substring h 0 (- maxwidth 2))
10725 total (+ total maxwidth 1))
10726 (if (string-match "[ \t]+\\'" h)
10727 (setq h (substring h 0 (match-beginning 0))))
10728 (setq h (concat h "..")))
10729 (org-add-props h nil 'face
10730 (nth (% (1- n) org-n-level-faces)
10731 org-level-faces))
10733 path "/")))))
10735 (defun org-display-outline-path (&optional file current)
10736 "Display the current outline path in the echo area."
10737 (interactive "P")
10738 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10739 (case-fold-search nil)
10740 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10741 (if current (setq path (append path
10742 (save-excursion
10743 (org-back-to-heading t)
10744 (if (looking-at org-complex-heading-regexp)
10745 (list (match-string 4)))))))
10746 (message "%s"
10747 (org-format-outline-path
10748 path
10749 (1- (frame-width))
10750 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10752 (defvar org-refile-history nil
10753 "History for refiling operations.")
10755 (defvar org-after-refile-insert-hook nil
10756 "Hook run after `org-refile' has inserted its stuff at the new location.
10757 Note that this is still *before* the stuff will be removed from
10758 the *old* location.")
10760 (defvar org-capture-last-stored-marker)
10761 (defun org-refile (&optional goto default-buffer rfloc)
10762 "Move the entry or entries at point to another heading.
10763 The list of target headings is compiled using the information in
10764 `org-refile-targets', which see.
10766 At the target location, the entry is filed as a subitem of the target
10767 heading. Depending on `org-reverse-note-order', the new subitem will
10768 either be the first or the last subitem.
10770 If there is an active region, all entries in that region will be moved.
10771 However, the region must fulfill the requirement that the first heading
10772 is the first one sets the top-level of the moved text - at most siblings
10773 below it are allowed.
10775 With prefix arg GOTO, the command will only visit the target location
10776 and not actually move anything.
10778 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10779 go to the location where the last refiling operation has put the subtree.
10780 With a prefix argument of `2', refile to the running clock.
10782 RFLOC can be a refile location obtained in a different way.
10784 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10786 If you are using target caching (see `org-refile-use-cache'),
10787 you have to clear the target cache in order to find new targets.
10788 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10789 prefix argument (`C-u C-u C-u C-c C-w')."
10791 (interactive "P")
10792 (if (member goto '(0 (64)))
10793 (org-refile-cache-clear)
10794 (let* ((cbuf (current-buffer))
10795 (regionp (org-region-active-p))
10796 (region-start (and regionp (region-beginning)))
10797 (region-end (and regionp (region-end)))
10798 (region-length (and regionp (- region-end region-start)))
10799 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10800 pos it nbuf file re level reversed)
10801 (setq last-command nil)
10802 (when regionp
10803 (goto-char region-start)
10804 (or (bolp) (goto-char (point-at-bol)))
10805 (setq region-start (point))
10806 (unless (or (org-kill-is-subtree-p
10807 (buffer-substring region-start region-end))
10808 (prog1 org-refile-active-region-within-subtree
10809 (org-toggle-heading)))
10810 (error "The region is not a (sequence of) subtree(s)")))
10811 (if (equal goto '(16))
10812 (org-refile-goto-last-stored)
10813 (when (or
10814 (and (equal goto 2)
10815 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10816 (prog1
10817 (setq it (list (or org-clock-heading "running clock")
10818 (buffer-file-name
10819 (marker-buffer org-clock-hd-marker))
10821 (marker-position org-clock-hd-marker)))
10822 (setq goto nil)))
10823 (setq it (or rfloc
10824 (let (heading-text)
10825 (save-excursion
10826 (unless goto
10827 (org-back-to-heading t)
10828 (setq heading-text
10829 (nth 4 (org-heading-components))))
10830 (org-refile-get-location
10831 (cond (goto "Goto")
10832 (regionp "Refile region to")
10833 (t (concat "Refile subtree \""
10834 heading-text "\" to")))
10835 default-buffer
10836 (and (not (equal '(4) goto))
10837 org-refile-allow-creating-parent-nodes)
10838 goto))))))
10839 (setq file (nth 1 it)
10840 re (nth 2 it)
10841 pos (nth 3 it))
10842 (if (and (not goto)
10844 (equal (buffer-file-name) file)
10845 (if regionp
10846 (and (>= pos region-start)
10847 (<= pos region-end))
10848 (and (>= pos (point))
10849 (< pos (save-excursion
10850 (org-end-of-subtree t t))))))
10851 (error "Cannot refile to position inside the tree or region"))
10853 (setq nbuf (or (find-buffer-visiting file)
10854 (find-file-noselect file)))
10855 (if goto
10856 (progn
10857 (org-pop-to-buffer-same-window nbuf)
10858 (goto-char pos)
10859 (org-show-context 'org-goto))
10860 (if regionp
10861 (progn
10862 (org-kill-new (buffer-substring region-start region-end))
10863 (org-save-markers-in-region region-start region-end))
10864 (org-copy-subtree 1 nil t))
10865 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10866 (find-file-noselect file)))
10867 (setq reversed (org-notes-order-reversed-p))
10868 (save-excursion
10869 (save-restriction
10870 (widen)
10871 (if pos
10872 (progn
10873 (goto-char pos)
10874 (looking-at org-outline-regexp)
10875 (setq level (org-get-valid-level (funcall outline-level) 1))
10876 (goto-char
10877 (if reversed
10878 (or (outline-next-heading) (point-max))
10879 (or (save-excursion (org-get-next-sibling))
10880 (org-end-of-subtree t t)
10881 (point-max)))))
10882 (setq level 1)
10883 (if (not reversed)
10884 (goto-char (point-max))
10885 (goto-char (point-min))
10886 (or (outline-next-heading) (goto-char (point-max)))))
10887 (if (not (bolp)) (newline))
10888 (org-paste-subtree level)
10889 (when org-log-refile
10890 (org-add-log-setup 'refile nil nil 'findpos
10891 org-log-refile)
10892 (unless (eq org-log-refile 'note)
10893 (save-excursion (org-add-log-note))))
10894 (and org-auto-align-tags
10895 (let ((org-loop-over-headlines-in-active-region nil))
10896 (org-set-tags nil t)))
10897 (with-demoted-errors
10898 (bookmark-set "org-refile-last-stored"))
10899 ;; If we are refiling for capture, make sure that the
10900 ;; last-capture pointers point here
10901 (when (org-bound-and-true-p org-refile-for-capture)
10902 (with-demoted-errors
10903 (bookmark-set "org-capture-last-stored-marker"))
10904 (move-marker org-capture-last-stored-marker (point)))
10905 (if (fboundp 'deactivate-mark) (deactivate-mark))
10906 (run-hooks 'org-after-refile-insert-hook))))
10907 (if regionp
10908 (delete-region (point) (+ (point) region-length))
10909 (org-cut-subtree))
10910 (when (featurep 'org-inlinetask)
10911 (org-inlinetask-remove-END-maybe))
10912 (setq org-markers-to-move nil)
10913 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10915 (defun org-refile-goto-last-stored ()
10916 "Go to the location where the last refile was stored."
10917 (interactive)
10918 (bookmark-jump "org-refile-last-stored")
10919 (message "This is the location of the last refile"))
10921 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10922 no-exclude)
10923 "Prompt the user for a refile location, using PROMPT.
10924 PROMPT should not be suffixed with a colon and a space, because
10925 this function appends the default value from
10926 `org-refile-history' automatically, if that is not empty.
10927 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10928 this is used for the GOTO interface."
10929 (let ((org-refile-targets org-refile-targets)
10930 (org-refile-use-outline-path org-refile-use-outline-path)
10931 excluded-entries)
10932 (when (and (derived-mode-p 'org-mode)
10933 (not org-refile-use-cache)
10934 (not no-exclude))
10935 (org-map-tree
10936 (lambda()
10937 (setq excluded-entries
10938 (append excluded-entries (list (org-get-heading t t)))))))
10939 (setq org-refile-target-table
10940 (org-refile-get-targets default-buffer excluded-entries)))
10941 (unless org-refile-target-table
10942 (error "No refile targets"))
10943 (let* ((prompt (concat prompt
10944 (and (car org-refile-history)
10945 (concat " (default " (car org-refile-history) ")"))
10946 ": "))
10947 (cbuf (current-buffer))
10948 (partial-completion-mode nil)
10949 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10950 (cfunc (if (and org-refile-use-outline-path
10951 org-outline-path-complete-in-steps)
10952 'org-olpath-completing-read
10953 'org-icompleting-read))
10954 (extra (if org-refile-use-outline-path "/" ""))
10955 (filename (and cfn (expand-file-name cfn)))
10956 (tbl (mapcar
10957 (lambda (x)
10958 (if (and (not (member org-refile-use-outline-path
10959 '(file full-file-path)))
10960 (not (equal filename (nth 1 x))))
10961 (cons (concat (car x) extra " ("
10962 (file-name-nondirectory (nth 1 x)) ")")
10963 (cdr x))
10964 (cons (concat (car x) extra) (cdr x))))
10965 org-refile-target-table))
10966 (completion-ignore-case t)
10967 pa answ parent-target child parent old-hist)
10968 (setq old-hist org-refile-history)
10969 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10970 nil 'org-refile-history (car org-refile-history)))
10971 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10972 (org-refile-check-position pa)
10973 (if pa
10974 (progn
10975 (when (or (not org-refile-history)
10976 (not (eq old-hist org-refile-history))
10977 (not (equal (car pa) (car org-refile-history))))
10978 (setq org-refile-history
10979 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10980 org-refile-history
10981 (cdr org-refile-history))))
10982 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10983 (pop org-refile-history)))
10985 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10986 (progn
10987 (setq parent (match-string 1 answ)
10988 child (match-string 2 answ))
10989 (setq parent-target (or (assoc parent tbl)
10990 (assoc (concat parent "/") tbl)))
10991 (when (and parent-target
10992 (or (eq new-nodes t)
10993 (and (eq new-nodes 'confirm)
10994 (y-or-n-p (format "Create new node \"%s\"? "
10995 child)))))
10996 (org-refile-new-child parent-target child)))
10997 (error "Invalid target location")))))
10999 (declare-function org-string-nw-p "org-macs" (s))
11000 (defun org-refile-check-position (refile-pointer)
11001 "Check if the refile pointer matches the headline to which it points."
11002 (let* ((file (nth 1 refile-pointer))
11003 (re (nth 2 refile-pointer))
11004 (pos (nth 3 refile-pointer))
11005 buffer)
11006 (if (and (not (markerp pos)) (not file))
11007 (error "Please save the buffer to a file before refiling")
11008 (when (org-string-nw-p re)
11009 (setq buffer (if (markerp pos)
11010 (marker-buffer pos)
11011 (or (find-buffer-visiting file)
11012 (find-file-noselect file))))
11013 (with-current-buffer buffer
11014 (save-excursion
11015 (save-restriction
11016 (widen)
11017 (goto-char pos)
11018 (beginning-of-line 1)
11019 (unless (org-looking-at-p re)
11020 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11022 (defun org-refile-new-child (parent-target child)
11023 "Use refile target PARENT-TARGET to add new CHILD below it."
11024 (unless parent-target
11025 (error "Cannot find parent for new node"))
11026 (let ((file (nth 1 parent-target))
11027 (pos (nth 3 parent-target))
11028 level)
11029 (with-current-buffer (or (find-buffer-visiting file)
11030 (find-file-noselect file))
11031 (save-excursion
11032 (save-restriction
11033 (widen)
11034 (if pos
11035 (goto-char pos)
11036 (goto-char (point-max))
11037 (if (not (bolp)) (newline)))
11038 (when (looking-at org-outline-regexp)
11039 (setq level (funcall outline-level))
11040 (org-end-of-subtree t t))
11041 (org-back-over-empty-lines)
11042 (insert "\n" (make-string
11043 (if pos (org-get-valid-level level 1) 1) ?*)
11044 " " child "\n")
11045 (beginning-of-line 0)
11046 (list (concat (car parent-target) "/" child) file "" (point)))))))
11048 (defun org-olpath-completing-read (prompt collection &rest args)
11049 "Read an outline path like a file name."
11050 (let ((thetable collection)
11051 (org-completion-use-ido nil) ; does not work with ido.
11052 (org-completion-use-iswitchb nil)) ; or iswitchb
11053 (apply
11054 'org-icompleting-read prompt
11055 (lambda (string predicate &optional flag)
11056 (let (rtn r f (l (length string)))
11057 (cond
11058 ((eq flag nil)
11059 ;; try completion
11060 (try-completion string thetable))
11061 ((eq flag t)
11062 ;; all-completions
11063 (setq rtn (all-completions string thetable predicate))
11064 (mapcar
11065 (lambda (x)
11066 (setq r (substring x l))
11067 (if (string-match " ([^)]*)$" x)
11068 (setq f (match-string 0 x))
11069 (setq f ""))
11070 (if (string-match "/" r)
11071 (concat string (substring r 0 (match-end 0)) f)
11073 rtn))
11074 ((eq flag 'lambda)
11075 ;; exact match?
11076 (assoc string thetable)))))
11077 args)))
11079 ;;;; Dynamic blocks
11081 (defun org-find-dblock (name)
11082 "Find the first dynamic block with name NAME in the buffer.
11083 If not found, stay at current position and return nil."
11084 (let ((case-fold-search t) pos)
11085 (save-excursion
11086 (goto-char (point-min))
11087 (setq pos (and (re-search-forward
11088 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11089 (match-beginning 0))))
11090 (if pos (goto-char pos))
11091 pos))
11093 (defconst org-dblock-start-re
11094 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11095 "Matches the start line of a dynamic block, with parameters.")
11097 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11098 "Matches the end of a dynamic block.")
11100 (defun org-create-dblock (plist)
11101 "Create a dynamic block section, with parameters taken from PLIST.
11102 PLIST must contain a :name entry which is used as name of the block."
11103 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11104 (end-of-line 1)
11105 (newline))
11106 (let ((col (current-column))
11107 (name (plist-get plist :name)))
11108 (insert "#+BEGIN: " name)
11109 (while plist
11110 (if (eq (car plist) :name)
11111 (setq plist (cddr plist))
11112 (insert " " (prin1-to-string (pop plist)))))
11113 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11114 (beginning-of-line -2)))
11116 (defun org-prepare-dblock ()
11117 "Prepare dynamic block for refresh.
11118 This empties the block, puts the cursor at the insert position and returns
11119 the property list including an extra property :name with the block name."
11120 (unless (looking-at org-dblock-start-re)
11121 (error "Not at a dynamic block"))
11122 (let* ((begdel (1+ (match-end 0)))
11123 (name (org-no-properties (match-string 1)))
11124 (params (append (list :name name)
11125 (read (concat "(" (match-string 3) ")")))))
11126 (save-excursion
11127 (beginning-of-line 1)
11128 (skip-chars-forward " \t")
11129 (setq params (plist-put params :indentation-column (current-column))))
11130 (unless (re-search-forward org-dblock-end-re nil t)
11131 (error "Dynamic block not terminated"))
11132 (setq params
11133 (append params
11134 (list :content (buffer-substring
11135 begdel (match-beginning 0)))))
11136 (delete-region begdel (match-beginning 0))
11137 (goto-char begdel)
11138 (open-line 1)
11139 params))
11141 (defun org-map-dblocks (&optional command)
11142 "Apply COMMAND to all dynamic blocks in the current buffer.
11143 If COMMAND is not given, use `org-update-dblock'."
11144 (let ((cmd (or command 'org-update-dblock)))
11145 (save-excursion
11146 (goto-char (point-min))
11147 (while (re-search-forward org-dblock-start-re nil t)
11148 (goto-char (match-beginning 0))
11149 (save-excursion
11150 (condition-case nil
11151 (funcall cmd)
11152 (error (message "Error during update of dynamic block"))))
11153 (unless (re-search-forward org-dblock-end-re nil t)
11154 (error "Dynamic block not terminated"))))))
11156 (defun org-dblock-update (&optional arg)
11157 "User command for updating dynamic blocks.
11158 Update the dynamic block at point. With prefix ARG, update all dynamic
11159 blocks in the buffer."
11160 (interactive "P")
11161 (if arg
11162 (org-update-all-dblocks)
11163 (or (looking-at org-dblock-start-re)
11164 (org-beginning-of-dblock))
11165 (org-update-dblock)))
11167 (defun org-update-dblock ()
11168 "Update the dynamic block at point.
11169 This means to empty the block, parse for parameters and then call
11170 the correct writing function."
11171 (interactive)
11172 (save-window-excursion
11173 (let* ((pos (point))
11174 (line (org-current-line))
11175 (params (org-prepare-dblock))
11176 (name (plist-get params :name))
11177 (indent (plist-get params :indentation-column))
11178 (cmd (intern (concat "org-dblock-write:" name))))
11179 (message "Updating dynamic block `%s' at line %d..." name line)
11180 (funcall cmd params)
11181 (message "Updating dynamic block `%s' at line %d...done" name line)
11182 (goto-char pos)
11183 (when (and indent (> indent 0))
11184 (setq indent (make-string indent ?\ ))
11185 (save-excursion
11186 (org-beginning-of-dblock)
11187 (forward-line 1)
11188 (while (not (looking-at org-dblock-end-re))
11189 (insert indent)
11190 (beginning-of-line 2))
11191 (when (looking-at org-dblock-end-re)
11192 (and (looking-at "[ \t]+")
11193 (replace-match ""))
11194 (insert indent)))))))
11196 (defun org-beginning-of-dblock ()
11197 "Find the beginning of the dynamic block at point.
11198 Error if there is no such block at point."
11199 (let ((pos (point))
11200 beg)
11201 (end-of-line 1)
11202 (if (and (re-search-backward org-dblock-start-re nil t)
11203 (setq beg (match-beginning 0))
11204 (re-search-forward org-dblock-end-re nil t)
11205 (> (match-end 0) pos))
11206 (goto-char beg)
11207 (goto-char pos)
11208 (error "Not in a dynamic block"))))
11210 (defun org-update-all-dblocks ()
11211 "Update all dynamic blocks in the buffer.
11212 This function can be used in a hook."
11213 (interactive)
11214 (when (derived-mode-p 'org-mode)
11215 (org-map-dblocks 'org-update-dblock)))
11218 ;;;; Completion
11220 (defconst org-additional-option-like-keywords
11221 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11222 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11223 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11224 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11225 "BEGIN:" "END:"
11226 "ORGTBL" "TBLFM:" "TBLNAME:"
11227 "BEGIN_EXAMPLE" "END_EXAMPLE"
11228 "BEGIN_VERBATIM" "END_VERBATIM"
11229 "BEGIN_QUOTE" "END_QUOTE"
11230 "BEGIN_VERSE" "END_VERSE"
11231 "BEGIN_CENTER" "END_CENTER"
11232 "BEGIN_SRC" "END_SRC"
11233 "BEGIN_RESULT" "END_RESULT"
11234 "BEGIN_lstlisting" "END_lstlisting"
11235 "NAME:" "RESULTS:"
11236 "HEADER:" "HEADERS:"
11237 "COLUMNS:" "PROPERTY:"
11238 "CAPTION:" "LABEL:"
11239 "SETUPFILE:"
11240 "INCLUDE:" "INDEX:"
11241 "BIND:"
11242 "MACRO:"))
11244 (defconst org-options-keywords
11245 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11246 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11247 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11248 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11249 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11250 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11251 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11253 (defconst org-additional-option-like-keywords-for-flyspell
11254 (delete-dups
11255 (split-string
11256 (mapconcat (lambda(k)
11257 (replace-regexp-in-string
11258 "_\\|:" " "
11259 (concat k " " (downcase k) " " (upcase k))))
11260 (append org-options-keywords org-additional-option-like-keywords)
11261 " ")
11262 " +" t)))
11264 (defcustom org-structure-template-alist
11265 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11266 "<src lang=\"?\">\n\n</src>")
11267 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11268 "<example>\n?\n</example>")
11269 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11270 "<quote>\n?\n</quote>")
11271 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11272 "<verse>\n?\n</verse>")
11273 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11274 "<verbatim>\n?\n</verbatim>")
11275 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11276 "<center>\n?\n</center>")
11277 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11278 "<literal style=\"latex\">\n?\n</literal>")
11279 ("L" "#+LaTeX: "
11280 "<literal style=\"latex\">?</literal>")
11281 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11282 "<literal style=\"html\">\n?\n</literal>")
11283 ("H" "#+HTML: "
11284 "<literal style=\"html\">?</literal>")
11285 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11286 ("A" "#+ASCII: ")
11287 ("i" "#+INDEX: ?"
11288 "#+INDEX: ?")
11289 ("I" "#+INCLUDE: %file ?"
11290 "<include file=%file markup=\"?\">"))
11291 "Structure completion elements.
11292 This is a list of abbreviation keys and values. The value gets inserted
11293 if you type `<' followed by the key and then press the completion key,
11294 usually `M-TAB'. %file will be replaced by a file name after prompting
11295 for the file using completion. The cursor will be placed at the position
11296 of the `?` in the template.
11297 There are two templates for each key, the first uses the original Org syntax,
11298 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11299 the default when the /org-mtags.el/ module has been loaded. See also the
11300 variable `org-mtags-prefer-muse-templates'."
11301 :group 'org-completion
11302 :type '(repeat
11303 (string :tag "Key")
11304 (string :tag "Template")
11305 (string :tag "Muse Template")))
11307 (defun org-try-structure-completion ()
11308 "Try to complete a structure template before point.
11309 This looks for strings like \"<e\" on an otherwise empty line and
11310 expands them."
11311 (let ((l (buffer-substring (point-at-bol) (point)))
11313 (when (and (looking-at "[ \t]*$")
11314 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11315 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11316 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11317 (match-beginning 1)) a)
11318 t)))
11320 (defun org-complete-expand-structure-template (start cell)
11321 "Expand a structure template."
11322 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11323 (rpl (nth (if musep 2 1) cell))
11324 (ind ""))
11325 (delete-region start (point))
11326 (when (string-match "\\`#\\+" rpl)
11327 (cond
11328 ((bolp))
11329 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11330 (setq ind (buffer-substring (point-at-bol) (point))))
11331 (t (newline))))
11332 (setq start (point))
11333 (if (string-match "%file" rpl)
11334 (setq rpl (replace-match
11335 (concat
11336 "\""
11337 (save-match-data
11338 (abbreviate-file-name (read-file-name "Include file: ")))
11339 "\"")
11340 t t rpl)))
11341 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11342 (concat "\n" ind)))
11343 (insert rpl)
11344 (if (re-search-backward "\\?" start t) (delete-char 1))))
11346 ;;;; TODO, DEADLINE, Comments
11348 (defun org-toggle-comment ()
11349 "Change the COMMENT state of an entry."
11350 (interactive)
11351 (save-excursion
11352 (org-back-to-heading)
11353 (let (case-fold-search)
11354 (cond
11355 ((looking-at (format org-heading-keyword-regexp-format
11356 org-comment-string))
11357 (goto-char (match-end 1))
11358 (looking-at (concat " +" org-comment-string))
11359 (replace-match "" t t)
11360 (when (eolp) (insert " ")))
11361 ((looking-at org-outline-regexp)
11362 (goto-char (match-end 0))
11363 (insert org-comment-string " "))))))
11365 (defvar org-last-todo-state-is-todo nil
11366 "This is non-nil when the last TODO state change led to a TODO state.
11367 If the last change removed the TODO tag or switched to DONE, then
11368 this is nil.")
11370 (defvar org-setting-tags nil) ; dynamically skipped
11372 (defvar org-todo-setup-filter-hook nil
11373 "Hook for functions that pre-filter todo specs.
11374 Each function takes a todo spec and returns either nil or the spec
11375 transformed into canonical form." )
11377 (defvar org-todo-get-default-hook nil
11378 "Hook for functions that get a default item for todo.
11379 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11380 nil or a string to be used for the todo mark." )
11382 (defvar org-agenda-headline-snapshot-before-repeat)
11384 (defun org-current-effective-time ()
11385 "Return current time adjusted for `org-extend-today-until' variable."
11386 (let* ((ct (org-current-time))
11387 (dct (decode-time ct))
11388 (ct1
11389 (if (and org-use-effective-time
11390 (< (nth 2 dct) org-extend-today-until))
11391 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11392 ct)))
11393 ct1))
11395 (defun org-todo-yesterday (&optional arg)
11396 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11397 (interactive "P")
11398 (if (eq major-mode 'org-agenda-mode)
11399 (apply 'org-agenda-todo-yesterday arg)
11400 (let* ((hour (third (decode-time
11401 (org-current-time))))
11402 (org-extend-today-until (1+ hour)))
11403 (org-todo arg))))
11405 (defun org-todo (&optional arg)
11406 "Change the TODO state of an item.
11407 The state of an item is given by a keyword at the start of the heading,
11408 like
11409 *** TODO Write paper
11410 *** DONE Call mom
11412 The different keywords are specified in the variable `org-todo-keywords'.
11413 By default the available states are \"TODO\" and \"DONE\".
11414 So for this example: when the item starts with TODO, it is changed to DONE.
11415 When it starts with DONE, the DONE is removed. And when neither TODO nor
11416 DONE are present, add TODO at the beginning of the heading.
11418 With \\[universal-argument] prefix arg, use completion to determine the new \
11419 state.
11420 With numeric prefix arg, switch to that state.
11421 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11422 keywords (nextset).
11423 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11424 With a numeric prefix arg of 0, inhibit note taking for the change.
11426 For calling through lisp, arg is also interpreted in the following way:
11427 'none -> empty state
11428 \"\"(empty string) -> switch to empty state
11429 'done -> switch to DONE
11430 'nextset -> switch to the next set of keywords
11431 'previousset -> switch to the previous set of keywords
11432 \"WAITING\" -> switch to the specified keyword, but only if it
11433 really is a member of `org-todo-keywords'."
11434 (interactive "P")
11435 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11436 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11437 'region-start-level 'region))
11438 org-loop-over-headlines-in-active-region)
11439 (org-map-entries
11440 `(org-todo ,arg)
11441 org-loop-over-headlines-in-active-region
11442 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11443 (if (equal arg '(16)) (setq arg 'nextset))
11444 (let ((org-blocker-hook org-blocker-hook)
11445 commentp
11446 case-fold-search)
11447 (when (equal arg '(64))
11448 (setq arg nil org-blocker-hook nil))
11449 (when (and org-blocker-hook
11450 (or org-inhibit-blocking
11451 (org-entry-get nil "NOBLOCKING")))
11452 (setq org-blocker-hook nil))
11453 (save-excursion
11454 (catch 'exit
11455 (org-back-to-heading t)
11456 (when (looking-at (concat "^\\*+ " org-comment-string))
11457 (org-toggle-comment)
11458 (setq commentp t))
11459 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11460 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11461 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11462 (let* ((match-data (match-data))
11463 (startpos (point-at-bol))
11464 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11465 (org-log-done org-log-done)
11466 (org-log-repeat org-log-repeat)
11467 (org-todo-log-states org-todo-log-states)
11468 (org-inhibit-logging
11469 (if (equal arg 0)
11470 (progn (setq arg nil) 'note) org-inhibit-logging))
11471 (this (match-string 1))
11472 (hl-pos (match-beginning 0))
11473 (head (org-get-todo-sequence-head this))
11474 (ass (assoc head org-todo-kwd-alist))
11475 (interpret (nth 1 ass))
11476 (done-word (nth 3 ass))
11477 (final-done-word (nth 4 ass))
11478 (org-last-state (or this ""))
11479 (completion-ignore-case t)
11480 (member (member this org-todo-keywords-1))
11481 (tail (cdr member))
11482 (org-state (cond
11483 ((and org-todo-key-trigger
11484 (or (and (equal arg '(4))
11485 (eq org-use-fast-todo-selection 'prefix))
11486 (and (not arg) org-use-fast-todo-selection
11487 (not (eq org-use-fast-todo-selection
11488 'prefix)))))
11489 ;; Use fast selection
11490 (org-fast-todo-selection))
11491 ((and (equal arg '(4))
11492 (or (not org-use-fast-todo-selection)
11493 (not org-todo-key-trigger)))
11494 ;; Read a state with completion
11495 (org-icompleting-read
11496 "State: " (mapcar (lambda(x) (list x))
11497 org-todo-keywords-1)
11498 nil t))
11499 ((eq arg 'right)
11500 (if this
11501 (if tail (car tail) nil)
11502 (car org-todo-keywords-1)))
11503 ((eq arg 'left)
11504 (if (equal member org-todo-keywords-1)
11506 (if this
11507 (nth (- (length org-todo-keywords-1)
11508 (length tail) 2)
11509 org-todo-keywords-1)
11510 (org-last org-todo-keywords-1))))
11511 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11512 (setq arg nil))) ; hack to fall back to cycling
11513 (arg
11514 ;; user or caller requests a specific state
11515 (cond
11516 ((equal arg "") nil)
11517 ((eq arg 'none) nil)
11518 ((eq arg 'done) (or done-word (car org-done-keywords)))
11519 ((eq arg 'nextset)
11520 (or (car (cdr (member head org-todo-heads)))
11521 (car org-todo-heads)))
11522 ((eq arg 'previousset)
11523 (let ((org-todo-heads (reverse org-todo-heads)))
11524 (or (car (cdr (member head org-todo-heads)))
11525 (car org-todo-heads))))
11526 ((car (member arg org-todo-keywords-1)))
11527 ((stringp arg)
11528 (error "State `%s' not valid in this file" arg))
11529 ((nth (1- (prefix-numeric-value arg))
11530 org-todo-keywords-1))))
11531 ((null member) (or head (car org-todo-keywords-1)))
11532 ((equal this final-done-word) nil) ;; -> make empty
11533 ((null tail) nil) ;; -> first entry
11534 ((memq interpret '(type priority))
11535 (if (eq this-command last-command)
11536 (car tail)
11537 (if (> (length tail) 0)
11538 (or done-word (car org-done-keywords))
11539 nil)))
11541 (car tail))))
11542 (org-state (or
11543 (run-hook-with-args-until-success
11544 'org-todo-get-default-hook org-state org-last-state)
11545 org-state))
11546 (next (if org-state (concat " " org-state " ") " "))
11547 (change-plist (list :type 'todo-state-change :from this :to org-state
11548 :position startpos))
11549 dolog now-done-p)
11550 (when org-blocker-hook
11551 (setq org-last-todo-state-is-todo
11552 (not (member this org-done-keywords)))
11553 (unless (save-excursion
11554 (save-match-data
11555 (org-with-wide-buffer
11556 (run-hook-with-args-until-failure
11557 'org-blocker-hook change-plist))))
11558 (if (org-called-interactively-p 'interactive)
11559 (error "TODO state change from %s to %s blocked" this org-state)
11560 ;; fail silently
11561 (message "TODO state change from %s to %s blocked" this org-state)
11562 (throw 'exit nil))))
11563 (store-match-data match-data)
11564 (replace-match next t t)
11565 (unless (pos-visible-in-window-p hl-pos)
11566 (message "TODO state changed to %s" (org-trim next)))
11567 (unless head
11568 (setq head (org-get-todo-sequence-head org-state)
11569 ass (assoc head org-todo-kwd-alist)
11570 interpret (nth 1 ass)
11571 done-word (nth 3 ass)
11572 final-done-word (nth 4 ass)))
11573 (when (memq arg '(nextset previousset))
11574 (message "Keyword-Set %d/%d: %s"
11575 (- (length org-todo-sets) -1
11576 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11577 (length org-todo-sets)
11578 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11579 (setq org-last-todo-state-is-todo
11580 (not (member org-state org-done-keywords)))
11581 (setq now-done-p (and (member org-state org-done-keywords)
11582 (not (member this org-done-keywords))))
11583 (and logging (org-local-logging logging))
11584 (when (and (or org-todo-log-states org-log-done)
11585 (not (eq org-inhibit-logging t))
11586 (not (memq arg '(nextset previousset))))
11587 ;; we need to look at recording a time and note
11588 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11589 (nth 2 (assoc this org-todo-log-states))))
11590 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11591 (setq dolog 'time))
11592 (when (and org-state
11593 (member org-state org-not-done-keywords)
11594 (not (member this org-not-done-keywords)))
11595 ;; This is now a todo state and was not one before
11596 ;; If there was a CLOSED time stamp, get rid of it.
11597 (org-add-planning-info nil nil 'closed))
11598 (when (and now-done-p org-log-done)
11599 ;; It is now done, and it was not done before
11600 (org-add-planning-info 'closed (org-current-effective-time))
11601 (if (and (not dolog) (eq 'note org-log-done))
11602 (org-add-log-setup 'done org-state this 'findpos 'note)))
11603 (when (and org-state dolog)
11604 ;; This is a non-nil state, and we need to log it
11605 (org-add-log-setup 'state org-state this 'findpos dolog)))
11606 ;; Fixup tag positioning
11607 (org-todo-trigger-tag-changes org-state)
11608 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11609 (when org-provide-todo-statistics
11610 (org-update-parent-todo-statistics))
11611 (run-hooks 'org-after-todo-state-change-hook)
11612 (if (and arg (not (member org-state org-done-keywords)))
11613 (setq head (org-get-todo-sequence-head org-state)))
11614 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11615 ;; Do we need to trigger a repeat?
11616 (when now-done-p
11617 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11618 ;; This is for the agenda, take a snapshot of the headline.
11619 (save-match-data
11620 (setq org-agenda-headline-snapshot-before-repeat
11621 (org-get-heading))))
11622 (org-auto-repeat-maybe org-state))
11623 ;; Fixup cursor location if close to the keyword
11624 (if (and (outline-on-heading-p)
11625 (not (bolp))
11626 (save-excursion (beginning-of-line 1)
11627 (looking-at org-todo-line-regexp))
11628 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11629 (progn
11630 (goto-char (or (match-end 2) (match-end 1)))
11631 (and (looking-at " ") (just-one-space))))
11632 (when org-trigger-hook
11633 (save-excursion
11634 (run-hook-with-args 'org-trigger-hook change-plist)))
11635 (when commentp (org-toggle-comment))))))))
11637 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11638 "Block turning an entry into a TODO, using the hierarchy.
11639 This checks whether the current task should be blocked from state
11640 changes. Such blocking occurs when:
11642 1. The task has children which are not all in a completed state.
11644 2. A task has a parent with the property :ORDERED:, and there
11645 are siblings prior to the current task with incomplete
11646 status.
11648 3. The parent of the task is blocked because it has siblings that should
11649 be done first, or is child of a block grandparent TODO entry."
11651 (if (not org-enforce-todo-dependencies)
11652 t ; if locally turned off don't block
11653 (catch 'dont-block
11654 ;; If this is not a todo state change, or if this entry is already DONE,
11655 ;; do not block
11656 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11657 (member (plist-get change-plist :from)
11658 (cons 'done org-done-keywords))
11659 (member (plist-get change-plist :to)
11660 (cons 'todo org-not-done-keywords))
11661 (not (plist-get change-plist :to)))
11662 (throw 'dont-block t))
11663 ;; If this task has children, and any are undone, it's blocked
11664 (save-excursion
11665 (org-back-to-heading t)
11666 (let ((this-level (funcall outline-level)))
11667 (outline-next-heading)
11668 (let ((child-level (funcall outline-level)))
11669 (while (and (not (eobp))
11670 (> child-level this-level))
11671 ;; this todo has children, check whether they are all
11672 ;; completed
11673 (if (and (not (org-entry-is-done-p))
11674 (org-entry-is-todo-p))
11675 (throw 'dont-block nil))
11676 (outline-next-heading)
11677 (setq child-level (funcall outline-level))))))
11678 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11679 ;; any previous siblings are undone, it's blocked
11680 (save-excursion
11681 (org-back-to-heading t)
11682 (let* ((pos (point))
11683 (parent-pos (and (org-up-heading-safe) (point))))
11684 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11685 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11686 (forward-line 1)
11687 (re-search-forward org-not-done-heading-regexp pos t))
11688 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11689 ;; Search further up the hierarchy, to see if an ancestor is blocked
11690 (while t
11691 (goto-char parent-pos)
11692 (if (not (looking-at org-not-done-heading-regexp))
11693 (throw 'dont-block t)) ; do not block, parent is not a TODO
11694 (setq pos (point))
11695 (setq parent-pos (and (org-up-heading-safe) (point)))
11696 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11697 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11698 (forward-line 1)
11699 (re-search-forward org-not-done-heading-regexp pos t))
11700 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11702 (defcustom org-track-ordered-property-with-tag nil
11703 "Should the ORDERED property also be shown as a tag?
11704 The ORDERED property decides if an entry should require subtasks to be
11705 completed in sequence. Since a property is not very visible, setting
11706 this option means that toggling the ORDERED property with the command
11707 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11708 not relevant for the behavior, but it makes things more visible.
11710 Note that toggling the tag with tags commands will not change the property
11711 and therefore not influence behavior!
11713 This can be t, meaning the tag ORDERED should be used, It can also be a
11714 string to select a different tag for this task."
11715 :group 'org-todo
11716 :type '(choice
11717 (const :tag "No tracking" nil)
11718 (const :tag "Track with ORDERED tag" t)
11719 (string :tag "Use other tag")))
11721 (defun org-toggle-ordered-property ()
11722 "Toggle the ORDERED property of the current entry.
11723 For better visibility, you can track the value of this property with a tag.
11724 See variable `org-track-ordered-property-with-tag'."
11725 (interactive)
11726 (let* ((t1 org-track-ordered-property-with-tag)
11727 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11728 (save-excursion
11729 (org-back-to-heading)
11730 (if (org-entry-get nil "ORDERED")
11731 (progn
11732 (org-delete-property "ORDERED")
11733 (and tag (org-toggle-tag tag 'off))
11734 (message "Subtasks can be completed in arbitrary order"))
11735 (org-entry-put nil "ORDERED" "t")
11736 (and tag (org-toggle-tag tag 'on))
11737 (message "Subtasks must be completed in sequence")))))
11739 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11740 (defun org-block-todo-from-checkboxes (change-plist)
11741 "Block turning an entry into a TODO, using checkboxes.
11742 This checks whether the current task should be blocked from state
11743 changes because there are unchecked boxes in this entry."
11744 (if (not org-enforce-todo-checkbox-dependencies)
11745 t ; if locally turned off don't block
11746 (catch 'dont-block
11747 ;; If this is not a todo state change, or if this entry is already DONE,
11748 ;; do not block
11749 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11750 (member (plist-get change-plist :from)
11751 (cons 'done org-done-keywords))
11752 (member (plist-get change-plist :to)
11753 (cons 'todo org-not-done-keywords))
11754 (not (plist-get change-plist :to)))
11755 (throw 'dont-block t))
11756 ;; If this task has checkboxes that are not checked, it's blocked
11757 (save-excursion
11758 (org-back-to-heading t)
11759 (let ((beg (point)) end)
11760 (outline-next-heading)
11761 (setq end (point))
11762 (goto-char beg)
11763 (if (org-list-search-forward
11764 (concat (org-item-beginning-re)
11765 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11766 "\\[[- ]\\]")
11767 end t)
11768 (progn
11769 (if (boundp 'org-blocked-by-checkboxes)
11770 (setq org-blocked-by-checkboxes t))
11771 (throw 'dont-block nil)))))
11772 t))) ; do not block
11774 (defun org-entry-blocked-p ()
11775 "Is the current entry blocked?"
11776 (org-with-buffer-modified-unmodified
11777 (if (org-entry-get nil "NOBLOCKING")
11778 nil ;; Never block this entry
11779 (not
11780 (run-hook-with-args-until-failure
11781 'org-blocker-hook
11782 (list :type 'todo-state-change
11783 :position (point)
11784 :from 'todo
11785 :to 'done))))))
11787 (defun org-update-statistics-cookies (all)
11788 "Update the statistics cookie, either from TODO or from checkboxes.
11789 This should be called with the cursor in a line with a statistics cookie."
11790 (interactive "P")
11791 (if all
11792 (progn
11793 (org-update-checkbox-count 'all)
11794 (org-map-entries 'org-update-parent-todo-statistics))
11795 (if (not (org-at-heading-p))
11796 (org-update-checkbox-count)
11797 (let ((pos (point-marker))
11798 end l1 l2)
11799 (ignore-errors (org-back-to-heading t))
11800 (if (not (org-at-heading-p))
11801 (org-update-checkbox-count)
11802 (setq l1 (org-outline-level))
11803 (setq end (save-excursion
11804 (outline-next-heading)
11805 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11806 (point)))
11807 (if (and (save-excursion
11808 (re-search-forward
11809 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11810 (not (save-excursion (re-search-forward
11811 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11812 (org-update-checkbox-count)
11813 (if (and l2 (> l2 l1))
11814 (progn
11815 (goto-char end)
11816 (org-update-parent-todo-statistics))
11817 (goto-char pos)
11818 (beginning-of-line 1)
11819 (while (re-search-forward
11820 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11821 (point-at-eol) t)
11822 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11823 (goto-char pos)
11824 (move-marker pos nil)))))
11826 (defvar org-entry-property-inherited-from) ;; defined below
11827 (defun org-update-parent-todo-statistics ()
11828 "Update any statistics cookie in the parent of the current headline.
11829 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11830 the entire subtree and this will travel up the hierarchy and update
11831 statistics everywhere."
11832 (let* ((prop (save-excursion (org-up-heading-safe)
11833 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11834 (recursive (or (not org-hierarchical-todo-statistics)
11835 (and prop (string-match "\\<recursive\\>" prop))))
11836 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11838 (first t)
11839 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11840 level ltoggle l1 new ndel
11841 (cnt-all 0) (cnt-done 0) is-percent kwd
11842 checkbox-beg ov ovs ove cookie-present)
11843 (catch 'exit
11844 (save-excursion
11845 (beginning-of-line 1)
11846 (setq ltoggle (funcall outline-level))
11847 ;; Three situations are to consider:
11849 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11850 ;; to the top-level ancestor on the headline;
11852 ;; 2. If parent has "recursive" property, repeat up to the
11853 ;; headline setting that property, taking inheritance into
11854 ;; account;
11856 ;; 3. Else, move up to direct parent and proceed only once.
11857 (while (and (setq level (org-up-heading-safe))
11858 (or recursive first)
11859 (>= (point) lim))
11860 (setq first nil cookie-present nil)
11861 (unless (and level
11862 (not (string-match
11863 "\\<checkbox\\>"
11864 (downcase (or (org-entry-get nil "COOKIE_DATA")
11865 "")))))
11866 (throw 'exit nil))
11867 (while (re-search-forward box-re (point-at-eol) t)
11868 (setq cnt-all 0 cnt-done 0 cookie-present t)
11869 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11870 (save-match-data
11871 (unless (outline-next-heading) (throw 'exit nil))
11872 (while (and (looking-at org-complex-heading-regexp)
11873 (> (setq l1 (length (match-string 1))) level))
11874 (setq kwd (and (or recursive (= l1 ltoggle))
11875 (match-string 2)))
11876 (if (or (eq org-provide-todo-statistics 'all-headlines)
11877 (and (listp org-provide-todo-statistics)
11878 (or (member kwd org-provide-todo-statistics)
11879 (member kwd org-done-keywords))))
11880 (setq cnt-all (1+ cnt-all))
11881 (if (eq org-provide-todo-statistics t)
11882 (and kwd (setq cnt-all (1+ cnt-all)))))
11883 (and (member kwd org-done-keywords)
11884 (setq cnt-done (1+ cnt-done)))
11885 (outline-next-heading)))
11886 (setq new
11887 (if is-percent
11888 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11889 (format "[%d/%d]" cnt-done cnt-all))
11890 ndel (- (match-end 0) checkbox-beg))
11891 ;; handle overlays when updating cookie from column view
11892 (when (setq ov (car (overlays-at checkbox-beg)))
11893 (setq ovs (overlay-start ov) ove (overlay-end ov))
11894 (delete-overlay ov))
11895 (goto-char checkbox-beg)
11896 (insert new)
11897 (delete-region (point) (+ (point) ndel))
11898 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11899 (when ov (move-overlay ov ovs ove)))
11900 (when cookie-present
11901 (run-hook-with-args 'org-after-todo-statistics-hook
11902 cnt-done (- cnt-all cnt-done))))))
11903 (run-hooks 'org-todo-statistics-hook)))
11905 (defvar org-after-todo-statistics-hook nil
11906 "Hook that is called after a TODO statistics cookie has been updated.
11907 Each function is called with two arguments: the number of not-done entries
11908 and the number of done entries.
11910 For example, the following function, when added to this hook, will switch
11911 an entry to DONE when all children are done, and back to TODO when new
11912 entries are set to a TODO status. Note that this hook is only called
11913 when there is a statistics cookie in the headline!
11915 (defun org-summary-todo (n-done n-not-done)
11916 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11917 (let (org-log-done org-log-states) ; turn off logging
11918 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11921 (defvar org-todo-statistics-hook nil
11922 "Hook that is run whenever Org thinks TODO statistics should be updated.
11923 This hook runs even if there is no statistics cookie present, in which case
11924 `org-after-todo-statistics-hook' would not run.")
11926 (defun org-todo-trigger-tag-changes (state)
11927 "Apply the changes defined in `org-todo-state-tags-triggers'."
11928 (let ((l org-todo-state-tags-triggers)
11929 changes)
11930 (when (or (not state) (equal state ""))
11931 (setq changes (append changes (cdr (assoc "" l)))))
11932 (when (and (stringp state) (> (length state) 0))
11933 (setq changes (append changes (cdr (assoc state l)))))
11934 (when (member state org-not-done-keywords)
11935 (setq changes (append changes (cdr (assoc 'todo l)))))
11936 (when (member state org-done-keywords)
11937 (setq changes (append changes (cdr (assoc 'done l)))))
11938 (dolist (c changes)
11939 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11941 (defun org-local-logging (value)
11942 "Get logging settings from a property VALUE."
11943 (let* (words w a)
11944 ;; directly set the variables, they are already local.
11945 (setq org-log-done nil
11946 org-log-repeat nil
11947 org-todo-log-states nil)
11948 (setq words (org-split-string value))
11949 (while (setq w (pop words))
11950 (cond
11951 ((setq a (assoc w org-startup-options))
11952 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11953 (set (nth 1 a) (nth 2 a))))
11954 ((setq a (org-extract-log-state-settings w))
11955 (and (member (car a) org-todo-keywords-1)
11956 (push a org-todo-log-states)))))))
11958 (defun org-get-todo-sequence-head (kwd)
11959 "Return the head of the TODO sequence to which KWD belongs.
11960 If KWD is not set, check if there is a text property remembering the
11961 right sequence."
11962 (let (p)
11963 (cond
11964 ((not kwd)
11965 (or (get-text-property (point-at-bol) 'org-todo-head)
11966 (progn
11967 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11968 nil (point-at-eol)))
11969 (get-text-property p 'org-todo-head))))
11970 ((not (member kwd org-todo-keywords-1))
11971 (car org-todo-keywords-1))
11972 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11974 (defun org-fast-todo-selection ()
11975 "Fast TODO keyword selection with single keys.
11976 Returns the new TODO keyword, or nil if no state change should occur."
11977 (let* ((fulltable org-todo-key-alist)
11978 (done-keywords org-done-keywords) ;; needed for the faces.
11979 (maxlen (apply 'max (mapcar
11980 (lambda (x)
11981 (if (stringp (car x)) (string-width (car x)) 0))
11982 fulltable)))
11983 (expert nil)
11984 (fwidth (+ maxlen 3 1 3))
11985 (ncol (/ (- (window-width) 4) fwidth))
11986 tg cnt e c tbl
11987 groups ingroup)
11988 (save-excursion
11989 (save-window-excursion
11990 (if expert
11991 (set-buffer (get-buffer-create " *Org todo*"))
11992 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11993 (erase-buffer)
11994 (org-set-local 'org-done-keywords done-keywords)
11995 (setq tbl fulltable cnt 0)
11996 (while (setq e (pop tbl))
11997 (cond
11998 ((equal e '(:startgroup))
11999 (push '() groups) (setq ingroup t)
12000 (when (not (= cnt 0))
12001 (setq cnt 0)
12002 (insert "\n"))
12003 (insert "{ "))
12004 ((equal e '(:endgroup))
12005 (setq ingroup nil cnt 0)
12006 (insert "}\n"))
12007 ((equal e '(:newline))
12008 (when (not (= cnt 0))
12009 (setq cnt 0)
12010 (insert "\n")
12011 (setq e (car tbl))
12012 (while (equal (car tbl) '(:newline))
12013 (insert "\n")
12014 (setq tbl (cdr tbl)))))
12016 (setq tg (car e) c (cdr e))
12017 (if ingroup (push tg (car groups)))
12018 (setq tg (org-add-props tg nil 'face
12019 (org-get-todo-face tg)))
12020 (if (and (= cnt 0) (not ingroup)) (insert " "))
12021 (insert "[" c "] " tg (make-string
12022 (- fwidth 4 (length tg)) ?\ ))
12023 (when (= (setq cnt (1+ cnt)) ncol)
12024 (insert "\n")
12025 (if ingroup (insert " "))
12026 (setq cnt 0)))))
12027 (insert "\n")
12028 (goto-char (point-min))
12029 (if (not expert) (org-fit-window-to-buffer))
12030 (message "[a-z..]:Set [SPC]:clear")
12031 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12032 (cond
12033 ((or (= c ?\C-g)
12034 (and (= c ?q) (not (rassoc c fulltable))))
12035 (setq quit-flag t))
12036 ((= c ?\ ) nil)
12037 ((setq e (rassoc c fulltable) tg (car e))
12039 (t (setq quit-flag t)))))))
12041 (defun org-entry-is-todo-p ()
12042 (member (org-get-todo-state) org-not-done-keywords))
12044 (defun org-entry-is-done-p ()
12045 (member (org-get-todo-state) org-done-keywords))
12047 (defun org-get-todo-state ()
12048 (save-excursion
12049 (org-back-to-heading t)
12050 (and (looking-at org-todo-line-regexp)
12051 (match-end 2)
12052 (match-string 2))))
12054 (defun org-at-date-range-p (&optional inactive-ok)
12055 "Is the cursor inside a date range?"
12056 (interactive)
12057 (save-excursion
12058 (catch 'exit
12059 (let ((pos (point)))
12060 (skip-chars-backward "^[<\r\n")
12061 (skip-chars-backward "<[")
12062 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12063 (>= (match-end 0) pos)
12064 (throw 'exit t))
12065 (skip-chars-backward "^<[\r\n")
12066 (skip-chars-backward "<[")
12067 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12068 (>= (match-end 0) pos)
12069 (throw 'exit t)))
12070 nil)))
12072 (defun org-get-repeat (&optional tagline)
12073 "Check if there is a deadline/schedule with repeater in this entry."
12074 (save-match-data
12075 (save-excursion
12076 (org-back-to-heading t)
12077 (and (re-search-forward (if tagline
12078 (concat tagline "\\s-*" org-repeat-re)
12079 org-repeat-re)
12080 (org-entry-end-position) t)
12081 (match-string-no-properties 1)))))
12083 (defvar org-last-changed-timestamp)
12084 (defvar org-last-inserted-timestamp)
12085 (defvar org-log-post-message)
12086 (defvar org-log-note-purpose)
12087 (defvar org-log-note-how)
12088 (defvar org-log-note-extra)
12089 (defun org-auto-repeat-maybe (done-word)
12090 "Check if the current headline contains a repeated deadline/schedule.
12091 If yes, set TODO state back to what it was and change the base date
12092 of repeating deadline/scheduled time stamps to new date.
12093 This function is run automatically after each state change to a DONE state."
12094 ;; last-state is dynamically scoped into this function
12095 (let* ((repeat (org-get-repeat))
12096 (aa (assoc org-last-state org-todo-kwd-alist))
12097 (interpret (nth 1 aa))
12098 (head (nth 2 aa))
12099 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12100 (msg "Entry repeats: ")
12101 (org-log-done nil)
12102 (org-todo-log-states nil)
12103 re type n what ts time to-state)
12104 (when repeat
12105 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12106 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12107 org-todo-repeat-to-state))
12108 (unless (and to-state (member to-state org-todo-keywords-1))
12109 (setq to-state (if (eq interpret 'type) org-last-state head)))
12110 (org-todo to-state)
12111 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12112 (org-entry-put nil "LAST_REPEAT" (format-time-string
12113 (org-time-stamp-format t t))))
12114 (when org-log-repeat
12115 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12116 (memq 'org-add-log-note post-command-hook))
12117 ;; OK, we are already setup for some record
12118 (if (eq org-log-repeat 'note)
12119 ;; make sure we take a note, not only a time stamp
12120 (setq org-log-note-how 'note))
12121 ;; Set up for taking a record
12122 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12123 org-last-state
12124 'findpos org-log-repeat)))
12125 (org-back-to-heading t)
12126 (org-add-planning-info nil nil 'closed)
12127 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12128 org-deadline-time-regexp "\\)\\|\\("
12129 org-ts-regexp "\\)"))
12130 (while (re-search-forward
12131 re (save-excursion (outline-next-heading) (point)) t)
12132 (setq type (if (match-end 1) org-scheduled-string
12133 (if (match-end 3) org-deadline-string "Plain:"))
12134 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12135 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12136 (setq n (string-to-number (match-string 2 ts))
12137 what (match-string 3 ts))
12138 (if (equal what "w") (setq n (* n 7) what "d"))
12139 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12140 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12141 ;; Preparation, see if we need to modify the start date for the change
12142 (when (match-end 1)
12143 (setq time (save-match-data (org-time-string-to-time ts)))
12144 (cond
12145 ((equal (match-string 1 ts) ".")
12146 ;; Shift starting date to today
12147 (org-timestamp-change
12148 (- (org-today) (time-to-days time))
12149 'day))
12150 ((equal (match-string 1 ts) "+")
12151 (let ((nshiftmax 10) (nshift 0))
12152 (while (or (= nshift 0)
12153 (<= (time-to-days time)
12154 (time-to-days (current-time))))
12155 (when (= (incf nshift) nshiftmax)
12156 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12157 (error "Abort")))
12158 (org-timestamp-change n (cdr (assoc what whata)))
12159 (org-at-timestamp-p t)
12160 (setq ts (match-string 1))
12161 (setq time (save-match-data (org-time-string-to-time ts)))))
12162 (org-timestamp-change (- n) (cdr (assoc what whata)))
12163 ;; rematch, so that we have everything in place for the real shift
12164 (org-at-timestamp-p t)
12165 (setq ts (match-string 1))
12166 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12167 (org-timestamp-change n (cdr (assoc what whata)))
12168 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12169 (setq org-log-post-message msg)
12170 (message "%s" msg))))
12172 (defun org-show-todo-tree (arg)
12173 "Make a compact tree which shows all headlines marked with TODO.
12174 The tree will show the lines where the regexp matches, and all higher
12175 headlines above the match.
12176 With a \\[universal-argument] prefix, prompt for a regexp to match.
12177 With a numeric prefix N, construct a sparse tree for the Nth element
12178 of `org-todo-keywords-1'."
12179 (interactive "P")
12180 (let ((case-fold-search nil)
12181 (kwd-re
12182 (cond ((null arg) org-not-done-regexp)
12183 ((equal arg '(4))
12184 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12185 (mapcar 'list org-todo-keywords-1))))
12186 (concat "\\("
12187 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12188 "\\)\\>")))
12189 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12190 (regexp-quote (nth (1- (prefix-numeric-value arg))
12191 org-todo-keywords-1)))
12192 (t (error "Invalid prefix argument: %s" arg)))))
12193 (message "%d TODO entries found"
12194 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12196 (defun org-deadline (&optional remove time)
12197 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12198 With argument REMOVE, remove any deadline from the item.
12199 With argument TIME, set the deadline at the corresponding date. TIME
12200 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12201 (interactive "P")
12202 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12203 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12204 'region-start-level 'region))
12205 org-loop-over-headlines-in-active-region)
12206 (org-map-entries
12207 `(org-deadline ',remove ,time)
12208 org-loop-over-headlines-in-active-region
12209 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12210 (let* ((old-date (org-entry-get nil "DEADLINE"))
12211 (repeater (and old-date
12212 (string-match
12213 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12214 old-date)
12215 (match-string 1 old-date))))
12216 (if remove
12217 (progn
12218 (when (and old-date org-log-redeadline)
12219 (org-add-log-setup 'deldeadline nil old-date 'findpos
12220 org-log-redeadline))
12221 (org-remove-timestamp-with-keyword org-deadline-string)
12222 (message "Item no longer has a deadline."))
12223 (org-add-planning-info 'deadline time 'closed)
12224 (when (and old-date org-log-redeadline
12225 (not (equal old-date
12226 (substring org-last-inserted-timestamp 1 -1))))
12227 (org-add-log-setup 'redeadline nil old-date 'findpos
12228 org-log-redeadline))
12229 (when repeater
12230 (save-excursion
12231 (org-back-to-heading t)
12232 (when (re-search-forward (concat org-deadline-string " "
12233 org-last-inserted-timestamp)
12234 (save-excursion
12235 (outline-next-heading) (point)) t)
12236 (goto-char (1- (match-end 0)))
12237 (insert " " repeater)
12238 (setq org-last-inserted-timestamp
12239 (concat (substring org-last-inserted-timestamp 0 -1)
12240 " " repeater
12241 (substring org-last-inserted-timestamp -1))))))
12242 (message "Deadline on %s" org-last-inserted-timestamp)))))
12244 (defun org-schedule (&optional remove time)
12245 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12246 With argument REMOVE, remove any scheduling date from the item.
12247 With argument TIME, scheduled at the corresponding date. TIME can
12248 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12249 (interactive "P")
12250 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12251 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12252 'region-start-level 'region))
12253 org-loop-over-headlines-in-active-region)
12254 (org-map-entries
12255 `(org-schedule ',remove ,time)
12256 org-loop-over-headlines-in-active-region
12257 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12258 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12259 (repeater (and old-date
12260 (string-match
12261 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12262 old-date)
12263 (match-string 1 old-date))))
12264 (if remove
12265 (progn
12266 (when (and old-date org-log-reschedule)
12267 (org-add-log-setup 'delschedule nil old-date 'findpos
12268 org-log-reschedule))
12269 (org-remove-timestamp-with-keyword org-scheduled-string)
12270 (message "Item is no longer scheduled."))
12271 (org-add-planning-info 'scheduled time 'closed)
12272 (when (and old-date org-log-reschedule
12273 (not (equal old-date
12274 (substring org-last-inserted-timestamp 1 -1))))
12275 (org-add-log-setup 'reschedule nil old-date 'findpos
12276 org-log-reschedule))
12277 (when repeater
12278 (save-excursion
12279 (org-back-to-heading t)
12280 (when (re-search-forward (concat org-scheduled-string " "
12281 org-last-inserted-timestamp)
12282 (save-excursion
12283 (outline-next-heading) (point)) t)
12284 (goto-char (1- (match-end 0)))
12285 (insert " " repeater)
12286 (setq org-last-inserted-timestamp
12287 (concat (substring org-last-inserted-timestamp 0 -1)
12288 " " repeater
12289 (substring org-last-inserted-timestamp -1))))))
12290 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12292 (defun org-get-scheduled-time (pom &optional inherit)
12293 "Get the scheduled time as a time tuple, of a format suitable
12294 for calling org-schedule with, or if there is no scheduling,
12295 returns nil."
12296 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12297 (when time
12298 (apply 'encode-time (org-parse-time-string time)))))
12300 (defun org-get-deadline-time (pom &optional inherit)
12301 "Get the deadline as a time tuple, of a format suitable for
12302 calling org-deadline with, or if there is no scheduling, returns
12303 nil."
12304 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12305 (when time
12306 (apply 'encode-time (org-parse-time-string time)))))
12308 (defun org-remove-timestamp-with-keyword (keyword)
12309 "Remove all time stamps with KEYWORD in the current entry."
12310 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12311 beg)
12312 (save-excursion
12313 (org-back-to-heading t)
12314 (setq beg (point))
12315 (outline-next-heading)
12316 (while (re-search-backward re beg t)
12317 (replace-match "")
12318 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12319 (equal (char-before) ?\ ))
12320 (backward-delete-char 1)
12321 (if (string-match "^[ \t]*$" (buffer-substring
12322 (point-at-bol) (point-at-eol)))
12323 (delete-region (point-at-bol)
12324 (min (point-max) (1+ (point-at-eol))))))))))
12326 (defun org-add-planning-info (what &optional time &rest remove)
12327 "Insert new timestamp with keyword in the line directly after the headline.
12328 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12329 If non is given, the user is prompted for a date.
12330 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12331 be removed."
12332 (interactive)
12333 (let (org-time-was-given org-end-time-was-given ts
12334 end default-time default-input)
12336 (catch 'exit
12337 (when (and (memq what '(scheduled deadline))
12338 (or (not time)
12339 (and (stringp time)
12340 (string-match "^[-+]+[0-9]" time))))
12341 ;; Try to get a default date/time from existing timestamp
12342 (save-excursion
12343 (org-back-to-heading t)
12344 (setq end (save-excursion (outline-next-heading) (point)))
12345 (when (re-search-forward (if (eq what 'scheduled)
12346 org-scheduled-time-regexp
12347 org-deadline-time-regexp)
12348 end t)
12349 (setq ts (match-string 1)
12350 default-time
12351 (apply 'encode-time (org-parse-time-string ts))
12352 default-input (and ts (org-get-compact-tod ts))))))
12353 (when what
12354 (setq time
12355 (if (stringp time)
12356 ;; This is a string (relative or absolute), set proper date
12357 (apply 'encode-time
12358 (org-read-date-analyze
12359 time default-time (decode-time default-time)))
12360 ;; If necessary, get the time from the user
12361 (or time (org-read-date nil 'to-time nil nil
12362 default-time default-input)))))
12364 (when (and org-insert-labeled-timestamps-at-point
12365 (member what '(scheduled deadline)))
12366 (insert
12367 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12368 (org-insert-time-stamp time org-time-was-given
12369 nil nil nil (list org-end-time-was-given))
12370 (setq what nil))
12371 (save-excursion
12372 (save-restriction
12373 (let (col list elt ts buffer-invisibility-spec)
12374 (org-back-to-heading t)
12375 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12376 (goto-char (match-end 1))
12377 (setq col (current-column))
12378 (goto-char (match-end 0))
12379 (if (eobp) (insert "\n") (forward-char 1))
12380 (when (and (not what)
12381 (not (looking-at
12382 (concat "[ \t]*"
12383 org-keyword-time-not-clock-regexp))))
12384 ;; Nothing to add, nothing to remove...... :-)
12385 (throw 'exit nil))
12386 (if (and (not (looking-at org-outline-regexp))
12387 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12388 "[^\r\n]*"))
12389 (not (equal (match-string 1) org-clock-string)))
12390 (narrow-to-region (match-beginning 0) (match-end 0))
12391 (insert-before-markers "\n")
12392 (backward-char 1)
12393 (narrow-to-region (point) (point))
12394 (and org-adapt-indentation (org-indent-to-column col)))
12395 ;; Check if we have to remove something.
12396 (setq list (cons what remove))
12397 (while list
12398 (setq elt (pop list))
12399 (when (or (and (eq elt 'scheduled)
12400 (re-search-forward org-scheduled-time-regexp nil t))
12401 (and (eq elt 'deadline)
12402 (re-search-forward org-deadline-time-regexp nil t))
12403 (and (eq elt 'closed)
12404 (re-search-forward org-closed-time-regexp nil t)))
12405 (replace-match "")
12406 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12407 (and (looking-at "[ \t]+") (replace-match ""))
12408 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12409 (when what
12410 (insert
12411 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12412 (cond ((eq what 'scheduled) org-scheduled-string)
12413 ((eq what 'deadline) org-deadline-string)
12414 ((eq what 'closed) org-closed-string))
12415 " ")
12416 (setq ts (org-insert-time-stamp
12417 time
12418 (or org-time-was-given
12419 (and (eq what 'closed) org-log-done-with-time))
12420 (eq what 'closed)
12421 nil nil (list org-end-time-was-given)))
12422 (insert
12423 (if (not (or (bolp) (eq (char-before) ?\ )
12424 (memq (char-after) '(32 10))
12425 (eobp))) " " ""))
12426 (end-of-line 1))
12427 (goto-char (point-min))
12428 (widen)
12429 (if (and (looking-at "[ \t]*\n")
12430 (equal (char-before) ?\n))
12431 (delete-region (1- (point)) (point-at-eol)))
12432 ts))))))
12434 (defvar org-log-note-marker (make-marker))
12435 (defvar org-log-note-purpose nil)
12436 (defvar org-log-note-state nil)
12437 (defvar org-log-note-previous-state nil)
12438 (defvar org-log-note-how nil)
12439 (defvar org-log-note-extra nil)
12440 (defvar org-log-note-window-configuration nil)
12441 (defvar org-log-note-return-to (make-marker))
12442 (defvar org-log-note-effective-time nil
12443 "Remembered current time so that dynamically scoped
12444 `org-extend-today-until' affects tha timestamps in state change
12445 log")
12447 (defvar org-log-post-message nil
12448 "Message to be displayed after a log note has been stored.
12449 The auto-repeater uses this.")
12451 (defun org-add-note ()
12452 "Add a note to the current entry.
12453 This is done in the same way as adding a state change note."
12454 (interactive)
12455 (org-add-log-setup 'note nil nil 'findpos nil))
12457 (defvar org-property-end-re)
12458 (defun org-add-log-setup (&optional purpose state prev-state
12459 findpos how extra)
12460 "Set up the post command hook to take a note.
12461 If this is about to TODO state change, the new state is expected in STATE.
12462 When FINDPOS is non-nil, find the correct position for the note in
12463 the current entry. If not, assume that it can be inserted at point.
12464 HOW is an indicator what kind of note should be created.
12465 EXTRA is additional text that will be inserted into the notes buffer."
12466 (let* ((org-log-into-drawer (org-log-into-drawer))
12467 (drawer (cond ((stringp org-log-into-drawer)
12468 org-log-into-drawer)
12469 (org-log-into-drawer "LOGBOOK"))))
12470 (save-restriction
12471 (save-excursion
12472 (when findpos
12473 (org-back-to-heading t)
12474 (narrow-to-region (point) (save-excursion
12475 (outline-next-heading) (point)))
12476 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12477 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12478 "[^\r\n]*\\)?"))
12479 (goto-char (match-end 0))
12480 (cond
12481 (drawer
12482 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12483 nil t)
12484 (progn
12485 (goto-char (match-end 0))
12486 (or org-log-states-order-reversed
12487 (and (re-search-forward org-property-end-re nil t)
12488 (goto-char (1- (match-beginning 0))))))
12489 (insert "\n:" drawer ":\n:END:")
12490 (beginning-of-line 0)
12491 (org-indent-line)
12492 (beginning-of-line 2)
12493 (org-indent-line)
12494 (end-of-line 0)))
12495 ((and org-log-state-notes-insert-after-drawers
12496 (save-excursion
12497 (forward-line) (looking-at org-drawer-regexp)))
12498 (forward-line)
12499 (while (looking-at org-drawer-regexp)
12500 (goto-char (match-end 0))
12501 (re-search-forward org-property-end-re (point-max) t)
12502 (forward-line))
12503 (forward-line -1)))
12504 (unless org-log-states-order-reversed
12505 (and (= (char-after) ?\n) (forward-char 1))
12506 (org-skip-over-state-notes)
12507 (skip-chars-backward " \t\n\r")))
12508 (move-marker org-log-note-marker (point))
12509 (setq org-log-note-purpose purpose
12510 org-log-note-state state
12511 org-log-note-previous-state prev-state
12512 org-log-note-how how
12513 org-log-note-extra extra
12514 org-log-note-effective-time (org-current-effective-time))
12515 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12517 (defun org-skip-over-state-notes ()
12518 "Skip past the list of State notes in an entry."
12519 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12520 (when (ignore-errors (goto-char (org-in-item-p)))
12521 (let* ((struct (org-list-struct))
12522 (prevs (org-list-prevs-alist struct)))
12523 (while (looking-at "[ \t]*- State")
12524 (goto-char (or (org-list-get-next-item (point) struct prevs)
12525 (org-list-get-item-end (point) struct)))))))
12527 (defun org-add-log-note (&optional purpose)
12528 "Pop up a window for taking a note, and add this note later at point."
12529 (remove-hook 'post-command-hook 'org-add-log-note)
12530 (setq org-log-note-window-configuration (current-window-configuration))
12531 (delete-other-windows)
12532 (move-marker org-log-note-return-to (point))
12533 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12534 (goto-char org-log-note-marker)
12535 (org-switch-to-buffer-other-window "*Org Note*")
12536 (erase-buffer)
12537 (if (memq org-log-note-how '(time state))
12538 (let (current-prefix-arg) (org-store-log-note))
12539 (let ((org-inhibit-startup t)) (org-mode))
12540 (insert (format "# Insert note for %s.
12541 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12542 (cond
12543 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12544 ((eq org-log-note-purpose 'done) "closed todo item")
12545 ((eq org-log-note-purpose 'state)
12546 (format "state change from \"%s\" to \"%s\""
12547 (or org-log-note-previous-state "")
12548 (or org-log-note-state "")))
12549 ((eq org-log-note-purpose 'reschedule)
12550 "rescheduling")
12551 ((eq org-log-note-purpose 'delschedule)
12552 "no longer scheduled")
12553 ((eq org-log-note-purpose 'redeadline)
12554 "changing deadline")
12555 ((eq org-log-note-purpose 'deldeadline)
12556 "removing deadline")
12557 ((eq org-log-note-purpose 'refile)
12558 "refiling")
12559 ((eq org-log-note-purpose 'note)
12560 "this entry")
12561 (t (error "This should not happen")))))
12562 (if org-log-note-extra (insert org-log-note-extra))
12563 (org-set-local 'org-finish-function 'org-store-log-note)
12564 (run-hooks 'org-log-buffer-setup-hook)))
12566 (defvar org-note-abort nil) ; dynamically scoped
12567 (defun org-store-log-note ()
12568 "Finish taking a log note, and insert it to where it belongs."
12569 (let ((txt (buffer-string))
12570 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12571 lines ind bul)
12572 (kill-buffer (current-buffer))
12573 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12574 (setq txt (replace-match "" t t txt)))
12575 (if (string-match "\\s-+\\'" txt)
12576 (setq txt (replace-match "" t t txt)))
12577 (setq lines (org-split-string txt "\n"))
12578 (when (and note (string-match "\\S-" note))
12579 (setq note
12580 (org-replace-escapes
12581 note
12582 (list (cons "%u" (user-login-name))
12583 (cons "%U" user-full-name)
12584 (cons "%t" (format-time-string
12585 (org-time-stamp-format 'long 'inactive)
12586 org-log-note-effective-time))
12587 (cons "%T" (format-time-string
12588 (org-time-stamp-format 'long nil)
12589 org-log-note-effective-time))
12590 (cons "%d" (format-time-string
12591 (org-time-stamp-format nil 'inactive)
12592 org-log-note-effective-time))
12593 (cons "%D" (format-time-string
12594 (org-time-stamp-format nil nil)
12595 org-log-note-effective-time))
12596 (cons "%s" (if org-log-note-state
12597 (concat "\"" org-log-note-state "\"")
12598 ""))
12599 (cons "%S" (if org-log-note-previous-state
12600 (concat "\"" org-log-note-previous-state "\"")
12601 "\"\"")))))
12602 (if lines (setq note (concat note " \\\\")))
12603 (push note lines))
12604 (when (or current-prefix-arg org-note-abort)
12605 (when org-log-into-drawer
12606 (org-remove-empty-drawer-at
12607 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12608 org-log-note-marker))
12609 (setq lines nil))
12610 (when lines
12611 (with-current-buffer (marker-buffer org-log-note-marker)
12612 (save-excursion
12613 (goto-char org-log-note-marker)
12614 (move-marker org-log-note-marker nil)
12615 (end-of-line 1)
12616 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12617 (setq ind (save-excursion
12618 (if (ignore-errors (goto-char (org-in-item-p)))
12619 (let ((struct (org-list-struct)))
12620 (org-list-get-ind
12621 (org-list-get-top-point struct) struct))
12622 (skip-chars-backward " \r\t\n")
12623 (cond
12624 ((and (org-at-heading-p)
12625 org-adapt-indentation)
12626 (1+ (org-current-level)))
12627 ((org-at-heading-p) 0)
12628 (t (org-get-indentation))))))
12629 (setq bul (org-list-bullet-string "-"))
12630 (org-indent-line-to ind)
12631 (insert bul (pop lines))
12632 (let ((ind-body (+ (length bul) ind)))
12633 (while lines
12634 (insert "\n")
12635 (org-indent-line-to ind-body)
12636 (insert (pop lines))))
12637 (message "Note stored")
12638 (org-back-to-heading t)
12639 (org-cycle-hide-drawers 'children)))))
12640 (set-window-configuration org-log-note-window-configuration)
12641 (with-current-buffer (marker-buffer org-log-note-return-to)
12642 (goto-char org-log-note-return-to))
12643 (move-marker org-log-note-return-to nil)
12644 (and org-log-post-message (message "%s" org-log-post-message)))
12646 (defun org-remove-empty-drawer-at (drawer pos)
12647 "Remove an empty drawer DRAWER at position POS.
12648 POS may also be a marker."
12649 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12650 (save-excursion
12651 (save-restriction
12652 (widen)
12653 (goto-char pos)
12654 (if (org-in-regexp
12655 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12656 (replace-match ""))))))
12658 (defvar org-ts-type nil)
12659 (defun org-sparse-tree (&optional arg type)
12660 "Create a sparse tree, prompt for the details.
12661 This command can create sparse trees. You first need to select the type
12662 of match used to create the tree:
12664 t Show all TODO entries.
12665 T Show entries with a specific TODO keyword.
12666 m Show entries selected by a tags/property match.
12667 p Enter a property name and its value (both with completion on existing
12668 names/values) and show entries with that property.
12669 r Show entries matching a regular expression (`/' can be used as well).
12670 b Show deadlines and scheduled items before a date.
12671 a Show deadlines and scheduled items after a date.
12672 d Show deadlines due within `org-deadline-warning-days'.
12673 D Show deadlines and scheduled items between a date range."
12674 (interactive "P")
12675 (let (ans kwd value ts-type)
12676 (setq type (or type org-sparse-tree-default-date-type))
12677 (setq org-ts-type type)
12678 (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"
12679 (cond ((eq type 'all) "all timestamps")
12680 ((eq type 'scheduled) "only scheduled")
12681 ((eq type 'deadline) "only deadline")
12682 ((eq type 'active) "only active timestamps")
12683 ((eq type 'inactive) "only inactive timestamps")
12684 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12685 (t "scheduled/deadline")))
12686 (setq ans (read-char-exclusive))
12687 (cond
12688 ((equal ans ?c)
12689 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12690 ((equal ans ?d)
12691 (call-interactively 'org-check-deadlines))
12692 ((equal ans ?b)
12693 (call-interactively 'org-check-before-date))
12694 ((equal ans ?a)
12695 (call-interactively 'org-check-after-date))
12696 ((equal ans ?D)
12697 (call-interactively 'org-check-dates-range))
12698 ((equal ans ?t)
12699 (call-interactively 'org-show-todo-tree))
12700 ((equal ans ?T)
12701 (org-show-todo-tree '(4)))
12702 ((member ans '(?T ?m))
12703 (call-interactively 'org-match-sparse-tree))
12704 ((member ans '(?p ?P))
12705 (setq kwd (org-icompleting-read "Property: "
12706 (mapcar 'list (org-buffer-property-keys))))
12707 (setq value (org-icompleting-read "Value: "
12708 (mapcar 'list (org-property-values kwd))))
12709 (unless (string-match "\\`{.*}\\'" value)
12710 (setq value (concat "\"" value "\"")))
12711 (org-match-sparse-tree arg (concat kwd "=" value)))
12712 ((member ans '(?r ?R ?/))
12713 (call-interactively 'org-occur))
12714 (t (error "No such sparse tree command \"%c\"" ans)))))
12716 (defvar org-occur-highlights nil
12717 "List of overlays used for occur matches.")
12718 (make-variable-buffer-local 'org-occur-highlights)
12719 (defvar org-occur-parameters nil
12720 "Parameters of the active org-occur calls.
12721 This is a list, each call to org-occur pushes as cons cell,
12722 containing the regular expression and the callback, onto the list.
12723 The list can contain several entries if `org-occur' has been called
12724 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12725 will only contain one set of parameters. When the highlights are
12726 removed (for example with `C-c C-c', or with the next edit (depending
12727 on `org-remove-highlights-with-change'), this variable is emptied
12728 as well.")
12729 (make-variable-buffer-local 'org-occur-parameters)
12731 (defun org-occur (regexp &optional keep-previous callback)
12732 "Make a compact tree which shows all matches of REGEXP.
12733 The tree will show the lines where the regexp matches, and all higher
12734 headlines above the match. It will also show the heading after the match,
12735 to make sure editing the matching entry is easy.
12736 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12737 call to `org-occur' will be kept, to allow stacking of calls to this
12738 command.
12739 If CALLBACK is non-nil, it is a function which is called to confirm
12740 that the match should indeed be shown."
12741 (interactive "sRegexp: \nP")
12742 (when (equal regexp "")
12743 (error "Regexp cannot be empty"))
12744 (unless keep-previous
12745 (org-remove-occur-highlights nil nil t))
12746 (push (cons regexp callback) org-occur-parameters)
12747 (let ((cnt 0))
12748 (save-excursion
12749 (goto-char (point-min))
12750 (if (or (not keep-previous) ; do not want to keep
12751 (not org-occur-highlights)) ; no previous matches
12752 ;; hide everything
12753 (org-overview))
12754 (while (re-search-forward regexp nil t)
12755 (when (or (not callback)
12756 (save-match-data (funcall callback)))
12757 (setq cnt (1+ cnt))
12758 (when org-highlight-sparse-tree-matches
12759 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12760 (org-show-context 'occur-tree))))
12761 (when org-remove-highlights-with-change
12762 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12763 nil 'local))
12764 (unless org-sparse-tree-open-archived-trees
12765 (org-hide-archived-subtrees (point-min) (point-max)))
12766 (run-hooks 'org-occur-hook)
12767 (if (org-called-interactively-p 'interactive)
12768 (message "%d match(es) for regexp %s" cnt regexp))
12769 cnt))
12771 (defun org-occur-next-match (&optional n reset)
12772 "Function for `next-error-function' to find sparse tree matches.
12773 N is the number of matches to move, when negative move backwards.
12774 RESET is entirely ignored - this function always goes back to the
12775 starting point when no match is found."
12776 (let* ((limit (if (< n 0) (point-min) (point-max)))
12777 (search-func (if (< n 0)
12778 'previous-single-char-property-change
12779 'next-single-char-property-change))
12780 (n (abs n))
12781 (pos (point))
12783 (catch 'exit
12784 (while (setq p1 (funcall search-func (point) 'org-type))
12785 (when (equal p1 limit)
12786 (goto-char pos)
12787 (error "No more matches"))
12788 (when (equal (get-char-property p1 'org-type) 'org-occur)
12789 (setq n (1- n))
12790 (when (= n 0)
12791 (goto-char p1)
12792 (throw 'exit (point))))
12793 (goto-char p1))
12794 (goto-char p1)
12795 (error "No more matches"))))
12797 (defun org-show-context (&optional key)
12798 "Make sure point and context are visible.
12799 How much context is shown depends upon the variables
12800 `org-show-hierarchy-above', `org-show-following-heading',
12801 `org-show-entry-below' and `org-show-siblings'."
12802 (let ((heading-p (org-at-heading-p t))
12803 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12804 (following-p (org-get-alist-option org-show-following-heading key))
12805 (entry-p (org-get-alist-option org-show-entry-below key))
12806 (siblings-p (org-get-alist-option org-show-siblings key)))
12807 (catch 'exit
12808 ;; Show heading or entry text
12809 (if (and heading-p (not entry-p))
12810 (org-flag-heading nil) ; only show the heading
12811 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12812 (org-show-hidden-entry))) ; show entire entry
12813 (when following-p
12814 ;; Show next sibling, or heading below text
12815 (save-excursion
12816 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12817 (org-flag-heading nil))))
12818 (when siblings-p (org-show-siblings))
12819 (when hierarchy-p
12820 ;; show all higher headings, possibly with siblings
12821 (save-excursion
12822 (while (and (condition-case nil
12823 (progn (org-up-heading-all 1) t)
12824 (error nil))
12825 (not (bobp)))
12826 (org-flag-heading nil)
12827 (when siblings-p (org-show-siblings))))))))
12829 (defvar org-reveal-start-hook nil
12830 "Hook run before revealing a location.")
12832 (defun org-reveal (&optional siblings)
12833 "Show current entry, hierarchy above it, and the following headline.
12834 This can be used to show a consistent set of context around locations
12835 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12836 not t for the search context.
12838 With optional argument SIBLINGS, on each level of the hierarchy all
12839 siblings are shown. This repairs the tree structure to what it would
12840 look like when opened with hierarchical calls to `org-cycle'.
12841 With double optional argument \\[universal-argument] \\[universal-argument], \
12842 go to the parent and show the
12843 entire tree."
12844 (interactive "P")
12845 (run-hooks 'org-reveal-start-hook)
12846 (let ((org-show-hierarchy-above t)
12847 (org-show-following-heading t)
12848 (org-show-siblings (if siblings t org-show-siblings)))
12849 (org-show-context nil))
12850 (when (equal siblings '(16))
12851 (save-excursion
12852 (when (org-up-heading-safe)
12853 (org-show-subtree)
12854 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12856 (defun org-highlight-new-match (beg end)
12857 "Highlight from BEG to END and mark the highlight is an occur headline."
12858 (let ((ov (make-overlay beg end)))
12859 (overlay-put ov 'face 'secondary-selection)
12860 (overlay-put ov 'org-type 'org-occur)
12861 (push ov org-occur-highlights)))
12863 (defun org-remove-occur-highlights (&optional beg end noremove)
12864 "Remove the occur highlights from the buffer.
12865 BEG and END are ignored. If NOREMOVE is nil, remove this function
12866 from the `before-change-functions' in the current buffer."
12867 (interactive)
12868 (unless org-inhibit-highlight-removal
12869 (mapc 'delete-overlay org-occur-highlights)
12870 (setq org-occur-highlights nil)
12871 (setq org-occur-parameters nil)
12872 (unless noremove
12873 (remove-hook 'before-change-functions
12874 'org-remove-occur-highlights 'local))))
12876 ;;;; Priorities
12878 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12879 "Regular expression matching the priority indicator.")
12881 (defvar org-remove-priority-next-time nil)
12883 (defun org-priority-up ()
12884 "Increase the priority of the current item."
12885 (interactive)
12886 (org-priority 'up))
12888 (defun org-priority-down ()
12889 "Decrease the priority of the current item."
12890 (interactive)
12891 (org-priority 'down))
12893 (defun org-priority (&optional action show)
12894 "Change the priority of an item.
12895 ACTION can be `set', `up', `down', or a character."
12896 (interactive "P")
12897 (if (equal action '(4))
12898 (org-show-priority)
12899 (unless org-enable-priority-commands
12900 (error "Priority commands are disabled"))
12901 (setq action (or action 'set))
12902 (let (current new news have remove)
12903 (save-excursion
12904 (org-back-to-heading t)
12905 (if (looking-at org-priority-regexp)
12906 (setq current (string-to-char (match-string 2))
12907 have t))
12908 (cond
12909 ((eq action 'remove)
12910 (setq remove t new ?\ ))
12911 ((or (eq action 'set)
12912 (if (featurep 'xemacs) (characterp action) (integerp action)))
12913 (if (not (eq action 'set))
12914 (setq new action)
12915 (message "Priority %c-%c, SPC to remove: "
12916 org-highest-priority org-lowest-priority)
12917 (save-match-data
12918 (setq new (read-char-exclusive))))
12919 (if (and (= (upcase org-highest-priority) org-highest-priority)
12920 (= (upcase org-lowest-priority) org-lowest-priority))
12921 (setq new (upcase new)))
12922 (cond ((equal new ?\ ) (setq remove t))
12923 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12924 (error "Priority must be between `%c' and `%c'"
12925 org-highest-priority org-lowest-priority))))
12926 ((eq action 'up)
12927 (setq new (if have
12928 (1- current) ; normal cycling
12929 ;; last priority was empty
12930 (if (eq last-command this-command)
12931 org-lowest-priority ; wrap around empty to lowest
12932 ;; default
12933 (if org-priority-start-cycle-with-default
12934 org-default-priority
12935 (1- org-default-priority))))))
12936 ((eq action 'down)
12937 (setq new (if have
12938 (1+ current) ; normal cycling
12939 ;; last priority was empty
12940 (if (eq last-command this-command)
12941 org-highest-priority ; wrap around empty to highest
12942 ;; default
12943 (if org-priority-start-cycle-with-default
12944 org-default-priority
12945 (1+ org-default-priority))))))
12946 (t (error "Invalid action")))
12947 (if (or (< (upcase new) org-highest-priority)
12948 (> (upcase new) org-lowest-priority))
12949 (if (and (memq action '(up down))
12950 (not have) (not (eq last-command this-command)))
12951 ;; `new' is from default priority
12952 (error
12953 "The default can not be set, see `org-default-priority' why")
12954 ;; normal cycling: `new' is beyond highest/lowest priority
12955 ;; and is wrapped around to the empty priority
12956 (setq remove t)))
12957 (setq news (format "%c" new))
12958 (if have
12959 (if remove
12960 (replace-match "" t t nil 1)
12961 (replace-match news t t nil 2))
12962 (if remove
12963 (error "No priority cookie found in line")
12964 (let ((case-fold-search nil))
12965 (looking-at org-todo-line-regexp))
12966 (if (match-end 2)
12967 (progn
12968 (goto-char (match-end 2))
12969 (insert " [#" news "]"))
12970 (goto-char (match-beginning 3))
12971 (insert "[#" news "] "))))
12972 (org-preserve-lc (org-set-tags nil 'align)))
12973 (if remove
12974 (message "Priority removed")
12975 (message "Priority of current item set to %s" news)))))
12977 (defun org-show-priority ()
12978 "Show the priority of the current item.
12979 This priority is composed of the main priority given with the [#A] cookies,
12980 and by additional input from the age of a schedules or deadline entry."
12981 (interactive)
12982 (let ((pri (if (eq major-mode 'org-agenda-mode)
12983 (org-get-at-bol 'priority)
12984 (save-excursion
12985 (save-match-data
12986 (beginning-of-line)
12987 (and (looking-at org-heading-regexp)
12988 (org-get-priority (match-string 0))))))))
12989 (message "Priority is %d" (if pri pri -1000))))
12991 (defun org-get-priority (s)
12992 "Find priority cookie and return priority."
12993 (if (functionp org-get-priority-function)
12994 (funcall org-get-priority-function)
12995 (save-match-data
12996 (if (not (string-match org-priority-regexp s))
12997 (* 1000 (- org-lowest-priority org-default-priority))
12998 (* 1000 (- org-lowest-priority
12999 (string-to-char (match-string 2 s))))))))
13001 ;;;; Tags
13003 (defvar org-agenda-archives-mode)
13004 (defvar org-map-continue-from nil
13005 "Position from where mapping should continue.
13006 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13008 (defvar org-scanner-tags nil
13009 "The current tag list while the tags scanner is running.")
13010 (defvar org-trust-scanner-tags nil
13011 "Should `org-get-tags-at' use the tags for the scanner.
13012 This is for internal dynamical scoping only.
13013 When this is non-nil, the function `org-get-tags-at' will return the value
13014 of `org-scanner-tags' instead of building the list by itself. This
13015 can lead to large speed-ups when the tags scanner is used in a file with
13016 many entries, and when the list of tags is retrieved, for example to
13017 obtain a list of properties. Building the tags list for each entry in such
13018 a file becomes an N^2 operation - but with this variable set, it scales
13019 as N.")
13021 (defun org-scan-tags (action matcher todo-only &optional start-level)
13022 "Scan headline tags with inheritance and produce output ACTION.
13024 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13025 or `agenda' to produce an entry list for an agenda view. It can also be
13026 a Lisp form or a function that should be called at each matched headline, in
13027 this case the return value is a list of all return values from these calls.
13029 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13030 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13031 only lines with a not-done TODO keyword are included in the output.
13032 This should be the same variable that was scoped into
13033 and set by `org-make-tags-matcher' when it constructed MATCHER.
13035 START-LEVEL can be a string with asterisks, reducing the scope to
13036 headlines matching this string."
13037 (require 'org-agenda)
13038 (let* ((re (concat "^"
13039 (if start-level
13040 ;; Get the correct level to match
13041 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13042 org-outline-regexp)
13043 " *\\(\\<\\("
13044 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13045 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13046 (props (list 'face 'default
13047 'done-face 'org-agenda-done
13048 'undone-face 'default
13049 'mouse-face 'highlight
13050 'org-not-done-regexp org-not-done-regexp
13051 'org-todo-regexp org-todo-regexp
13052 'org-complex-heading-regexp org-complex-heading-regexp
13053 'help-echo
13054 (format "mouse-2 or RET jump to org file %s"
13055 (abbreviate-file-name
13056 (or (buffer-file-name (buffer-base-buffer))
13057 (buffer-name (buffer-base-buffer)))))))
13058 (case-fold-search nil)
13059 (org-map-continue-from nil)
13060 lspos tags tags-list
13061 (tags-alist (list (cons 0 org-file-tags)))
13062 (llast 0) rtn rtn1 level category i txt
13063 todo marker entry priority)
13064 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13065 (setq action (list 'lambda nil action)))
13066 (save-excursion
13067 (goto-char (point-min))
13068 (when (eq action 'sparse-tree)
13069 (org-overview)
13070 (org-remove-occur-highlights))
13071 (while (re-search-forward re nil t)
13072 (setq org-map-continue-from nil)
13073 (catch :skip
13074 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13075 tags (if (match-end 4) (org-match-string-no-properties 4)))
13076 (goto-char (setq lspos (match-beginning 0)))
13077 (setq level (org-reduced-level (funcall outline-level))
13078 category (org-get-category))
13079 (setq i llast llast level)
13080 ;; remove tag lists from same and sublevels
13081 (while (>= i level)
13082 (when (setq entry (assoc i tags-alist))
13083 (setq tags-alist (delete entry tags-alist)))
13084 (setq i (1- i)))
13085 ;; add the next tags
13086 (when tags
13087 (setq tags (org-split-string tags ":")
13088 tags-alist
13089 (cons (cons level tags) tags-alist)))
13090 ;; compile tags for current headline
13091 (setq tags-list
13092 (if org-use-tag-inheritance
13093 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13094 tags)
13095 org-scanner-tags tags-list)
13096 (when org-use-tag-inheritance
13097 (setcdr (car tags-alist)
13098 (mapcar (lambda (x)
13099 (setq x (copy-sequence x))
13100 (org-add-prop-inherited x))
13101 (cdar tags-alist))))
13102 (when (and tags org-use-tag-inheritance
13103 (or (not (eq t org-use-tag-inheritance))
13104 org-tags-exclude-from-inheritance))
13105 ;; selective inheritance, remove uninherited ones
13106 (setcdr (car tags-alist)
13107 (org-remove-uninherited-tags (cdar tags-alist))))
13108 (when (and
13110 ;; eval matcher only when the todo condition is OK
13111 (and (or (not todo-only) (member todo org-not-done-keywords))
13112 (let ((case-fold-search t) (org-trust-scanner-tags t))
13113 (eval matcher)))
13115 ;; Call the skipper, but return t if it does not skip,
13116 ;; so that the `and' form continues evaluating
13117 (progn
13118 (unless (eq action 'sparse-tree) (org-agenda-skip))
13121 ;; Check if timestamps are deselecting this entry
13122 (or (not todo-only)
13123 (and (member todo org-not-done-keywords)
13124 (or (not org-agenda-tags-todo-honor-ignore-options)
13125 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13127 ;; Extra check for the archive tag
13128 ;; FIXME: Does the skipper already do this????
13130 (not (member org-archive-tag tags-list))
13131 ;; we have an archive tag, should we use this anyway?
13132 (or (not org-agenda-skip-archived-trees)
13133 (and (eq action 'agenda) org-agenda-archives-mode))))
13135 ;; select this headline
13137 (cond
13138 ((eq action 'sparse-tree)
13139 (and org-highlight-sparse-tree-matches
13140 (org-get-heading) (match-end 0)
13141 (org-highlight-new-match
13142 (match-beginning 1) (match-end 1)))
13143 (org-show-context 'tags-tree))
13144 ((eq action 'agenda)
13145 (setq txt (org-agenda-format-item
13147 (concat
13148 (if (eq org-tags-match-list-sublevels 'indented)
13149 (make-string (1- level) ?.) "")
13150 (org-get-heading))
13151 category
13152 tags-list)
13153 priority (org-get-priority txt))
13154 (goto-char lspos)
13155 (setq marker (org-agenda-new-marker))
13156 (org-add-props txt props
13157 'org-marker marker 'org-hd-marker marker 'org-category category
13158 'todo-state todo
13159 'priority priority 'type "tagsmatch")
13160 (push txt rtn))
13161 ((functionp action)
13162 (setq org-map-continue-from nil)
13163 (save-excursion
13164 (setq rtn1 (funcall action))
13165 (push rtn1 rtn)))
13166 (t (error "Invalid action")))
13168 ;; if we are to skip sublevels, jump to end of subtree
13169 (unless org-tags-match-list-sublevels
13170 (org-end-of-subtree t)
13171 (backward-char 1))))
13172 ;; Get the correct position from where to continue
13173 (if org-map-continue-from
13174 (goto-char org-map-continue-from)
13175 (and (= (point) lspos) (end-of-line 1)))))
13176 (when (and (eq action 'sparse-tree)
13177 (not org-sparse-tree-open-archived-trees))
13178 (org-hide-archived-subtrees (point-min) (point-max)))
13179 (nreverse rtn)))
13181 (defun org-remove-uninherited-tags (tags)
13182 "Remove all tags that are not inherited from the list TAGS."
13183 (cond
13184 ((eq org-use-tag-inheritance t)
13185 (if org-tags-exclude-from-inheritance
13186 (org-delete-all org-tags-exclude-from-inheritance tags)
13187 tags))
13188 ((not org-use-tag-inheritance) nil)
13189 ((stringp org-use-tag-inheritance)
13190 (delq nil (mapcar
13191 (lambda (x)
13192 (if (and (string-match org-use-tag-inheritance x)
13193 (not (member x org-tags-exclude-from-inheritance)))
13194 x nil))
13195 tags)))
13196 ((listp org-use-tag-inheritance)
13197 (delq nil (mapcar
13198 (lambda (x)
13199 (if (member x org-use-tag-inheritance) x nil))
13200 tags)))))
13202 (defun org-match-sparse-tree (&optional todo-only match)
13203 "Create a sparse tree according to tags string MATCH.
13204 MATCH can contain positive and negative selection of tags, like
13205 \"+WORK+URGENT-WITHBOSS\".
13206 If optional argument TODO-ONLY is non-nil, only select lines that are
13207 also TODO lines."
13208 (interactive "P")
13209 (org-agenda-prepare-buffers (list (current-buffer)))
13210 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13212 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13214 (defvar org-cached-props nil)
13215 (defun org-cached-entry-get (pom property)
13216 (if (or (eq t org-use-property-inheritance)
13217 (and (stringp org-use-property-inheritance)
13218 (string-match org-use-property-inheritance property))
13219 (and (listp org-use-property-inheritance)
13220 (member property org-use-property-inheritance)))
13221 ;; Caching is not possible, check it directly
13222 (org-entry-get pom property 'inherit)
13223 ;; Get all properties, so that we can do complicated checks easily
13224 (cdr (assoc property (or org-cached-props
13225 (setq org-cached-props
13226 (org-entry-properties pom)))))))
13228 (defun org-global-tags-completion-table (&optional files)
13229 "Return the list of all tags in all agenda buffer/files.
13230 Optional FILES argument is a list of files which can be used
13231 instead of the agenda files."
13232 (save-excursion
13233 (org-uniquify
13234 (delq nil
13235 (apply 'append
13236 (mapcar
13237 (lambda (file)
13238 (set-buffer (find-file-noselect file))
13239 (append (org-get-buffer-tags)
13240 (mapcar (lambda (x) (if (stringp (car-safe x))
13241 (list (car-safe x)) nil))
13242 org-tag-alist)))
13243 (if (and files (car files))
13244 files
13245 (org-agenda-files))))))))
13247 (defun org-make-tags-matcher (match)
13248 "Create the TAGS/TODO matcher form for the selection string MATCH.
13250 The variable `todo-only' is scoped dynamically into this function.
13251 It will be set to t if the matcher restricts matching to TODO entries,
13252 otherwise will not be touched.
13254 Returns a cons of the selection string MATCH and the constructed
13255 lisp form implementing the matcher. The matcher is to be evaluated
13256 at an Org entry, with point on the headline, and returns t if the
13257 entry matches the selection string MATCH. The returned lisp form
13258 references two variables with information about the entry, which
13259 must be bound around the form's evaluation: todo, the TODO keyword
13260 at the entry (or nil of none); and tags-list, the list of all tags
13261 at the entry including inherited ones. Additionally, the category
13262 of the entry (if any) must be specified as the text property
13263 'org-category on the headline.
13265 See also `org-scan-tags'.
13267 (declare (special todo-only))
13268 (unless (boundp 'todo-only)
13269 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13270 (unless match
13271 ;; Get a new match request, with completion
13272 (let ((org-last-tags-completion-table
13273 (org-global-tags-completion-table)))
13274 (setq match (org-completing-read-no-i
13275 "Match: " 'org-tags-completion-function nil nil nil
13276 'org-tags-history))))
13278 ;; Parse the string and create a lisp form
13279 (let ((match0 match)
13280 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13281 minus tag mm
13282 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13283 orterms term orlist re-p str-p level-p level-op time-p
13284 prop-p pn pv po gv rest)
13285 (if (string-match "/+" match)
13286 ;; match contains also a todo-matching request
13287 (progn
13288 (setq tagsmatch (substring match 0 (match-beginning 0))
13289 todomatch (substring match (match-end 0)))
13290 (if (string-match "^!" todomatch)
13291 (setq todo-only t todomatch (substring todomatch 1)))
13292 (if (string-match "^\\s-*$" todomatch)
13293 (setq todomatch nil)))
13294 ;; only matching tags
13295 (setq tagsmatch match todomatch nil))
13297 ;; Make the tags matcher
13298 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13299 (setq tagsmatcher t)
13300 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13301 (while (setq term (pop orterms))
13302 (while (and (equal (substring term -1) "\\") orterms)
13303 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13304 (while (string-match re term)
13305 (setq rest (substring term (match-end 0))
13306 minus (and (match-end 1)
13307 (equal (match-string 1 term) "-"))
13308 tag (save-match-data (replace-regexp-in-string
13309 "\\\\-" "-"
13310 (match-string 2 term)))
13311 re-p (equal (string-to-char tag) ?{)
13312 level-p (match-end 4)
13313 prop-p (match-end 5)
13314 mm (cond
13315 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13316 (level-p
13317 (setq level-op (org-op-to-function (match-string 3 term)))
13318 `(,level-op level ,(string-to-number
13319 (match-string 4 term))))
13320 (prop-p
13321 (setq pn (match-string 5 term)
13322 po (match-string 6 term)
13323 pv (match-string 7 term)
13324 re-p (equal (string-to-char pv) ?{)
13325 str-p (equal (string-to-char pv) ?\")
13326 time-p (save-match-data
13327 (string-match "^\"[[<].*[]>]\"$" pv))
13328 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13329 (if time-p (setq pv (org-matcher-time pv)))
13330 (setq po (org-op-to-function po (if time-p 'time str-p)))
13331 (cond
13332 ((equal pn "CATEGORY")
13333 (setq gv '(get-text-property (point) 'org-category)))
13334 ((equal pn "TODO")
13335 (setq gv 'todo))
13337 (setq gv `(org-cached-entry-get nil ,pn))))
13338 (if re-p
13339 (if (eq po 'org<>)
13340 `(not (string-match ,pv (or ,gv "")))
13341 `(string-match ,pv (or ,gv "")))
13342 (if str-p
13343 `(,po (or ,gv "") ,pv)
13344 `(,po (string-to-number (or ,gv ""))
13345 ,(string-to-number pv) ))))
13346 (t `(member ,tag tags-list)))
13347 mm (if minus (list 'not mm) mm)
13348 term rest)
13349 (push mm tagsmatcher))
13350 (push (if (> (length tagsmatcher) 1)
13351 (cons 'and tagsmatcher)
13352 (car tagsmatcher))
13353 orlist)
13354 (setq tagsmatcher nil))
13355 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13356 (setq tagsmatcher
13357 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13358 ;; Make the todo matcher
13359 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13360 (setq todomatcher t)
13361 (setq orterms (org-split-string todomatch "|") orlist nil)
13362 (while (setq term (pop orterms))
13363 (while (string-match re term)
13364 (setq minus (and (match-end 1)
13365 (equal (match-string 1 term) "-"))
13366 kwd (match-string 2 term)
13367 re-p (equal (string-to-char kwd) ?{)
13368 term (substring term (match-end 0))
13369 mm (if re-p
13370 `(string-match ,(substring kwd 1 -1) todo)
13371 (list 'equal 'todo kwd))
13372 mm (if minus (list 'not mm) mm))
13373 (push mm todomatcher))
13374 (push (if (> (length todomatcher) 1)
13375 (cons 'and todomatcher)
13376 (car todomatcher))
13377 orlist)
13378 (setq todomatcher nil))
13379 (setq todomatcher (if (> (length orlist) 1)
13380 (cons 'or orlist) (car orlist))))
13382 ;; Return the string and lisp forms of the matcher
13383 (setq matcher (if todomatcher
13384 (list 'and tagsmatcher todomatcher)
13385 tagsmatcher))
13386 (when todo-only
13387 (setq matcher (list 'and '(member todo org-not-done-keywords)
13388 matcher)))
13389 (cons match0 matcher)))
13391 (defun org-op-to-function (op &optional stringp)
13392 "Turn an operator into the appropriate function."
13393 (setq op
13394 (cond
13395 ((equal op "<" ) '(< string< org-time<))
13396 ((equal op ">" ) '(> org-string> org-time>))
13397 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13398 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13399 ((member op '("=" "==")) '(= string= org-time=))
13400 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13401 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13403 (defun org<> (a b) (not (= a b)))
13404 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13405 (defun org-string>= (a b) (not (string< a b)))
13406 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13407 (defun org-string<> (a b) (not (string= a b)))
13408 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13409 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13410 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13411 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13412 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13413 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13414 (defun org-2ft (s)
13415 "Convert S to a floating point time.
13416 If S is already a number, just return it. If it is a string, parse
13417 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13418 (cond
13419 ((numberp s) s)
13420 ((stringp s)
13421 (condition-case nil
13422 (float-time (apply 'encode-time (org-parse-time-string s)))
13423 (error 0.)))
13424 (t 0.)))
13426 (defun org-time-today ()
13427 "Time in seconds today at 0:00.
13428 Returns the float number of seconds since the beginning of the
13429 epoch to the beginning of today (00:00)."
13430 (float-time (apply 'encode-time
13431 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13433 (defun org-matcher-time (s)
13434 "Interpret a time comparison value."
13435 (save-match-data
13436 (cond
13437 ((string= s "<now>") (float-time))
13438 ((string= s "<today>") (org-time-today))
13439 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13440 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13441 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13442 (+ (org-time-today)
13443 (* (string-to-number (match-string 1 s))
13444 (cdr (assoc (match-string 2 s)
13445 '(("d" . 86400.0) ("w" . 604800.0)
13446 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13447 (t (org-2ft s)))))
13449 (defun org-match-any-p (re list)
13450 "Does re match any element of list?"
13451 (setq list (mapcar (lambda (x) (string-match re x)) list))
13452 (delq nil list))
13454 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13455 (defvar org-tags-overlay (make-overlay 1 1))
13456 (org-detach-overlay org-tags-overlay)
13458 (defun org-get-local-tags-at (&optional pos)
13459 "Get a list of tags defined in the current headline."
13460 (org-get-tags-at pos 'local))
13462 (defun org-get-local-tags ()
13463 "Get a list of tags defined in the current headline."
13464 (org-get-tags-at nil 'local))
13466 (defun org-get-tags-at (&optional pos local)
13467 "Get a list of all headline tags applicable at POS.
13468 POS defaults to point. If tags are inherited, the list contains
13469 the targets in the same sequence as the headlines appear, i.e.
13470 the tags of the current headline come last.
13471 When LOCAL is non-nil, only return tags from the current headline,
13472 ignore inherited ones."
13473 (interactive)
13474 (if (and org-trust-scanner-tags
13475 (or (not pos) (equal pos (point)))
13476 (not local))
13477 org-scanner-tags
13478 (let (tags ltags lastpos parent)
13479 (save-excursion
13480 (save-restriction
13481 (widen)
13482 (goto-char (or pos (point)))
13483 (save-match-data
13484 (catch 'done
13485 (condition-case nil
13486 (progn
13487 (org-back-to-heading t)
13488 (while (not (equal lastpos (point)))
13489 (setq lastpos (point))
13490 (when (looking-at
13491 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13492 (setq ltags (org-split-string
13493 (org-match-string-no-properties 1) ":"))
13494 (when parent
13495 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13496 (setq tags (append
13497 (if parent
13498 (org-remove-uninherited-tags ltags)
13499 ltags)
13500 tags)))
13501 (or org-use-tag-inheritance (throw 'done t))
13502 (if local (throw 'done t))
13503 (or (org-up-heading-safe) (error nil))
13504 (setq parent t)))
13505 (error nil)))))
13506 (if local
13507 tags
13508 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13510 (defun org-add-prop-inherited (s)
13511 (add-text-properties 0 (length s) '(inherited t) s)
13514 (defun org-toggle-tag (tag &optional onoff)
13515 "Toggle the tag TAG for the current line.
13516 If ONOFF is `on' or `off', don't toggle but set to this state."
13517 (let (res current)
13518 (save-excursion
13519 (org-back-to-heading t)
13520 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13521 (point-at-eol) t)
13522 (progn
13523 (setq current (match-string 1))
13524 (replace-match ""))
13525 (setq current ""))
13526 (setq current (nreverse (org-split-string current ":")))
13527 (cond
13528 ((eq onoff 'on)
13529 (setq res t)
13530 (or (member tag current) (push tag current)))
13531 ((eq onoff 'off)
13532 (or (not (member tag current)) (setq current (delete tag current))))
13533 (t (if (member tag current)
13534 (setq current (delete tag current))
13535 (setq res t)
13536 (push tag current))))
13537 (end-of-line 1)
13538 (if current
13539 (progn
13540 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13541 (org-set-tags nil t))
13542 (delete-horizontal-space))
13543 (run-hooks 'org-after-tags-change-hook))
13544 res))
13546 (defun org-align-tags-here (to-col)
13547 ;; Assumes that this is a headline
13548 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13549 (beginning-of-line 1)
13550 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13551 (< pos (match-beginning 2)))
13552 (progn
13553 (setq tags-l (- (match-end 2) (match-beginning 2)))
13554 (goto-char (match-beginning 1))
13555 (insert " ")
13556 (delete-region (point) (1+ (match-beginning 2)))
13557 (setq ncol (max (current-column)
13558 (1+ col)
13559 (if (> to-col 0)
13560 to-col
13561 (- (abs to-col) tags-l))))
13562 (setq p (point))
13563 (insert (make-string (- ncol (current-column)) ?\ ))
13564 (setq ncol (current-column))
13565 (when indent-tabs-mode (tabify p (point-at-eol)))
13566 (org-move-to-column (min ncol col) t))
13567 (goto-char pos))))
13569 (defun org-set-tags-command (&optional arg just-align)
13570 "Call the set-tags command for the current entry."
13571 (interactive "P")
13572 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13573 (org-set-tags arg just-align)
13574 (save-excursion
13575 (org-back-to-heading t)
13576 (org-set-tags arg just-align))))
13578 (defun org-set-tags-to (data)
13579 "Set the tags of the current entry to DATA, replacing the current tags.
13580 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13581 If DATA is nil or the empty string, any tags will be removed."
13582 (interactive "sTags: ")
13583 (setq data
13584 (cond
13585 ((eq data nil) "")
13586 ((equal data "") "")
13587 ((stringp data)
13588 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13589 ":"))
13590 ((listp data)
13591 (concat ":" (mapconcat 'identity data ":") ":"))))
13592 (when data
13593 (save-excursion
13594 (org-back-to-heading t)
13595 (when (looking-at org-complex-heading-regexp)
13596 (if (match-end 5)
13597 (progn
13598 (goto-char (match-beginning 5))
13599 (insert data)
13600 (delete-region (point) (point-at-eol))
13601 (org-set-tags nil 'align))
13602 (goto-char (point-at-eol))
13603 (insert " " data)
13604 (org-set-tags nil 'align)))
13605 (beginning-of-line 1)
13606 (if (looking-at ".*?\\([ \t]+\\)$")
13607 (delete-region (match-beginning 1) (match-end 1))))))
13609 (defun org-align-all-tags ()
13610 "Align the tags i all headings."
13611 (interactive)
13612 (save-excursion
13613 (or (ignore-errors (org-back-to-heading t))
13614 (outline-next-heading))
13615 (if (org-at-heading-p)
13616 (org-set-tags t)
13617 (message "No headings"))))
13619 (defvar org-indent-indentation-per-level)
13620 (defun org-set-tags (&optional arg just-align)
13621 "Set the tags for the current headline.
13622 With prefix ARG, realign all tags in headings in the current buffer."
13623 (interactive "P")
13624 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13625 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13626 'region-start-level 'region))
13627 org-loop-over-headlines-in-active-region)
13628 (org-map-entries
13629 ;; We don't use ARG and JUST-ALIGN here these args are not
13630 ;; useful when looping over headlines
13631 `(org-set-tags)
13632 org-loop-over-headlines-in-active-region
13633 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13634 (let* ((re org-outline-regexp-bol)
13635 (current (unless arg (org-get-tags-string)))
13636 (col (current-column))
13637 (org-setting-tags t)
13638 table current-tags inherited-tags ; computed below when needed
13639 tags p0 c0 c1 rpl di tc level)
13640 (if arg
13641 (save-excursion
13642 (goto-char (point-min))
13643 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13644 (while (re-search-forward re nil t)
13645 (org-set-tags nil t)
13646 (end-of-line 1)))
13647 (message "All tags realigned to column %d" org-tags-column))
13648 (if just-align
13649 (setq tags current)
13650 ;; Get a new set of tags from the user
13651 (save-excursion
13652 (setq table (append org-tag-persistent-alist
13653 (or org-tag-alist (org-get-buffer-tags))
13654 (and
13655 org-complete-tags-always-offer-all-agenda-tags
13656 (org-global-tags-completion-table
13657 (org-agenda-files))))
13658 org-last-tags-completion-table table
13659 current-tags (org-split-string current ":")
13660 inherited-tags (nreverse
13661 (nthcdr (length current-tags)
13662 (nreverse (org-get-tags-at))))
13663 tags
13664 (if (or (eq t org-use-fast-tag-selection)
13665 (and org-use-fast-tag-selection
13666 (delq nil (mapcar 'cdr table))))
13667 (org-fast-tag-selection
13668 current-tags inherited-tags table
13669 (if org-fast-tag-selection-include-todo
13670 org-todo-key-alist))
13671 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13672 (org-trim
13673 (org-icompleting-read "Tags: "
13674 'org-tags-completion-function
13675 nil nil current 'org-tags-history))))))
13676 (while (string-match "[-+&]+" tags)
13677 ;; No boolean logic, just a list
13678 (setq tags (replace-match ":" t t tags))))
13680 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13682 (if org-tags-sort-function
13683 (setq tags (mapconcat 'identity
13684 (sort (org-split-string
13685 tags (org-re "[^[:alnum:]_@#%]+"))
13686 org-tags-sort-function) ":")))
13688 (if (string-match "\\`[\t ]*\\'" tags)
13689 (setq tags "")
13690 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13691 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13693 ;; Insert new tags at the correct column
13694 (beginning-of-line 1)
13695 (setq level (or (and (looking-at org-outline-regexp)
13696 (- (match-end 0) (point) 1))
13698 (cond
13699 ((and (equal current "") (equal tags "")))
13700 ((re-search-forward
13701 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13702 (point-at-eol) t)
13703 (if (equal tags "")
13704 (setq rpl "")
13705 (goto-char (match-beginning 0))
13706 (setq c0 (current-column)
13707 ;; compute offset for the case of org-indent-mode active
13708 di (if org-indent-mode
13709 (* (1- org-indent-indentation-per-level) (1- level))
13711 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13712 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13713 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13714 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13715 (replace-match rpl t t)
13716 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13717 tags)
13718 (t (error "Tags alignment failed")))
13719 (org-move-to-column col)
13720 (unless just-align
13721 (run-hooks 'org-after-tags-change-hook))))))
13723 (defun org-change-tag-in-region (beg end tag off)
13724 "Add or remove TAG for each entry in the region.
13725 This works in the agenda, and also in an org-mode buffer."
13726 (interactive
13727 (list (region-beginning) (region-end)
13728 (let ((org-last-tags-completion-table
13729 (if (derived-mode-p 'org-mode)
13730 (org-get-buffer-tags)
13731 (org-global-tags-completion-table))))
13732 (org-icompleting-read
13733 "Tag: " 'org-tags-completion-function nil nil nil
13734 'org-tags-history))
13735 (progn
13736 (message "[s]et or [r]emove? ")
13737 (equal (read-char-exclusive) ?r))))
13738 (if (fboundp 'deactivate-mark) (deactivate-mark))
13739 (let ((agendap (equal major-mode 'org-agenda-mode))
13740 l1 l2 m buf pos newhead (cnt 0))
13741 (goto-char end)
13742 (setq l2 (1- (org-current-line)))
13743 (goto-char beg)
13744 (setq l1 (org-current-line))
13745 (loop for l from l1 to l2 do
13746 (org-goto-line l)
13747 (setq m (get-text-property (point) 'org-hd-marker))
13748 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13749 (and agendap m))
13750 (setq buf (if agendap (marker-buffer m) (current-buffer))
13751 pos (if agendap m (point)))
13752 (with-current-buffer buf
13753 (save-excursion
13754 (save-restriction
13755 (goto-char pos)
13756 (setq cnt (1+ cnt))
13757 (org-toggle-tag tag (if off 'off 'on))
13758 (setq newhead (org-get-heading)))))
13759 (and agendap (org-agenda-change-all-lines newhead m))))
13760 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13762 (defun org-tags-completion-function (string predicate &optional flag)
13763 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13764 (confirm (lambda (x) (stringp (car x)))))
13765 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13766 (setq s1 (match-string 1 string)
13767 s2 (match-string 2 string))
13768 (setq s1 "" s2 string))
13769 (cond
13770 ((eq flag nil)
13771 ;; try completion
13772 (setq rtn (try-completion s2 ctable confirm))
13773 (if (stringp rtn)
13774 (setq rtn
13775 (concat s1 s2 (substring rtn (length s2))
13776 (if (and org-add-colon-after-tag-completion
13777 (assoc rtn ctable))
13778 ":" ""))))
13779 rtn)
13780 ((eq flag t)
13781 ;; all-completions
13782 (all-completions s2 ctable confirm)
13784 ((eq flag 'lambda)
13785 ;; exact match?
13786 (assoc s2 ctable)))
13789 (defun org-fast-tag-insert (kwd tags face &optional end)
13790 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13791 (insert (format "%-12s" (concat kwd ":"))
13792 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13793 (or end "")))
13795 (defun org-fast-tag-show-exit (flag)
13796 (save-excursion
13797 (org-goto-line 3)
13798 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13799 (replace-match ""))
13800 (when flag
13801 (end-of-line 1)
13802 (org-move-to-column (- (window-width) 19) t)
13803 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13805 (defun org-set-current-tags-overlay (current prefix)
13806 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13807 (if (featurep 'xemacs)
13808 (org-overlay-display org-tags-overlay (concat prefix s)
13809 'secondary-selection)
13810 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13811 (org-overlay-display org-tags-overlay (concat prefix s)))))
13813 (defvar org-last-tag-selection-key nil)
13814 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13815 "Fast tag selection with single keys.
13816 CURRENT is the current list of tags in the headline, INHERITED is the
13817 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13818 possibly with grouping information. TODO-TABLE is a similar table with
13819 TODO keywords, should these have keys assigned to them.
13820 If the keys are nil, a-z are automatically assigned.
13821 Returns the new tags string, or nil to not change the current settings."
13822 (let* ((fulltable (append table todo-table))
13823 (maxlen (apply 'max (mapcar
13824 (lambda (x)
13825 (if (stringp (car x)) (string-width (car x)) 0))
13826 fulltable)))
13827 (buf (current-buffer))
13828 (expert (eq org-fast-tag-selection-single-key 'expert))
13829 (buffer-tags nil)
13830 (fwidth (+ maxlen 3 1 3))
13831 (ncol (/ (- (window-width) 4) fwidth))
13832 (i-face 'org-done)
13833 (c-face 'org-todo)
13834 tg cnt e c char c1 c2 ntable tbl rtn
13835 ov-start ov-end ov-prefix
13836 (exit-after-next org-fast-tag-selection-single-key)
13837 (done-keywords org-done-keywords)
13838 groups ingroup)
13839 (save-excursion
13840 (beginning-of-line 1)
13841 (if (looking-at
13842 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13843 (setq ov-start (match-beginning 1)
13844 ov-end (match-end 1)
13845 ov-prefix "")
13846 (setq ov-start (1- (point-at-eol))
13847 ov-end (1+ ov-start))
13848 (skip-chars-forward "^\n\r")
13849 (setq ov-prefix
13850 (concat
13851 (buffer-substring (1- (point)) (point))
13852 (if (> (current-column) org-tags-column)
13854 (make-string (- org-tags-column (current-column)) ?\ ))))))
13855 (move-overlay org-tags-overlay ov-start ov-end)
13856 (save-window-excursion
13857 (if expert
13858 (set-buffer (get-buffer-create " *Org tags*"))
13859 (delete-other-windows)
13860 (split-window-vertically)
13861 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13862 (erase-buffer)
13863 (org-set-local 'org-done-keywords done-keywords)
13864 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13865 (org-fast-tag-insert "Current" current c-face "\n\n")
13866 (org-fast-tag-show-exit exit-after-next)
13867 (org-set-current-tags-overlay current ov-prefix)
13868 (setq tbl fulltable char ?a cnt 0)
13869 (while (setq e (pop tbl))
13870 (cond
13871 ((equal (car e) :startgroup)
13872 (push '() groups) (setq ingroup t)
13873 (when (not (= cnt 0))
13874 (setq cnt 0)
13875 (insert "\n"))
13876 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13877 ((equal (car e) :endgroup)
13878 (setq ingroup nil cnt 0)
13879 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13880 ((equal e '(:newline))
13881 (when (not (= cnt 0))
13882 (setq cnt 0)
13883 (insert "\n")
13884 (setq e (car tbl))
13885 (while (equal (car tbl) '(:newline))
13886 (insert "\n")
13887 (setq tbl (cdr tbl)))))
13889 (setq tg (copy-sequence (car e)) c2 nil)
13890 (if (cdr e)
13891 (setq c (cdr e))
13892 ;; automatically assign a character.
13893 (setq c1 (string-to-char
13894 (downcase (substring
13895 tg (if (= (string-to-char tg) ?@) 1 0)))))
13896 (if (or (rassoc c1 ntable) (rassoc c1 table))
13897 (while (or (rassoc char ntable) (rassoc char table))
13898 (setq char (1+ char)))
13899 (setq c2 c1))
13900 (setq c (or c2 char)))
13901 (if ingroup (push tg (car groups)))
13902 (setq tg (org-add-props tg nil 'face
13903 (cond
13904 ((not (assoc tg table))
13905 (org-get-todo-face tg))
13906 ((member tg current) c-face)
13907 ((member tg inherited) i-face))))
13908 (if (and (= cnt 0) (not ingroup)) (insert " "))
13909 (insert "[" c "] " tg (make-string
13910 (- fwidth 4 (length tg)) ?\ ))
13911 (push (cons tg c) ntable)
13912 (when (= (setq cnt (1+ cnt)) ncol)
13913 (insert "\n")
13914 (if ingroup (insert " "))
13915 (setq cnt 0)))))
13916 (setq ntable (nreverse ntable))
13917 (insert "\n")
13918 (goto-char (point-min))
13919 (if (not expert) (org-fit-window-to-buffer))
13920 (setq rtn
13921 (catch 'exit
13922 (while t
13923 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13924 (if (not groups) "no " "")
13925 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13926 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13927 (setq org-last-tag-selection-key c)
13928 (cond
13929 ((= c ?\r) (throw 'exit t))
13930 ((= c ?!)
13931 (setq groups (not groups))
13932 (goto-char (point-min))
13933 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13934 ((= c ?\C-c)
13935 (if (not expert)
13936 (org-fast-tag-show-exit
13937 (setq exit-after-next (not exit-after-next)))
13938 (setq expert nil)
13939 (delete-other-windows)
13940 (set-window-buffer (split-window-vertically) " *Org tags*")
13941 (org-switch-to-buffer-other-window " *Org tags*")
13942 (org-fit-window-to-buffer)))
13943 ((or (= c ?\C-g)
13944 (and (= c ?q) (not (rassoc c ntable))))
13945 (org-detach-overlay org-tags-overlay)
13946 (setq quit-flag t))
13947 ((= c ?\ )
13948 (setq current nil)
13949 (if exit-after-next (setq exit-after-next 'now)))
13950 ((= c ?\t)
13951 (condition-case nil
13952 (setq tg (org-icompleting-read
13953 "Tag: "
13954 (or buffer-tags
13955 (with-current-buffer buf
13956 (org-get-buffer-tags)))))
13957 (quit (setq tg "")))
13958 (when (string-match "\\S-" tg)
13959 (add-to-list 'buffer-tags (list tg))
13960 (if (member tg current)
13961 (setq current (delete tg current))
13962 (push tg current)))
13963 (if exit-after-next (setq exit-after-next 'now)))
13964 ((setq e (rassoc c todo-table) tg (car e))
13965 (with-current-buffer buf
13966 (save-excursion (org-todo tg)))
13967 (if exit-after-next (setq exit-after-next 'now)))
13968 ((setq e (rassoc c ntable) tg (car e))
13969 (if (member tg current)
13970 (setq current (delete tg current))
13971 (loop for g in groups do
13972 (if (member tg g)
13973 (mapc (lambda (x)
13974 (setq current (delete x current)))
13975 g)))
13976 (push tg current))
13977 (if exit-after-next (setq exit-after-next 'now))))
13979 ;; Create a sorted list
13980 (setq current
13981 (sort current
13982 (lambda (a b)
13983 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13984 (if (eq exit-after-next 'now) (throw 'exit t))
13985 (goto-char (point-min))
13986 (beginning-of-line 2)
13987 (delete-region (point) (point-at-eol))
13988 (org-fast-tag-insert "Current" current c-face)
13989 (org-set-current-tags-overlay current ov-prefix)
13990 (while (re-search-forward
13991 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13992 (setq tg (match-string 1))
13993 (add-text-properties
13994 (match-beginning 1) (match-end 1)
13995 (list 'face
13996 (cond
13997 ((member tg current) c-face)
13998 ((member tg inherited) i-face)
13999 (t (get-text-property (match-beginning 1) 'face))))))
14000 (goto-char (point-min)))))
14001 (org-detach-overlay org-tags-overlay)
14002 (if rtn
14003 (mapconcat 'identity current ":")
14004 nil))))
14006 (defun org-get-tags-string ()
14007 "Get the TAGS string in the current headline."
14008 (unless (org-at-heading-p t)
14009 (error "Not on a heading"))
14010 (save-excursion
14011 (beginning-of-line 1)
14012 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14013 (org-match-string-no-properties 1)
14014 "")))
14016 (defun org-get-tags ()
14017 "Get the list of tags specified in the current headline."
14018 (org-split-string (org-get-tags-string) ":"))
14020 (defun org-get-buffer-tags ()
14021 "Get a table of all tags used in the buffer, for completion."
14022 (let (tags)
14023 (save-excursion
14024 (goto-char (point-min))
14025 (while (re-search-forward
14026 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14027 (when (equal (char-after (point-at-bol 0)) ?*)
14028 (mapc (lambda (x) (add-to-list 'tags x))
14029 (org-split-string (org-match-string-no-properties 1) ":")))))
14030 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14031 (mapcar 'list tags)))
14033 ;;;; The mapping API
14035 (defun org-map-entries (func &optional match scope &rest skip)
14036 "Call FUNC at each headline selected by MATCH in SCOPE.
14038 FUNC is a function or a lisp form. The function will be called without
14039 arguments, with the cursor positioned at the beginning of the headline.
14040 The return values of all calls to the function will be collected and
14041 returned as a list.
14043 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14044 does not need to preserve point. After evaluation, the cursor will be
14045 moved to the end of the line (presumably of the headline of the
14046 processed entry) and search continues from there. Under some
14047 circumstances, this may not produce the wanted results. For example,
14048 if you have removed (e.g. archived) the current (sub)tree it could
14049 mean that the next entry will be skipped entirely. In such cases, you
14050 can specify the position from where search should continue by making
14051 FUNC set the variable `org-map-continue-from' to the desired buffer
14052 position.
14054 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14055 Only headlines that are matched by this query will be considered during
14056 the iteration. When MATCH is nil or t, all headlines will be
14057 visited by the iteration.
14059 SCOPE determines the scope of this command. It can be any of:
14061 nil The current buffer, respecting the restriction if any
14062 tree The subtree started with the entry at point
14063 region The entries within the active region, if any
14064 region-start-level
14065 The entries within the active region, but only those at
14066 the same level than the first one.
14067 file The current buffer, without restriction
14068 file-with-archives
14069 The current buffer, and any archives associated with it
14070 agenda All agenda files
14071 agenda-with-archives
14072 All agenda files with any archive files associated with them
14073 \(file1 file2 ...)
14074 If this is a list, all files in the list will be scanned
14076 The remaining args are treated as settings for the skipping facilities of
14077 the scanner. The following items can be given here:
14079 archive skip trees with the archive tag.
14080 comment skip trees with the COMMENT keyword
14081 function or Emacs Lisp form:
14082 will be used as value for `org-agenda-skip-function', so whenever
14083 the function returns t, FUNC will not be called for that
14084 entry and search will continue from the point where the
14085 function leaves it.
14087 If your function needs to retrieve the tags including inherited tags
14088 at the *current* entry, you can use the value of the variable
14089 `org-scanner-tags' which will be much faster than getting the value
14090 with `org-get-tags-at'. If your function gets properties with
14091 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14092 to t around the call to `org-entry-properties' to get the same speedup.
14093 Note that if your function moves around to retrieve tags and properties at
14094 a *different* entry, you cannot use these techniques."
14095 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14096 (not (org-region-active-p)))
14097 (let* ((org-agenda-archives-mode nil) ; just to make sure
14098 (org-agenda-skip-archived-trees (memq 'archive skip))
14099 (org-agenda-skip-comment-trees (memq 'comment skip))
14100 (org-agenda-skip-function
14101 (car (org-delete-all '(comment archive) skip)))
14102 (org-tags-match-list-sublevels t)
14103 (start-level (eq scope 'region-start-level))
14104 matcher file res
14105 org-todo-keywords-for-agenda
14106 org-done-keywords-for-agenda
14107 org-todo-keyword-alist-for-agenda
14108 org-drawers-for-agenda
14109 org-tag-alist-for-agenda
14110 todo-only)
14112 (cond
14113 ((eq match t) (setq matcher t))
14114 ((eq match nil) (setq matcher t))
14115 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14117 (save-excursion
14118 (save-restriction
14119 (cond ((eq scope 'tree)
14120 (org-back-to-heading t)
14121 (org-narrow-to-subtree)
14122 (setq scope nil))
14123 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14124 (org-region-active-p))
14125 ;; If needed, set start-level to a string like "2"
14126 (when start-level
14127 (save-excursion
14128 (goto-char (region-beginning))
14129 (unless (org-at-heading-p) (outline-next-heading))
14130 (setq start-level (org-current-level))))
14131 (narrow-to-region (region-beginning)
14132 (save-excursion
14133 (goto-char (region-end))
14134 (unless (and (bolp) (org-at-heading-p))
14135 (outline-next-heading))
14136 (point)))
14137 (setq scope nil)))
14139 (if (not scope)
14140 (progn
14141 (org-agenda-prepare-buffers
14142 (list (buffer-file-name (current-buffer))))
14143 (setq res (org-scan-tags func matcher todo-only start-level)))
14144 ;; Get the right scope
14145 (cond
14146 ((and scope (listp scope) (symbolp (car scope)))
14147 (setq scope (eval scope)))
14148 ((eq scope 'agenda)
14149 (setq scope (org-agenda-files t)))
14150 ((eq scope 'agenda-with-archives)
14151 (setq scope (org-agenda-files t))
14152 (setq scope (org-add-archive-files scope)))
14153 ((eq scope 'file)
14154 (setq scope (list (buffer-file-name))))
14155 ((eq scope 'file-with-archives)
14156 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14157 (org-agenda-prepare-buffers scope)
14158 (while (setq file (pop scope))
14159 (with-current-buffer (org-find-base-buffer-visiting file)
14160 (save-excursion
14161 (save-restriction
14162 (widen)
14163 (goto-char (point-min))
14164 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14165 res)))
14167 ;;;; Properties
14169 ;;; Setting and retrieving properties
14171 (defconst org-special-properties
14172 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14173 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14174 "The special properties valid in Org-mode.
14176 These are properties that are not defined in the property drawer,
14177 but in some other way.")
14179 (defconst org-default-properties
14180 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14181 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14182 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14183 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14184 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14185 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14186 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14187 "Some properties that are used by Org-mode for various purposes.
14188 Being in this list makes sure that they are offered for completion.")
14190 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14191 "Regular expression matching the first line of a property drawer.")
14193 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14194 "Regular expression matching the last line of a property drawer.")
14196 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14197 "Regular expression matching the first line of a property drawer.")
14199 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14200 "Regular expression matching the first line of a property drawer.")
14202 (defconst org-property-drawer-re
14203 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14204 org-property-end-re "\\)\n?")
14205 "Matches an entire property drawer.")
14207 (defconst org-clock-drawer-re
14208 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14209 org-property-end-re "\\)\n?")
14210 "Matches an entire clock drawer.")
14212 (defsubst org-re-property (property)
14213 "Return a regexp matching a PROPERTY line.
14214 Match group 1 will be set to the value."
14215 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14217 (defsubst org-re-property-keyword (property)
14218 "Return a regexp matching a PROPERTY line, possibly with no
14219 value for the property."
14220 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14222 (defun org-property-action ()
14223 "Do an action on properties."
14224 (interactive)
14225 (let (c)
14226 (org-at-property-p)
14227 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14228 (setq c (read-char-exclusive))
14229 (cond
14230 ((equal c ?s)
14231 (call-interactively 'org-set-property))
14232 ((equal c ?d)
14233 (call-interactively 'org-delete-property))
14234 ((equal c ?D)
14235 (call-interactively 'org-delete-property-globally))
14236 ((equal c ?c)
14237 (call-interactively 'org-compute-property-at-point))
14238 (t (error "No such property action %c" c)))))
14240 (defun org-inc-effort ()
14241 "Increment the value of the effort property in the current entry."
14242 (interactive)
14243 (org-set-effort nil t))
14245 (defun org-set-effort (&optional value increment)
14246 "Set the effort property of the current entry.
14247 With numerical prefix arg, use the nth allowed value, 0 stands for the
14248 10th allowed value.
14250 When INCREMENT is non-nil, set the property to the next allowed value."
14251 (interactive "P")
14252 (if (equal value 0) (setq value 10))
14253 (let* ((completion-ignore-case t)
14254 (prop org-effort-property)
14255 (cur (org-entry-get nil prop))
14256 (allowed (org-property-get-allowed-values nil prop 'table))
14257 (existing (mapcar 'list (org-property-values prop)))
14259 (val (cond
14260 ((stringp value) value)
14261 ((and allowed (integerp value))
14262 (or (car (nth (1- value) allowed))
14263 (car (org-last allowed))))
14264 ((and allowed increment)
14265 (or (caadr (member (list cur) allowed))
14266 (error "Allowed effort values are not set")))
14267 (allowed
14268 (message "Select 1-9,0, [RET%s]: %s"
14269 (if cur (concat "=" cur) "")
14270 (mapconcat 'car allowed " "))
14271 (setq rpl (read-char-exclusive))
14272 (if (equal rpl ?\r)
14274 (setq rpl (- rpl ?0))
14275 (if (equal rpl 0) (setq rpl 10))
14276 (if (and (> rpl 0) (<= rpl (length allowed)))
14277 (car (nth (1- rpl) allowed))
14278 (org-completing-read "Effort: " allowed nil))))
14280 (let (org-completion-use-ido org-completion-use-iswitchb)
14281 (org-completing-read
14282 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14283 (concat "[" cur "]") "")
14284 ": ")
14285 existing nil nil "" nil cur))))))
14286 (unless (equal (org-entry-get nil prop) val)
14287 (org-entry-put nil prop val))
14288 (message "%s is now %s" prop val)))
14290 (defun org-at-property-p ()
14291 "Is cursor inside a property drawer?"
14292 (save-excursion
14293 (beginning-of-line 1)
14294 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14295 (save-match-data ;; Used by calling procedures
14296 (let ((p (point))
14297 (range (unless (org-before-first-heading-p)
14298 (org-get-property-block))))
14299 (and range (<= (car range) p) (< p (cdr range))))))))
14301 (defun org-get-property-block (&optional beg end force)
14302 "Return the (beg . end) range of the body of the property drawer.
14303 BEG and END are the beginning and end of the current subtree, or of
14304 the part before the first headline. If they are not given, they will
14305 be found. If the drawer does not exist and FORCE is non-nil, create
14306 the drawer."
14307 (catch 'exit
14308 (save-excursion
14309 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14310 (progn (org-back-to-heading t) (point))))
14311 (end (or end (and (not (outline-next-heading)) (point-max))
14312 (point))))
14313 (goto-char beg)
14314 (if (re-search-forward org-property-start-re end t)
14315 (setq beg (1+ (match-end 0)))
14316 (if force
14317 (save-excursion
14318 (org-insert-property-drawer)
14319 (setq end (progn (outline-next-heading) (point))))
14320 (throw 'exit nil))
14321 (goto-char beg)
14322 (if (re-search-forward org-property-start-re end t)
14323 (setq beg (1+ (match-end 0)))))
14324 (if (re-search-forward org-property-end-re end t)
14325 (setq end (match-beginning 0))
14326 (or force (throw 'exit nil))
14327 (goto-char beg)
14328 (setq end beg)
14329 (org-indent-line)
14330 (insert ":END:\n"))
14331 (cons beg end)))))
14333 (defun org-entry-properties (&optional pom which specific)
14334 "Get all properties of the entry at point-or-marker POM.
14335 This includes the TODO keyword, the tags, time strings for deadline,
14336 scheduled, and clocking, and any additional properties defined in the
14337 entry. The return value is an alist, keys may occur multiple times
14338 if the property key was used several times.
14339 POM may also be nil, in which case the current entry is used.
14340 If WHICH is nil or `all', get all properties. If WHICH is
14341 `special' or `standard', only get that subclass. If WHICH
14342 is a string only get exactly this property. SPECIFIC can be a string, the
14343 specific property we are interested in. Specifying it can speed
14344 things up because then unnecessary parsing is avoided."
14345 (setq which (or which 'all))
14346 (org-with-point-at pom
14347 (let ((clockstr (substring org-clock-string 0 -1))
14348 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14349 (case-fold-search nil)
14350 beg end range props sum-props key key1 value string clocksum clocksumt)
14351 (save-excursion
14352 (when (condition-case nil
14353 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14354 (error nil))
14355 (setq beg (point))
14356 (setq sum-props (get-text-property (point) 'org-summaries))
14357 (setq clocksum (get-text-property (point) :org-clock-minutes)
14358 clocksumt (get-text-property (point) :org-clock-minutes-today))
14359 (outline-next-heading)
14360 (setq end (point))
14361 (when (memq which '(all special))
14362 ;; Get the special properties, like TODO and tags
14363 (goto-char beg)
14364 (when (and (or (not specific) (string= specific "TODO"))
14365 (looking-at org-todo-line-regexp) (match-end 2))
14366 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14367 (when (and (or (not specific) (string= specific "PRIORITY"))
14368 (looking-at org-priority-regexp))
14369 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14370 (when (or (not specific) (string= specific "FILE"))
14371 (push (cons "FILE" buffer-file-name) props))
14372 (when (and (or (not specific) (string= specific "TAGS"))
14373 (setq value (org-get-tags-string))
14374 (string-match "\\S-" value))
14375 (push (cons "TAGS" value) props))
14376 (when (and (or (not specific) (string= specific "ALLTAGS"))
14377 (setq value (org-get-tags-at)))
14378 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14379 ":"))
14380 props))
14381 (when (or (not specific) (string= specific "BLOCKED"))
14382 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14383 (when (or (not specific)
14384 (member specific
14385 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14386 "TIMESTAMP" "TIMESTAMP_IA")))
14387 (catch 'match
14388 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14389 (setq key (if (match-end 1)
14390 (substring (org-match-string-no-properties 1)
14391 0 -1))
14392 string (if (equal key clockstr)
14393 (org-trim
14394 (buffer-substring-no-properties
14395 (match-beginning 3) (goto-char
14396 (point-at-eol))))
14397 (substring (org-match-string-no-properties 3)
14398 1 -1)))
14399 ;; Get the correct property name from the key. This is
14400 ;; necessary if the user has configured time keywords.
14401 (setq key1 (concat key ":"))
14402 (cond
14403 ((not key)
14404 (setq key
14405 (if (= (char-after (match-beginning 3)) ?\[)
14406 "TIMESTAMP_IA" "TIMESTAMP")))
14407 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14408 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14409 ((equal key1 org-closed-string) (setq key "CLOSED"))
14410 ((equal key1 org-clock-string) (setq key "CLOCK")))
14411 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14412 (progn
14413 (push (cons key string) props)
14414 ;; no need to search further if match is found
14415 (throw 'match t))
14416 (when (or (equal key "CLOCK") (not (assoc key props)))
14417 (push (cons key string) props)))))))
14419 (when (memq which '(all standard))
14420 ;; Get the standard properties, like :PROP: ...
14421 (setq range (org-get-property-block beg end))
14422 (when range
14423 (goto-char (car range))
14424 (while (re-search-forward
14425 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14426 (cdr range) t)
14427 (setq key (org-match-string-no-properties 1)
14428 value (org-trim (or (org-match-string-no-properties 2) "")))
14429 (unless (member key excluded)
14430 (push (cons key (or value "")) props)))))
14431 (if clocksum
14432 (push (cons "CLOCKSUM"
14433 (org-columns-number-to-string (/ (float clocksum) 60.)
14434 'add_times))
14435 props))
14436 (if clocksumt
14437 (push (cons "CLOCKSUM_T"
14438 (org-columns-number-to-string (/ (float clocksumt) 60.)
14439 'add_times))
14440 props))
14441 (unless (assoc "CATEGORY" props)
14442 (push (cons "CATEGORY" (org-get-category)) props))
14443 (append sum-props (nreverse props)))))))
14445 (defun org-entry-get (pom property &optional inherit literal-nil)
14446 "Get value of PROPERTY for entry or content at point-or-marker POM.
14447 If INHERIT is non-nil and the entry does not have the property,
14448 then also check higher levels of the hierarchy.
14449 If INHERIT is the symbol `selective', use inheritance only if the setting
14450 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14451 If the property is present but empty, the return value is the empty string.
14452 If the property is not present at all, nil is returned.
14454 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14455 do not interpret it as the list atom nil. This is used for inheritance
14456 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14457 (org-with-point-at pom
14458 (if (and inherit (if (eq inherit 'selective)
14459 (org-property-inherit-p property)
14461 (org-entry-get-with-inheritance property literal-nil)
14462 (if (member property org-special-properties)
14463 ;; We need a special property. Use `org-entry-properties' to
14464 ;; retrieve it, but specify the wanted property
14465 (cdr (assoc property (org-entry-properties nil 'special property)))
14466 (let* ((range (org-get-property-block))
14467 (props (list (or (assoc property org-file-properties)
14468 (assoc property org-global-properties)
14469 (assoc property org-global-properties-fixed))))
14470 (ap (lambda (key)
14471 (when (re-search-forward
14472 (org-re-property key) (cdr range) t)
14473 (setq props
14474 (org-update-property-plist
14476 (if (match-end 1)
14477 (org-match-string-no-properties 1) "")
14478 props)))))
14479 val)
14480 (when (and range (goto-char (car range)))
14481 (funcall ap property)
14482 (goto-char (car range))
14483 (while (funcall ap (concat property "+")))
14484 (setq val (cdr (assoc property props)))
14485 (when val (if literal-nil val (org-not-nil val)))))))))
14487 (defun org-property-or-variable-value (var &optional inherit)
14488 "Check if there is a property fixing the value of VAR.
14489 If yes, return this value. If not, return the current value of the variable."
14490 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14491 (if (and prop (stringp prop) (string-match "\\S-" prop))
14492 (read prop)
14493 (symbol-value var))))
14495 (defun org-entry-delete (pom property)
14496 "Delete the property PROPERTY from entry at point-or-marker POM."
14497 (org-with-point-at pom
14498 (if (member property org-special-properties)
14499 nil ; cannot delete these properties.
14500 (let ((range (org-get-property-block)))
14501 (if (and range
14502 (goto-char (car range))
14503 (re-search-forward
14504 (org-re-property property)
14505 (cdr range) t))
14506 (progn
14507 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14509 nil)))))
14511 ;; Multi-values properties are properties that contain multiple values
14512 ;; These values are assumed to be single words, separated by whitespace.
14513 (defun org-entry-add-to-multivalued-property (pom property value)
14514 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14515 (let* ((old (org-entry-get pom property))
14516 (values (and old (org-split-string old "[ \t]"))))
14517 (setq value (org-entry-protect-space value))
14518 (unless (member value values)
14519 (setq values (cons value values))
14520 (org-entry-put pom property
14521 (mapconcat 'identity values " ")))))
14523 (defun org-entry-remove-from-multivalued-property (pom property value)
14524 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14525 (let* ((old (org-entry-get pom property))
14526 (values (and old (org-split-string old "[ \t]"))))
14527 (setq value (org-entry-protect-space value))
14528 (when (member value values)
14529 (setq values (delete value values))
14530 (org-entry-put pom property
14531 (mapconcat 'identity values " ")))))
14533 (defun org-entry-member-in-multivalued-property (pom property value)
14534 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14535 (let* ((old (org-entry-get pom property))
14536 (values (and old (org-split-string old "[ \t]"))))
14537 (setq value (org-entry-protect-space value))
14538 (member value values)))
14540 (defun org-entry-get-multivalued-property (pom property)
14541 "Return a list of values in a multivalued property."
14542 (let* ((value (org-entry-get pom property))
14543 (values (and value (org-split-string value "[ \t]"))))
14544 (mapcar 'org-entry-restore-space values)))
14546 (defun org-entry-put-multivalued-property (pom property &rest values)
14547 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14548 VALUES should be a list of strings. Spaces will be protected."
14549 (org-entry-put pom property
14550 (mapconcat 'org-entry-protect-space values " "))
14551 (let* ((value (org-entry-get pom property))
14552 (values (and value (org-split-string value "[ \t]"))))
14553 (mapcar 'org-entry-restore-space values)))
14555 (defun org-entry-protect-space (s)
14556 "Protect spaces and newline in string S."
14557 (while (string-match " " s)
14558 (setq s (replace-match "%20" t t s)))
14559 (while (string-match "\n" s)
14560 (setq s (replace-match "%0A" t t s)))
14563 (defun org-entry-restore-space (s)
14564 "Restore spaces and newline in string S."
14565 (while (string-match "%20" s)
14566 (setq s (replace-match " " t t s)))
14567 (while (string-match "%0A" s)
14568 (setq s (replace-match "\n" t t s)))
14571 (defvar org-entry-property-inherited-from (make-marker)
14572 "Marker pointing to the entry from where a property was inherited.
14573 Each call to `org-entry-get-with-inheritance' will set this marker to the
14574 location of the entry where the inheritance search matched. If there was
14575 no match, the marker will point nowhere.
14576 Note that also `org-entry-get' calls this function, if the INHERIT flag
14577 is set.")
14579 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14580 "Get PROPERTY of entry or content at point, search higher levels if needed.
14581 The search will stop at the first ancestor which has the property defined.
14582 If the value found is \"nil\", return nil to show that the property
14583 should be considered as undefined (this is the meaning of nil here).
14584 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14585 (move-marker org-entry-property-inherited-from nil)
14586 (let (tmp)
14587 (save-excursion
14588 (save-restriction
14589 (widen)
14590 (catch 'ex
14591 (while t
14592 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14593 (or (ignore-errors (org-back-to-heading t))
14594 (goto-char (point-min)))
14595 (move-marker org-entry-property-inherited-from (point))
14596 (throw 'ex tmp))
14597 (or (ignore-errors (org-up-heading-safe))
14598 (throw 'ex nil))))))
14599 (setq tmp (or tmp
14600 (cdr (assoc property org-file-properties))
14601 (cdr (assoc property org-global-properties))
14602 (cdr (assoc property org-global-properties-fixed))))
14603 (if literal-nil tmp (org-not-nil tmp))))
14605 (defvar org-property-changed-functions nil
14606 "Hook called when the value of a property has changed.
14607 Each hook function should accept two arguments, the name of the property
14608 and the new value.")
14610 (defun org-entry-put (pom property value)
14611 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14612 (org-with-point-at pom
14613 (org-back-to-heading t)
14614 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14615 range)
14616 (cond
14617 ((equal property "TODO")
14618 (when (and (stringp value) (string-match "\\S-" value)
14619 (not (member value org-todo-keywords-1)))
14620 (error "\"%s\" is not a valid TODO state" value))
14621 (if (or (not value)
14622 (not (string-match "\\S-" value)))
14623 (setq value 'none))
14624 (org-todo value)
14625 (org-set-tags nil 'align))
14626 ((equal property "PRIORITY")
14627 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14628 (string-to-char value) ?\ ))
14629 (org-set-tags nil 'align))
14630 ((equal property "SCHEDULED")
14631 (if (re-search-forward org-scheduled-time-regexp end t)
14632 (cond
14633 ((eq value 'earlier) (org-timestamp-change -1 'day))
14634 ((eq value 'later) (org-timestamp-change 1 'day))
14635 (t (call-interactively 'org-schedule)))
14636 (call-interactively 'org-schedule)))
14637 ((equal property "DEADLINE")
14638 (if (re-search-forward org-deadline-time-regexp end t)
14639 (cond
14640 ((eq value 'earlier) (org-timestamp-change -1 'day))
14641 ((eq value 'later) (org-timestamp-change 1 'day))
14642 (t (call-interactively 'org-deadline)))
14643 (call-interactively 'org-deadline)))
14644 ((member property org-special-properties)
14645 (error "The %s property can not yet be set with `org-entry-put'"
14646 property))
14647 (t ; a non-special property
14648 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14649 (setq range (org-get-property-block beg end 'force))
14650 (goto-char (car range))
14651 (if (re-search-forward
14652 (org-re-property-keyword property) (cdr range) t)
14653 (progn
14654 (delete-region (match-beginning 0) (match-end 0))
14655 (goto-char (match-beginning 0)))
14656 (goto-char (cdr range))
14657 (insert "\n")
14658 (backward-char 1)
14659 (org-indent-line))
14660 (insert ":" property ":")
14661 (and value (insert " " value))
14662 (org-indent-line)))))
14663 (run-hook-with-args 'org-property-changed-functions property value)))
14665 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14666 "Get all property keys in the current buffer.
14667 With INCLUDE-SPECIALS, also list the special properties that reflect things
14668 like tags and TODO state.
14669 With INCLUDE-DEFAULTS, also include properties that has special meaning
14670 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14671 and others.
14672 With INCLUDE-COLUMNS, also include property names given in COLUMN
14673 formats in the current buffer."
14674 (let (rtn range cfmt s p)
14675 (save-excursion
14676 (save-restriction
14677 (widen)
14678 (goto-char (point-min))
14679 (while (re-search-forward org-property-start-re nil t)
14680 (setq range (org-get-property-block))
14681 (goto-char (car range))
14682 (while (re-search-forward
14683 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14684 (cdr range) t)
14685 (add-to-list 'rtn (org-match-string-no-properties 1)))
14686 (outline-next-heading))))
14688 (when include-specials
14689 (setq rtn (append org-special-properties rtn)))
14691 (when include-defaults
14692 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14693 (add-to-list 'rtn org-effort-property))
14695 (when include-columns
14696 (save-excursion
14697 (save-restriction
14698 (widen)
14699 (goto-char (point-min))
14700 (while (re-search-forward
14701 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14702 nil t)
14703 (setq cfmt (match-string 2) s 0)
14704 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14705 cfmt s)
14706 (setq s (match-end 0)
14707 p (match-string 1 cfmt))
14708 (unless (or (equal p "ITEM")
14709 (member p org-special-properties))
14710 (add-to-list 'rtn (match-string 1 cfmt))))))))
14712 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14714 (defun org-property-values (key)
14715 "Return a list of all values of property KEY in the current buffer."
14716 (save-excursion
14717 (save-restriction
14718 (widen)
14719 (goto-char (point-min))
14720 (let ((re (org-re-property key))
14721 values)
14722 (while (re-search-forward re nil t)
14723 (add-to-list 'values (org-trim (match-string 1))))
14724 (delete "" values)))))
14726 (defun org-insert-property-drawer ()
14727 "Insert a property drawer into the current entry."
14728 (org-back-to-heading t)
14729 (looking-at org-outline-regexp)
14730 (let ((indent (if org-adapt-indentation
14731 (- (match-end 0) (match-beginning 0))
14733 (beg (point))
14734 (re (concat "^[ \t]*" org-keyword-time-regexp))
14735 end hiddenp)
14736 (outline-next-heading)
14737 (setq end (point))
14738 (goto-char beg)
14739 (while (re-search-forward re end t))
14740 (setq hiddenp (outline-invisible-p))
14741 (end-of-line 1)
14742 (and (equal (char-after) ?\n) (forward-char 1))
14743 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14744 (if (member (match-string 1) '("CLOCK:" ":END:"))
14745 ;; just skip this line
14746 (beginning-of-line 2)
14747 ;; Drawer start, find the end
14748 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14749 (beginning-of-line 1)))
14750 (org-skip-over-state-notes)
14751 (skip-chars-backward " \t\n\r")
14752 (if (eq (char-before) ?*) (forward-char 1))
14753 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14754 (beginning-of-line 0)
14755 (org-indent-to-column indent)
14756 (beginning-of-line 2)
14757 (org-indent-to-column indent)
14758 (beginning-of-line 0)
14759 (if hiddenp
14760 (save-excursion
14761 (org-back-to-heading t)
14762 (hide-entry))
14763 (org-flag-drawer t))))
14765 (defun org-insert-drawer (&optional arg drawer)
14766 "Insert a drawer at point.
14768 Optional argument DRAWER, when non-nil, is a string representing
14769 drawer's name. Otherwise, the user is prompted for a name.
14771 If a region is active, insert the drawer around that region
14772 instead.
14774 Point is left between drawer's boundaries."
14775 (interactive "P")
14776 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14777 "LOGBOOK"))
14778 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14779 ;; internally by Org. They are meant to be inserted
14780 ;; automatically.
14781 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14782 ;; Remove system drawers from list. Note: For some reason,
14783 ;; `org-completing-read' ignores the predicate while
14784 ;; `completing-read' handles it fine.
14785 (drawer (if arg "PROPERTIES"
14786 (or drawer
14787 (completing-read
14788 "Drawer: " org-drawers
14789 (lambda (d) (not (member d system-drawers))))))))
14790 (cond
14791 ;; With C-u, fall back on `org-insert-property-drawer'
14792 (arg (org-insert-property-drawer))
14793 ;; With an active region, insert a drawer at point.
14794 ((not (org-region-active-p))
14795 (progn
14796 (unless (bolp) (insert "\n"))
14797 (insert (format ":%s:\n\n:END:\n" drawer))
14798 (forward-line -2)))
14799 ;; Otherwise, insert the drawer at point
14801 (let ((rbeg (region-beginning))
14802 (rend (copy-marker (region-end))))
14803 (unwind-protect
14804 (progn
14805 (goto-char rbeg)
14806 (beginning-of-line)
14807 (when (save-excursion
14808 (re-search-forward org-outline-regexp-bol rend t))
14809 (error "Drawers cannot contain headlines"))
14810 ;; Position point at the beginning of the first
14811 ;; non-blank line in region. Insert drawer's opening
14812 ;; there, then indent it.
14813 (org-skip-whitespace)
14814 (beginning-of-line)
14815 (insert ":" drawer ":\n")
14816 (forward-line -1)
14817 (indent-for-tab-command)
14818 ;; Move point to the beginning of the first blank line
14819 ;; after the last non-blank line in region. Insert
14820 ;; drawer's closing, then indent it.
14821 (goto-char rend)
14822 (skip-chars-backward " \r\t\n")
14823 (insert "\n:END:")
14824 (deactivate-mark t)
14825 (indent-for-tab-command)
14826 (unless (eolp) (insert "\n")))
14827 ;; Clear marker, whatever the outcome of insertion is.
14828 (set-marker rend nil)))))))
14830 (defvar org-property-set-functions-alist nil
14831 "Property set function alist.
14832 Each entry should have the following format:
14834 (PROPERTY . READ-FUNCTION)
14836 The read function will be called with the same argument as
14837 `org-completing-read'.")
14839 (defun org-set-property-function (property)
14840 "Get the function that should be used to set PROPERTY.
14841 This is computed according to `org-property-set-functions-alist'."
14842 (or (cdr (assoc property org-property-set-functions-alist))
14843 'org-completing-read))
14845 (defun org-read-property-value (property)
14846 "Read PROPERTY value from user."
14847 (let* ((completion-ignore-case t)
14848 (allowed (org-property-get-allowed-values nil property 'table))
14849 (cur (org-entry-get nil property))
14850 (prompt (concat property " value"
14851 (if (and cur (string-match "\\S-" cur))
14852 (concat " [" cur "]") "") ": "))
14853 (set-function (org-set-property-function property))
14854 (val (if allowed
14855 (funcall set-function prompt allowed nil
14856 (not (get-text-property 0 'org-unrestricted
14857 (caar allowed))))
14858 (let (org-completion-use-ido org-completion-use-iswitchb)
14859 (funcall set-function prompt
14860 (mapcar 'list (org-property-values property))
14861 nil nil "" nil cur)))))
14862 (if (equal val "")
14864 val)))
14866 (defvar org-last-set-property nil)
14867 (defun org-read-property-name ()
14868 "Read a property name."
14869 (let* ((completion-ignore-case t)
14870 (keys (org-buffer-property-keys nil t t))
14871 (default-prop (or (save-excursion
14872 (save-match-data
14873 (beginning-of-line)
14874 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14875 (null (string= (match-string 1) "END"))
14876 (match-string 1))))
14877 org-last-set-property))
14878 (property (org-icompleting-read
14879 (concat "Property"
14880 (if default-prop (concat " [" default-prop "]") "")
14881 ": ")
14882 (mapcar 'list keys)
14883 nil nil nil nil
14884 default-prop
14886 (if (member property keys)
14887 property
14888 (or (cdr (assoc (downcase property)
14889 (mapcar (lambda (x) (cons (downcase x) x))
14890 keys)))
14891 property))))
14893 (defun org-set-property (property value)
14894 "In the current entry, set PROPERTY to VALUE.
14895 When called interactively, this will prompt for a property name, offering
14896 completion on existing and default properties. And then it will prompt
14897 for a value, offering completion either on allowed values (via an inherited
14898 xxx_ALL property) or on existing values in other instances of this property
14899 in the current file."
14900 (interactive (list nil nil))
14901 (let* ((property (or property (org-read-property-name)))
14902 (value (or value (org-read-property-value property)))
14903 (fn (cdr (assoc property org-properties-postprocess-alist))))
14904 (setq org-last-set-property property)
14905 ;; Possibly postprocess the inserted value:
14906 (when fn (setq value (funcall fn value)))
14907 (unless (equal (org-entry-get nil property) value)
14908 (org-entry-put nil property value))))
14910 (defun org-delete-property (property)
14911 "In the current entry, delete PROPERTY."
14912 (interactive
14913 (let* ((completion-ignore-case t)
14914 (prop (org-icompleting-read "Property: "
14915 (org-entry-properties nil 'standard))))
14916 (list prop)))
14917 (message "Property %s %s" property
14918 (if (org-entry-delete nil property)
14919 "deleted"
14920 "was not present in the entry")))
14922 (defun org-delete-property-globally (property)
14923 "Remove PROPERTY globally, from all entries."
14924 (interactive
14925 (let* ((completion-ignore-case t)
14926 (prop (org-icompleting-read
14927 "Globally remove property: "
14928 (mapcar 'list (org-buffer-property-keys)))))
14929 (list prop)))
14930 (save-excursion
14931 (save-restriction
14932 (widen)
14933 (goto-char (point-min))
14934 (let ((cnt 0))
14935 (while (re-search-forward
14936 (org-re-property property)
14937 nil t)
14938 (setq cnt (1+ cnt))
14939 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14940 (message "Property \"%s\" removed from %d entries" property cnt)))))
14942 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14944 (defun org-compute-property-at-point ()
14945 "Compute the property at point.
14946 This looks for an enclosing column format, extracts the operator and
14947 then applies it to the property in the column format's scope."
14948 (interactive)
14949 (unless (org-at-property-p)
14950 (error "Not at a property"))
14951 (let ((prop (org-match-string-no-properties 2)))
14952 (org-columns-get-format-and-top-level)
14953 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14954 (error "No operator defined for property %s" prop))
14955 (org-columns-compute prop)))
14957 (defvar org-property-allowed-value-functions nil
14958 "Hook for functions supplying allowed values for a specific property.
14959 The functions must take a single argument, the name of the property, and
14960 return a flat list of allowed values. If \":ETC\" is one of
14961 the values, this means that these values are intended as defaults for
14962 completion, but that other values should be allowed too.
14963 The functions must return nil if they are not responsible for this
14964 property.")
14966 (defun org-property-get-allowed-values (pom property &optional table)
14967 "Get allowed values for the property PROPERTY.
14968 When TABLE is non-nil, return an alist that can directly be used for
14969 completion."
14970 (let (vals)
14971 (cond
14972 ((equal property "TODO")
14973 (setq vals (org-with-point-at pom
14974 (append org-todo-keywords-1 '("")))))
14975 ((equal property "PRIORITY")
14976 (let ((n org-lowest-priority))
14977 (while (>= n org-highest-priority)
14978 (push (char-to-string n) vals)
14979 (setq n (1- n)))))
14980 ((member property org-special-properties))
14981 ((setq vals (run-hook-with-args-until-success
14982 'org-property-allowed-value-functions property)))
14984 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14985 (when (and vals (string-match "\\S-" vals))
14986 (setq vals (car (read-from-string (concat "(" vals ")"))))
14987 (setq vals (mapcar (lambda (x)
14988 (cond ((stringp x) x)
14989 ((numberp x) (number-to-string x))
14990 ((symbolp x) (symbol-name x))
14991 (t "???")))
14992 vals)))))
14993 (when (member ":ETC" vals)
14994 (setq vals (remove ":ETC" vals))
14995 (org-add-props (car vals) '(org-unrestricted t)))
14996 (if table (mapcar 'list vals) vals)))
14998 (defun org-property-previous-allowed-value (&optional previous)
14999 "Switch to the next allowed value for this property."
15000 (interactive)
15001 (org-property-next-allowed-value t))
15003 (defun org-property-next-allowed-value (&optional previous)
15004 "Switch to the next allowed value for this property."
15005 (interactive)
15006 (unless (org-at-property-p)
15007 (error "Not at a property"))
15008 (let* ((key (match-string 2))
15009 (value (match-string 3))
15010 (allowed (or (org-property-get-allowed-values (point) key)
15011 (and (member value '("[ ]" "[-]" "[X]"))
15012 '("[ ]" "[X]"))))
15013 nval)
15014 (unless allowed
15015 (error "Allowed values for this property have not been defined"))
15016 (if previous (setq allowed (reverse allowed)))
15017 (if (member value allowed)
15018 (setq nval (car (cdr (member value allowed)))))
15019 (setq nval (or nval (car allowed)))
15020 (if (equal nval value)
15021 (error "Only one allowed value for this property"))
15022 (org-at-property-p)
15023 (replace-match (concat " :" key ": " nval) t t)
15024 (org-indent-line)
15025 (beginning-of-line 1)
15026 (skip-chars-forward " \t")
15027 (run-hook-with-args 'org-property-changed-functions key nval)))
15029 (defun org-find-olp (path &optional this-buffer)
15030 "Return a marker pointing to the entry at outline path OLP.
15031 If anything goes wrong, throw an error.
15032 You can wrap this call to catch the error like this:
15034 (condition-case msg
15035 (org-mobile-locate-entry (match-string 4))
15036 (error (nth 1 msg)))
15038 The return value will then be either a string with the error message,
15039 or a marker if everything is OK.
15041 If THIS-BUFFER is set, the outline path does not contain a file,
15042 only headings."
15043 (let* ((file (if this-buffer buffer-file-name (pop path)))
15044 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15045 (level 1)
15046 (lmin 1)
15047 (lmax 1)
15048 limit re end found pos heading cnt flevel)
15049 (unless buffer (error "File not found :%s" file))
15050 (with-current-buffer buffer
15051 (save-excursion
15052 (save-restriction
15053 (widen)
15054 (setq limit (point-max))
15055 (goto-char (point-min))
15056 (while (setq heading (pop path))
15057 (setq re (format org-complex-heading-regexp-format
15058 (regexp-quote heading)))
15059 (setq cnt 0 pos (point))
15060 (while (re-search-forward re end t)
15061 (setq level (- (match-end 1) (match-beginning 1)))
15062 (if (and (>= level lmin) (<= level lmax))
15063 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15064 (when (= cnt 0) (error "Heading not found on level %d: %s"
15065 lmax heading))
15066 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15067 lmax heading))
15068 (goto-char found)
15069 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15070 (setq end (save-excursion (org-end-of-subtree t t))))
15071 (when (org-at-heading-p)
15072 (point-marker)))))))
15074 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15075 "Find node HEADING in BUFFER.
15076 Return a marker to the heading if it was found, or nil if not.
15077 If POS-ONLY is set, return just the position instead of a marker.
15079 The heading text must match exact, but it may have a TODO keyword,
15080 a priority cookie and tags in the standard locations."
15081 (with-current-buffer (or buffer (current-buffer))
15082 (save-excursion
15083 (save-restriction
15084 (widen)
15085 (goto-char (point-min))
15086 (let (case-fold-search)
15087 (if (re-search-forward
15088 (format org-complex-heading-regexp-format
15089 (regexp-quote heading)) nil t)
15090 (if pos-only
15091 (match-beginning 0)
15092 (move-marker (make-marker) (match-beginning 0)))))))))
15094 (defun org-find-exact-heading-in-directory (heading &optional dir)
15095 "Find Org node headline HEADING in all .org files in directory DIR.
15096 When the target headline is found, return a marker to this location."
15097 (let ((files (directory-files (or dir default-directory)
15098 nil "\\`[^.#].*\\.org\\'"))
15099 file visiting m buffer)
15100 (catch 'found
15101 (while (setq file (pop files))
15102 (message "trying %s" file)
15103 (setq visiting (org-find-base-buffer-visiting file))
15104 (setq buffer (or visiting (find-file-noselect file)))
15105 (setq m (org-find-exact-headline-in-buffer
15106 heading buffer))
15107 (when (and (not m) (not visiting)) (kill-buffer buffer))
15108 (and m (throw 'found m))))))
15110 (defun org-find-entry-with-id (ident)
15111 "Locate the entry that contains the ID property with exact value IDENT.
15112 IDENT can be a string, a symbol or a number, this function will search for
15113 the string representation of it.
15114 Return the position where this entry starts, or nil if there is no such entry."
15115 (interactive "sID: ")
15116 (let ((id (cond
15117 ((stringp ident) ident)
15118 ((symbol-name ident) (symbol-name ident))
15119 ((numberp ident) (number-to-string ident))
15120 (t (error "IDENT %s must be a string, symbol or number" ident))))
15121 (case-fold-search nil))
15122 (save-excursion
15123 (save-restriction
15124 (widen)
15125 (goto-char (point-min))
15126 (when (re-search-forward
15127 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15128 nil t)
15129 (org-back-to-heading t)
15130 (point))))))
15132 ;;;; Timestamps
15134 (defvar org-last-changed-timestamp nil)
15135 (defvar org-last-inserted-timestamp nil
15136 "The last time stamp inserted with `org-insert-time-stamp'.")
15137 (defvar org-time-was-given) ; dynamically scoped parameter
15138 (defvar org-end-time-was-given) ; dynamically scoped parameter
15139 (defvar org-ts-what) ; dynamically scoped parameter
15141 (defun org-time-stamp (arg &optional inactive)
15142 "Prompt for a date/time and insert a time stamp.
15143 If the user specifies a time like HH:MM or if this command is
15144 called with at least one prefix argument, the time stamp contains
15145 the date and the time. Otherwise, only the date is be included.
15147 All parts of a date not specified by the user is filled in from
15148 the current date/time. So if you just press return without
15149 typing anything, the time stamp will represent the current
15150 date/time.
15152 If there is already a timestamp at the cursor, it will be
15153 modified.
15155 With two universal prefix arguments, insert an active timestamp
15156 with the current time without prompting the user."
15157 (interactive "P")
15158 (let* ((ts nil)
15159 (default-time
15160 ;; Default time is either today, or, when entering a range,
15161 ;; the range start.
15162 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15163 (save-excursion
15164 (re-search-backward
15165 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15166 (- (point) 20) t)))
15167 (apply 'encode-time (org-parse-time-string (match-string 1)))
15168 (current-time)))
15169 (default-input (and ts (org-get-compact-tod ts)))
15170 (repeater (save-excursion
15171 (save-match-data
15172 (beginning-of-line)
15173 (when (re-search-forward
15174 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15175 (save-excursion (progn (end-of-line) (point))) t)
15176 (match-string 0)))))
15177 org-time-was-given org-end-time-was-given time)
15178 (cond
15179 ((and (org-at-timestamp-p t)
15180 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15181 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15182 (insert "--")
15183 (setq time (let ((this-command this-command))
15184 (org-read-date arg 'totime nil nil
15185 default-time default-input inactive)))
15186 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15187 ((org-at-timestamp-p t)
15188 (setq time (let ((this-command this-command))
15189 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15190 (when (org-at-timestamp-p t) ; just to get the match data
15191 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15192 (replace-match "")
15193 (setq org-last-changed-timestamp
15194 (org-insert-time-stamp
15195 time (or org-time-was-given arg)
15196 inactive nil nil (list org-end-time-was-given)))
15197 (when repeater (goto-char (1- (point))) (insert " " repeater)
15198 (setq org-last-changed-timestamp
15199 (concat (substring org-last-inserted-timestamp 0 -1)
15200 " " repeater ">"))))
15201 (message "Timestamp updated"))
15202 ((equal arg '(16))
15203 (org-insert-time-stamp (current-time) t))
15205 (setq time (let ((this-command this-command))
15206 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15207 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15208 nil nil (list org-end-time-was-given))))))
15210 ;; FIXME: can we use this for something else, like computing time differences?
15211 (defun org-get-compact-tod (s)
15212 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15213 (let* ((t1 (match-string 1 s))
15214 (h1 (string-to-number (match-string 2 s)))
15215 (m1 (string-to-number (match-string 3 s)))
15216 (t2 (and (match-end 4) (match-string 5 s)))
15217 (h2 (and t2 (string-to-number (match-string 6 s))))
15218 (m2 (and t2 (string-to-number (match-string 7 s))))
15219 dh dm)
15220 (if (not t2)
15222 (setq dh (- h2 h1) dm (- m2 m1))
15223 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15224 (concat t1 "+" (number-to-string dh)
15225 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15227 (defun org-time-stamp-inactive (&optional arg)
15228 "Insert an inactive time stamp.
15229 An inactive time stamp is enclosed in square brackets instead of angle
15230 brackets. It is inactive in the sense that it does not trigger agenda entries,
15231 does not link to the calendar and cannot be changed with the S-cursor keys.
15232 So these are more for recording a certain time/date."
15233 (interactive "P")
15234 (org-time-stamp arg 'inactive))
15236 (defvar org-date-ovl (make-overlay 1 1))
15237 (overlay-put org-date-ovl 'face 'org-date-selected)
15238 (org-detach-overlay org-date-ovl)
15240 (defvar org-ans1) ; dynamically scoped parameter
15241 (defvar org-ans2) ; dynamically scoped parameter
15243 (defvar org-plain-time-of-day-regexp) ; defined below
15245 (defvar org-overriding-default-time nil) ; dynamically scoped
15246 (defvar org-read-date-overlay nil)
15247 (defvar org-dcst nil) ; dynamically scoped
15248 (defvar org-read-date-history nil)
15249 (defvar org-read-date-final-answer nil)
15250 (defvar org-read-date-analyze-futurep nil)
15251 (defvar org-read-date-analyze-forced-year nil)
15252 (defvar org-read-date-inactive)
15254 (defun org-read-date (&optional org-with-time to-time from-string prompt
15255 default-time default-input inactive)
15256 "Read a date, possibly a time, and make things smooth for the user.
15257 The prompt will suggest to enter an ISO date, but you can also enter anything
15258 which will at least partially be understood by `parse-time-string'.
15259 Unrecognized parts of the date will default to the current day, month, year,
15260 hour and minute. If this command is called to replace a timestamp at point,
15261 or to enter the second timestamp of a range, the default time is taken
15262 from the existing stamp. Furthermore, the command prefers the future,
15263 so if you are giving a date where the year is not given, and the day-month
15264 combination is already past in the current year, it will assume you
15265 mean next year. For details, see the manual. A few examples:
15267 3-2-5 --> 2003-02-05
15268 feb 15 --> currentyear-02-15
15269 2/15 --> currentyear-02-15
15270 sep 12 9 --> 2009-09-12
15271 12:45 --> today 12:45
15272 22 sept 0:34 --> currentyear-09-22 0:34
15273 12 --> currentyear-currentmonth-12
15274 Fri --> nearest Friday (today or later)
15275 etc.
15277 Furthermore you can specify a relative date by giving, as the *first* thing
15278 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15279 change in days weeks, months, years.
15280 With a single plus or minus, the date is relative to today. With a double
15281 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15282 +4d --> four days from today
15283 +4 --> same as above
15284 +2w --> two weeks from today
15285 ++5 --> five days from default date
15287 The function understands only English month and weekday abbreviations.
15289 While prompting, a calendar is popped up - you can also select the
15290 date with the mouse (button 1). The calendar shows a period of three
15291 months. To scroll it to other months, use the keys `>' and `<'.
15292 If you don't like the calendar, turn it off with
15293 \(setq org-read-date-popup-calendar nil)
15295 With optional argument TO-TIME, the date will immediately be converted
15296 to an internal time.
15297 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15298 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15299 still enter a time, and this function will inform the calling routine
15300 about this change. The calling routine may then choose to change the
15301 format used to insert the time stamp into the buffer to include the time.
15302 With optional argument FROM-STRING, read from this string instead from
15303 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15304 the time/date that is used for everything that is not specified by the
15305 user."
15306 (require 'parse-time)
15307 (let* ((org-time-stamp-rounding-minutes
15308 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15309 (org-dcst org-display-custom-times)
15310 (ct (org-current-time))
15311 (org-def (or org-overriding-default-time default-time ct))
15312 (org-defdecode (decode-time org-def))
15313 (dummy (progn
15314 (when (< (nth 2 org-defdecode) org-extend-today-until)
15315 (setcar (nthcdr 2 org-defdecode) -1)
15316 (setcar (nthcdr 1 org-defdecode) 59)
15317 (setq org-def (apply 'encode-time org-defdecode)
15318 org-defdecode (decode-time org-def)))))
15319 (calendar-frame-setup nil)
15320 (calendar-setup nil)
15321 (calendar-move-hook nil)
15322 (calendar-view-diary-initially-flag nil)
15323 (calendar-view-holidays-initially-flag nil)
15324 (timestr (format-time-string
15325 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15326 (prompt (concat (if prompt (concat prompt " ") "")
15327 (format "Date+time [%s]: " timestr)))
15328 ans (org-ans0 "") org-ans1 org-ans2 final)
15330 (cond
15331 (from-string (setq ans from-string))
15332 (org-read-date-popup-calendar
15333 (save-excursion
15334 (save-window-excursion
15335 (calendar)
15336 (org-eval-in-calendar '(setq cursor-type nil) t)
15337 (unwind-protect
15338 (progn
15339 (calendar-forward-day (- (time-to-days org-def)
15340 (calendar-absolute-from-gregorian
15341 (calendar-current-date))))
15342 (org-eval-in-calendar nil t)
15343 (let* ((old-map (current-local-map))
15344 (map (copy-keymap calendar-mode-map))
15345 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15346 (org-defkey map (kbd "RET") 'org-calendar-select)
15347 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15348 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15349 (org-defkey minibuffer-local-map [(meta shift left)]
15350 (lambda () (interactive)
15351 (org-eval-in-calendar '(calendar-backward-month 1))))
15352 (org-defkey minibuffer-local-map [(meta shift right)]
15353 (lambda () (interactive)
15354 (org-eval-in-calendar '(calendar-forward-month 1))))
15355 (org-defkey minibuffer-local-map [(meta shift up)]
15356 (lambda () (interactive)
15357 (org-eval-in-calendar '(calendar-backward-year 1))))
15358 (org-defkey minibuffer-local-map [(meta shift down)]
15359 (lambda () (interactive)
15360 (org-eval-in-calendar '(calendar-forward-year 1))))
15361 (org-defkey minibuffer-local-map [?\e (shift left)]
15362 (lambda () (interactive)
15363 (org-eval-in-calendar '(calendar-backward-month 1))))
15364 (org-defkey minibuffer-local-map [?\e (shift right)]
15365 (lambda () (interactive)
15366 (org-eval-in-calendar '(calendar-forward-month 1))))
15367 (org-defkey minibuffer-local-map [?\e (shift up)]
15368 (lambda () (interactive)
15369 (org-eval-in-calendar '(calendar-backward-year 1))))
15370 (org-defkey minibuffer-local-map [?\e (shift down)]
15371 (lambda () (interactive)
15372 (org-eval-in-calendar '(calendar-forward-year 1))))
15373 (org-defkey minibuffer-local-map [(shift up)]
15374 (lambda () (interactive)
15375 (org-eval-in-calendar '(calendar-backward-week 1))))
15376 (org-defkey minibuffer-local-map [(shift down)]
15377 (lambda () (interactive)
15378 (org-eval-in-calendar '(calendar-forward-week 1))))
15379 (org-defkey minibuffer-local-map [(shift left)]
15380 (lambda () (interactive)
15381 (org-eval-in-calendar '(calendar-backward-day 1))))
15382 (org-defkey minibuffer-local-map [(shift right)]
15383 (lambda () (interactive)
15384 (org-eval-in-calendar '(calendar-forward-day 1))))
15385 (org-defkey minibuffer-local-map ">"
15386 (lambda () (interactive)
15387 (org-eval-in-calendar '(scroll-calendar-left 1))))
15388 (org-defkey minibuffer-local-map "<"
15389 (lambda () (interactive)
15390 (org-eval-in-calendar '(scroll-calendar-right 1))))
15391 (org-defkey minibuffer-local-map "\C-v"
15392 (lambda () (interactive)
15393 (org-eval-in-calendar
15394 '(calendar-scroll-left-three-months 1))))
15395 (org-defkey minibuffer-local-map "\M-v"
15396 (lambda () (interactive)
15397 (org-eval-in-calendar
15398 '(calendar-scroll-right-three-months 1))))
15399 (run-hooks 'org-read-date-minibuffer-setup-hook)
15400 (unwind-protect
15401 (progn
15402 (use-local-map map)
15403 (setq org-read-date-inactive inactive)
15404 (add-hook 'post-command-hook 'org-read-date-display)
15405 (setq org-ans0 (read-string prompt default-input
15406 'org-read-date-history nil))
15407 ;; org-ans0: from prompt
15408 ;; org-ans1: from mouse click
15409 ;; org-ans2: from calendar motion
15410 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15411 (remove-hook 'post-command-hook 'org-read-date-display)
15412 (use-local-map old-map)
15413 (when org-read-date-overlay
15414 (delete-overlay org-read-date-overlay)
15415 (setq org-read-date-overlay nil)))))
15416 (bury-buffer "*Calendar*")))))
15418 (t ; Naked prompt only
15419 (unwind-protect
15420 (setq ans (read-string prompt default-input
15421 'org-read-date-history timestr))
15422 (when org-read-date-overlay
15423 (delete-overlay org-read-date-overlay)
15424 (setq org-read-date-overlay nil)))))
15426 (setq final (org-read-date-analyze ans org-def org-defdecode))
15428 (when org-read-date-analyze-forced-year
15429 (message "Year was forced into %s"
15430 (if org-read-date-force-compatible-dates
15431 "compatible range (1970-2037)"
15432 "range representable on this machine"))
15433 (ding))
15435 ;; One round trip to get rid of 34th of August and stuff like that....
15436 (setq final (decode-time (apply 'encode-time final)))
15438 (setq org-read-date-final-answer ans)
15440 (if to-time
15441 (apply 'encode-time final)
15442 (if (and (boundp 'org-time-was-given) org-time-was-given)
15443 (format "%04d-%02d-%02d %02d:%02d"
15444 (nth 5 final) (nth 4 final) (nth 3 final)
15445 (nth 2 final) (nth 1 final))
15446 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15448 (defvar org-def)
15449 (defvar org-defdecode)
15450 (defvar org-with-time)
15451 (defun org-read-date-display ()
15452 "Display the current date prompt interpretation in the minibuffer."
15453 (when org-read-date-display-live
15454 (when org-read-date-overlay
15455 (delete-overlay org-read-date-overlay))
15456 (when (minibufferp (current-buffer))
15457 (save-excursion
15458 (end-of-line 1)
15459 (while (not (equal (buffer-substring
15460 (max (point-min) (- (point) 4)) (point))
15461 " "))
15462 (insert " ")))
15463 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15464 " " (or org-ans1 org-ans2)))
15465 (org-end-time-was-given nil)
15466 (f (org-read-date-analyze ans org-def org-defdecode))
15467 (fmts (if org-dcst
15468 org-time-stamp-custom-formats
15469 org-time-stamp-formats))
15470 (fmt (if (or org-with-time
15471 (and (boundp 'org-time-was-given) org-time-was-given))
15472 (cdr fmts)
15473 (car fmts)))
15474 (txt (format-time-string fmt (apply 'encode-time f)))
15475 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15476 (txt (concat "=> " txt)))
15477 (when (and org-end-time-was-given
15478 (string-match org-plain-time-of-day-regexp txt))
15479 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15480 org-end-time-was-given
15481 (substring txt (match-end 0)))))
15482 (when org-read-date-analyze-futurep
15483 (setq txt (concat txt " (=>F)")))
15484 (setq org-read-date-overlay
15485 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15486 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15488 (defun org-read-date-analyze (ans org-def org-defdecode)
15489 "Analyze the combined answer of the date prompt."
15490 ;; FIXME: cleanup and comment
15491 (let ((nowdecode (decode-time (current-time)))
15492 delta deltan deltaw deltadef year month day
15493 hour minute second wday pm h2 m2 tl wday1
15494 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15495 (setq org-read-date-analyze-futurep nil
15496 org-read-date-analyze-forced-year nil)
15497 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15498 (setq ans "+0"))
15500 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15501 (setq ans (replace-match "" t t ans)
15502 deltan (car delta)
15503 deltaw (nth 1 delta)
15504 deltadef (nth 2 delta)))
15506 ;; Check if there is an iso week date in there. If yes, store the
15507 ;; info and postpone interpreting it until the rest of the parsing
15508 ;; is done.
15509 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15510 (setq iso-year (if (match-end 1)
15511 (org-small-year-to-year
15512 (string-to-number (match-string 1 ans))))
15513 iso-weekday (if (match-end 3)
15514 (string-to-number (match-string 3 ans)))
15515 iso-week (string-to-number (match-string 2 ans)))
15516 (setq ans (replace-match "" t t ans)))
15518 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15519 (when (string-match
15520 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15521 (setq year (if (match-end 2)
15522 (string-to-number (match-string 2 ans))
15523 (progn (setq kill-year t)
15524 (string-to-number (format-time-string "%Y"))))
15525 month (string-to-number (match-string 3 ans))
15526 day (string-to-number (match-string 4 ans)))
15527 (if (< year 100) (setq year (+ 2000 year)))
15528 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15529 t nil ans)))
15531 ;; Help matching dotted european dates
15532 (when (string-match
15533 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15534 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15535 (setq kill-year t)
15536 (string-to-number (format-time-string "%Y")))
15537 day (string-to-number (match-string 1 ans))
15538 month (string-to-number (match-string 2 ans))
15539 ans (replace-match (format "%04d-%02d-%02d" year month day)
15540 t nil ans)))
15542 ;; Help matching american dates, like 5/30 or 5/30/7
15543 (when (string-match
15544 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15545 (setq year (if (match-end 4)
15546 (string-to-number (match-string 4 ans))
15547 (progn (setq kill-year t)
15548 (string-to-number (format-time-string "%Y"))))
15549 month (string-to-number (match-string 1 ans))
15550 day (string-to-number (match-string 2 ans)))
15551 (if (< year 100) (setq year (+ 2000 year)))
15552 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15553 t nil ans)))
15554 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15555 ;; If there is a time with am/pm, and *no* time without it, we convert
15556 ;; so that matching will be successful.
15557 (loop for i from 1 to 2 do ; twice, for end time as well
15558 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15559 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15560 (setq hour (string-to-number (match-string 1 ans))
15561 minute (if (match-end 3)
15562 (string-to-number (match-string 3 ans))
15564 pm (equal ?p
15565 (string-to-char (downcase (match-string 4 ans)))))
15566 (if (and (= hour 12) (not pm))
15567 (setq hour 0)
15568 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15569 (setq ans (replace-match (format "%02d:%02d" hour minute)
15570 t t ans))))
15572 ;; Check if a time range is given as a duration
15573 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15574 (setq hour (string-to-number (match-string 1 ans))
15575 h2 (+ hour (string-to-number (match-string 3 ans)))
15576 minute (string-to-number (match-string 2 ans))
15577 m2 (+ minute (if (match-end 5) (string-to-number
15578 (match-string 5 ans))0)))
15579 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15580 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15581 t t ans)))
15583 ;; Check if there is a time range
15584 (when (boundp 'org-end-time-was-given)
15585 (setq org-time-was-given nil)
15586 (when (and (string-match org-plain-time-of-day-regexp ans)
15587 (match-end 8))
15588 (setq org-end-time-was-given (match-string 8 ans))
15589 (setq ans (concat (substring ans 0 (match-beginning 7))
15590 (substring ans (match-end 7))))))
15592 (setq tl (parse-time-string ans)
15593 day (or (nth 3 tl) (nth 3 org-defdecode))
15594 month (or (nth 4 tl)
15595 (if (and org-read-date-prefer-future
15596 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15597 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15598 (nth 4 org-defdecode)))
15599 year (or (and (not kill-year) (nth 5 tl))
15600 (if (and org-read-date-prefer-future
15601 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15602 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15603 (nth 5 org-defdecode)))
15604 hour (or (nth 2 tl) (nth 2 org-defdecode))
15605 minute (or (nth 1 tl) (nth 1 org-defdecode))
15606 second (or (nth 0 tl) 0)
15607 wday (nth 6 tl))
15609 (when (and (eq org-read-date-prefer-future 'time)
15610 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15611 (equal day (nth 3 nowdecode))
15612 (equal month (nth 4 nowdecode))
15613 (equal year (nth 5 nowdecode))
15614 (nth 2 tl)
15615 (or (< (nth 2 tl) (nth 2 nowdecode))
15616 (and (= (nth 2 tl) (nth 2 nowdecode))
15617 (nth 1 tl)
15618 (< (nth 1 tl) (nth 1 nowdecode)))))
15619 (setq day (1+ day)
15620 futurep t))
15622 ;; Special date definitions below
15623 (cond
15624 (iso-week
15625 ;; There was an iso week
15626 (require 'cal-iso)
15627 (setq futurep nil)
15628 (setq year (or iso-year year)
15629 day (or iso-weekday wday 1)
15630 wday nil ; to make sure that the trigger below does not match
15631 iso-date (calendar-gregorian-from-absolute
15632 (calendar-absolute-from-iso
15633 (list iso-week day year))))
15634 ; FIXME: Should we also push ISO weeks into the future?
15635 ; (when (and org-read-date-prefer-future
15636 ; (not iso-year)
15637 ; (< (calendar-absolute-from-gregorian iso-date)
15638 ; (time-to-days (current-time))))
15639 ; (setq year (1+ year)
15640 ; iso-date (calendar-gregorian-from-absolute
15641 ; (calendar-absolute-from-iso
15642 ; (list iso-week day year)))))
15643 (setq month (car iso-date)
15644 year (nth 2 iso-date)
15645 day (nth 1 iso-date)))
15646 (deltan
15647 (setq futurep nil)
15648 (unless deltadef
15649 (let ((now (decode-time (current-time))))
15650 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15651 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15652 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15653 ((equal deltaw "m") (setq month (+ month deltan)))
15654 ((equal deltaw "y") (setq year (+ year deltan)))))
15655 ((and wday (not (nth 3 tl)))
15656 ;; Weekday was given, but no day, so pick that day in the week
15657 ;; on or after the derived date.
15658 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15659 (unless (equal wday wday1)
15660 (setq day (+ day (% (- wday wday1 -7) 7))))))
15661 (if (and (boundp 'org-time-was-given)
15662 (nth 2 tl))
15663 (setq org-time-was-given t))
15664 (if (< year 100) (setq year (+ 2000 year)))
15665 ;; Check of the date is representable
15666 (if org-read-date-force-compatible-dates
15667 (progn
15668 (if (< year 1970)
15669 (setq year 1970 org-read-date-analyze-forced-year t))
15670 (if (> year 2037)
15671 (setq year 2037 org-read-date-analyze-forced-year t)))
15672 (condition-case nil
15673 (ignore (encode-time second minute hour day month year))
15674 (error
15675 (setq year (nth 5 org-defdecode))
15676 (setq org-read-date-analyze-forced-year t))))
15677 (setq org-read-date-analyze-futurep futurep)
15678 (list second minute hour day month year)))
15680 (defvar parse-time-weekdays)
15681 (defun org-read-date-get-relative (s today default)
15682 "Check string S for special relative date string.
15683 TODAY and DEFAULT are internal times, for today and for a default.
15684 Return shift list (N what def-flag)
15685 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15686 N is the number of WHATs to shift.
15687 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15688 the DEFAULT date rather than TODAY."
15689 (require 'parse-time)
15690 (when (and
15691 (string-match
15692 (concat
15693 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15694 "\\([0-9]+\\)?"
15695 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15696 "\\([ \t]\\|$\\)") s)
15697 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15698 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15699 (string-to-char (substring (match-string 1 s) -1))
15700 ?+))
15701 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15702 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15703 (what (if (match-end 3) (match-string 3 s) "d"))
15704 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15705 (date (if rel default today))
15706 (wday (nth 6 (decode-time date)))
15707 delta)
15708 (if wday1
15709 (progn
15710 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15711 (if (= dir ?-) (setq delta (- delta 7)))
15712 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15713 (list delta "d" rel))
15714 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15716 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15717 "Turn a user-specified date into the internal representation.
15718 The internal representation needed by the calendar is (month day year).
15719 This is a wrapper to handle the brain-dead convention in calendar that
15720 user function argument order change dependent on argument order."
15721 (if (boundp 'calendar-date-style)
15722 (cond
15723 ((eq calendar-date-style 'american)
15724 (list arg1 arg2 arg3))
15725 ((eq calendar-date-style 'european)
15726 (list arg2 arg1 arg3))
15727 ((eq calendar-date-style 'iso)
15728 (list arg2 arg3 arg1)))
15729 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15730 (if (org-bound-and-true-p european-calendar-style)
15731 (list arg2 arg1 arg3)
15732 (list arg1 arg2 arg3)))))
15734 (defun org-eval-in-calendar (form &optional keepdate)
15735 "Eval FORM in the calendar window and return to current window.
15736 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15737 otherwise stick to the current value of `org-ans2'."
15738 (let ((sf (selected-frame))
15739 (sw (selected-window)))
15740 (select-window (get-buffer-window "*Calendar*" t))
15741 (eval form)
15742 (when (and (not keepdate) (calendar-cursor-to-date))
15743 (let* ((date (calendar-cursor-to-date))
15744 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15745 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15746 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15747 (select-window sw)
15748 (org-select-frame-set-input-focus sf)))
15750 (defun org-calendar-select ()
15751 "Return to `org-read-date' with the date currently selected.
15752 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15753 (interactive)
15754 (when (calendar-cursor-to-date)
15755 (let* ((date (calendar-cursor-to-date))
15756 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15757 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15758 (if (active-minibuffer-window) (exit-minibuffer))))
15760 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15761 "Insert a date stamp for the date given by the internal TIME.
15762 WITH-HM means use the stamp format that includes the time of the day.
15763 INACTIVE means use square brackets instead of angular ones, so that the
15764 stamp will not contribute to the agenda.
15765 PRE and POST are optional strings to be inserted before and after the
15766 stamp.
15767 The command returns the inserted time stamp."
15768 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15769 stamp)
15770 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15771 (insert-before-markers (or pre ""))
15772 (when (listp extra)
15773 (setq extra (car extra))
15774 (if (and (stringp extra)
15775 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15776 (setq extra (format "-%02d:%02d"
15777 (string-to-number (match-string 1 extra))
15778 (string-to-number (match-string 2 extra))))
15779 (setq extra nil)))
15780 (when extra
15781 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15782 (insert-before-markers (setq stamp (format-time-string fmt time)))
15783 (insert-before-markers (or post ""))
15784 (setq org-last-inserted-timestamp stamp)))
15786 (defun org-toggle-time-stamp-overlays ()
15787 "Toggle the use of custom time stamp formats."
15788 (interactive)
15789 (setq org-display-custom-times (not org-display-custom-times))
15790 (unless org-display-custom-times
15791 (let ((p (point-min)) (bmp (buffer-modified-p)))
15792 (while (setq p (next-single-property-change p 'display))
15793 (if (and (get-text-property p 'display)
15794 (eq (get-text-property p 'face) 'org-date))
15795 (remove-text-properties
15796 p (setq p (next-single-property-change p 'display))
15797 '(display t))))
15798 (set-buffer-modified-p bmp)))
15799 (if (featurep 'xemacs)
15800 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15801 (org-restart-font-lock)
15802 (setq org-table-may-need-update t)
15803 (if org-display-custom-times
15804 (message "Time stamps are overlaid with custom format")
15805 (message "Time stamp overlays removed")))
15807 (defun org-display-custom-time (beg end)
15808 "Overlay modified time stamp format over timestamp between BEG and END."
15809 (let* ((ts (buffer-substring beg end))
15810 t1 w1 with-hm tf time str w2 (off 0))
15811 (save-match-data
15812 (setq t1 (org-parse-time-string ts t))
15813 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15814 (setq off (- (match-end 0) (match-beginning 0)))))
15815 (setq end (- end off))
15816 (setq w1 (- end beg)
15817 with-hm (and (nth 1 t1) (nth 2 t1))
15818 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15819 time (org-fix-decoded-time t1)
15820 str (org-add-props
15821 (format-time-string
15822 (substring tf 1 -1) (apply 'encode-time time))
15823 nil 'mouse-face 'highlight)
15824 w2 (length str))
15825 (if (not (= w2 w1))
15826 (add-text-properties (1+ beg) (+ 2 beg)
15827 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15828 (if (featurep 'xemacs)
15829 (progn
15830 (put-text-property beg end 'invisible t)
15831 (put-text-property beg end 'end-glyph (make-glyph str)))
15832 (put-text-property beg end 'display str))))
15834 (defun org-translate-time (string)
15835 "Translate all timestamps in STRING to custom format.
15836 But do this only if the variable `org-display-custom-times' is set."
15837 (when org-display-custom-times
15838 (save-match-data
15839 (let* ((start 0)
15840 (re org-ts-regexp-both)
15841 t1 with-hm inactive tf time str beg end)
15842 (while (setq start (string-match re string start))
15843 (setq beg (match-beginning 0)
15844 end (match-end 0)
15845 t1 (save-match-data
15846 (org-parse-time-string (substring string beg end) t))
15847 with-hm (and (nth 1 t1) (nth 2 t1))
15848 inactive (equal (substring string beg (1+ beg)) "[")
15849 tf (funcall (if with-hm 'cdr 'car)
15850 org-time-stamp-custom-formats)
15851 time (org-fix-decoded-time t1)
15852 str (format-time-string
15853 (concat
15854 (if inactive "[" "<") (substring tf 1 -1)
15855 (if inactive "]" ">"))
15856 (apply 'encode-time time))
15857 string (replace-match str t t string)
15858 start (+ start (length str)))))))
15859 string)
15861 (defun org-fix-decoded-time (time)
15862 "Set 0 instead of nil for the first 6 elements of time.
15863 Don't touch the rest."
15864 (let ((n 0))
15865 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15867 (defun org-days-to-time (timestamp-string)
15868 "Difference between TIMESTAMP-STRING and now in days."
15869 (- (time-to-days (org-time-string-to-time timestamp-string))
15870 (time-to-days (current-time))))
15872 (defun org-deadline-close (timestamp-string &optional ndays)
15873 "Is the time in TIMESTAMP-STRING close to the current date?"
15874 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15875 (and (< (org-days-to-time timestamp-string) ndays)
15876 (not (org-entry-is-done-p))))
15878 (defun org-get-wdays (ts)
15879 "Get the deadline lead time appropriate for timestring TS."
15880 (cond
15881 ((<= org-deadline-warning-days 0)
15882 ;; 0 or negative, enforce this value no matter what
15883 (- org-deadline-warning-days))
15884 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15885 ;; lead time is specified.
15886 (floor (* (string-to-number (match-string 1 ts))
15887 (cdr (assoc (match-string 2 ts)
15888 '(("d" . 1) ("w" . 7)
15889 ("m" . 30.4) ("y" . 365.25)))))))
15890 ;; go for the default.
15891 (t org-deadline-warning-days)))
15893 (defun org-calendar-select-mouse (ev)
15894 "Return to `org-read-date' with the date currently selected.
15895 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15896 (interactive "e")
15897 (mouse-set-point ev)
15898 (when (calendar-cursor-to-date)
15899 (let* ((date (calendar-cursor-to-date))
15900 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15901 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15902 (if (active-minibuffer-window) (exit-minibuffer))))
15904 (defun org-check-deadlines (ndays)
15905 "Check if there are any deadlines due or past due.
15906 A deadline is considered due if it happens within `org-deadline-warning-days'
15907 days from today's date. If the deadline appears in an entry marked DONE,
15908 it is not shown. The prefix arg NDAYS can be used to test that many
15909 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15910 (interactive "P")
15911 (let* ((org-warn-days
15912 (cond
15913 ((equal ndays '(4)) 100000)
15914 (ndays (prefix-numeric-value ndays))
15915 (t (abs org-deadline-warning-days))))
15916 (case-fold-search nil)
15917 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15918 (callback
15919 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15921 (message "%d deadlines past-due or due within %d days"
15922 (org-occur regexp nil callback)
15923 org-warn-days)))
15925 (defsubst org-re-timestamp (type)
15926 "Return a regexp for timestamp TYPE.
15927 Allowed values for TYPE are:
15929 all: all timestamps
15930 active: only active timestamps (<...>)
15931 inactive: only inactive timestamps ([...])
15932 scheduled: only scheduled timestamps
15933 deadline: only deadline timestamps
15935 When TYPE is nil, fall back on returning a regexp that matches
15936 both scheduled and deadline timestamps."
15937 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15938 ((eq type 'active) org-ts-regexp)
15939 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15940 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15941 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15942 ((eq type 'scheduled-or-deadline)
15943 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15945 (defun org-check-before-date (date)
15946 "Check if there are deadlines or scheduled entries before DATE."
15947 (interactive (list (org-read-date)))
15948 (let ((case-fold-search nil)
15949 (regexp (org-re-timestamp org-ts-type))
15950 (callback
15951 (lambda () (time-less-p
15952 (org-time-string-to-time (match-string 1))
15953 (org-time-string-to-time date)))))
15954 (message "%d entries before %s"
15955 (org-occur regexp nil callback) date)))
15957 (defun org-check-after-date (date)
15958 "Check if there are deadlines or scheduled entries after DATE."
15959 (interactive (list (org-read-date)))
15960 (let ((case-fold-search nil)
15961 (regexp (org-re-timestamp org-ts-type))
15962 (callback
15963 (lambda () (not
15964 (time-less-p
15965 (org-time-string-to-time (match-string 1))
15966 (org-time-string-to-time date))))))
15967 (message "%d entries after %s"
15968 (org-occur regexp nil callback) date)))
15970 (defun org-check-dates-range (start-date end-date)
15971 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15972 (interactive (list (org-read-date nil nil nil "Range starts")
15973 (org-read-date nil nil nil "Range end")))
15974 (let ((case-fold-search nil)
15975 (regexp (org-re-timestamp org-ts-type))
15976 (callback
15977 (lambda ()
15978 (let ((match (match-string 1)))
15979 (and
15980 (not (time-less-p
15981 (org-time-string-to-time match)
15982 (org-time-string-to-time start-date)))
15983 (time-less-p
15984 (org-time-string-to-time match)
15985 (org-time-string-to-time end-date)))))))
15986 (message "%d entries between %s and %s"
15987 (org-occur regexp nil callback) start-date end-date)))
15989 (defun org-evaluate-time-range (&optional to-buffer)
15990 "Evaluate a time range by computing the difference between start and end.
15991 Normally the result is just printed in the echo area, but with prefix arg
15992 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15993 If the time range is actually in a table, the result is inserted into the
15994 next column.
15995 For time difference computation, a year is assumed to be exactly 365
15996 days in order to avoid rounding problems."
15997 (interactive "P")
15999 (org-clock-update-time-maybe)
16000 (save-excursion
16001 (unless (org-at-date-range-p t)
16002 (goto-char (point-at-bol))
16003 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16004 (if (not (org-at-date-range-p t))
16005 (error "Not at a time-stamp range, and none found in current line")))
16006 (let* ((ts1 (match-string 1))
16007 (ts2 (match-string 2))
16008 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16009 (match-end (match-end 0))
16010 (time1 (org-time-string-to-time ts1))
16011 (time2 (org-time-string-to-time ts2))
16012 (t1 (org-float-time time1))
16013 (t2 (org-float-time time2))
16014 (diff (abs (- t2 t1)))
16015 (negative (< (- t2 t1) 0))
16016 ;; (ys (floor (* 365 24 60 60)))
16017 (ds (* 24 60 60))
16018 (hs (* 60 60))
16019 (fy "%dy %dd %02d:%02d")
16020 (fy1 "%dy %dd")
16021 (fd "%dd %02d:%02d")
16022 (fd1 "%dd")
16023 (fh "%02d:%02d")
16024 y d h m align)
16025 (if havetime
16026 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16028 d (floor (/ diff ds)) diff (mod diff ds)
16029 h (floor (/ diff hs)) diff (mod diff hs)
16030 m (floor (/ diff 60)))
16031 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16033 d (floor (+ (/ diff ds) 0.5))
16034 h 0 m 0))
16035 (if (not to-buffer)
16036 (message "%s" (org-make-tdiff-string y d h m))
16037 (if (org-at-table-p)
16038 (progn
16039 (goto-char match-end)
16040 (setq align t)
16041 (and (looking-at " *|") (goto-char (match-end 0))))
16042 (goto-char match-end))
16043 (if (looking-at
16044 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16045 (replace-match ""))
16046 (if negative (insert " -"))
16047 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16048 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16049 (insert " " (format fh h m))))
16050 (if align (org-table-align))
16051 (message "Time difference inserted")))))
16053 (defun org-make-tdiff-string (y d h m)
16054 (let ((fmt "")
16055 (l nil))
16056 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16057 l (push y l)))
16058 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16059 l (push d l)))
16060 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16061 l (push h l)))
16062 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16063 l (push m l)))
16064 (apply 'format fmt (nreverse l))))
16066 (defun org-time-string-to-time (s &optional buffer pos)
16067 "Convert a timestamp string into internal time."
16068 (condition-case errdata
16069 (apply 'encode-time (org-parse-time-string s))
16070 (error (error "Bad timestamp `%s'%s\nError was: %s"
16071 s (if (not (and buffer pos))
16073 (format " at %d in buffer `%s'" pos buffer))
16074 (cdr errdata)))))
16076 (defun org-time-string-to-seconds (s)
16077 "Convert a timestamp string to a number of seconds."
16078 (org-float-time (org-time-string-to-time s)))
16080 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16081 "Convert a time stamp to an absolute day number.
16082 If there is a specifier for a cyclic time stamp, get the closest date to
16083 DAYNR.
16084 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16085 The variable date is bound by the calendar when this is called."
16086 (cond
16087 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16088 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16089 daynr
16090 (+ daynr 1000)))
16091 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16092 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16093 (time-to-days (current-time))) (match-string 0 s)
16094 prefer show-all))
16095 (t (time-to-days
16096 (condition-case errdata
16097 (apply 'encode-time (org-parse-time-string s))
16098 (error (error "Bad timestamp `%s'%s\nError was: %s"
16099 s (if (not (and buffer pos))
16101 (format " at %d in buffer `%s'" pos buffer))
16102 (cdr errdata))))))))
16104 (defun org-days-to-iso-week (days)
16105 "Return the iso week number."
16106 (require 'cal-iso)
16107 (car (calendar-iso-from-absolute days)))
16109 (defun org-small-year-to-year (year)
16110 "Convert 2-digit years into 4-digit years.
16111 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16112 The year 2000 cannot be abbreviated. Any year larger than 99
16113 is returned unchanged."
16114 (if (< year 38)
16115 (setq year (+ 2000 year))
16116 (if (< year 100)
16117 (setq year (+ 1900 year))))
16118 year)
16120 (defun org-time-from-absolute (d)
16121 "Return the time corresponding to date D.
16122 D may be an absolute day number, or a calendar-type list (month day year)."
16123 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16124 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16126 (defun org-calendar-holiday ()
16127 "List of holidays, for Diary display in Org-mode."
16128 (require 'holidays)
16129 (let ((hl (funcall
16130 (if (fboundp 'calendar-check-holidays)
16131 'calendar-check-holidays 'check-calendar-holidays) date)))
16132 (if hl (mapconcat 'identity hl "; "))))
16134 (defun org-diary-sexp-entry (sexp entry date)
16135 "Process a SEXP diary ENTRY for DATE."
16136 (require 'diary-lib)
16137 (let ((result (if calendar-debug-sexp
16138 (let ((stack-trace-on-error t))
16139 (eval (car (read-from-string sexp))))
16140 (condition-case nil
16141 (eval (car (read-from-string sexp)))
16142 (error
16143 (beep)
16144 (message "Bad sexp at line %d in %s: %s"
16145 (org-current-line)
16146 (buffer-file-name) sexp)
16147 (sleep-for 2))))))
16148 (cond ((stringp result) (split-string result "; "))
16149 ((and (consp result)
16150 (not (consp (cdr result)))
16151 (stringp (cdr result))) (cdr result))
16152 ((and (consp result)
16153 (stringp (car result))) result)
16154 (result entry))))
16156 (defun org-diary-to-ical-string (frombuf)
16157 "Get iCalendar entries from diary entries in buffer FROMBUF.
16158 This uses the icalendar.el library."
16159 (let* ((tmpdir (if (featurep 'xemacs)
16160 (temp-directory)
16161 temporary-file-directory))
16162 (tmpfile (make-temp-name
16163 (expand-file-name "orgics" tmpdir)))
16164 buf rtn b e)
16165 (with-current-buffer frombuf
16166 (icalendar-export-region (point-min) (point-max) tmpfile)
16167 (setq buf (find-buffer-visiting tmpfile))
16168 (set-buffer buf)
16169 (goto-char (point-min))
16170 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16171 (setq b (match-beginning 0)))
16172 (goto-char (point-max))
16173 (if (re-search-backward "^END:VEVENT" nil t)
16174 (setq e (match-end 0)))
16175 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16176 (kill-buffer buf)
16177 (delete-file tmpfile)
16178 rtn))
16180 (defun org-closest-date (start current change prefer show-all)
16181 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16182 When PREFER is `past', return a date that is either CURRENT or past.
16183 When PREFER is `future', return a date that is either CURRENT or future.
16184 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16185 ;; Make the proper lists from the dates
16186 (catch 'exit
16187 (let ((a1 '(("h" . hour)
16188 ("d" . day)
16189 ("w" . week)
16190 ("m" . month)
16191 ("y" . year)))
16192 (shour (nth 2 (org-parse-time-string start)))
16193 dn dw sday cday n1 n2 n0
16194 d m y y1 y2 date1 date2 nmonths nm ny m2)
16196 (setq start (org-date-to-gregorian start)
16197 current (org-date-to-gregorian
16198 (if show-all
16199 current
16200 (time-to-days (current-time))))
16201 sday (calendar-absolute-from-gregorian start)
16202 cday (calendar-absolute-from-gregorian current))
16204 (if (<= cday sday) (throw 'exit sday))
16206 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16207 (setq dn (string-to-number (match-string 1 change))
16208 dw (cdr (assoc (match-string 2 change) a1)))
16209 (error "Invalid change specifier: %s" change))
16210 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16211 (cond
16212 ((eq dw 'hour)
16213 (let ((missing-hours
16214 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16215 dn)))
16216 (setq n1 (if (zerop missing-hours) cday
16217 (- cday (1+ (floor (/ missing-hours 24)))))
16218 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16219 ((eq dw 'day)
16220 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16221 n2 (+ n1 dn)))
16222 ((eq dw 'year)
16223 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16224 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16225 (setq date1 (list m d y1)
16226 n1 (calendar-absolute-from-gregorian date1)
16227 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16228 n2 (calendar-absolute-from-gregorian date2)))
16229 ((eq dw 'month)
16230 ;; approx number of month between the two dates
16231 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16232 ;; How often does dn fit in there?
16233 (setq d (nth 1 start) m (car start) y (nth 2 start)
16234 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16235 m (+ m nm)
16236 ny (floor (/ m 12))
16237 y (+ y ny)
16238 m (- m (* ny 12)))
16239 (while (> m 12) (setq m (- m 12) y (1+ y)))
16240 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16241 (setq m2 (+ m dn) y2 y)
16242 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16243 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16244 (while (<= n2 cday)
16245 (setq n1 n2 m m2 y y2)
16246 (setq m2 (+ m dn) y2 y)
16247 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16248 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16249 ;; Make sure n1 is the earlier date
16250 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16251 (if show-all
16252 (cond
16253 ((eq prefer 'past) (if (= cday n2) n2 n1))
16254 ((eq prefer 'future) (if (= cday n1) n1 n2))
16255 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16256 (cond
16257 ((eq prefer 'past) (if (= cday n2) n2 n1))
16258 ((eq prefer 'future) (if (= cday n1) n1 n2))
16259 (t (if (= cday n1) n1 n2)))))))
16261 (defun org-date-to-gregorian (date)
16262 "Turn any specification of DATE into a Gregorian date for the calendar."
16263 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16264 ((and (listp date) (= (length date) 3)) date)
16265 ((stringp date)
16266 (setq date (org-parse-time-string date))
16267 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16268 ((listp date)
16269 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16271 (defun org-parse-time-string (s &optional nodefault)
16272 "Parse the standard Org-mode time string.
16273 This should be a lot faster than the normal `parse-time-string'.
16274 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16275 hour and minute fields will be nil if not given."
16276 (if (string-match org-ts-regexp0 s)
16277 (list 0
16278 (if (or (match-beginning 8) (not nodefault))
16279 (string-to-number (or (match-string 8 s) "0")))
16280 (if (or (match-beginning 7) (not nodefault))
16281 (string-to-number (or (match-string 7 s) "0")))
16282 (string-to-number (match-string 4 s))
16283 (string-to-number (match-string 3 s))
16284 (string-to-number (match-string 2 s))
16285 nil nil nil)
16286 (error "Not a standard Org-mode time string: %s" s)))
16288 (defun org-timestamp-up (&optional arg)
16289 "Increase the date item at the cursor by one.
16290 If the cursor is on the year, change the year. If it is on the month,
16291 the day or the time, change that.
16292 With prefix ARG, change by that many units."
16293 (interactive "p")
16294 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16296 (defun org-timestamp-down (&optional arg)
16297 "Decrease the date item at the cursor by one.
16298 If the cursor is on the year, change the year. If it is on the month,
16299 the day or the time, change that.
16300 With prefix ARG, change by that many units."
16301 (interactive "p")
16302 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16304 (defun org-timestamp-up-day (&optional arg)
16305 "Increase the date in the time stamp by one day.
16306 With prefix ARG, change that many days."
16307 (interactive "p")
16308 (if (and (not (org-at-timestamp-p t))
16309 (org-at-heading-p))
16310 (org-todo 'up)
16311 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16313 (defun org-timestamp-down-day (&optional arg)
16314 "Decrease the date in the time stamp by one day.
16315 With prefix ARG, change that many days."
16316 (interactive "p")
16317 (if (and (not (org-at-timestamp-p t))
16318 (org-at-heading-p))
16319 (org-todo 'down)
16320 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16322 (defun org-at-timestamp-p (&optional inactive-ok)
16323 "Determine if the cursor is in or at a timestamp."
16324 (interactive)
16325 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16326 (pos (point))
16327 (ans (or (looking-at tsr)
16328 (save-excursion
16329 (skip-chars-backward "^[<\n\r\t")
16330 (if (> (point) (point-min)) (backward-char 1))
16331 (and (looking-at tsr)
16332 (> (- (match-end 0) pos) -1))))))
16333 (and ans
16334 (boundp 'org-ts-what)
16335 (setq org-ts-what
16336 (cond
16337 ((= pos (match-beginning 0)) 'bracket)
16338 ;; Point is considered to be "on the bracket" whether
16339 ;; it's really on it or right after it.
16340 ((= pos (1- (match-end 0))) 'bracket)
16341 ((= pos (match-end 0)) 'after)
16342 ((org-pos-in-match-range pos 2) 'year)
16343 ((org-pos-in-match-range pos 3) 'month)
16344 ((org-pos-in-match-range pos 7) 'hour)
16345 ((org-pos-in-match-range pos 8) 'minute)
16346 ((or (org-pos-in-match-range pos 4)
16347 (org-pos-in-match-range pos 5)) 'day)
16348 ((and (> pos (or (match-end 8) (match-end 5)))
16349 (< pos (match-end 0)))
16350 (- pos (or (match-end 8) (match-end 5))))
16351 (t 'day))))
16352 ans))
16354 (defun org-toggle-timestamp-type ()
16355 "Toggle the type (<active> or [inactive]) of a time stamp."
16356 (interactive)
16357 (when (org-at-timestamp-p t)
16358 (let ((beg (match-beginning 0)) (end (match-end 0))
16359 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16360 (save-excursion
16361 (goto-char beg)
16362 (while (re-search-forward "[][<>]" end t)
16363 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16364 t t)))
16365 (message "Timestamp is now %sactive"
16366 (if (equal (char-after beg) ?<) "" "in")))))
16368 (defvar org-clock-history) ; defined in org-clock.el
16369 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16370 (defun org-timestamp-change (n &optional what updown)
16371 "Change the date in the time stamp at point.
16372 The date will be changed by N times WHAT. WHAT can be `day', `month',
16373 `year', `minute', `second'. If WHAT is not given, the cursor position
16374 in the timestamp determines what will be changed."
16375 (let ((origin (point)) origin-cat
16376 with-hm inactive
16377 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16378 org-ts-what
16379 extra rem
16380 ts time time0 fixnext clrgx)
16381 (if (not (org-at-timestamp-p t))
16382 (error "Not at a timestamp"))
16383 (if (and (not what) (eq org-ts-what 'bracket))
16384 (org-toggle-timestamp-type)
16385 ;; Point isn't on brackets. Remember the part of the time-stamp
16386 ;; the point was in. Indeed, size of time-stamps may change,
16387 ;; but point must be kept in the same category nonetheless.
16388 (setq origin-cat org-ts-what)
16389 (if (and (not what) (not (eq org-ts-what 'day))
16390 org-display-custom-times
16391 (get-text-property (point) 'display)
16392 (not (get-text-property (1- (point)) 'display)))
16393 (setq org-ts-what 'day))
16394 (setq org-ts-what (or what org-ts-what)
16395 inactive (= (char-after (match-beginning 0)) ?\[)
16396 ts (match-string 0))
16397 (replace-match "")
16398 (if (string-match
16399 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16401 (setq extra (match-string 1 ts)))
16402 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16403 (setq with-hm t))
16404 (setq time0 (org-parse-time-string ts))
16405 (when (and updown
16406 (eq org-ts-what 'minute)
16407 (not current-prefix-arg))
16408 ;; This looks like s-up and s-down. Change by one rounding step.
16409 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16410 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16411 (setcar (cdr time0) (+ (nth 1 time0)
16412 (if (> n 0) (- rem) (- dm rem))))))
16413 (setq time
16414 (encode-time (or (car time0) 0)
16415 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16416 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16417 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16418 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16419 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16420 (nthcdr 6 time0)))
16421 (when (and (member org-ts-what '(hour minute))
16422 extra
16423 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16424 (setq extra (org-modify-ts-extra
16425 extra
16426 (if (eq org-ts-what 'hour) 2 5)
16427 n dm)))
16428 (when (integerp org-ts-what)
16429 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16430 (if (eq what 'calendar)
16431 (let ((cal-date (org-get-date-from-calendar)))
16432 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16433 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16434 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16435 (setcar time0 (or (car time0) 0))
16436 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16437 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16438 (setq time (apply 'encode-time time0))))
16439 ;; Insert the new time-stamp, and ensure point stays in the same
16440 ;; category as before (i.e. not after the last position in that
16441 ;; category).
16442 (let ((pos (point)))
16443 ;; Stay before inserted string. `save-excursion' is of no use.
16444 (setq org-last-changed-timestamp
16445 (org-insert-time-stamp time with-hm inactive nil nil extra))
16446 (goto-char pos))
16447 (save-match-data
16448 (looking-at org-ts-regexp3)
16449 (goto-char (cond
16450 ;; `day' category ends before `hour' if any, or at
16451 ;; the end of the day name.
16452 ((eq origin-cat 'day)
16453 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16454 ((eq origin-cat 'hour) (min (match-end 7) origin))
16455 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16456 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16457 ;; `year' and `month' have both fixed size: point
16458 ;; couldn't have moved into another part.
16459 (t origin))))
16460 ;; Update clock if on a CLOCK line.
16461 (org-clock-update-time-maybe)
16462 ;; Maybe adjust the closest clock in `org-clock-history'
16463 (when org-clock-adjust-closest
16464 (if (not (and (org-at-clock-log-p)
16465 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16466 org-clock-history))))))
16467 (message "No clock to adjust")
16468 (cond ((save-excursion ; fix previous clock?
16469 (re-search-backward org-ts-regexp0 nil t)
16470 (org-looking-back (concat org-clock-string " \\[")))
16471 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16472 ((save-excursion ; fix next clock?
16473 (re-search-backward org-ts-regexp0 nil t)
16474 (looking-at (concat org-ts-regexp0 "\\] =>")))
16475 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16476 (save-window-excursion
16477 ;; Find closest clock to point, adjust the previous/next one in history
16478 (let* ((p (save-excursion (org-back-to-heading t)))
16479 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16480 (clfixnth
16481 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16482 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16483 (if (not clfixpos)
16484 (message "No clock to adjust")
16485 (save-excursion
16486 (org-goto-marker-or-bmk clfixpos)
16487 (org-show-subtree)
16488 (when (re-search-forward clrgx nil t)
16489 (goto-char (match-beginning 1))
16490 (let (org-clock-adjust-closest)
16491 (org-timestamp-change n org-ts-what updown))
16492 (message "Clock adjusted in %s for heading: %s"
16493 (file-name-nondirectory (buffer-file-name))
16494 (org-get-heading t t)))))))))
16495 ;; Try to recenter the calendar window, if any.
16496 (if (and org-calendar-follow-timestamp-change
16497 (get-buffer-window "*Calendar*" t)
16498 (memq org-ts-what '(day month year)))
16499 (org-recenter-calendar (time-to-days time))))))
16501 (defun org-modify-ts-extra (s pos n dm)
16502 "Change the different parts of the lead-time and repeat fields in timestamp."
16503 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16504 ng h m new rem)
16505 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16506 (cond
16507 ((or (org-pos-in-match-range pos 2)
16508 (org-pos-in-match-range pos 3))
16509 (setq m (string-to-number (match-string 3 s))
16510 h (string-to-number (match-string 2 s)))
16511 (if (org-pos-in-match-range pos 2)
16512 (setq h (+ h n))
16513 (setq n (* dm (org-no-warnings (signum n))))
16514 (when (not (= 0 (setq rem (% m dm))))
16515 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16516 (setq m (+ m n)))
16517 (if (< m 0) (setq m (+ m 60) h (1- h)))
16518 (if (> m 59) (setq m (- m 60) h (1+ h)))
16519 (setq h (min 24 (max 0 h)))
16520 (setq ng 1 new (format "-%02d:%02d" h m)))
16521 ((org-pos-in-match-range pos 6)
16522 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16523 ((org-pos-in-match-range pos 5)
16524 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16526 ((org-pos-in-match-range pos 9)
16527 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16528 ((org-pos-in-match-range pos 8)
16529 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16531 (when ng
16532 (setq s (concat
16533 (substring s 0 (match-beginning ng))
16535 (substring s (match-end ng))))))
16538 (defun org-recenter-calendar (date)
16539 "If the calendar is visible, recenter it to DATE."
16540 (let ((cwin (get-buffer-window "*Calendar*" t)))
16541 (when cwin
16542 (let ((calendar-move-hook nil))
16543 (with-selected-window cwin
16544 (calendar-goto-date (if (listp date) date
16545 (calendar-gregorian-from-absolute date))))))))
16547 (defun org-goto-calendar (&optional arg)
16548 "Go to the Emacs calendar at the current date.
16549 If there is a time stamp in the current line, go to that date.
16550 A prefix ARG can be used to force the current date."
16551 (interactive "P")
16552 (let ((tsr org-ts-regexp) diff
16553 (calendar-move-hook nil)
16554 (calendar-view-holidays-initially-flag nil)
16555 (calendar-view-diary-initially-flag nil))
16556 (if (or (org-at-timestamp-p)
16557 (save-excursion
16558 (beginning-of-line 1)
16559 (looking-at (concat ".*" tsr))))
16560 (let ((d1 (time-to-days (current-time)))
16561 (d2 (time-to-days
16562 (org-time-string-to-time (match-string 1)))))
16563 (setq diff (- d2 d1))))
16564 (calendar)
16565 (calendar-goto-today)
16566 (if (and diff (not arg)) (calendar-forward-day diff))))
16568 (defun org-get-date-from-calendar ()
16569 "Return a list (month day year) of date at point in calendar."
16570 (with-current-buffer "*Calendar*"
16571 (save-match-data
16572 (calendar-cursor-to-date))))
16574 (defun org-date-from-calendar ()
16575 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16576 If there is already a time stamp at the cursor position, update it."
16577 (interactive)
16578 (if (org-at-timestamp-p t)
16579 (org-timestamp-change 0 'calendar)
16580 (let ((cal-date (org-get-date-from-calendar)))
16581 (org-insert-time-stamp
16582 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16584 (defun org-minutes-to-hh:mm-string (m)
16585 "Compute H:MM from a number of minutes."
16586 (let ((h (/ m 60)))
16587 (setq m (- m (* 60 h)))
16588 (format org-time-clocksum-format h m)))
16590 (defun org-hh:mm-string-to-minutes (s)
16591 "Convert a string H:MM to a number of minutes.
16592 If the string is just a number, interpret it as minutes.
16593 In fact, the first hh:mm or number in the string will be taken,
16594 there can be extra stuff in the string.
16595 If no number is found, the return value is 0."
16596 (cond
16597 ((integerp s) s)
16598 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16599 (+ (* (string-to-number (match-string 1 s)) 60)
16600 (string-to-number (match-string 2 s))))
16601 ((string-match "\\([0-9]+\\)" s)
16602 (string-to-number (match-string 1 s)))
16603 (t 0)))
16605 (defcustom org-effort-durations
16606 `(("h" . 60)
16607 ("d" . ,(* 60 8))
16608 ("w" . ,(* 60 8 5))
16609 ("m" . ,(* 60 8 5 4))
16610 ("y" . ,(* 60 8 5 40)))
16611 "Conversion factor to minutes for an effort modifier.
16613 Each entry has the form (MODIFIER . MINUTES).
16615 In an effort string, a number followed by MODIFIER is multiplied
16616 by the specified number of MINUTES to obtain an effort in
16617 minutes.
16619 For example, if the value of this variable is ((\"hours\" . 60)), then an
16620 effort string \"2hours\" is equivalent to 120 minutes."
16621 :group 'org-agenda
16622 :version "24.1"
16623 :type '(alist :key-type (string :tag "Modifier")
16624 :value-type (number :tag "Minutes")))
16626 (defun org-duration-string-to-minutes (s &optional output-to-string)
16627 "Convert a duration string S to minutes.
16629 A bare number is interpreted as minutes, modifiers can be set by
16630 customizing `org-effort-durations' (which see).
16632 Entries containing a colon are interpreted as H:MM by
16633 `org-hh:mm-string-to-minutes'."
16634 (let ((result 0)
16635 (re (concat "\\([0-9.]+\\) *\\("
16636 (regexp-opt (mapcar 'car org-effort-durations))
16637 "\\)")))
16638 (while (string-match re s)
16639 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16640 (string-to-number (match-string 1 s))))
16641 (setq s (replace-match "" nil t s)))
16642 (setq result (floor result))
16643 (incf result (org-hh:mm-string-to-minutes s))
16644 (if output-to-string (number-to-string result) result)))
16646 ;;;; Files
16648 (defun org-save-all-org-buffers ()
16649 "Save all Org-mode buffers without user confirmation."
16650 (interactive)
16651 (message "Saving all Org-mode buffers...")
16652 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16653 (when (featurep 'org-id) (org-id-locations-save))
16654 (message "Saving all Org-mode buffers... done"))
16656 (defun org-revert-all-org-buffers ()
16657 "Revert all Org-mode buffers.
16658 Prompt for confirmation when there are unsaved changes.
16659 Be sure you know what you are doing before letting this function
16660 overwrite your changes.
16662 This function is useful in a setup where one tracks org files
16663 with a version control system, to revert on one machine after pulling
16664 changes from another. I believe the procedure must be like this:
16666 1. M-x org-save-all-org-buffers
16667 2. Pull changes from the other machine, resolve conflicts
16668 3. M-x org-revert-all-org-buffers"
16669 (interactive)
16670 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16671 (error "Abort"))
16672 (save-excursion
16673 (save-window-excursion
16674 (mapc
16675 (lambda (b)
16676 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16677 (with-current-buffer b buffer-file-name))
16678 (org-pop-to-buffer-same-window b)
16679 (revert-buffer t 'no-confirm)))
16680 (buffer-list))
16681 (when (and (featurep 'org-id) org-id-track-globally)
16682 (org-id-locations-load)))))
16684 ;;;; Agenda files
16686 ;;;###autoload
16687 (defun org-switchb (&optional arg)
16688 "Switch between Org buffers.
16689 With one prefix argument, restrict available buffers to files.
16690 With two prefix arguments, restrict available buffers to agenda files.
16692 Defaults to `iswitchb' for buffer name completion.
16693 Set `org-completion-use-ido' to make it use ido instead."
16694 (interactive "P")
16695 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16696 ((equal arg '(16)) (org-buffer-list 'agenda))
16697 (t (org-buffer-list))))
16698 (org-completion-use-iswitchb org-completion-use-iswitchb)
16699 (org-completion-use-ido org-completion-use-ido))
16700 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16701 (setq org-completion-use-iswitchb t))
16702 (org-pop-to-buffer-same-window
16703 (org-icompleting-read "Org buffer: "
16704 (mapcar 'list (mapcar 'buffer-name blist))
16705 nil t))))
16707 ;;; Define some older names previously used for this functionality
16708 ;;;###autoload
16709 (defalias 'org-ido-switchb 'org-switchb)
16710 ;;;###autoload
16711 (defalias 'org-iswitchb 'org-switchb)
16713 (defun org-buffer-list (&optional predicate exclude-tmp)
16714 "Return a list of Org buffers.
16715 PREDICATE can be `export', `files' or `agenda'.
16717 export restrict the list to Export buffers.
16718 files restrict the list to buffers visiting Org files.
16719 agenda restrict the list to buffers visiting agenda files.
16721 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16722 (let* ((bfn nil)
16723 (agenda-files (and (eq predicate 'agenda)
16724 (mapcar 'file-truename (org-agenda-files t))))
16725 (filter
16726 (cond
16727 ((eq predicate 'files)
16728 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16729 ((eq predicate 'export)
16730 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16731 ((eq predicate 'agenda)
16732 (lambda (b)
16733 (with-current-buffer b
16734 (and (derived-mode-p 'org-mode)
16735 (setq bfn (buffer-file-name b))
16736 (member (file-truename bfn) agenda-files)))))
16737 (t (lambda (b) (with-current-buffer b
16738 (or (derived-mode-p 'org-mode)
16739 (string-match "\*Org .*Export"
16740 (buffer-name b)))))))))
16741 (delq nil
16742 (mapcar
16743 (lambda(b)
16744 (if (and (funcall filter b)
16745 (or (not exclude-tmp)
16746 (not (string-match "tmp" (buffer-name b)))))
16748 nil))
16749 (buffer-list)))))
16751 (defun org-agenda-files (&optional unrestricted archives)
16752 "Get the list of agenda files.
16753 Optional UNRESTRICTED means return the full list even if a restriction
16754 is currently in place.
16755 When ARCHIVES is t, include all archive files that are really being
16756 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16757 `org-agenda-archives-mode' is t."
16758 (let ((files
16759 (cond
16760 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16761 ((stringp org-agenda-files) (org-read-agenda-file-list))
16762 ((listp org-agenda-files) org-agenda-files)
16763 (t (error "Invalid value of `org-agenda-files'")))))
16764 (setq files (apply 'append
16765 (mapcar (lambda (f)
16766 (if (file-directory-p f)
16767 (directory-files
16768 f t org-agenda-file-regexp)
16769 (list f)))
16770 files)))
16771 (when org-agenda-skip-unavailable-files
16772 (setq files (delq nil
16773 (mapcar (function
16774 (lambda (file)
16775 (and (file-readable-p file) file)))
16776 files))))
16777 (when (or (eq archives t)
16778 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16779 (setq files (org-add-archive-files files)))
16780 files))
16782 (defun org-agenda-file-p (&optional file)
16783 "Return non-nil, if FILE is an agenda file.
16784 If FILE is omitted, use the file associated with the current
16785 buffer."
16786 (member (or file (buffer-file-name))
16787 (org-agenda-files t)))
16789 (defun org-edit-agenda-file-list ()
16790 "Edit the list of agenda files.
16791 Depending on setup, this either uses customize to edit the variable
16792 `org-agenda-files', or it visits the file that is holding the list. In the
16793 latter case, the buffer is set up in a way that saving it automatically kills
16794 the buffer and restores the previous window configuration."
16795 (interactive)
16796 (if (stringp org-agenda-files)
16797 (let ((cw (current-window-configuration)))
16798 (find-file org-agenda-files)
16799 (org-set-local 'org-window-configuration cw)
16800 (org-add-hook 'after-save-hook
16801 (lambda ()
16802 (set-window-configuration
16803 (prog1 org-window-configuration
16804 (kill-buffer (current-buffer))))
16805 (org-install-agenda-files-menu)
16806 (message "New agenda file list installed"))
16807 nil 'local)
16808 (message "%s" (substitute-command-keys
16809 "Edit list and finish with \\[save-buffer]")))
16810 (customize-variable 'org-agenda-files)))
16812 (defun org-store-new-agenda-file-list (list)
16813 "Set new value for the agenda file list and save it correctly."
16814 (if (stringp org-agenda-files)
16815 (let ((fe (org-read-agenda-file-list t)) b u)
16816 (while (setq b (find-buffer-visiting org-agenda-files))
16817 (kill-buffer b))
16818 (with-temp-file org-agenda-files
16819 (insert
16820 (mapconcat
16821 (lambda (f) ;; Keep un-expanded entries.
16822 (if (setq u (assoc f fe))
16823 (cdr u)
16825 list "\n")
16826 "\n")))
16827 (let ((org-mode-hook nil) (org-inhibit-startup t)
16828 (org-insert-mode-line-in-empty-file nil))
16829 (setq org-agenda-files list)
16830 (customize-save-variable 'org-agenda-files org-agenda-files))))
16832 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16833 "Read the list of agenda files from a file.
16834 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16835 filenames, used by `org-store-new-agenda-file-list' to write back
16836 un-expanded file names."
16837 (when (file-directory-p org-agenda-files)
16838 (error "`org-agenda-files' cannot be a single directory"))
16839 (when (stringp org-agenda-files)
16840 (with-temp-buffer
16841 (insert-file-contents org-agenda-files)
16842 (mapcar
16843 (lambda (f)
16844 (let ((e (expand-file-name (substitute-in-file-name f)
16845 org-directory)))
16846 (if pair-with-expansion
16847 (cons e f)
16848 e)))
16849 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16851 ;;;###autoload
16852 (defun org-cycle-agenda-files ()
16853 "Cycle through the files in `org-agenda-files'.
16854 If the current buffer visits an agenda file, find the next one in the list.
16855 If the current buffer does not, find the first agenda file."
16856 (interactive)
16857 (let* ((fs (org-agenda-files t))
16858 (files (append fs (list (car fs))))
16859 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16860 file)
16861 (unless files (error "No agenda files"))
16862 (catch 'exit
16863 (while (setq file (pop files))
16864 (if (equal (file-truename file) tcf)
16865 (when (car files)
16866 (find-file (car files))
16867 (throw 'exit t))))
16868 (find-file (car fs)))
16869 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16871 (defun org-agenda-file-to-front (&optional to-end)
16872 "Move/add the current file to the top of the agenda file list.
16873 If the file is not present in the list, it is added to the front. If it is
16874 present, it is moved there. With optional argument TO-END, add/move to the
16875 end of the list."
16876 (interactive "P")
16877 (let ((org-agenda-skip-unavailable-files nil)
16878 (file-alist (mapcar (lambda (x)
16879 (cons (file-truename x) x))
16880 (org-agenda-files t)))
16881 (ctf (file-truename
16882 (or buffer-file-name
16883 (error "Please save the current buffer to a file"))))
16884 x had)
16885 (setq x (assoc ctf file-alist) had x)
16887 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16888 (if to-end
16889 (setq file-alist (append (delq x file-alist) (list x)))
16890 (setq file-alist (cons x (delq x file-alist))))
16891 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16892 (org-install-agenda-files-menu)
16893 (message "File %s to %s of agenda file list"
16894 (if had "moved" "added") (if to-end "end" "front"))))
16896 (defun org-remove-file (&optional file)
16897 "Remove current file from the list of files in variable `org-agenda-files'.
16898 These are the files which are being checked for agenda entries.
16899 Optional argument FILE means use this file instead of the current."
16900 (interactive)
16901 (let* ((org-agenda-skip-unavailable-files nil)
16902 (file (or file buffer-file-name
16903 (error "Current buffer does not visit a file")))
16904 (true-file (file-truename file))
16905 (afile (abbreviate-file-name file))
16906 (files (delq nil (mapcar
16907 (lambda (x)
16908 (if (equal true-file
16909 (file-truename x))
16910 nil x))
16911 (org-agenda-files t)))))
16912 (if (not (= (length files) (length (org-agenda-files t))))
16913 (progn
16914 (org-store-new-agenda-file-list files)
16915 (org-install-agenda-files-menu)
16916 (message "Removed file: %s" afile))
16917 (message "File was not in list: %s (not removed)" afile))))
16919 (defun org-file-menu-entry (file)
16920 (vector file (list 'find-file file) t))
16922 (defun org-check-agenda-file (file)
16923 "Make sure FILE exists. If not, ask user what to do."
16924 (when (not (file-exists-p file))
16925 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16926 (abbreviate-file-name file))
16927 (let ((r (downcase (read-char-exclusive))))
16928 (cond
16929 ((equal r ?r)
16930 (org-remove-file file)
16931 (throw 'nextfile t))
16932 (t (error "Abort"))))))
16934 (defun org-get-agenda-file-buffer (file)
16935 "Get a buffer visiting FILE. If the buffer needs to be created, add
16936 it to the list of buffers which might be released later."
16937 (let ((buf (org-find-base-buffer-visiting file)))
16938 (if buf
16939 buf ; just return it
16940 ;; Make a new buffer and remember it
16941 (setq buf (find-file-noselect file))
16942 (if buf (push buf org-agenda-new-buffers))
16943 buf)))
16945 (defun org-release-buffers (blist)
16946 "Release all buffers in list, asking the user for confirmation when needed.
16947 When a buffer is unmodified, it is just killed. When modified, it is saved
16948 \(if the user agrees) and then killed."
16949 (let (buf file)
16950 (while (setq buf (pop blist))
16951 (setq file (buffer-file-name buf))
16952 (when (and (buffer-modified-p buf)
16953 file
16954 (y-or-n-p (format "Save file %s? " file)))
16955 (with-current-buffer buf (save-buffer)))
16956 (kill-buffer buf))))
16958 (defun org-agenda-prepare-buffers (files)
16959 "Create buffers for all agenda files, protect archived trees and comments."
16960 (interactive)
16961 (let ((pa '(:org-archived t))
16962 (pc '(:org-comment t))
16963 (pall '(:org-archived t :org-comment t))
16964 (inhibit-read-only t)
16965 (rea (concat ":" org-archive-tag ":"))
16966 bmp file re)
16967 (save-excursion
16968 (save-restriction
16969 (while (setq file (pop files))
16970 (catch 'nextfile
16971 (if (bufferp file)
16972 (set-buffer file)
16973 (org-check-agenda-file file)
16974 (set-buffer (org-get-agenda-file-buffer file)))
16975 (widen)
16976 (setq bmp (buffer-modified-p))
16977 (org-refresh-category-properties)
16978 (setq org-todo-keywords-for-agenda
16979 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16980 (setq org-done-keywords-for-agenda
16981 (append org-done-keywords-for-agenda org-done-keywords))
16982 (setq org-todo-keyword-alist-for-agenda
16983 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16984 (setq org-drawers-for-agenda
16985 (append org-drawers-for-agenda org-drawers))
16986 (setq org-tag-alist-for-agenda
16987 (append org-tag-alist-for-agenda org-tag-alist))
16989 (save-excursion
16990 (remove-text-properties (point-min) (point-max) pall)
16991 (when org-agenda-skip-archived-trees
16992 (goto-char (point-min))
16993 (while (re-search-forward rea nil t)
16994 (if (org-at-heading-p t)
16995 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16996 (goto-char (point-min))
16997 (setq re (format org-heading-keyword-regexp-format
16998 org-comment-string))
16999 (while (re-search-forward re nil t)
17000 (add-text-properties
17001 (match-beginning 0) (org-end-of-subtree t) pc)))
17002 (set-buffer-modified-p bmp)))))
17003 (setq org-todo-keywords-for-agenda
17004 (org-uniquify org-todo-keywords-for-agenda))
17005 (setq org-todo-keyword-alist-for-agenda
17006 (org-uniquify org-todo-keyword-alist-for-agenda)
17007 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17009 ;;;; Embedded LaTeX
17011 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17012 "Keymap for the minor `org-cdlatex-mode'.")
17014 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17015 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17016 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17017 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17018 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17020 (defvar org-cdlatex-texmathp-advice-is-done nil
17021 "Flag remembering if we have applied the advice to texmathp already.")
17023 (define-minor-mode org-cdlatex-mode
17024 "Toggle the minor `org-cdlatex-mode'.
17025 This mode supports entering LaTeX environment and math in LaTeX fragments
17026 in Org-mode.
17027 \\{org-cdlatex-mode-map}"
17028 nil " OCDL" nil
17029 (when org-cdlatex-mode
17030 (require 'cdlatex)
17031 (run-hooks 'cdlatex-mode-hook)
17032 (cdlatex-compute-tables))
17033 (unless org-cdlatex-texmathp-advice-is-done
17034 (setq org-cdlatex-texmathp-advice-is-done t)
17035 (defadvice texmathp (around org-math-always-on activate)
17036 "Always return t in org-mode buffers.
17037 This is because we want to insert math symbols without dollars even outside
17038 the LaTeX math segments. If Orgmode thinks that point is actually inside
17039 an embedded LaTeX fragment, let texmathp do its job.
17040 \\[org-cdlatex-mode-map]"
17041 (interactive)
17042 (let (p)
17043 (cond
17044 ((not (derived-mode-p 'org-mode)) ad-do-it)
17045 ((eq this-command 'cdlatex-math-symbol)
17046 (setq ad-return-value t
17047 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17049 (let ((p (org-inside-LaTeX-fragment-p)))
17050 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17051 (setq ad-return-value t
17052 texmathp-why '("Org-mode embedded math" . 0))
17053 (if p ad-do-it)))))))))
17055 (defun turn-on-org-cdlatex ()
17056 "Unconditionally turn on `org-cdlatex-mode'."
17057 (org-cdlatex-mode 1))
17059 (defun org-inside-LaTeX-fragment-p ()
17060 "Test if point is inside a LaTeX fragment.
17061 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17062 sequence appearing also before point.
17063 Even though the matchers for math are configurable, this function assumes
17064 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17065 delimiters are skipped when they have been removed by customization.
17066 The return value is nil, or a cons cell with the delimiter and the
17067 position of this delimiter.
17069 This function does a reasonably good job, but can locally be fooled by
17070 for example currency specifications. For example it will assume being in
17071 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17072 fragments that are properly closed, but during editing, we have to live
17073 with the uncertainty caused by missing closing delimiters. This function
17074 looks only before point, not after."
17075 (catch 'exit
17076 (let ((pos (point))
17077 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17078 (lim (progn
17079 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17080 (point)))
17081 dd-on str (start 0) m re)
17082 (goto-char pos)
17083 (when dodollar
17084 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17085 re (nth 1 (assoc "$" org-latex-regexps)))
17086 (while (string-match re str start)
17087 (cond
17088 ((= (match-end 0) (length str))
17089 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17090 ((= (match-end 0) (- (length str) 5))
17091 (throw 'exit nil))
17092 (t (setq start (match-end 0))))))
17093 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17094 (goto-char pos)
17095 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17096 (and (match-beginning 2) (throw 'exit nil))
17097 ;; count $$
17098 (while (re-search-backward "\\$\\$" lim t)
17099 (setq dd-on (not dd-on)))
17100 (goto-char pos)
17101 (if dd-on (cons "$$" m))))))
17103 (defun org-inside-latex-macro-p ()
17104 "Is point inside a LaTeX macro or its arguments?"
17105 (save-match-data
17106 (org-in-regexp
17107 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17109 (defun org-try-cdlatex-tab ()
17110 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17111 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17112 - inside a LaTeX fragment, or
17113 - after the first word in a line, where an abbreviation expansion could
17114 insert a LaTeX environment."
17115 (when org-cdlatex-mode
17116 (cond
17117 ;; Before any word on the line: No expansion possible.
17118 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17119 ;; Just after first word on the line: Expand it. Make sure it
17120 ;; cannot happen on headlines, though.
17121 ((save-excursion
17122 (skip-chars-backward "a-zA-Z0-9*")
17123 (skip-chars-backward " \t")
17124 (and (bolp) (not (org-at-heading-p))))
17125 (cdlatex-tab) t)
17126 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17128 (defun org-cdlatex-underscore-caret (&optional arg)
17129 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17130 Revert to the normal definition outside of these fragments."
17131 (interactive "P")
17132 (if (org-inside-LaTeX-fragment-p)
17133 (call-interactively 'cdlatex-sub-superscript)
17134 (let (org-cdlatex-mode)
17135 (call-interactively (key-binding (vector last-input-event))))))
17137 (defun org-cdlatex-math-modify (&optional arg)
17138 "Execute `cdlatex-math-modify' in LaTeX fragments.
17139 Revert to the normal definition outside of these fragments."
17140 (interactive "P")
17141 (if (org-inside-LaTeX-fragment-p)
17142 (call-interactively 'cdlatex-math-modify)
17143 (let (org-cdlatex-mode)
17144 (call-interactively (key-binding (vector last-input-event))))))
17146 (defvar org-latex-fragment-image-overlays nil
17147 "List of overlays carrying the images of latex fragments.")
17148 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17150 (defun org-remove-latex-fragment-image-overlays ()
17151 "Remove all overlays with LaTeX fragment images in current buffer."
17152 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17153 (setq org-latex-fragment-image-overlays nil))
17155 (defun org-preview-latex-fragment (&optional subtree)
17156 "Preview the LaTeX fragment at point, or all locally or globally.
17157 If the cursor is in a LaTeX fragment, create the image and overlay
17158 it over the source code. If there is no fragment at point, display
17159 all fragments in the current text, from one headline to the next. With
17160 prefix SUBTREE, display all fragments in the current subtree. With a
17161 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17162 the cursor is before the first headline,
17163 display all fragments in the buffer.
17164 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17165 (interactive "P")
17166 (unless buffer-file-name
17167 (error "Can't preview LaTeX fragment in a non-file buffer"))
17168 (org-remove-latex-fragment-image-overlays)
17169 (save-excursion
17170 (save-restriction
17171 (let (beg end at msg)
17172 (cond
17173 ((or (equal subtree '(16))
17174 (not (save-excursion
17175 (re-search-backward org-outline-regexp-bol nil t))))
17176 (setq beg (point-min) end (point-max)
17177 msg "Creating images for buffer...%s"))
17178 ((equal subtree '(4))
17179 (org-back-to-heading)
17180 (setq beg (point) end (org-end-of-subtree t)
17181 msg "Creating images for subtree...%s"))
17183 (if (setq at (org-inside-LaTeX-fragment-p))
17184 (goto-char (max (point-min) (- (cdr at) 2)))
17185 (org-back-to-heading))
17186 (setq beg (point) end (progn (outline-next-heading) (point))
17187 msg (if at "Creating image...%s"
17188 "Creating images for entry...%s"))))
17189 (message msg "")
17190 (narrow-to-region beg end)
17191 (goto-char beg)
17192 (org-format-latex
17193 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17194 (file-name-nondirectory
17195 buffer-file-name)))
17196 default-directory 'overlays msg at 'forbuffer
17197 org-latex-create-formula-image-program)
17198 (message msg "done. Use `C-c C-c' to remove images.")))))
17200 (defvar org-latex-regexps
17201 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17202 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17203 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17204 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17205 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17206 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17207 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17208 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17209 "Regular expressions for matching embedded LaTeX.")
17211 (defvar org-export-have-math nil) ;; dynamic scoping
17212 (defun org-format-latex (prefix &optional dir overlays msg at
17213 forbuffer processing-type)
17214 "Replace LaTeX fragments with links to an image, and produce images.
17215 Some of the options can be changed using the variable
17216 `org-format-latex-options'."
17217 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17218 (let* ((prefixnodir (file-name-nondirectory prefix))
17219 (absprefix (expand-file-name prefix dir))
17220 (todir (file-name-directory absprefix))
17221 (opt org-format-latex-options)
17222 (matchers (plist-get opt :matchers))
17223 (re-list org-latex-regexps)
17224 (org-format-latex-header-extra
17225 (plist-get (org-infile-export-plist) :latex-header-extra))
17226 (cnt 0) txt hash link beg end re e checkdir
17227 executables-checked string
17228 m n block-type block linkfile movefile ov)
17229 ;; Check the different regular expressions
17230 (while (setq e (pop re-list))
17231 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17232 block (if block-type "\n\n" ""))
17233 (when (member m matchers)
17234 (goto-char (point-min))
17235 (while (re-search-forward re nil t)
17236 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17237 (not (get-text-property (match-beginning n)
17238 'org-protected))
17239 (or (not overlays)
17240 (not (eq (get-char-property (match-beginning n)
17241 'org-overlay-type)
17242 'org-latex-overlay))))
17243 (setq org-export-have-math t)
17244 (cond
17245 ((eq processing-type 'verbatim)
17246 ;; Leave the text verbatim, just protect it
17247 (add-text-properties (match-beginning n) (match-end n)
17248 '(org-protected t)))
17249 ((eq processing-type 'mathjax)
17250 ;; Prepare for MathJax processing
17251 (setq string (match-string n))
17252 (if (member m '("$" "$1"))
17253 (save-excursion
17254 (delete-region (match-beginning n) (match-end n))
17255 (goto-char (match-beginning n))
17256 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17257 "\\)")
17258 '(org-protected t))))
17259 (add-text-properties (match-beginning n) (match-end n)
17260 '(org-protected t))))
17261 ((or (eq processing-type 'dvipng)
17262 (eq processing-type 'imagemagick))
17263 ;; Process to an image
17264 (setq txt (match-string n)
17265 beg (match-beginning n) end (match-end n)
17266 cnt (1+ cnt))
17267 (let (print-length print-level) ; make sure full list is printed
17268 (setq hash (sha1 (prin1-to-string
17269 (list org-format-latex-header
17270 org-format-latex-header-extra
17271 org-export-latex-default-packages-alist
17272 org-export-latex-packages-alist
17273 org-format-latex-options
17274 forbuffer txt)))
17275 linkfile (format "%s_%s.png" prefix hash)
17276 movefile (format "%s_%s.png" absprefix hash)))
17277 (setq link (concat block "[[file:" linkfile "]]" block))
17278 (if msg (message msg cnt))
17279 (goto-char beg)
17280 (unless checkdir ; make sure the directory exists
17281 (setq checkdir t)
17282 (or (file-directory-p todir) (make-directory todir t)))
17283 (cond
17284 ((eq processing-type 'dvipng)
17285 (unless executables-checked
17286 (org-check-external-command
17287 "latex" "needed to convert LaTeX fragments to images")
17288 (org-check-external-command
17289 "dvipng" "needed to convert LaTeX fragments to images")
17290 (setq executables-checked t))
17291 (unless (file-exists-p movefile)
17292 (org-create-formula-image-with-dvipng
17293 txt movefile opt forbuffer)))
17294 ((eq processing-type 'imagemagick)
17295 (unless executables-checked
17296 (org-check-external-command
17297 "convert" "you need to install imagemagick")
17298 (setq executables-checked t))
17299 (unless (file-exists-p movefile)
17300 (org-create-formula-image-with-imagemagick
17301 txt movefile opt forbuffer))))
17302 (if overlays
17303 (progn
17304 (mapc (lambda (o)
17305 (if (eq (overlay-get o 'org-overlay-type)
17306 'org-latex-overlay)
17307 (delete-overlay o)))
17308 (overlays-in beg end))
17309 (setq ov (make-overlay beg end))
17310 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17311 (if (featurep 'xemacs)
17312 (progn
17313 (overlay-put ov 'invisible t)
17314 (overlay-put
17315 ov 'end-glyph
17316 (make-glyph (vector 'png :file movefile))))
17317 (overlay-put
17318 ov 'display
17319 (list 'image :type 'png :file movefile :ascent 'center)))
17320 (push ov org-latex-fragment-image-overlays)
17321 (goto-char end))
17322 (delete-region beg end)
17323 (insert (org-add-props link
17324 (list 'org-latex-src
17325 (replace-regexp-in-string
17326 "\"" "" txt)
17327 'org-latex-src-embed-type
17328 (if block-type 'paragraph 'character))))))
17329 ((eq processing-type 'mathml)
17330 ;; Process to MathML
17331 (unless executables-checked
17332 (unless (save-match-data (org-format-latex-mathml-available-p))
17333 (error "LaTeX to MathML converter not configured"))
17334 (setq executables-checked t))
17335 (setq txt (match-string n)
17336 beg (match-beginning n) end (match-end n)
17337 cnt (1+ cnt))
17338 (if msg (message msg cnt))
17339 (goto-char beg)
17340 (delete-region beg end)
17341 (insert (org-format-latex-as-mathml
17342 txt block-type prefix dir)))
17344 (error "Unknown conversion type %s for latex fragments"
17345 processing-type)))))))))
17347 (defun org-create-math-formula (latex-frag &optional mathml-file)
17348 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17349 Use `org-latex-to-mathml-convert-command'. If the conversion is
17350 sucessful, return the portion between \"<math...> </math>\"
17351 elements otherwise return nil. When MATHML-FILE is specified,
17352 write the results in to that file. When invoked as an
17353 interactive command, prompt for LATEX-FRAG, with initial value
17354 set to the current active region and echo the results for user
17355 inspection."
17356 (interactive (list (let ((frag (when (org-region-active-p)
17357 (buffer-substring-no-properties
17358 (region-beginning) (region-end)))))
17359 (read-string "LaTeX Fragment: " frag nil frag))))
17360 (unless latex-frag (error "Invalid latex-frag"))
17361 (let* ((tmp-in-file (file-relative-name
17362 (make-temp-name (expand-file-name "ltxmathml-in"))))
17363 (ignore (write-region latex-frag nil tmp-in-file))
17364 (tmp-out-file (file-relative-name
17365 (make-temp-name (expand-file-name "ltxmathml-out"))))
17366 (cmd (format-spec
17367 org-latex-to-mathml-convert-command
17368 `((?j . ,(shell-quote-argument
17369 (expand-file-name org-latex-to-mathml-jar-file)))
17370 (?I . ,(shell-quote-argument tmp-in-file))
17371 (?o . ,(shell-quote-argument tmp-out-file)))))
17372 mathml shell-command-output)
17373 (when (org-called-interactively-p 'any)
17374 (unless (org-format-latex-mathml-available-p)
17375 (error "LaTeX to MathML converter not configured")))
17376 (message "Running %s" cmd)
17377 (setq shell-command-output (shell-command-to-string cmd))
17378 (setq mathml
17379 (when (file-readable-p tmp-out-file)
17380 (with-current-buffer (find-file-noselect tmp-out-file t)
17381 (goto-char (point-min))
17382 (when (re-search-forward
17383 (concat
17384 (regexp-quote
17385 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17386 "\\(.\\|\n\\)*"
17387 (regexp-quote "</math>")) nil t)
17388 (prog1 (match-string 0) (kill-buffer))))))
17389 (cond
17390 (mathml
17391 (setq mathml
17392 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17393 (when mathml-file
17394 (write-region mathml nil mathml-file))
17395 (when (org-called-interactively-p 'any)
17396 (message mathml)))
17397 ((message "LaTeX to MathML conversion failed")
17398 (message shell-command-output)))
17399 (delete-file tmp-in-file)
17400 (when (file-exists-p tmp-out-file)
17401 (delete-file tmp-out-file))
17402 mathml))
17404 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17405 prefix &optional dir)
17406 "Use `org-create-math-formula' but check local cache first."
17407 (let* ((absprefix (expand-file-name prefix dir))
17408 (print-length nil) (print-level nil)
17409 (formula-id (concat
17410 "formula-"
17411 (sha1
17412 (prin1-to-string
17413 (list latex-frag
17414 org-latex-to-mathml-convert-command)))))
17415 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17416 (formula-cache-dir (file-name-directory formula-cache)))
17418 (unless (file-directory-p formula-cache-dir)
17419 (make-directory formula-cache-dir t))
17421 (unless (file-exists-p formula-cache)
17422 (org-create-math-formula latex-frag formula-cache))
17424 (if (file-exists-p formula-cache)
17425 ;; Successful conversion. Return the link to MathML file.
17426 (org-add-props
17427 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17428 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17429 'org-latex-src-embed-type (if latex-frag-type
17430 'paragraph 'character)))
17431 ;; Failed conversion. Return the LaTeX fragment verbatim
17432 (add-text-properties
17433 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17434 latex-frag)))
17436 ;; This function borrows from Ganesh Swami's latex2png.el
17437 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17438 "This calls dvipng."
17439 (require 'org-latex)
17440 (let* ((tmpdir (if (featurep 'xemacs)
17441 (temp-directory)
17442 temporary-file-directory))
17443 (texfilebase (make-temp-name
17444 (expand-file-name "orgtex" tmpdir)))
17445 (texfile (concat texfilebase ".tex"))
17446 (dvifile (concat texfilebase ".dvi"))
17447 (pngfile (concat texfilebase ".png"))
17448 (fnh (if (featurep 'xemacs)
17449 (font-height (face-font 'default))
17450 (face-attribute 'default :height nil)))
17451 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17452 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17453 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17454 "Black"))
17455 (bg (or (plist-get options (if buffer :background :html-background))
17456 "Transparent")))
17457 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17458 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17459 (with-temp-file texfile
17460 (insert (org-splice-latex-header
17461 org-format-latex-header
17462 org-export-latex-default-packages-alist
17463 org-export-latex-packages-alist t
17464 org-format-latex-header-extra))
17465 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17466 (require 'org-latex)
17467 (org-export-latex-fix-inputenc))
17468 (let ((dir default-directory))
17469 (condition-case nil
17470 (progn
17471 (cd tmpdir)
17472 (call-process "latex" nil nil nil texfile))
17473 (error nil))
17474 (cd dir))
17475 (if (not (file-exists-p dvifile))
17476 (progn (message "Failed to create dvi file from %s" texfile) nil)
17477 (condition-case nil
17478 (if (featurep 'xemacs)
17479 (call-process "dvipng" nil nil nil
17480 "-fg" fg "-bg" bg
17481 "-T" "tight"
17482 "-o" pngfile
17483 dvifile)
17484 (call-process "dvipng" nil nil nil
17485 "-fg" fg "-bg" bg
17486 "-D" dpi
17487 ;;"-x" scale "-y" scale
17488 "-T" "tight"
17489 "-o" pngfile
17490 dvifile))
17491 (error nil))
17492 (if (not (file-exists-p pngfile))
17493 (if org-format-latex-signal-error
17494 (error "Failed to create png file from %s" texfile)
17495 (message "Failed to create png file from %s" texfile)
17496 nil)
17497 ;; Use the requested file name and clean up
17498 (copy-file pngfile tofile 'replace)
17499 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17500 (if (file-exists-p (concat texfilebase e))
17501 (delete-file (concat texfilebase e))))
17502 pngfile))))
17504 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17505 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17506 "This calls convert, which is included into imagemagick."
17507 (require 'org-latex)
17508 (let* ((tmpdir (if (featurep 'xemacs)
17509 (temp-directory)
17510 temporary-file-directory))
17511 (texfilebase (make-temp-name
17512 (expand-file-name "orgtex" tmpdir)))
17513 (texfile (concat texfilebase ".tex"))
17514 (pdffile (concat texfilebase ".pdf"))
17515 (pngfile (concat texfilebase ".png"))
17516 (fnh (if (featurep 'xemacs)
17517 (font-height (face-font 'default))
17518 (face-attribute 'default :height nil)))
17519 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17520 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17521 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17522 "black"))
17523 (bg (or (plist-get options (if buffer :background :html-background))
17524 "white")))
17525 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17526 (setq fg (org-latex-color-format fg)))
17527 (if (eq bg 'default) (setq bg (org-latex-color :background))
17528 (setq bg (org-latex-color-format
17529 (if (string= bg "Transparent")(setq bg "white")))))
17530 (with-temp-file texfile
17531 (insert (org-splice-latex-header
17532 org-format-latex-header
17533 org-export-latex-default-packages-alist
17534 org-export-latex-packages-alist t
17535 org-format-latex-header-extra))
17536 (insert "\n\\begin{document}\n"
17537 "\\definecolor{fg}{rgb}{" fg "}\n"
17538 "\\definecolor{bg}{rgb}{" bg "}\n"
17539 "\n\\pagecolor{bg}\n"
17540 "\n{\\color{fg}\n"
17541 string
17542 "\n}\n"
17543 "\n\\end{document}\n" )
17544 (require 'org-latex)
17545 (org-export-latex-fix-inputenc))
17546 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17547 (condition-case nil
17548 (progn
17549 (cd tmpdir)
17550 (setq cmds org-latex-to-pdf-process)
17551 (while cmds
17552 (setq latex-frags-cmds (pop cmds))
17553 (if (listp latex-frags-cmds)
17554 (setq cmds nil)
17555 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17556 (while latex-frags-cmds
17557 (setq cmd (pop latex-frags-cmds))
17558 (while (string-match "%b" cmd)
17559 (setq cmd (replace-match
17560 (save-match-data
17561 (shell-quote-argument texfile))
17562 t t cmd)))
17563 (while (string-match "%f" cmd)
17564 (setq cmd (replace-match
17565 (save-match-data
17566 (shell-quote-argument (file-name-nondirectory texfile)))
17567 t t cmd)))
17568 (while (string-match "%o" cmd)
17569 (setq cmd (replace-match
17570 (save-match-data
17571 (shell-quote-argument (file-name-directory texfile)))
17572 t t cmd)))
17573 (setq cmd (split-string cmd))
17574 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17575 (error nil))
17576 (cd dir))
17577 (if (not (file-exists-p pdffile))
17578 (progn (message "Failed to create pdf file from %s" texfile) nil)
17579 (condition-case nil
17580 (if (featurep 'xemacs)
17581 (call-process "convert" nil nil nil
17582 "-density" "96"
17583 "-trim"
17584 "-antialias"
17585 pdffile
17586 "-quality" "100"
17587 ;; "-sharpen" "0x1.0"
17588 pngfile)
17589 (call-process "convert" nil nil nil
17590 "-density" dpi
17591 "-trim"
17592 "-antialias"
17593 pdffile
17594 "-quality" "100"
17595 ; "-sharpen" "0x1.0"
17596 pngfile))
17597 (error nil))
17598 (if (not (file-exists-p pngfile))
17599 (if org-format-latex-signal-error
17600 (error "Failed to create png file from %s" texfile)
17601 (message "Failed to create png file from %s" texfile)
17602 nil)
17603 ;; Use the requested file name and clean up
17604 (copy-file pngfile tofile 'replace)
17605 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17606 (if (file-exists-p (concat texfilebase e))
17607 (delete-file (concat texfilebase e))))
17608 pngfile))))
17610 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17611 "Fill a LaTeX header template TPL.
17612 In the template, the following place holders will be recognized:
17614 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17615 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17616 [PACKAGES] \\usepackage statements for PKG
17617 [NO-PACKAGES] do not include PKG
17618 [EXTRA] the string EXTRA
17619 [NO-EXTRA] do not include EXTRA
17621 For backward compatibility, if both the positive and the negative place
17622 holder is missing, the positive one (without the \"NO-\") will be
17623 assumed to be present at the end of the template.
17624 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17625 EXTRA is a string.
17626 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17627 (let (rpl (end ""))
17628 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17629 (setq rpl (if (or (match-end 1) (not def-pkg))
17630 "" (org-latex-packages-to-string def-pkg snippets-p t))
17631 tpl (replace-match rpl t t tpl))
17632 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17634 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17635 (setq rpl (if (or (match-end 1) (not pkg))
17636 "" (org-latex-packages-to-string pkg snippets-p t))
17637 tpl (replace-match rpl t t tpl))
17638 (if pkg (setq end
17639 (concat end "\n"
17640 (org-latex-packages-to-string pkg snippets-p)))))
17642 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17643 (setq rpl (if (or (match-end 1) (not extra))
17644 "" (concat extra "\n"))
17645 tpl (replace-match rpl t t tpl))
17646 (if (and extra (string-match "\\S-" extra))
17647 (setq end (concat end "\n" extra))))
17649 (if (string-match "\\S-" end)
17650 (concat tpl "\n" end)
17651 tpl)))
17653 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17654 "Turn an alist of packages into a string with the \\usepackage macros."
17655 (setq pkg (mapconcat (lambda(p)
17656 (cond
17657 ((stringp p) p)
17658 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17659 (format "%% Package %s omitted" (cadr p)))
17660 ((equal "" (car p))
17661 (format "\\usepackage{%s}" (cadr p)))
17663 (format "\\usepackage[%s]{%s}"
17664 (car p) (cadr p)))))
17666 "\n"))
17667 (if newline (concat pkg "\n") pkg))
17669 (defun org-dvipng-color (attr)
17670 "Return a RGB color specification for dvipng."
17671 (apply 'format "rgb %s %s %s"
17672 (mapcar 'org-normalize-color
17673 (if (featurep 'xemacs)
17674 (color-rgb-components
17675 (face-property 'default
17676 (cond ((eq attr :foreground) 'foreground)
17677 ((eq attr :background) 'background))))
17678 (color-values (face-attribute 'default attr nil))))))
17680 (defun org-latex-color (attr)
17681 "Return a RGB color for the LaTeX color package."
17682 (apply 'format "%s,%s,%s"
17683 (mapcar 'org-normalize-color
17684 (if (featurep 'xemacs)
17685 (color-rgb-components
17686 (face-property 'default
17687 (cond ((eq attr :foreground) 'foreground)
17688 ((eq attr :background) 'background))))
17689 (color-values (face-attribute 'default attr nil))))))
17691 (defun org-latex-color-format (color-name)
17692 "Convert COLOR-NAME to a RGB color value."
17693 (apply 'format "%s,%s,%s"
17694 (mapcar 'org-normalize-color
17695 (color-values color-name))))
17697 (defun org-normalize-color (value)
17698 "Return string to be used as color value for an RGB component."
17699 (format "%g" (/ value 65535.0)))
17701 ;; Image display
17704 (defvar org-inline-image-overlays nil)
17705 (make-variable-buffer-local 'org-inline-image-overlays)
17707 (defun org-toggle-inline-images (&optional include-linked)
17708 "Toggle the display of inline images.
17709 INCLUDE-LINKED is passed to `org-display-inline-images'."
17710 (interactive "P")
17711 (if org-inline-image-overlays
17712 (progn
17713 (org-remove-inline-images)
17714 (message "Inline image display turned off"))
17715 (org-display-inline-images include-linked)
17716 (if org-inline-image-overlays
17717 (message "%d images displayed inline"
17718 (length org-inline-image-overlays))
17719 (message "No images to display inline"))))
17721 (defun org-redisplay-inline-images ()
17722 "Refresh the display of inline images."
17723 (interactive)
17724 (if (not org-inline-image-overlays)
17725 (org-toggle-inline-images)
17726 (org-toggle-inline-images)
17727 (org-toggle-inline-images)))
17729 (defun org-display-inline-images (&optional include-linked refresh beg end)
17730 "Display inline images.
17731 Normally only links without a description part are inlined, because this
17732 is how it will work for export. When INCLUDE-LINKED is set, also links
17733 with a description part will be inlined. This can be nice for a quick
17734 look at those images, but it does not reflect what exported files will look
17735 like.
17736 When REFRESH is set, refresh existing images between BEG and END.
17737 This will create new image displays only if necessary.
17738 BEG and END default to the buffer boundaries."
17739 (interactive "P")
17740 (unless refresh
17741 (org-remove-inline-images)
17742 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17743 (save-excursion
17744 (save-restriction
17745 (widen)
17746 (setq beg (or beg (point-min)) end (or end (point-max)))
17747 (goto-char beg)
17748 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17749 (substring (org-image-file-name-regexp) 0 -2)
17750 "\\)\\]" (if include-linked "" "\\]")))
17751 old file ov img)
17752 (while (re-search-forward re end t)
17753 (setq old (get-char-property-and-overlay (match-beginning 1)
17754 'org-image-overlay))
17755 (setq file (expand-file-name
17756 (concat (or (match-string 3) "") (match-string 4))))
17757 (when (file-exists-p file)
17758 (if (and (car-safe old) refresh)
17759 (image-refresh (overlay-get (cdr old) 'display))
17760 (setq img (save-match-data (create-image file)))
17761 (when img
17762 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17763 (overlay-put ov 'display img)
17764 (overlay-put ov 'face 'default)
17765 (overlay-put ov 'org-image-overlay t)
17766 (overlay-put ov 'modification-hooks
17767 (list 'org-display-inline-remove-overlay))
17768 (push ov org-inline-image-overlays)))))))))
17770 (define-obsolete-function-alias
17771 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17773 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17774 "Remove inline-display overlay if a corresponding region is modified."
17775 (let ((inhibit-modification-hooks t))
17776 (when (and ov after)
17777 (delete ov org-inline-image-overlays)
17778 (delete-overlay ov))))
17780 (defun org-remove-inline-images ()
17781 "Remove inline display of images."
17782 (interactive)
17783 (mapc 'delete-overlay org-inline-image-overlays)
17784 (setq org-inline-image-overlays nil))
17786 ;;;; Key bindings
17788 ;; Outline functions from `outline-mode-prefix-map'
17789 ;; that can be remapped in Org:
17790 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17791 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17792 (define-key org-mode-map [remap outline-forward-same-level]
17793 'org-forward-heading-same-level)
17794 (define-key org-mode-map [remap outline-backward-same-level]
17795 'org-backward-heading-same-level)
17796 (define-key org-mode-map [remap show-branches]
17797 'org-kill-note-or-show-branches)
17798 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17799 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17800 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17802 ;; Outline functions from `outline-mode-prefix-map' that can not
17803 ;; be remapped in Org:
17805 ;; - the column "key binding" shows whether the Outline function is still
17806 ;; available in Org mode on the same key that it has been bound to in
17807 ;; Outline mode:
17808 ;; - "overridden": key used for a different functionality in Org mode
17809 ;; - else: key still bound to the same Outline function in Org mode
17811 ;; | Outline function | key binding | Org replacement |
17812 ;; |------------------------------------+-------------+-----------------------|
17813 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17814 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17815 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17816 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17817 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17818 ;; | `show-entry' | overridden | no replacement |
17819 ;; | `show-children' | `C-c C-i' | visibility cycling |
17820 ;; | `show-branches' | `C-c C-k' | still same function |
17821 ;; | `show-subtree' | overridden | visibility cycling |
17822 ;; | `show-all' | overridden | no replacement |
17823 ;; | `hide-subtree' | overridden | visibility cycling |
17824 ;; | `hide-body' | overridden | no replacement |
17825 ;; | `hide-entry' | overridden | visibility cycling |
17826 ;; | `hide-leaves' | overridden | no replacement |
17827 ;; | `hide-sublevels' | overridden | no replacement |
17828 ;; | `hide-other' | overridden | no replacement |
17830 ;; Make `C-c C-x' a prefix key
17831 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17833 ;; TAB key with modifiers
17834 (org-defkey org-mode-map "\C-i" 'org-cycle)
17835 (org-defkey org-mode-map [(tab)] 'org-cycle)
17836 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17837 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17838 ;; The following line is necessary under Suse GNU/Linux
17839 (unless (featurep 'xemacs)
17840 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17841 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17842 (define-key org-mode-map [backtab] 'org-shifttab)
17844 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17845 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17846 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17848 ;; Cursor keys with modifiers
17849 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17850 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17851 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17852 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17854 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17855 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17856 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17857 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17859 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17860 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17861 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17862 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17864 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17865 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17866 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17867 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17869 ;; Babel keys
17870 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17871 (mapc (lambda (pair)
17872 (define-key org-babel-map (car pair) (cdr pair)))
17873 org-babel-key-bindings)
17875 ;;; Extra keys for tty access.
17876 ;; We only set them when really needed because otherwise the
17877 ;; menus don't show the simple keys
17879 (when (or org-use-extra-keys
17880 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17881 (not window-system))
17882 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17883 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17884 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17885 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17886 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17887 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17888 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17889 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17890 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17891 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17892 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17893 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17894 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17895 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17896 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17897 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17898 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17899 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17900 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17901 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17902 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17903 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17904 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17905 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17906 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17907 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17908 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17909 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17911 ;; All the other keys
17913 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17914 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17915 (if (boundp 'narrow-map)
17916 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17917 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17918 (if (boundp 'narrow-map)
17919 (org-defkey narrow-map "b" 'org-narrow-to-block)
17920 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17921 (if (boundp 'narrow-map)
17922 (org-defkey narrow-map "e" 'org-narrow-to-element)
17923 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17924 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17925 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17926 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17927 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17928 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17929 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17930 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17931 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17932 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17933 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17934 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17935 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17936 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17937 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17938 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17939 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17940 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17941 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17942 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17943 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17944 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17945 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17946 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17947 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17948 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17949 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17950 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17951 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17952 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17953 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17954 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17955 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17956 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17957 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17958 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17959 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17960 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17961 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17962 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17963 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17964 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17965 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17966 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17967 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17968 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17969 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17970 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17971 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17972 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17973 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17974 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17975 (org-defkey org-mode-map "\C-c^" 'org-sort)
17976 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17977 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17978 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17979 (org-defkey org-mode-map "\C-m" 'org-return)
17980 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17981 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17982 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17983 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17984 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17985 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17986 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17987 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17988 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17989 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17990 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17991 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17992 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17993 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17994 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17995 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17996 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17997 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17998 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17999 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18000 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18001 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18002 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18004 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18005 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18006 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18008 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18009 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18010 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18011 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18012 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18013 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18014 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18015 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18016 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18017 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18018 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18019 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18020 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18021 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18022 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18023 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18024 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18025 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18026 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18027 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18028 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18029 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18031 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18032 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18033 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18034 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18035 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18037 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18039 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18041 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18042 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18044 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18047 (when (featurep 'xemacs)
18048 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18051 (defconst org-speed-commands-default
18053 ("Outline Navigation")
18054 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18055 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18056 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18057 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18058 ("u" . (org-speed-move-safe 'outline-up-heading))
18059 ("j" . org-goto)
18060 ("g" . (org-refile t))
18061 ("Outline Visibility")
18062 ("c" . org-cycle)
18063 ("C" . org-shifttab)
18064 (" " . org-display-outline-path)
18065 (":" . org-columns)
18066 ("Outline Structure Editing")
18067 ("U" . org-shiftmetaup)
18068 ("D" . org-shiftmetadown)
18069 ("r" . org-metaright)
18070 ("l" . org-metaleft)
18071 ("R" . org-shiftmetaright)
18072 ("L" . org-shiftmetaleft)
18073 ("i" . (progn (forward-char 1) (call-interactively
18074 'org-insert-heading-respect-content)))
18075 ("^" . org-sort)
18076 ("w" . org-refile)
18077 ("a" . org-archive-subtree-default-with-confirmation)
18078 ("." . org-mark-subtree)
18079 ("#" . org-toggle-comment)
18080 ("Clock Commands")
18081 ("I" . org-clock-in)
18082 ("O" . org-clock-out)
18083 ("Meta Data Editing")
18084 ("t" . org-todo)
18085 ("," . (org-priority))
18086 ("0" . (org-priority ?\ ))
18087 ("1" . (org-priority ?A))
18088 ("2" . (org-priority ?B))
18089 ("3" . (org-priority ?C))
18090 (";" . org-set-tags-command)
18091 ("e" . org-set-effort)
18092 ("E" . org-inc-effort)
18093 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18094 (org-entry-put (point) "APPT_WARNTIME" m)))
18095 ("Agenda Views etc")
18096 ("v" . org-agenda)
18097 ("/" . org-sparse-tree)
18098 ("Misc")
18099 ("o" . org-open-at-point)
18100 ("?" . org-speed-command-help)
18101 ("<" . (org-agenda-set-restriction-lock 'subtree))
18102 (">" . (org-agenda-remove-restriction-lock))
18104 "The default speed commands.")
18106 (defun org-print-speed-command (e)
18107 (if (> (length (car e)) 1)
18108 (progn
18109 (princ "\n")
18110 (princ (car e))
18111 (princ "\n")
18112 (princ (make-string (length (car e)) ?-))
18113 (princ "\n"))
18114 (princ (car e))
18115 (princ " ")
18116 (if (symbolp (cdr e))
18117 (princ (symbol-name (cdr e)))
18118 (prin1 (cdr e)))
18119 (princ "\n")))
18121 (defun org-speed-command-help ()
18122 "Show the available speed commands."
18123 (interactive)
18124 (if (not org-use-speed-commands)
18125 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18126 (with-output-to-temp-buffer "*Help*"
18127 (princ "User-defined Speed commands\n===========================\n")
18128 (mapc 'org-print-speed-command org-speed-commands-user)
18129 (princ "\n")
18130 (princ "Built-in Speed commands\n=======================\n")
18131 (mapc 'org-print-speed-command org-speed-commands-default))
18132 (with-current-buffer "*Help*"
18133 (setq truncate-lines t))))
18135 (defun org-speed-move-safe (cmd)
18136 "Execute CMD, but make sure that the cursor always ends up in a headline.
18137 If not, return to the original position and throw an error."
18138 (interactive)
18139 (let ((pos (point)))
18140 (call-interactively cmd)
18141 (unless (and (bolp) (org-at-heading-p))
18142 (goto-char pos)
18143 (error "Boundary reached while executing %s" cmd))))
18145 (defvar org-self-insert-command-undo-counter 0)
18147 (defvar org-table-auto-blank-field) ; defined in org-table.el
18148 (defvar org-speed-command nil)
18150 (define-obsolete-function-alias
18151 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18153 (defun org-speed-command-activate (keys)
18154 "Hook for activating single-letter speed commands.
18155 `org-speed-commands-default' specifies a minimal command set.
18156 Use `org-speed-commands-user' for further customization."
18157 (when (or (and (bolp) (looking-at org-outline-regexp))
18158 (and (functionp org-use-speed-commands)
18159 (funcall org-use-speed-commands)))
18160 (cdr (assoc keys (append org-speed-commands-user
18161 org-speed-commands-default)))))
18163 (define-obsolete-function-alias
18164 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18166 (defun org-babel-speed-command-activate (keys)
18167 "Hook for activating single-letter code block commands."
18168 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18169 (cdr (assoc keys org-babel-key-bindings))))
18171 (defcustom org-speed-command-hook
18172 '(org-speed-command-default-hook org-babel-speed-command-hook)
18173 "Hook for activating speed commands at strategic locations.
18174 Hook functions are called in sequence until a valid handler is
18175 found.
18177 Each hook takes a single argument, a user-pressed command key
18178 which is also a `self-insert-command' from the global map.
18180 Within the hook, examine the cursor position and the command key
18181 and return nil or a valid handler as appropriate. Handler could
18182 be one of an interactive command, a function, or a form.
18184 Set `org-use-speed-commands' to non-nil value to enable this
18185 hook. The default setting is `org-speed-command-activate'."
18186 :group 'org-structure
18187 :version "24.1"
18188 :type 'hook)
18190 (defun org-self-insert-command (N)
18191 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18192 If the cursor is in a table looking at whitespace, the whitespace is
18193 overwritten, and the table is not marked as requiring realignment."
18194 (interactive "p")
18195 (org-check-before-invisible-edit 'insert)
18196 (cond
18197 ((and org-use-speed-commands
18198 (setq org-speed-command
18199 (run-hook-with-args-until-success
18200 'org-speed-command-hook (this-command-keys))))
18201 (cond
18202 ((commandp org-speed-command)
18203 (setq this-command org-speed-command)
18204 (call-interactively org-speed-command))
18205 ((functionp org-speed-command)
18206 (funcall org-speed-command))
18207 ((and org-speed-command (listp org-speed-command))
18208 (eval org-speed-command))
18209 (t (let (org-use-speed-commands)
18210 (call-interactively 'org-self-insert-command)))))
18211 ((and
18212 (org-table-p)
18213 (progn
18214 ;; check if we blank the field, and if that triggers align
18215 (and (featurep 'org-table) org-table-auto-blank-field
18216 (member last-command
18217 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18218 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18219 ;; got extra space, this field does not determine column width
18220 (let (org-table-may-need-update) (org-table-blank-field))
18221 ;; no extra space, this field may determine column width
18222 (org-table-blank-field)))
18224 (eq N 1)
18225 (looking-at "[^|\n]* |"))
18226 (let (org-table-may-need-update)
18227 (goto-char (1- (match-end 0)))
18228 (backward-delete-char 1)
18229 (goto-char (match-beginning 0))
18230 (self-insert-command N)))
18232 (setq org-table-may-need-update t)
18233 (self-insert-command N)
18234 (org-fix-tags-on-the-fly)
18235 (if org-self-insert-cluster-for-undo
18236 (if (not (eq last-command 'org-self-insert-command))
18237 (setq org-self-insert-command-undo-counter 1)
18238 (if (>= org-self-insert-command-undo-counter 20)
18239 (setq org-self-insert-command-undo-counter 1)
18240 (and (> org-self-insert-command-undo-counter 0)
18241 buffer-undo-list (listp buffer-undo-list)
18242 (not (cadr buffer-undo-list)) ; remove nil entry
18243 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18244 (setq org-self-insert-command-undo-counter
18245 (1+ org-self-insert-command-undo-counter))))))))
18247 (defun org-check-before-invisible-edit (kind)
18248 "Check is editing if kind KIND would be dangerous with invisible text around.
18249 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18250 ;; First, try to get out of here as quickly as possible, to reduce overhead
18251 (if (and org-catch-invisible-edits
18252 (or (not (boundp 'visible-mode)) (not visible-mode))
18253 (or (get-char-property (point) 'invisible)
18254 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18255 ;; OK, we need to take a closer look
18256 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18257 (invisible-before-point (if (bobp) nil (get-char-property
18258 (1- (point)) 'invisible)))
18259 (border-and-ok-direction
18261 ;; Check if we are acting predictably before invisible text
18262 (and invisible-at-point (not invisible-before-point)
18263 (memq kind '(insert delete-backward)))
18264 ;; Check if we are acting predictably after invisible text
18265 ;; This works not well, and I have turned it off. It seems
18266 ;; better to always show and stop after invisible text.
18267 ;; (and (not invisible-at-point) invisible-before-point
18268 ;; (memq kind '(insert delete)))
18270 (when (or (memq invisible-at-point '(outline org-hide-block t))
18271 (memq invisible-before-point '(outline org-hide-block t)))
18272 (if (eq org-catch-invisible-edits 'error)
18273 (error "Editing in invisible areas is prohibited - make visible first"))
18274 (if (and org-custom-properties-overlays
18275 (y-or-n-p "Display invisible properties in this buffer? "))
18276 (org-toggle-custom-properties-visibility)
18277 ;; Make the area visible
18278 (save-excursion
18279 (if invisible-before-point
18280 (goto-char (previous-single-char-property-change
18281 (point) 'invisible)))
18282 (org-cycle))
18283 (cond
18284 ((eq org-catch-invisible-edits 'show)
18285 ;; That's it, we do the edit after showing
18286 (message
18287 "Unfolding invisible region around point before editing")
18288 (sit-for 1))
18289 ((and (eq org-catch-invisible-edits 'smart)
18290 border-and-ok-direction)
18291 (message "Unfolding invisible region around point before editing"))
18293 ;; Don't do the edit, make the user repeat it in full visibility
18294 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18296 (defun org-fix-tags-on-the-fly ()
18297 (when (and (equal (char-after (point-at-bol)) ?*)
18298 (org-at-heading-p))
18299 (org-align-tags-here org-tags-column)))
18301 (defun org-delete-backward-char (N)
18302 "Like `delete-backward-char', insert whitespace at field end in tables.
18303 When deleting backwards, in tables this function will insert whitespace in
18304 front of the next \"|\" separator, to keep the table aligned. The table will
18305 still be marked for re-alignment if the field did fill the entire column,
18306 because, in this case the deletion might narrow the column."
18307 (interactive "p")
18308 (save-match-data
18309 (org-check-before-invisible-edit 'delete-backward)
18310 (if (and (org-table-p)
18311 (eq N 1)
18312 (string-match "|" (buffer-substring (point-at-bol) (point)))
18313 (looking-at ".*?|"))
18314 (let ((pos (point))
18315 (noalign (looking-at "[^|\n\r]* |"))
18316 (c org-table-may-need-update))
18317 (backward-delete-char N)
18318 (if (not overwrite-mode)
18319 (progn
18320 (skip-chars-forward "^|")
18321 (insert " ")
18322 (goto-char (1- pos))))
18323 ;; noalign: if there were two spaces at the end, this field
18324 ;; does not determine the width of the column.
18325 (if noalign (setq org-table-may-need-update c)))
18326 (backward-delete-char N)
18327 (org-fix-tags-on-the-fly))))
18329 (defun org-delete-char (N)
18330 "Like `delete-char', but insert whitespace at field end in tables.
18331 When deleting characters, in tables this function will insert whitespace in
18332 front of the next \"|\" separator, to keep the table aligned. The table will
18333 still be marked for re-alignment if the field did fill the entire column,
18334 because, in this case the deletion might narrow the column."
18335 (interactive "p")
18336 (save-match-data
18337 (org-check-before-invisible-edit 'delete)
18338 (if (and (org-table-p)
18339 (not (bolp))
18340 (not (= (char-after) ?|))
18341 (eq N 1))
18342 (if (looking-at ".*?|")
18343 (let ((pos (point))
18344 (noalign (looking-at "[^|\n\r]* |"))
18345 (c org-table-may-need-update))
18346 (replace-match (concat
18347 (substring (match-string 0) 1 -1)
18348 " |"))
18349 (goto-char pos)
18350 ;; noalign: if there were two spaces at the end, this field
18351 ;; does not determine the width of the column.
18352 (if noalign (setq org-table-may-need-update c)))
18353 (delete-char N))
18354 (delete-char N)
18355 (org-fix-tags-on-the-fly))))
18357 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18358 (put 'org-self-insert-command 'delete-selection t)
18359 (put 'orgtbl-self-insert-command 'delete-selection t)
18360 (put 'org-delete-char 'delete-selection 'supersede)
18361 (put 'org-delete-backward-char 'delete-selection 'supersede)
18362 (put 'org-yank 'delete-selection 'yank)
18364 ;; Make `flyspell-mode' delay after some commands
18365 (put 'org-self-insert-command 'flyspell-delayed t)
18366 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18367 (put 'org-delete-char 'flyspell-delayed t)
18368 (put 'org-delete-backward-char 'flyspell-delayed t)
18370 ;; Make pabbrev-mode expand after org-mode commands
18371 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18372 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18374 ;; How to do this: Measure non-white length of current string
18375 ;; If equal to column width, we should realign.
18377 (defun org-remap (map &rest commands)
18378 "In MAP, remap the functions given in COMMANDS.
18379 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18380 (let (new old)
18381 (while commands
18382 (setq old (pop commands) new (pop commands))
18383 (if (fboundp 'command-remapping)
18384 (org-defkey map (vector 'remap old) new)
18385 (substitute-key-definition old new map global-map)))))
18387 (when (eq org-enable-table-editor 'optimized)
18388 ;; If the user wants maximum table support, we need to hijack
18389 ;; some standard editing functions
18390 (org-remap org-mode-map
18391 'self-insert-command 'org-self-insert-command
18392 'delete-char 'org-delete-char
18393 'delete-backward-char 'org-delete-backward-char)
18394 (org-defkey org-mode-map "|" 'org-force-self-insert))
18396 (defvar org-ctrl-c-ctrl-c-hook nil
18397 "Hook for functions attaching themselves to `C-c C-c'.
18399 This can be used to add additional functionality to the C-c C-c
18400 key which executes context-dependent commands. This hook is run
18401 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18402 run after the last test.
18404 Each function will be called with no arguments. The function
18405 must check if the context is appropriate for it to act. If yes,
18406 it should do its thing and then return a non-nil value. If the
18407 context is wrong, just do nothing and return nil.")
18409 (defvar org-ctrl-c-ctrl-c-final-hook nil
18410 "Hook for functions attaching themselves to `C-c C-c'.
18412 This can be used to add additional functionality to the C-c C-c
18413 key which executes context-dependent commands. This hook is run
18414 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18415 before the first test.
18417 Each function will be called with no arguments. The function
18418 must check if the context is appropriate for it to act. If yes,
18419 it should do its thing and then return a non-nil value. If the
18420 context is wrong, just do nothing and return nil.")
18422 (defvar org-tab-first-hook nil
18423 "Hook for functions to attach themselves to TAB.
18424 See `org-ctrl-c-ctrl-c-hook' for more information.
18425 This hook runs as the first action when TAB is pressed, even before
18426 `org-cycle' messes around with the `outline-regexp' to cater for
18427 inline tasks and plain list item folding.
18428 If any function in this hook returns t, any other actions that
18429 would have been caused by TAB (such as table field motion or visibility
18430 cycling) will not occur.")
18432 (defvar org-tab-after-check-for-table-hook nil
18433 "Hook for functions to attach themselves to TAB.
18434 See `org-ctrl-c-ctrl-c-hook' for more information.
18435 This hook runs after it has been established that the cursor is not in a
18436 table, but before checking if the cursor is in a headline or if global cycling
18437 should be done.
18438 If any function in this hook returns t, not other actions like visibility
18439 cycling will be done.")
18441 (defvar org-tab-after-check-for-cycling-hook nil
18442 "Hook for functions to attach themselves to TAB.
18443 See `org-ctrl-c-ctrl-c-hook' for more information.
18444 This hook runs after it has been established that not table field motion and
18445 not visibility should be done because of current context. This is probably
18446 the place where a package like yasnippets can hook in.")
18448 (defvar org-tab-before-tab-emulation-hook nil
18449 "Hook for functions to attach themselves to TAB.
18450 See `org-ctrl-c-ctrl-c-hook' for more information.
18451 This hook runs after every other options for TAB have been exhausted, but
18452 before indentation and \t insertion takes place.")
18454 (defvar org-metaleft-hook nil
18455 "Hook for functions attaching themselves to `M-left'.
18456 See `org-ctrl-c-ctrl-c-hook' for more information.")
18457 (defvar org-metaright-hook nil
18458 "Hook for functions attaching themselves to `M-right'.
18459 See `org-ctrl-c-ctrl-c-hook' for more information.")
18460 (defvar org-metaup-hook nil
18461 "Hook for functions attaching themselves to `M-up'.
18462 See `org-ctrl-c-ctrl-c-hook' for more information.")
18463 (defvar org-metadown-hook nil
18464 "Hook for functions attaching themselves to `M-down'.
18465 See `org-ctrl-c-ctrl-c-hook' for more information.")
18466 (defvar org-shiftmetaleft-hook nil
18467 "Hook for functions attaching themselves to `M-S-left'.
18468 See `org-ctrl-c-ctrl-c-hook' for more information.")
18469 (defvar org-shiftmetaright-hook nil
18470 "Hook for functions attaching themselves to `M-S-right'.
18471 See `org-ctrl-c-ctrl-c-hook' for more information.")
18472 (defvar org-shiftmetaup-hook nil
18473 "Hook for functions attaching themselves to `M-S-up'.
18474 See `org-ctrl-c-ctrl-c-hook' for more information.")
18475 (defvar org-shiftmetadown-hook nil
18476 "Hook for functions attaching themselves to `M-S-down'.
18477 See `org-ctrl-c-ctrl-c-hook' for more information.")
18478 (defvar org-metareturn-hook nil
18479 "Hook for functions attaching themselves to `M-RET'.
18480 See `org-ctrl-c-ctrl-c-hook' for more information.")
18481 (defvar org-shiftup-hook nil
18482 "Hook for functions attaching themselves to `S-up'.
18483 See `org-ctrl-c-ctrl-c-hook' for more information.")
18484 (defvar org-shiftup-final-hook nil
18485 "Hook for functions attaching themselves to `S-up'.
18486 This one runs after all other options except shift-select have been excluded.
18487 See `org-ctrl-c-ctrl-c-hook' for more information.")
18488 (defvar org-shiftdown-hook nil
18489 "Hook for functions attaching themselves to `S-down'.
18490 See `org-ctrl-c-ctrl-c-hook' for more information.")
18491 (defvar org-shiftdown-final-hook nil
18492 "Hook for functions attaching themselves to `S-down'.
18493 This one runs after all other options except shift-select have been excluded.
18494 See `org-ctrl-c-ctrl-c-hook' for more information.")
18495 (defvar org-shiftleft-hook nil
18496 "Hook for functions attaching themselves to `S-left'.
18497 See `org-ctrl-c-ctrl-c-hook' for more information.")
18498 (defvar org-shiftleft-final-hook nil
18499 "Hook for functions attaching themselves to `S-left'.
18500 This one runs after all other options except shift-select have been excluded.
18501 See `org-ctrl-c-ctrl-c-hook' for more information.")
18502 (defvar org-shiftright-hook nil
18503 "Hook for functions attaching themselves to `S-right'.
18504 See `org-ctrl-c-ctrl-c-hook' for more information.")
18505 (defvar org-shiftright-final-hook nil
18506 "Hook for functions attaching themselves to `S-right'.
18507 This one runs after all other options except shift-select have been excluded.
18508 See `org-ctrl-c-ctrl-c-hook' for more information.")
18510 (defun org-modifier-cursor-error ()
18511 "Throw an error, a modified cursor command was applied in wrong context."
18512 (error "This command is active in special context like tables, headlines or items"))
18514 (defun org-shiftselect-error ()
18515 "Throw an error because Shift-Cursor command was applied in wrong context."
18516 (if (and (boundp 'shift-select-mode) shift-select-mode)
18517 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18518 (error "This command works only in special context like headlines or timestamps")))
18520 (defun org-call-for-shift-select (cmd)
18521 (let ((this-command-keys-shift-translated t))
18522 (call-interactively cmd)))
18524 (defun org-shifttab (&optional arg)
18525 "Global visibility cycling or move to previous table field.
18526 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18527 on context.
18528 See the individual commands for more information."
18529 (interactive "P")
18530 (cond
18531 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18532 ((integerp arg)
18533 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18534 (message "Content view to level: %d" arg)
18535 (org-content (prefix-numeric-value arg2))
18536 (setq org-cycle-global-status 'overview)))
18537 (t (call-interactively 'org-global-cycle))))
18539 (defun org-shiftmetaleft ()
18540 "Promote subtree or delete table column.
18541 Calls `org-promote-subtree', `org-outdent-item-tree', or
18542 `org-table-delete-column', depending on context. See the
18543 individual commands for more information."
18544 (interactive)
18545 (cond
18546 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18547 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18548 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18549 ((if (not (org-region-active-p)) (org-at-item-p)
18550 (save-excursion (goto-char (region-beginning))
18551 (org-at-item-p)))
18552 (call-interactively 'org-outdent-item-tree))
18553 (t (org-modifier-cursor-error))))
18555 (defun org-shiftmetaright ()
18556 "Demote subtree or insert table column.
18557 Calls `org-demote-subtree', `org-indent-item-tree', or
18558 `org-table-insert-column', depending on context. See the
18559 individual commands for more information."
18560 (interactive)
18561 (cond
18562 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18563 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18564 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18565 ((if (not (org-region-active-p)) (org-at-item-p)
18566 (save-excursion (goto-char (region-beginning))
18567 (org-at-item-p)))
18568 (call-interactively 'org-indent-item-tree))
18569 (t (org-modifier-cursor-error))))
18571 (defun org-shiftmetaup (&optional arg)
18572 "Move subtree up or kill table row.
18573 Calls `org-move-subtree-up' or `org-table-kill-row' or
18574 `org-move-item-up' or `org-timestamp-up', depending on context.
18575 See the individual commands for more information."
18576 (interactive "P")
18577 (cond
18578 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18579 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18580 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18581 ((org-at-item-p) (call-interactively 'org-move-item-up))
18582 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18583 (call-interactively 'org-timestamp-up)))
18584 (t (org-modifier-cursor-error))))
18586 (defun org-shiftmetadown (&optional arg)
18587 "Move subtree down or insert table row.
18588 Calls `org-move-subtree-down' or `org-table-insert-row' or
18589 `org-move-item-down' or `org-timestamp-up', depending on context.
18590 See the individual commands for more information."
18591 (interactive "P")
18592 (cond
18593 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18594 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18595 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18596 ((org-at-item-p) (call-interactively 'org-move-item-down))
18597 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18598 (call-interactively 'org-timestamp-down)))
18599 (t (org-modifier-cursor-error))))
18601 (defsubst org-hidden-tree-error ()
18602 (error
18603 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18605 (defun org-metaleft (&optional arg)
18606 "Promote heading or move table column to left.
18607 Calls `org-do-promote' or `org-table-move-column', depending on context.
18608 With no specific context, calls the Emacs default `backward-word'.
18609 See the individual commands for more information."
18610 (interactive "P")
18611 (cond
18612 ((run-hook-with-args-until-success 'org-metaleft-hook))
18613 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18614 ((org-with-limited-levels
18615 (or (org-at-heading-p)
18616 (and (org-region-active-p)
18617 (save-excursion
18618 (goto-char (region-beginning))
18619 (org-at-heading-p)))))
18620 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18621 (call-interactively 'org-do-promote))
18622 ;; At an inline task.
18623 ((org-at-heading-p)
18624 (call-interactively 'org-inlinetask-promote))
18625 ((or (org-at-item-p)
18626 (and (org-region-active-p)
18627 (save-excursion
18628 (goto-char (region-beginning))
18629 (org-at-item-p))))
18630 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18631 (call-interactively 'org-outdent-item))
18632 (t (call-interactively 'backward-word))))
18634 (defun org-metaright (&optional arg)
18635 "Demote a subtree, a list item or move table column to right.
18636 In front of a drawer or a block keyword, indent it correctly.
18637 With no specific context, calls the Emacs default `forward-word'.
18638 See the individual commands for more information."
18639 (interactive "P")
18640 (cond
18641 ((run-hook-with-args-until-success 'org-metaright-hook))
18642 ((org-at-table-p) (call-interactively 'org-table-move-column))
18643 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18644 ((org-at-block-p) (call-interactively 'org-indent-block))
18645 ((org-with-limited-levels
18646 (or (org-at-heading-p)
18647 (and (org-region-active-p)
18648 (save-excursion
18649 (goto-char (region-beginning))
18650 (org-at-heading-p)))))
18651 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18652 (call-interactively 'org-do-demote))
18653 ;; At an inline task.
18654 ((org-at-heading-p)
18655 (call-interactively 'org-inlinetask-demote))
18656 ((or (org-at-item-p)
18657 (and (org-region-active-p)
18658 (save-excursion
18659 (goto-char (region-beginning))
18660 (org-at-item-p))))
18661 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18662 (call-interactively 'org-indent-item))
18663 (t (call-interactively 'forward-word))))
18665 (defun org-check-for-hidden (what)
18666 "Check if there are hidden headlines/items in the current visual line.
18667 WHAT can be either `headlines' or `items'. If the current line is
18668 an outline or item heading and it has a folded subtree below it,
18669 this function returns t, nil otherwise."
18670 (let ((re (cond
18671 ((eq what 'headlines) org-outline-regexp-bol)
18672 ((eq what 'items) (org-item-beginning-re))
18673 (t (error "This should not happen"))))
18674 beg end)
18675 (save-excursion
18676 (catch 'exit
18677 (unless (org-region-active-p)
18678 (setq beg (point-at-bol))
18679 (beginning-of-line 2)
18680 (while (and (not (eobp)) ;; this is like `next-line'
18681 (get-char-property (1- (point)) 'invisible))
18682 (beginning-of-line 2))
18683 (setq end (point))
18684 (goto-char beg)
18685 (goto-char (point-at-eol))
18686 (setq end (max end (point)))
18687 (while (re-search-forward re end t)
18688 (if (get-char-property (match-beginning 0) 'invisible)
18689 (throw 'exit t))))
18690 nil))))
18692 (autoload 'org-element-at-point "org-element")
18693 (autoload 'org-element-type "org-element")
18695 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18696 (declare-function org-element-type "org-element" (element))
18697 (declare-function org-element-contents "org-element" (element))
18698 (declare-function org-element-property "org-element" (property element))
18699 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18700 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18701 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18702 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18703 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18705 (defun org-metaup (&optional arg)
18706 "Move subtree up or move table row up.
18707 Calls `org-move-subtree-up' or `org-table-move-row' or
18708 `org-move-item-up', depending on context. See the individual commands
18709 for more information."
18710 (interactive "P")
18711 (cond
18712 ((run-hook-with-args-until-success 'org-metaup-hook))
18713 ((org-region-active-p)
18714 (let* ((a (min (region-beginning) (region-end)))
18715 (b (1- (max (region-beginning) (region-end))))
18716 (c (save-excursion (goto-char a)
18717 (move-beginning-of-line 0)))
18718 (d (save-excursion (goto-char a)
18719 (move-end-of-line 0) (point))))
18720 (transpose-regions a b c d)
18721 (goto-char c)))
18722 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18723 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18724 ((org-at-item-p) (call-interactively 'org-move-item-up))
18725 (t (org-drag-element-backward))))
18727 (defun org-metadown (&optional arg)
18728 "Move subtree down or move table row down.
18729 Calls `org-move-subtree-down' or `org-table-move-row' or
18730 `org-move-item-down', depending on context. See the individual
18731 commands for more information."
18732 (interactive "P")
18733 (cond
18734 ((run-hook-with-args-until-success 'org-metadown-hook))
18735 ((org-region-active-p)
18736 (let* ((a (min (region-beginning) (region-end)))
18737 (b (max (region-beginning) (region-end)))
18738 (c (save-excursion (goto-char b)
18739 (move-beginning-of-line 1)))
18740 (d (save-excursion (goto-char b)
18741 (move-end-of-line 1) (1+ (point)))))
18742 (transpose-regions a b c d)
18743 (goto-char d)))
18744 ((org-at-table-p) (call-interactively 'org-table-move-row))
18745 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18746 ((org-at-item-p) (call-interactively 'org-move-item-down))
18747 (t (org-drag-element-forward))))
18749 (defun org-shiftup (&optional arg)
18750 "Increase item in timestamp or increase priority of current headline.
18751 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18752 depending on context. See the individual commands for more information."
18753 (interactive "P")
18754 (cond
18755 ((run-hook-with-args-until-success 'org-shiftup-hook))
18756 ((and org-support-shift-select (org-region-active-p))
18757 (org-call-for-shift-select 'previous-line))
18758 ((org-at-timestamp-p t)
18759 (call-interactively (if org-edit-timestamp-down-means-later
18760 'org-timestamp-down 'org-timestamp-up)))
18761 ((and (not (eq org-support-shift-select 'always))
18762 org-enable-priority-commands
18763 (org-at-heading-p))
18764 (call-interactively 'org-priority-up))
18765 ((and (not org-support-shift-select) (org-at-item-p))
18766 (call-interactively 'org-previous-item))
18767 ((org-clocktable-try-shift 'up arg))
18768 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18769 (org-support-shift-select
18770 (org-call-for-shift-select 'previous-line))
18771 (t (org-shiftselect-error))))
18773 (defun org-shiftdown (&optional arg)
18774 "Decrease item in timestamp or decrease priority of current headline.
18775 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18776 depending on context. See the individual commands for more information."
18777 (interactive "P")
18778 (cond
18779 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18780 ((and org-support-shift-select (org-region-active-p))
18781 (org-call-for-shift-select 'next-line))
18782 ((org-at-timestamp-p t)
18783 (call-interactively (if org-edit-timestamp-down-means-later
18784 'org-timestamp-up 'org-timestamp-down)))
18785 ((and (not (eq org-support-shift-select 'always))
18786 org-enable-priority-commands
18787 (org-at-heading-p))
18788 (call-interactively 'org-priority-down))
18789 ((and (not org-support-shift-select) (org-at-item-p))
18790 (call-interactively 'org-next-item))
18791 ((org-clocktable-try-shift 'down arg))
18792 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18793 (org-support-shift-select
18794 (org-call-for-shift-select 'next-line))
18795 (t (org-shiftselect-error))))
18797 (defun org-shiftright (&optional arg)
18798 "Cycle the thing at point or in the current line, depending on context.
18799 Depending on context, this does one of the following:
18801 - switch a timestamp at point one day into the future
18802 - on a headline, switch to the next TODO keyword.
18803 - on an item, switch entire list to the next bullet type
18804 - on a property line, switch to the next allowed value
18805 - on a clocktable definition line, move time block into the future"
18806 (interactive "P")
18807 (cond
18808 ((run-hook-with-args-until-success 'org-shiftright-hook))
18809 ((and org-support-shift-select (org-region-active-p))
18810 (org-call-for-shift-select 'forward-char))
18811 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18812 ((and (not (eq org-support-shift-select 'always))
18813 (org-at-heading-p))
18814 (let ((org-inhibit-logging
18815 (not org-treat-S-cursor-todo-selection-as-state-change))
18816 (org-inhibit-blocking
18817 (not org-treat-S-cursor-todo-selection-as-state-change)))
18818 (org-call-with-arg 'org-todo 'right)))
18819 ((or (and org-support-shift-select
18820 (not (eq org-support-shift-select 'always))
18821 (org-at-item-bullet-p))
18822 (and (not org-support-shift-select) (org-at-item-p)))
18823 (org-call-with-arg 'org-cycle-list-bullet nil))
18824 ((and (not (eq org-support-shift-select 'always))
18825 (org-at-property-p))
18826 (call-interactively 'org-property-next-allowed-value))
18827 ((org-clocktable-try-shift 'right arg))
18828 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18829 (org-support-shift-select
18830 (org-call-for-shift-select 'forward-char))
18831 (t (org-shiftselect-error))))
18833 (defun org-shiftleft (&optional arg)
18834 "Cycle the thing at point or in the current line, depending on context.
18835 Depending on context, this does one of the following:
18837 - switch a timestamp at point one day into the past
18838 - on a headline, switch to the previous TODO keyword.
18839 - on an item, switch entire list to the previous bullet type
18840 - on a property line, switch to the previous allowed value
18841 - on a clocktable definition line, move time block into the past"
18842 (interactive "P")
18843 (cond
18844 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18845 ((and org-support-shift-select (org-region-active-p))
18846 (org-call-for-shift-select 'backward-char))
18847 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18848 ((and (not (eq org-support-shift-select 'always))
18849 (org-at-heading-p))
18850 (let ((org-inhibit-logging
18851 (not org-treat-S-cursor-todo-selection-as-state-change))
18852 (org-inhibit-blocking
18853 (not org-treat-S-cursor-todo-selection-as-state-change)))
18854 (org-call-with-arg 'org-todo 'left)))
18855 ((or (and org-support-shift-select
18856 (not (eq org-support-shift-select 'always))
18857 (org-at-item-bullet-p))
18858 (and (not org-support-shift-select) (org-at-item-p)))
18859 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18860 ((and (not (eq org-support-shift-select 'always))
18861 (org-at-property-p))
18862 (call-interactively 'org-property-previous-allowed-value))
18863 ((org-clocktable-try-shift 'left arg))
18864 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18865 (org-support-shift-select
18866 (org-call-for-shift-select 'backward-char))
18867 (t (org-shiftselect-error))))
18869 (defun org-shiftcontrolright ()
18870 "Switch to next TODO set."
18871 (interactive)
18872 (cond
18873 ((and org-support-shift-select (org-region-active-p))
18874 (org-call-for-shift-select 'forward-word))
18875 ((and (not (eq org-support-shift-select 'always))
18876 (org-at-heading-p))
18877 (org-call-with-arg 'org-todo 'nextset))
18878 (org-support-shift-select
18879 (org-call-for-shift-select 'forward-word))
18880 (t (org-shiftselect-error))))
18882 (defun org-shiftcontrolleft ()
18883 "Switch to previous TODO set."
18884 (interactive)
18885 (cond
18886 ((and org-support-shift-select (org-region-active-p))
18887 (org-call-for-shift-select 'backward-word))
18888 ((and (not (eq org-support-shift-select 'always))
18889 (org-at-heading-p))
18890 (org-call-with-arg 'org-todo 'previousset))
18891 (org-support-shift-select
18892 (org-call-for-shift-select 'backward-word))
18893 (t (org-shiftselect-error))))
18895 (defun org-shiftcontrolup ()
18896 "Change timestamps synchronously up in CLOCK log lines."
18897 (interactive)
18898 (cond ((and (not org-support-shift-select)
18899 (org-at-clock-log-p)
18900 (org-at-timestamp-p t))
18901 (org-clock-timestamps-up))
18902 (t (org-shiftselect-error))))
18904 (defun org-shiftcontroldown ()
18905 "Change timestamps synchronously down in CLOCK log lines."
18906 (interactive)
18907 (cond ((and (not org-support-shift-select)
18908 (org-at-clock-log-p)
18909 (org-at-timestamp-p t))
18910 (org-clock-timestamps-down))
18911 (t (org-shiftselect-error))))
18913 (defun org-ctrl-c-ret ()
18914 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18915 (interactive)
18916 (cond
18917 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18918 (t (call-interactively 'org-insert-heading))))
18920 (defun org-find-visible ()
18921 (let ((s (point)))
18922 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18923 (get-char-property s 'invisible)))
18925 (defun org-find-invisible ()
18926 (let ((s (point)))
18927 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18928 (not (get-char-property s 'invisible))))
18931 (defun org-copy-visible (beg end)
18932 "Copy the visible parts of the region."
18933 (interactive "r")
18934 (let (snippets s)
18935 (save-excursion
18936 (save-restriction
18937 (narrow-to-region beg end)
18938 (setq s (goto-char (point-min)))
18939 (while (not (= (point) (point-max)))
18940 (goto-char (org-find-invisible))
18941 (push (buffer-substring s (point)) snippets)
18942 (setq s (goto-char (org-find-visible))))))
18943 (kill-new (apply 'concat (nreverse snippets)))))
18945 (defun org-copy-special ()
18946 "Copy region in table or copy current subtree.
18947 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18948 See the individual commands for more information."
18949 (interactive)
18950 (call-interactively
18951 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18953 (defun org-cut-special ()
18954 "Cut region in table or cut current subtree.
18955 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18956 See the individual commands for more information."
18957 (interactive)
18958 (call-interactively
18959 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18961 (defun org-paste-special (arg)
18962 "Paste rectangular region into table, or past subtree relative to level.
18963 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18964 See the individual commands for more information."
18965 (interactive "P")
18966 (if (org-at-table-p)
18967 (org-table-paste-rectangle)
18968 (org-paste-subtree arg)))
18970 (defsubst org-in-fixed-width-region-p ()
18971 "Is point in a fixed-width region?"
18972 (save-match-data
18973 (eq 'fixed-width (org-element-type (org-element-at-point)))))
18975 (defun org-edit-special (&optional arg)
18976 "Call a special editor for the stuff at point.
18977 When at a table, call the formula editor with `org-table-edit-formulas'.
18978 When in a source code block, call `org-edit-src-code'.
18979 When in a fixed-width region, call `org-edit-fixed-width-region'.
18980 When in an #+include line, visit the included file.
18981 On a link, call `ffap' to visit the link at point.
18982 Otherwise, return a user error."
18983 (interactive)
18984 ;; possibly prep session before editing source
18985 (when (and (org-in-src-block-p) arg)
18986 (let* ((info (org-babel-get-src-block-info))
18987 (lang (nth 0 info))
18988 (params (nth 2 info))
18989 (session (cdr (assoc :session params))))
18990 (when (and info session) ;; we are in a source-code block with a session
18991 (funcall
18992 (intern (concat "org-babel-prep-session:" lang)) session params))))
18993 (cond ;; proceed with `org-edit-special'
18994 ((save-excursion
18995 (beginning-of-line 1)
18996 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18997 (find-file (org-trim (match-string 1))))
18998 ((or (org-at-table-p)
18999 (save-excursion
19000 (beginning-of-line 1)
19001 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19002 (call-interactively 'org-table-edit-formulas))
19003 ((or (org-in-block-p '("src" "example" "latex" "html"))
19004 (org-at-table.el-p))
19005 (org-edit-src-code))
19006 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19007 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19008 (t (user-error "No special environment to edit here"))))
19010 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19011 (defun org-ctrl-c-ctrl-c (&optional arg)
19012 "Set tags in headline, or update according to changed information at point.
19014 This command does many different things, depending on context:
19016 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19017 this is what we do.
19019 - If the cursor is on a statistics cookie, update it.
19021 - If the cursor is in a headline, prompt for tags and insert them
19022 into the current line, aligned to `org-tags-column'. When called
19023 with prefix arg, realign all tags in the current buffer.
19025 - If the cursor is in one of the special #+KEYWORD lines, this
19026 triggers scanning the buffer for these lines and updating the
19027 information.
19029 - If the cursor is inside a table, realign the table. This command
19030 works even if the automatic table editor has been turned off.
19032 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19033 the entire table.
19035 - If the cursor is at a footnote reference or definition, jump to
19036 the corresponding definition or references, respectively.
19038 - If the cursor is a the beginning of a dynamic block, update it.
19040 - If the current buffer is a capture buffer, close note and file it.
19042 - If the cursor is on a <<<target>>>, update radio targets and
19043 corresponding links in this buffer.
19045 - If the cursor is on a numbered item in a plain list, renumber the
19046 ordered list.
19048 - If the cursor is on a checkbox, toggle it.
19050 - If the cursor is on a code block, evaluate it. The variable
19051 `org-confirm-babel-evaluate' can be used to control prompting
19052 before code block evaluation, by default every code block
19053 evaluation requires confirmation. Code block evaluation can be
19054 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19055 (interactive "P")
19056 (let ((org-enable-table-editor t))
19057 (cond
19058 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19059 org-occur-highlights
19060 org-latex-fragment-image-overlays)
19061 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19062 (org-remove-occur-highlights)
19063 (org-remove-latex-fragment-image-overlays)
19064 (message "Temporary highlights/overlays removed from current buffer"))
19065 ((and (local-variable-p 'org-finish-function (current-buffer))
19066 (fboundp org-finish-function))
19067 (funcall org-finish-function))
19068 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19069 ((org-in-regexp org-ts-regexp-both)
19070 (org-timestamp-change 0 'day))
19071 ((or (looking-at org-property-start-re)
19072 (org-at-property-p))
19073 (call-interactively 'org-property-action))
19074 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19075 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19076 (or (org-at-heading-p) (org-at-item-p)))
19077 (call-interactively 'org-update-statistics-cookies))
19078 ((org-at-heading-p) (call-interactively 'org-set-tags))
19079 ((org-at-table.el-p)
19080 (message "Use C-c ' to edit table.el tables"))
19081 ((org-at-table-p)
19082 (org-table-maybe-eval-formula)
19083 (if arg
19084 (call-interactively 'org-table-recalculate)
19085 (org-table-maybe-recalculate-line))
19086 (call-interactively 'org-table-align)
19087 (orgtbl-send-table 'maybe))
19088 ((or (org-footnote-at-reference-p)
19089 (org-footnote-at-definition-p))
19090 (call-interactively 'org-footnote-action))
19091 ((org-at-item-checkbox-p)
19092 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19093 ;; list only if at top item.
19094 (let* ((cbox (match-string 1))
19095 (struct (org-list-struct))
19096 (old-struct (copy-tree struct))
19097 (parents (org-list-parents-alist struct))
19098 (orderedp (org-entry-get nil "ORDERED"))
19099 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19100 block-item)
19101 ;; Use a light version of `org-toggle-checkbox' to avoid
19102 ;; computing list structure twice.
19103 (let ((new-box (cond
19104 ((equal arg '(16)) "[-]")
19105 ((equal arg '(4)) nil)
19106 ((equal "[X]" cbox) "[ ]")
19107 (t "[X]"))))
19108 (if (and firstp arg)
19109 ;; If at first item of sub-list, remove check-box from
19110 ;; every item at the same level.
19111 (mapc
19112 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19113 (org-list-get-all-items
19114 (point-at-bol) struct (org-list-prevs-alist struct)))
19115 (org-list-set-checkbox (point-at-bol) struct new-box)))
19116 ;; Replicate `org-list-write-struct', while grabbing a return
19117 ;; value from `org-list-struct-fix-box'.
19118 (org-list-struct-fix-ind struct parents 2)
19119 (org-list-struct-fix-item-end struct)
19120 (let ((prevs (org-list-prevs-alist struct)))
19121 (org-list-struct-fix-bul struct prevs)
19122 (org-list-struct-fix-ind struct parents)
19123 (setq block-item
19124 (org-list-struct-fix-box struct parents prevs orderedp)))
19125 (org-list-struct-apply-struct struct old-struct)
19126 (org-update-checkbox-count-maybe)
19127 (when block-item
19128 (message
19129 "Checkboxes were removed due to unchecked box at line %d"
19130 (org-current-line block-item)))
19131 (when firstp (org-list-send-list 'maybe))))
19132 ((org-at-item-p)
19133 ;; Cursor at an item: repair list. Do checkbox related actions
19134 ;; only if function was called with an argument. Send list only
19135 ;; if at top item.
19136 (let* ((struct (org-list-struct))
19137 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19138 old-struct)
19139 (when arg
19140 (setq old-struct (copy-tree struct))
19141 (if firstp
19142 ;; If at first item of sub-list, add check-box to every
19143 ;; item at the same level.
19144 (mapc
19145 (lambda (pos)
19146 (unless (org-list-get-checkbox pos struct)
19147 (org-list-set-checkbox pos struct "[ ]")))
19148 (org-list-get-all-items
19149 (point-at-bol) struct (org-list-prevs-alist struct)))
19150 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19151 (org-list-write-struct
19152 struct (org-list-parents-alist struct) old-struct)
19153 (when arg (org-update-checkbox-count-maybe))
19154 (when firstp (org-list-send-list 'maybe))))
19155 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19156 ;; Dynamic block
19157 (beginning-of-line 1)
19158 (save-excursion (org-update-dblock)))
19159 ((save-excursion
19160 (let ((case-fold-search t))
19161 (beginning-of-line 1)
19162 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19163 (cond
19164 ((or (equal (match-string 1) "TBLFM")
19165 (equal (match-string 1) "tblfm"))
19166 ;; Recalculate the table before this line
19167 (save-excursion
19168 (beginning-of-line 1)
19169 (skip-chars-backward " \r\n\t")
19170 (if (org-at-table-p)
19171 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19173 (let ((org-inhibit-startup-visibility-stuff t)
19174 (org-startup-align-all-tables nil))
19175 (when (boundp 'org-table-coordinate-overlays)
19176 (mapc 'delete-overlay org-table-coordinate-overlays)
19177 (setq org-table-coordinate-overlays nil))
19178 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19179 (message "Local setup has been refreshed"))))
19180 ((org-clock-update-time-maybe))
19182 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19183 (error "C-c C-c can do nothing useful at this location"))))))
19185 (defun org-mode-restart ()
19186 "Restart Org-mode, to scan again for special lines.
19187 Also updates the keyword regular expressions."
19188 (interactive)
19189 (org-mode)
19190 (message "Org-mode restarted"))
19192 (defun org-kill-note-or-show-branches ()
19193 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19194 (interactive)
19195 (if (not org-finish-function)
19196 (progn
19197 (hide-subtree)
19198 (call-interactively 'show-branches))
19199 (let ((org-note-abort t))
19200 (funcall org-finish-function))))
19202 (defun org-return (&optional indent)
19203 "Goto next table row or insert a newline.
19204 Calls `org-table-next-row' or `newline', depending on context.
19205 See the individual commands for more information."
19206 (interactive)
19207 (let (org-ts-what)
19208 (cond
19209 ((or (bobp) (org-in-src-block-p))
19210 (if indent (newline-and-indent) (newline)))
19211 ((org-at-table-p)
19212 (org-table-justify-field-maybe)
19213 (call-interactively 'org-table-next-row))
19214 ;; when `newline-and-indent' is called within a list, make sure
19215 ;; text moved stays inside the item.
19216 ((and (org-in-item-p) indent)
19217 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19218 (progn
19219 (save-match-data (newline))
19220 (org-indent-line-to (length (match-string 0))))
19221 (let ((ind (org-get-indentation)))
19222 (newline)
19223 (if (org-looking-back org-list-end-re)
19224 (org-indent-line)
19225 (org-indent-line-to ind)))))
19226 ((and org-return-follows-link
19227 (org-at-timestamp-p t)
19228 (not (eq org-ts-what 'after)))
19229 (org-follow-timestamp-link))
19230 ((and org-return-follows-link
19231 (let ((tprop (get-text-property (point) 'face)))
19232 (or (eq tprop 'org-link)
19233 (and (listp tprop) (memq 'org-link tprop)))))
19234 (call-interactively 'org-open-at-point))
19235 ((and (org-at-heading-p)
19236 (looking-at
19237 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19238 (org-show-entry)
19239 (end-of-line 1)
19240 (newline))
19241 (t (if indent (newline-and-indent) (newline))))))
19243 (defun org-return-indent ()
19244 "Goto next table row or insert a newline and indent.
19245 Calls `org-table-next-row' or `newline-and-indent', depending on
19246 context. See the individual commands for more information."
19247 (interactive)
19248 (org-return t))
19250 (defun org-ctrl-c-star ()
19251 "Compute table, or change heading status of lines.
19252 Calls `org-table-recalculate' or `org-toggle-heading',
19253 depending on context."
19254 (interactive)
19255 (cond
19256 ((org-at-table-p)
19257 (call-interactively 'org-table-recalculate))
19259 ;; Convert all lines in region to list items
19260 (call-interactively 'org-toggle-heading))))
19262 (defun org-ctrl-c-minus ()
19263 "Insert separator line in table or modify bullet status of line.
19264 Also turns a plain line or a region of lines into list items.
19265 Calls `org-table-insert-hline', `org-toggle-item', or
19266 `org-cycle-list-bullet', depending on context."
19267 (interactive)
19268 (cond
19269 ((org-at-table-p)
19270 (call-interactively 'org-table-insert-hline))
19271 ((org-region-active-p)
19272 (call-interactively 'org-toggle-item))
19273 ((org-in-item-p)
19274 (call-interactively 'org-cycle-list-bullet))
19276 (call-interactively 'org-toggle-item))))
19278 (defun org-toggle-item (arg)
19279 "Convert headings or normal lines to items, items to normal lines.
19280 If there is no active region, only the current line is considered.
19282 If the first non blank line in the region is an headline, convert
19283 all headlines to items, shifting text accordingly.
19285 If it is an item, convert all items to normal lines.
19287 If it is normal text, change region into an item. With a prefix
19288 argument ARG, change each line in region into an item."
19289 (interactive "P")
19290 (let ((shift-text
19291 (function
19292 ;; Shift text in current section to IND, from point to END.
19293 ;; The function leaves point to END line.
19294 (lambda (ind end)
19295 (let ((min-i 1000) (end (copy-marker end)))
19296 ;; First determine the minimum indentation (MIN-I) of
19297 ;; the text.
19298 (save-excursion
19299 (catch 'exit
19300 (while (< (point) end)
19301 (let ((i (org-get-indentation)))
19302 (cond
19303 ;; Skip blank lines and inline tasks.
19304 ((looking-at "^[ \t]*$"))
19305 ((looking-at org-outline-regexp-bol))
19306 ;; We can't find less than 0 indentation.
19307 ((zerop i) (throw 'exit (setq min-i 0)))
19308 ((< i min-i) (setq min-i i))))
19309 (forward-line))))
19310 ;; Then indent each line so that a line indented to
19311 ;; MIN-I becomes indented to IND. Ignore blank lines
19312 ;; and inline tasks in the process.
19313 (let ((delta (- ind min-i)))
19314 (while (< (point) end)
19315 (unless (or (looking-at "^[ \t]*$")
19316 (looking-at org-outline-regexp-bol))
19317 (org-indent-line-to (+ (org-get-indentation) delta)))
19318 (forward-line)))))))
19319 (skip-blanks
19320 (function
19321 ;; Return beginning of first non-blank line, starting from
19322 ;; line at POS.
19323 (lambda (pos)
19324 (save-excursion
19325 (goto-char pos)
19326 (skip-chars-forward " \r\t\n")
19327 (point-at-bol)))))
19328 beg end)
19329 ;; Determine boundaries of changes.
19330 (if (org-region-active-p)
19331 (setq beg (funcall skip-blanks (region-beginning))
19332 end (copy-marker (region-end)))
19333 (setq beg (funcall skip-blanks (point-at-bol))
19334 end (copy-marker (point-at-eol))))
19335 ;; Depending on the starting line, choose an action on the text
19336 ;; between BEG and END.
19337 (org-with-limited-levels
19338 (save-excursion
19339 (goto-char beg)
19340 (cond
19341 ;; Case 1. Start at an item: de-itemize. Note that it only
19342 ;; happens when a region is active: `org-ctrl-c-minus'
19343 ;; would call `org-cycle-list-bullet' otherwise.
19344 ((org-at-item-p)
19345 (while (< (point) end)
19346 (when (org-at-item-p)
19347 (skip-chars-forward " \t")
19348 (delete-region (point) (match-end 0)))
19349 (forward-line)))
19350 ;; Case 2. Start at an heading: convert to items.
19351 ((org-at-heading-p)
19352 (let* ((bul (org-list-bullet-string "-"))
19353 (bul-len (length bul))
19354 ;; Indentation of the first heading. It should be
19355 ;; relative to the indentation of its parent, if any.
19356 (start-ind (save-excursion
19357 (cond
19358 ((not org-adapt-indentation) 0)
19359 ((not (outline-previous-heading)) 0)
19360 (t (length (match-string 0))))))
19361 ;; Level of first heading. Further headings will be
19362 ;; compared to it to determine hierarchy in the list.
19363 (ref-level (org-reduced-level (org-outline-level))))
19364 (while (< (point) end)
19365 (let* ((level (org-reduced-level (org-outline-level)))
19366 (delta (max 0 (- level ref-level))))
19367 ;; If current headline is less indented than the first
19368 ;; one, set it as reference, in order to preserve
19369 ;; subtrees.
19370 (when (< level ref-level) (setq ref-level level))
19371 (replace-match bul t t)
19372 (org-indent-line-to (+ start-ind (* delta bul-len)))
19373 ;; Ensure all text down to END (or SECTION-END) belongs
19374 ;; to the newly created item.
19375 (let ((section-end (save-excursion
19376 (or (outline-next-heading) (point)))))
19377 (forward-line)
19378 (funcall shift-text
19379 (+ start-ind (* (1+ delta) bul-len))
19380 (min end section-end)))))))
19381 ;; Case 3. Normal line with ARG: turn each non-item line into
19382 ;; an item.
19383 (arg
19384 (while (< (point) end)
19385 (unless (or (org-at-heading-p) (org-at-item-p))
19386 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19387 (replace-match
19388 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19389 (forward-line)))
19390 ;; Case 4. Normal line without ARG: make the first line of
19391 ;; region an item, and shift indentation of others
19392 ;; lines to set them as item's body.
19393 (t (let* ((bul (org-list-bullet-string "-"))
19394 (bul-len (length bul))
19395 (ref-ind (org-get-indentation)))
19396 (skip-chars-forward " \t")
19397 (insert bul)
19398 (forward-line)
19399 (while (< (point) end)
19400 ;; Ensure that lines less indented than first one
19401 ;; still get included in item body.
19402 (funcall shift-text
19403 (+ ref-ind bul-len)
19404 (min end (save-excursion (or (outline-next-heading)
19405 (point)))))
19406 (forward-line)))))))))
19408 (defun org-toggle-heading (&optional nstars)
19409 "Convert headings to normal text, or items or text to headings.
19410 If there is no active region, only the current line is considered.
19412 With a \\[universal-argument] prefix, convert the whole list at
19413 point into heading.
19415 In a region:
19417 - If the first non blank line is an headline, remove the stars
19418 from all headlines in the region.
19420 - If it is a normal line turn each and every normal line (i.e. not an
19421 heading or an item) in the region into a heading.
19423 - If it is a plain list item, turn all plain list items into headings.
19425 When converting a line into a heading, the number of stars is chosen
19426 such that the lines become children of the current entry. However,
19427 when a prefix argument is given, its value determines the number of
19428 stars to add."
19429 (interactive "P")
19430 (let ((skip-blanks
19431 (function
19432 ;; Return beginning of first non-blank line, starting from
19433 ;; line at POS.
19434 (lambda (pos)
19435 (save-excursion
19436 (goto-char pos)
19437 (while (org-at-comment-p) (forward-line))
19438 (skip-chars-forward " \r\t\n")
19439 (point-at-bol)))))
19440 beg end toggled)
19441 ;; Determine boundaries of changes. If a universal prefix has
19442 ;; been given, put the list in a region. If region ends at a bol,
19443 ;; do not consider the last line to be in the region.
19445 (when (and current-prefix-arg (org-at-item-p))
19446 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19447 (org-mark-element))
19449 (if (org-region-active-p)
19450 (setq beg (funcall skip-blanks (region-beginning))
19451 end (copy-marker (save-excursion
19452 (goto-char (region-end))
19453 (if (bolp) (point) (point-at-eol)))))
19454 (setq beg (funcall skip-blanks (point-at-bol))
19455 end (copy-marker (point-at-eol))))
19456 ;; Ensure inline tasks don't count as headings.
19457 (org-with-limited-levels
19458 (save-excursion
19459 (goto-char beg)
19460 (cond
19461 ;; Case 1. Started at an heading: de-star headings.
19462 ((org-at-heading-p)
19463 (while (< (point) end)
19464 (when (org-at-heading-p t)
19465 (looking-at org-outline-regexp) (replace-match "")
19466 (setq toggled t))
19467 (forward-line)))
19468 ;; Case 2. Started at an item: change items into headlines.
19469 ;; One star will be added by `org-list-to-subtree'.
19470 ((org-at-item-p)
19471 (let* ((stars (make-string
19472 (if nstars
19473 ;; subtract the star that will be added again by
19474 ;; `org-list-to-subtree'
19475 (1- (prefix-numeric-value current-prefix-arg))
19476 (or (org-current-level) 0))
19477 ?*))
19478 (add-stars
19479 (cond (nstars "") ; stars from prefix only
19480 ((equal stars "") "") ; before first heading
19481 (org-odd-levels-only "*") ; inside heading, odd
19482 (t "")))) ; inside heading, oddeven
19483 (while (< (point) end)
19484 (when (org-at-item-p)
19485 ;; Pay attention to cases when region ends before list.
19486 (let* ((struct (org-list-struct))
19487 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19488 (save-restriction
19489 (narrow-to-region (point) list-end)
19490 (insert
19491 (org-list-to-subtree
19492 (org-list-parse-list t)
19493 '(:istart (concat stars add-stars (funcall get-stars depth))
19494 :icount (concat stars add-stars (funcall get-stars depth)))))))
19495 (setq toggled t))
19496 (forward-line))))
19497 ;; Case 3. Started at normal text: make every line an heading,
19498 ;; skipping headlines and items.
19499 (t (let* ((stars (make-string
19500 (if nstars
19501 (prefix-numeric-value current-prefix-arg)
19502 (or (org-current-level) 0))
19503 ?*))
19504 (add-stars
19505 (cond (nstars "") ; stars from prefix only
19506 ((equal stars "") "*") ; before first heading
19507 (org-odd-levels-only "**") ; inside heading, odd
19508 (t "*"))) ; inside heading, oddeven
19509 (rpl (concat stars add-stars " ")))
19510 (while (< (point) end)
19511 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19512 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19513 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19514 (forward-line)))))))
19515 (unless toggled (message "Cannot toggle heading from here"))))
19517 (defun org-meta-return (&optional arg)
19518 "Insert a new heading or wrap a region in a table.
19519 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19520 See the individual commands for more information."
19521 (interactive "P")
19522 (cond
19523 ((run-hook-with-args-until-success 'org-metareturn-hook))
19524 ((or (org-at-drawer-p) (org-at-property-p))
19525 (newline-and-indent))
19526 ((org-at-table-p)
19527 (call-interactively 'org-table-wrap-region))
19528 (t (call-interactively 'org-insert-heading))))
19530 ;;; Menu entries
19532 (defsubst org-in-subtree-not-table-p ()
19533 "Are we in a subtree and not in a table?"
19534 (and (not (org-before-first-heading-p))
19535 (not (org-at-table-p))))
19537 ;; Define the Org-mode menus
19538 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19539 '("Tbl"
19540 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19541 ["Next Field" org-cycle (org-at-table-p)]
19542 ["Previous Field" org-shifttab (org-at-table-p)]
19543 ["Next Row" org-return (org-at-table-p)]
19544 "--"
19545 ["Blank Field" org-table-blank-field (org-at-table-p)]
19546 ["Edit Field" org-table-edit-field (org-at-table-p)]
19547 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19548 "--"
19549 ("Column"
19550 ["Move Column Left" org-metaleft (org-at-table-p)]
19551 ["Move Column Right" org-metaright (org-at-table-p)]
19552 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19553 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19554 ("Row"
19555 ["Move Row Up" org-metaup (org-at-table-p)]
19556 ["Move Row Down" org-metadown (org-at-table-p)]
19557 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19558 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19559 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19560 "--"
19561 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19562 ("Rectangle"
19563 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19564 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19565 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19566 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19567 "--"
19568 ("Calculate"
19569 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19570 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19571 ["Edit Formulas" org-edit-special (org-at-table-p)]
19572 "--"
19573 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19574 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19575 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19576 "--"
19577 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19578 "--"
19579 ["Sum Column/Rectangle" org-table-sum
19580 (or (org-at-table-p) (org-region-active-p))]
19581 ["Which Column?" org-table-current-column (org-at-table-p)])
19582 ["Debug Formulas"
19583 org-table-toggle-formula-debugger
19584 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19585 ["Show Col/Row Numbers"
19586 org-table-toggle-coordinate-overlays
19587 :style toggle
19588 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19589 "--"
19590 ["Create" org-table-create (and (not (org-at-table-p))
19591 org-enable-table-editor)]
19592 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19593 ["Import from File" org-table-import (not (org-at-table-p))]
19594 ["Export to File" org-table-export (org-at-table-p)]
19595 "--"
19596 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19598 (easy-menu-define org-org-menu org-mode-map "Org menu"
19599 '("Org"
19600 ("Show/Hide"
19601 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19602 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19603 ["Sparse Tree..." org-sparse-tree t]
19604 ["Reveal Context" org-reveal t]
19605 ["Show All" show-all t]
19606 "--"
19607 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19608 "--"
19609 ["New Heading" org-insert-heading t]
19610 ("Navigate Headings"
19611 ["Up" outline-up-heading t]
19612 ["Next" outline-next-visible-heading t]
19613 ["Previous" outline-previous-visible-heading t]
19614 ["Next Same Level" outline-forward-same-level t]
19615 ["Previous Same Level" outline-backward-same-level t]
19616 "--"
19617 ["Jump" org-goto t])
19618 ("Edit Structure"
19619 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19620 "--"
19621 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19622 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19623 "--"
19624 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19625 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19626 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19627 "--"
19628 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19629 "--"
19630 ["Copy visible text" org-copy-visible t]
19631 "--"
19632 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19633 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19634 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19635 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19636 "--"
19637 ["Sort Region/Children" org-sort t]
19638 "--"
19639 ["Convert to odd levels" org-convert-to-odd-levels t]
19640 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19641 ("Editing"
19642 ["Emphasis..." org-emphasize t]
19643 ["Edit Source Example" org-edit-special t]
19644 "--"
19645 ["Footnote new/jump" org-footnote-action t]
19646 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19647 ("Archive"
19648 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19649 "--"
19650 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19651 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19652 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19654 "--"
19655 ("Hyperlinks"
19656 ["Store Link (Global)" org-store-link t]
19657 ["Find existing link to here" org-occur-link-in-agenda-files t]
19658 ["Insert Link" org-insert-link t]
19659 ["Follow Link" org-open-at-point t]
19660 "--"
19661 ["Next link" org-next-link t]
19662 ["Previous link" org-previous-link t]
19663 "--"
19664 ["Descriptive Links"
19665 org-toggle-link-display
19666 :style radio
19667 :selected org-descriptive-links
19669 ["Literal Links"
19670 org-toggle-link-display
19671 :style radio
19672 :selected (not org-descriptive-links)])
19673 "--"
19674 ("TODO Lists"
19675 ["TODO/DONE/-" org-todo t]
19676 ("Select keyword"
19677 ["Next keyword" org-shiftright (org-at-heading-p)]
19678 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19679 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19680 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19681 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19682 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19683 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19684 "--"
19685 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19686 :selected org-enforce-todo-dependencies :style toggle :active t]
19687 "Settings for tree at point"
19688 ["Do Children sequentially" org-toggle-ordered-property :style radio
19689 :selected (org-entry-get nil "ORDERED")
19690 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19691 ["Do Children parallel" org-toggle-ordered-property :style radio
19692 :selected (not (org-entry-get nil "ORDERED"))
19693 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19694 "--"
19695 ["Set Priority" org-priority t]
19696 ["Priority Up" org-shiftup t]
19697 ["Priority Down" org-shiftdown t]
19698 "--"
19699 ["Get news from all feeds" org-feed-update-all t]
19700 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19701 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19702 ("TAGS and Properties"
19703 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19704 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19705 "--"
19706 ["Set property" org-set-property (not (org-before-first-heading-p))]
19707 ["Column view of properties" org-columns t]
19708 ["Insert Column View DBlock" org-insert-columns-dblock t])
19709 ("Dates and Scheduling"
19710 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19711 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19712 ("Change Date"
19713 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19714 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19715 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19716 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19717 ["Compute Time Range" org-evaluate-time-range t]
19718 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19719 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19720 "--"
19721 ["Custom time format" org-toggle-time-stamp-overlays
19722 :style radio :selected org-display-custom-times]
19723 "--"
19724 ["Goto Calendar" org-goto-calendar t]
19725 ["Date from Calendar" org-date-from-calendar t]
19726 "--"
19727 ["Start/Restart Timer" org-timer-start t]
19728 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19729 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19730 ["Insert Timer String" org-timer t]
19731 ["Insert Timer Item" org-timer-item t])
19732 ("Logging work"
19733 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19734 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19735 ["Clock out" org-clock-out t]
19736 ["Clock cancel" org-clock-cancel t]
19737 "--"
19738 ["Mark as default task" org-clock-mark-default-task t]
19739 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19740 ["Goto running clock" org-clock-goto t]
19741 "--"
19742 ["Display times" org-clock-display t]
19743 ["Create clock table" org-clock-report t]
19744 "--"
19745 ["Record DONE time"
19746 (progn (setq org-log-done (not org-log-done))
19747 (message "Switching to %s will %s record a timestamp"
19748 (car org-done-keywords)
19749 (if org-log-done "automatically" "not")))
19750 :style toggle :selected org-log-done])
19751 "--"
19752 ["Agenda Command..." org-agenda t]
19753 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19754 ("File List for Agenda")
19755 ("Special views current file"
19756 ["TODO Tree" org-show-todo-tree t]
19757 ["Check Deadlines" org-check-deadlines t]
19758 ["Timeline" org-timeline t]
19759 ["Tags/Property tree" org-match-sparse-tree t])
19760 "--"
19761 ["Export/Publish..." org-export t]
19762 ("LaTeX"
19763 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19764 :selected org-cdlatex-mode]
19765 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19766 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19767 ["Modify math symbol" org-cdlatex-math-modify
19768 (org-inside-LaTeX-fragment-p)]
19769 ["Insert citation" org-reftex-citation t]
19770 "--"
19771 ["Template for BEAMER" (progn (require 'org-beamer)
19772 (org-insert-beamer-options-template)) t])
19773 "--"
19774 ("MobileOrg"
19775 ["Push Files and Views" org-mobile-push t]
19776 ["Get Captured and Flagged" org-mobile-pull t]
19777 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19778 "--"
19779 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19780 "--"
19781 ("Documentation"
19782 ["Show Version" org-version t]
19783 ["Info Documentation" org-info t])
19784 ("Customize"
19785 ["Browse Org Group" org-customize t]
19786 "--"
19787 ["Expand This Menu" org-create-customize-menu
19788 (fboundp 'customize-menu-create)])
19789 ["Send bug report" org-submit-bug-report t]
19790 "--"
19791 ("Refresh/Reload"
19792 ["Refresh setup current buffer" org-mode-restart t]
19793 ["Reload Org (after update)" org-reload t]
19794 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19797 (defun org-info (&optional node)
19798 "Read documentation for Org-mode in the info system.
19799 With optional NODE, go directly to that node."
19800 (interactive)
19801 (info (format "(org)%s" (or node ""))))
19803 ;;;###autoload
19804 (defun org-submit-bug-report ()
19805 "Submit a bug report on Org-mode via mail.
19807 Don't hesitate to report any problems or inaccurate documentation.
19809 If you don't have setup sending mail from (X)Emacs, please copy the
19810 output buffer into your mail program, as it gives us important
19811 information about your Org-mode version and configuration."
19812 (interactive)
19813 (require 'reporter)
19814 (org-load-modules-maybe)
19815 (org-require-autoloaded-modules)
19816 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19817 (reporter-submit-bug-report
19818 "emacs-orgmode@gnu.org"
19819 (org-version nil 'full)
19820 (let (list)
19821 (save-window-excursion
19822 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19823 (delete-other-windows)
19824 (erase-buffer)
19825 (insert "You are about to submit a bug report to the Org-mode mailing list.
19827 We would like to add your full Org-mode and Outline configuration to the
19828 bug report. This greatly simplifies the work of the maintainer and
19829 other experts on the mailing list.
19831 HOWEVER, some variables you have customized may contain private
19832 information. The names of customers, colleagues, or friends, might
19833 appear in the form of file names, tags, todo states, or search strings.
19834 If you answer yes to the prompt, you might want to check and remove
19835 such private information before sending the email.")
19836 (add-text-properties (point-min) (point-max) '(face org-warning))
19837 (when (yes-or-no-p "Include your Org-mode configuration ")
19838 (mapatoms
19839 (lambda (v)
19840 (and (boundp v)
19841 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19842 (or (and (symbol-value v)
19843 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19844 (and
19845 (get v 'custom-type) (get v 'standard-value)
19846 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19847 (push v list)))))
19848 (kill-buffer (get-buffer "*Warn about privacy*"))
19849 list))
19850 nil nil
19851 "Remember to cover the basics, that is, what you expected to happen and
19852 what in fact did happen. You don't know how to make a good report? See
19854 http://orgmode.org/manual/Feedback.html#Feedback
19856 Your bug report will be posted to the Org-mode mailing list.
19857 ------------------------------------------------------------------------")
19858 (save-excursion
19859 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19860 (replace-match "\\1Bug: \\3 [\\2]")))))
19863 (defun org-install-agenda-files-menu ()
19864 (let ((bl (buffer-list)))
19865 (save-excursion
19866 (while bl
19867 (set-buffer (pop bl))
19868 (if (derived-mode-p 'org-mode) (setq bl nil)))
19869 (when (derived-mode-p 'org-mode)
19870 (easy-menu-change
19871 '("Org") "File List for Agenda"
19872 (append
19873 (list
19874 ["Edit File List" (org-edit-agenda-file-list) t]
19875 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19876 ["Remove Current File from List" org-remove-file t]
19877 ["Cycle through agenda files" org-cycle-agenda-files t]
19878 ["Occur in all agenda files" org-occur-in-agenda-files t]
19879 "--")
19880 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19882 ;;;; Documentation
19884 (defun org-require-autoloaded-modules ()
19885 (interactive)
19886 (mapc 'require
19887 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19888 org-docbook org-exp org-html org-icalendar
19889 org-id org-latex
19890 org-publish org-remember org-table
19891 org-timer org-xoxo)))
19893 ;;;###autoload
19894 (defun org-reload (&optional uncompiled)
19895 "Reload all org lisp files.
19896 With prefix arg UNCOMPILED, load the uncompiled versions."
19897 (interactive "P")
19898 (require 'find-func)
19899 (let* ((file-re "^org\\(-.*\\)?\\.el")
19900 (dir-org (file-name-directory (org-find-library-dir "org")))
19901 (dir-org-contrib (ignore-errors
19902 (file-name-directory
19903 (org-find-library-dir "org-contribdir"))))
19904 (babel-files
19905 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19906 (append (list nil "comint" "eval" "exp" "keys"
19907 "lob" "ref" "table" "tangle")
19908 (delq nil
19909 (mapcar
19910 (lambda (lang)
19911 (when (cdr lang) (symbol-name (car lang))))
19912 org-babel-load-languages)))))
19913 (files
19914 (append babel-files
19915 (and dir-org-contrib
19916 (directory-files dir-org-contrib t file-re))
19917 (directory-files dir-org t file-re)))
19918 (remove-re (concat (if (featurep 'xemacs)
19919 "org-colview" "org-colview-xemacs")
19920 "\\'")))
19921 (setq files (mapcar 'file-name-sans-extension files))
19922 (setq files (mapcar
19923 (lambda (x) (if (string-match remove-re x) nil x))
19924 files))
19925 (setq files (delq nil files))
19926 (mapc
19927 (lambda (f)
19928 (when (featurep (intern (file-name-nondirectory f)))
19929 (if (and (not uncompiled)
19930 (file-exists-p (concat f ".elc")))
19931 (load (concat f ".elc") nil nil 'nosuffix)
19932 (load (concat f ".el") nil nil 'nosuffix))))
19933 files)
19934 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19935 (org-version nil 'full 'message))
19937 ;;;###autoload
19938 (defun org-customize ()
19939 "Call the customize function with org as argument."
19940 (interactive)
19941 (org-load-modules-maybe)
19942 (org-require-autoloaded-modules)
19943 (customize-browse 'org))
19945 (defun org-create-customize-menu ()
19946 "Create a full customization menu for Org-mode, insert it into the menu."
19947 (interactive)
19948 (org-load-modules-maybe)
19949 (org-require-autoloaded-modules)
19950 (if (fboundp 'customize-menu-create)
19951 (progn
19952 (easy-menu-change
19953 '("Org") "Customize"
19954 `(["Browse Org group" org-customize t]
19955 "--"
19956 ,(customize-menu-create 'org)
19957 ["Set" Custom-set t]
19958 ["Save" Custom-save t]
19959 ["Reset to Current" Custom-reset-current t]
19960 ["Reset to Saved" Custom-reset-saved t]
19961 ["Reset to Standard Settings" Custom-reset-standard t]))
19962 (message "\"Org\"-menu now contains full customization menu"))
19963 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19965 ;;;; Miscellaneous stuff
19967 ;;; Generally useful functions
19969 (defun org-get-at-bol (property)
19970 "Get text property PROPERTY at beginning of line."
19971 (get-text-property (point-at-bol) property))
19973 (defun org-find-text-property-in-string (prop s)
19974 "Return the first non-nil value of property PROP in string S."
19975 (or (get-text-property 0 prop s)
19976 (get-text-property (or (next-single-property-change 0 prop s) 0)
19977 prop s)))
19979 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19980 "Display the given MESSAGE as a warning."
19981 (if (fboundp 'display-warning)
19982 (display-warning 'org message
19983 (if (featurep 'xemacs) 'warning :warning))
19984 (let ((buf (get-buffer-create "*Org warnings*")))
19985 (with-current-buffer buf
19986 (goto-char (point-max))
19987 (insert "Warning (Org): " message)
19988 (unless (bolp)
19989 (newline)))
19990 (display-buffer buf)
19991 (sit-for 0))))
19993 (defun org-eval (form)
19994 "Eval FORM and return result."
19995 (condition-case error
19996 (eval form)
19997 (error (format "%%![Error: %s]" error))))
19999 (defun org-in-clocktable-p ()
20000 "Check if the cursor is in a clocktable."
20001 (let ((pos (point)) start)
20002 (save-excursion
20003 (end-of-line 1)
20004 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20005 (setq start (match-beginning 0))
20006 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20007 (>= (match-end 0) pos)
20008 start))))
20010 (defun org-in-commented-line ()
20011 "Is point in a line starting with `#'?"
20012 (equal (char-after (point-at-bol)) ?#))
20014 (defun org-in-indented-comment-line ()
20015 "Is point in a line starting with `#' after some white space?"
20016 (save-excursion
20017 (save-match-data
20018 (goto-char (point-at-bol))
20019 (looking-at "[ \t]*#"))))
20021 (defun org-in-verbatim-emphasis ()
20022 (save-match-data
20023 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20025 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20026 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20027 (if (and marker (marker-buffer marker)
20028 (buffer-live-p (marker-buffer marker)))
20029 (progn
20030 (org-pop-to-buffer-same-window (marker-buffer marker))
20031 (if (or (> marker (point-max)) (< marker (point-min)))
20032 (widen))
20033 (goto-char marker)
20034 (org-show-context 'org-goto))
20035 (if bookmark
20036 (bookmark-jump bookmark)
20037 (error "Cannot find location"))))
20039 (defun org-quote-csv-field (s)
20040 "Quote field for inclusion in CSV material."
20041 (if (string-match "[\",]" s)
20042 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20045 (defun org-force-self-insert (N)
20046 "Needed to enforce self-insert under remapping."
20047 (interactive "p")
20048 (self-insert-command N))
20050 (defun org-string-width (s)
20051 "Compute width of string, ignoring invisible characters.
20052 This ignores character with invisibility property `org-link', and also
20053 characters with property `org-cwidth', because these will become invisible
20054 upon the next fontification round."
20055 (let (b l)
20056 (when (or (eq t buffer-invisibility-spec)
20057 (assq 'org-link buffer-invisibility-spec))
20058 (while (setq b (text-property-any 0 (length s)
20059 'invisible 'org-link s))
20060 (setq s (concat (substring s 0 b)
20061 (substring s (or (next-single-property-change
20062 b 'invisible s) (length s)))))))
20063 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20064 (setq s (concat (substring s 0 b)
20065 (substring s (or (next-single-property-change
20066 b 'org-cwidth s) (length s))))))
20067 (setq l (string-width s) b -1)
20068 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20069 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20072 (defun org-shorten-string (s maxlength)
20073 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20074 If the string is shorter or has length MAXLENGTH, just return the
20075 original string. If it is longer, the functions finds a space in the
20076 string, breaks this string off at that locations and adds three dots
20077 as ellipsis. Including the ellipsis, the string will not be longer
20078 than MAXLENGTH. If finding a good breaking point in the string does
20079 not work, the string is just chopped off in the middle of a word
20080 if necessary."
20081 (if (<= (length s) maxlength)
20083 (let* ((n (max (- maxlength 4) 1))
20084 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20085 (if (string-match re s)
20086 (concat (match-string 1 s) "...")
20087 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20089 (defun org-get-indentation (&optional line)
20090 "Get the indentation of the current line, interpreting tabs.
20091 When LINE is given, assume it represents a line and compute its indentation."
20092 (if line
20093 (if (string-match "^ *" (org-remove-tabs line))
20094 (match-end 0))
20095 (save-excursion
20096 (beginning-of-line 1)
20097 (skip-chars-forward " \t")
20098 (current-column))))
20100 (defun org-get-string-indentation (s)
20101 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20102 (let ((n -1) (i 0) (w tab-width) c)
20103 (catch 'exit
20104 (while (< (setq n (1+ n)) (length s))
20105 (setq c (aref s n))
20106 (cond ((= c ?\ ) (setq i (1+ i)))
20107 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20108 (t (throw 'exit t)))))
20111 (defun org-remove-tabs (s &optional width)
20112 "Replace tabulators in S with spaces.
20113 Assumes that s is a single line, starting in column 0."
20114 (setq width (or width tab-width))
20115 (while (string-match "\t" s)
20116 (setq s (replace-match
20117 (make-string
20118 (- (* width (/ (+ (match-beginning 0) width) width))
20119 (match-beginning 0)) ?\ )
20120 t t s)))
20123 (defun org-fix-indentation (line ind)
20124 "Fix indentation in LINE.
20125 IND is a cons cell with target and minimum indentation.
20126 If the current indentation in LINE is smaller than the minimum,
20127 leave it alone. If it is larger than ind, set it to the target."
20128 (let* ((l (org-remove-tabs line))
20129 (i (org-get-indentation l))
20130 (i1 (car ind)) (i2 (cdr ind)))
20131 (if (>= i i2) (setq l (substring line i2)))
20132 (if (> i1 0)
20133 (concat (make-string i1 ?\ ) l)
20134 l)))
20136 (defun org-remove-indentation (code &optional n)
20137 "Remove the maximum common indentation from the lines in CODE.
20138 N may optionally be the number of spaces to remove."
20139 (with-temp-buffer
20140 (insert code)
20141 (org-do-remove-indentation n)
20142 (buffer-string)))
20144 (defun org-do-remove-indentation (&optional n)
20145 "Remove the maximum common indentation from the buffer."
20146 (untabify (point-min) (point-max))
20147 (let ((min 10000) re)
20148 (if n
20149 (setq min n)
20150 (goto-char (point-min))
20151 (while (re-search-forward "^ *[^ \n]" nil t)
20152 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20153 (unless (or (= min 0) (= min 10000))
20154 (setq re (format "^ \\{%d\\}" min))
20155 (goto-char (point-min))
20156 (while (re-search-forward re nil t)
20157 (replace-match "")
20158 (end-of-line 1))
20159 min)))
20161 (defun org-fill-template (template alist)
20162 "Find each %key of ALIST in TEMPLATE and replace it."
20163 (let ((case-fold-search nil)
20164 entry key value)
20165 (setq alist (sort (copy-sequence alist)
20166 (lambda (a b) (< (length (car a)) (length (car b))))))
20167 (while (setq entry (pop alist))
20168 (setq template
20169 (replace-regexp-in-string
20170 (concat "%" (regexp-quote (car entry)))
20171 (or (cdr entry) "") template t t)))
20172 template))
20174 (defun org-base-buffer (buffer)
20175 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20176 (if (not buffer)
20177 buffer
20178 (or (buffer-base-buffer buffer)
20179 buffer)))
20181 (defun org-trim (s)
20182 "Remove whitespace at beginning and end of string."
20183 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20184 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20187 (defun org-wrap (string &optional width lines)
20188 "Wrap string to either a number of lines, or a width in characters.
20189 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20190 that costs. If there is a word longer than WIDTH, the text is actually
20191 wrapped to the length of that word.
20192 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20193 many lines, whatever width that takes.
20194 The return value is a list of lines, without newlines at the end."
20195 (let* ((words (org-split-string string "[ \t\n]+"))
20196 (maxword (apply 'max (mapcar 'org-string-width words)))
20197 w ll)
20198 (cond (width
20199 (org-do-wrap words (max maxword width)))
20200 (lines
20201 (setq w maxword)
20202 (setq ll (org-do-wrap words maxword))
20203 (if (<= (length ll) lines)
20205 (setq ll words)
20206 (while (> (length ll) lines)
20207 (setq w (1+ w))
20208 (setq ll (org-do-wrap words w)))
20209 ll))
20210 (t (error "Cannot wrap this")))))
20212 (defun org-do-wrap (words width)
20213 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20214 (let (lines line)
20215 (while words
20216 (setq line (pop words))
20217 (while (and words (< (+ (length line) (length (car words))) width))
20218 (setq line (concat line " " (pop words))))
20219 (setq lines (push line lines)))
20220 (nreverse lines)))
20222 (defun org-split-string (string &optional separators)
20223 "Splits STRING into substrings at SEPARATORS.
20224 No empty strings are returned if there are matches at the beginning
20225 and end of string."
20226 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20227 (start 0)
20228 notfirst
20229 (list nil))
20230 (while (and (string-match rexp string
20231 (if (and notfirst
20232 (= start (match-beginning 0))
20233 (< start (length string)))
20234 (1+ start) start))
20235 (< (match-beginning 0) (length string)))
20236 (setq notfirst t)
20237 (or (eq (match-beginning 0) 0)
20238 (and (eq (match-beginning 0) (match-end 0))
20239 (eq (match-beginning 0) start))
20240 (setq list
20241 (cons (substring string start (match-beginning 0))
20242 list)))
20243 (setq start (match-end 0)))
20244 (or (eq start (length string))
20245 (setq list
20246 (cons (substring string start)
20247 list)))
20248 (nreverse list)))
20250 (defun org-quote-vert (s)
20251 "Replace \"|\" with \"\\vert\"."
20252 (while (string-match "|" s)
20253 (setq s (replace-match "\\vert" t t s)))
20256 (defun org-uuidgen-p (s)
20257 "Is S an ID created by UUIDGEN?"
20258 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20260 (defun org-in-src-block-p (&optional inside)
20261 "Whether point is in a code source block.
20262 When INSIDE is non-nil, don't consider we are within a src block
20263 when point is at #+BEGIN_SRC or #+END_SRC."
20264 (let ((case-fold-search t) ov)
20265 (or (and (setq ov (overlays-at (point)))
20266 (memq 'org-block-background
20267 (overlay-properties (car ov))))
20268 (and (not inside)
20269 (save-match-data
20270 (save-excursion
20271 (beginning-of-line)
20272 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20274 (defun org-context ()
20275 "Return a list of contexts of the current cursor position.
20276 If several contexts apply, all are returned.
20277 Each context entry is a list with a symbol naming the context, and
20278 two positions indicating start and end of the context. Possible
20279 contexts are:
20281 :headline anywhere in a headline
20282 :headline-stars on the leading stars in a headline
20283 :todo-keyword on a TODO keyword (including DONE) in a headline
20284 :tags on the TAGS in a headline
20285 :priority on the priority cookie in a headline
20286 :item on the first line of a plain list item
20287 :item-bullet on the bullet/number of a plain list item
20288 :checkbox on the checkbox in a plain list item
20289 :table in an org-mode table
20290 :table-special on a special filed in a table
20291 :table-table in a table.el table
20292 :clocktable in a clocktable
20293 :src-block in a source block
20294 :link on a hyperlink
20295 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20296 :target on a <<target>>
20297 :radio-target on a <<<radio-target>>>
20298 :latex-fragment on a LaTeX fragment
20299 :latex-preview on a LaTeX fragment with overlaid preview image
20301 This function expects the position to be visible because it uses font-lock
20302 faces as a help to recognize the following contexts: :table-special, :link,
20303 and :keyword."
20304 (let* ((f (get-text-property (point) 'face))
20305 (faces (if (listp f) f (list f)))
20306 (case-fold-search t)
20307 (p (point)) clist o)
20308 ;; First the large context
20309 (cond
20310 ((org-at-heading-p t)
20311 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20312 (when (progn
20313 (beginning-of-line 1)
20314 (looking-at org-todo-line-tags-regexp))
20315 (push (org-point-in-group p 1 :headline-stars) clist)
20316 (push (org-point-in-group p 2 :todo-keyword) clist)
20317 (push (org-point-in-group p 4 :tags) clist))
20318 (goto-char p)
20319 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20320 (if (looking-at "\\[#[A-Z0-9]\\]")
20321 (push (org-point-in-group p 0 :priority) clist)))
20323 ((org-at-item-p)
20324 (push (org-point-in-group p 2 :item-bullet) clist)
20325 (push (list :item (point-at-bol)
20326 (save-excursion (org-end-of-item) (point)))
20327 clist)
20328 (and (org-at-item-checkbox-p)
20329 (push (org-point-in-group p 0 :checkbox) clist)))
20331 ((org-at-table-p)
20332 (push (list :table (org-table-begin) (org-table-end)) clist)
20333 (if (memq 'org-formula faces)
20334 (push (list :table-special
20335 (previous-single-property-change p 'face)
20336 (next-single-property-change p 'face)) clist)))
20337 ((org-at-table-p 'any)
20338 (push (list :table-table) clist)))
20339 (goto-char p)
20341 (let ((case-fold-search t))
20342 ;; New the "medium" contexts: clocktables, source blocks
20343 (cond ((org-in-clocktable-p)
20344 (push (list :clocktable
20345 (and (or (looking-at "#\\+BEGIN: clocktable")
20346 (search-backward "#+BEGIN: clocktable" nil t))
20347 (match-beginning 0))
20348 (and (re-search-forward "#\\+END:?" nil t)
20349 (match-end 0))) clist))
20350 ((org-in-src-block-p)
20351 (push (list :src-block
20352 (and (or (looking-at "#\\+BEGIN_SRC")
20353 (search-backward "#+BEGIN_SRC" nil t))
20354 (match-beginning 0))
20355 (and (search-forward "#+END_SRC" nil t)
20356 (match-beginning 0))) clist))))
20357 (goto-char p)
20359 ;; Now the small context
20360 (cond
20361 ((org-at-timestamp-p)
20362 (push (org-point-in-group p 0 :timestamp) clist))
20363 ((memq 'org-link faces)
20364 (push (list :link
20365 (previous-single-property-change p 'face)
20366 (next-single-property-change p 'face)) clist))
20367 ((memq 'org-special-keyword faces)
20368 (push (list :keyword
20369 (previous-single-property-change p 'face)
20370 (next-single-property-change p 'face)) clist))
20371 ((org-at-target-p)
20372 (push (org-point-in-group p 0 :target) clist)
20373 (goto-char (1- (match-beginning 0)))
20374 (if (looking-at org-radio-target-regexp)
20375 (push (org-point-in-group p 0 :radio-target) clist))
20376 (goto-char p))
20377 ((setq o (car (delq nil
20378 (mapcar
20379 (lambda (x)
20380 (if (memq x org-latex-fragment-image-overlays) x))
20381 (overlays-at (point))))))
20382 (push (list :latex-fragment
20383 (overlay-start o) (overlay-end o)) clist)
20384 (push (list :latex-preview
20385 (overlay-start o) (overlay-end o)) clist))
20386 ((org-inside-LaTeX-fragment-p)
20387 ;; FIXME: positions wrong.
20388 (push (list :latex-fragment (point) (point)) clist)))
20390 (setq clist (nreverse (delq nil clist)))
20391 clist))
20393 ;; FIXME: Compare with at-regexp-p Do we need both?
20394 (defun org-in-regexp (re &optional nlines visually)
20395 "Check if point is inside a match of regexp.
20396 Normally only the current line is checked, but you can include NLINES extra
20397 lines both before and after point into the search.
20398 If VISUALLY is set, require that the cursor is not after the match but
20399 really on, so that the block visually is on the match."
20400 (catch 'exit
20401 (let ((pos (point))
20402 (eol (point-at-eol (+ 1 (or nlines 0))))
20403 (inc (if visually 1 0)))
20404 (save-excursion
20405 (beginning-of-line (- 1 (or nlines 0)))
20406 (while (re-search-forward re eol t)
20407 (if (and (<= (match-beginning 0) pos)
20408 (>= (+ inc (match-end 0)) pos))
20409 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20411 (defun org-at-regexp-p (regexp)
20412 "Is point inside a match of REGEXP in the current line?"
20413 (catch 'exit
20414 (save-excursion
20415 (let ((pos (point)) (end (point-at-eol)))
20416 (beginning-of-line 1)
20417 (while (re-search-forward regexp end t)
20418 (if (and (<= (match-beginning 0) pos)
20419 (>= (match-end 0) pos))
20420 (throw 'exit t)))
20421 nil))))
20423 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20424 "Non-nil when point is between matches of START-RE and END-RE.
20426 Also return a non-nil value when point is on one of the matches.
20428 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20429 buffer positions. Default values are the positions of headlines
20430 surrounding the point.
20432 The functions returns a cons cell whose car (resp. cdr) is the
20433 position before START-RE (resp. after END-RE)."
20434 (save-match-data
20435 (let ((pos (point))
20436 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20437 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20438 beg end)
20439 (save-excursion
20440 ;; Point is on a block when on START-RE or if START-RE can be
20441 ;; found before it...
20442 (and (or (org-at-regexp-p start-re)
20443 (re-search-backward start-re limit-up t))
20444 (setq beg (match-beginning 0))
20445 ;; ... and END-RE after it...
20446 (goto-char (match-end 0))
20447 (re-search-forward end-re limit-down t)
20448 (> (setq end (match-end 0)) pos)
20449 ;; ... without another START-RE in-between.
20450 (goto-char (match-beginning 0))
20451 (not (re-search-backward start-re (1+ beg) t))
20452 ;; Return value.
20453 (cons beg end))))))
20455 (defun org-in-block-p (names)
20456 "Non-nil when point belongs to a block whose name belongs to NAMES.
20458 NAMES is a list of strings containing names of blocks.
20460 Return first block name matched, or nil. Beware that in case of
20461 nested blocks, the returned name may not belong to the closest
20462 block from point."
20463 (save-match-data
20464 (catch 'exit
20465 (let ((case-fold-search t)
20466 (lim-up (save-excursion (outline-previous-heading)))
20467 (lim-down (save-excursion (outline-next-heading))))
20468 (mapc (lambda (name)
20469 (let ((n (regexp-quote name)))
20470 (when (org-between-regexps-p
20471 (concat "^[ \t]*#\\+begin_" n)
20472 (concat "^[ \t]*#\\+end_" n)
20473 lim-up lim-down)
20474 (throw 'exit n))))
20475 names))
20476 nil)))
20478 (defun org-occur-in-agenda-files (regexp &optional nlines)
20479 "Call `multi-occur' with buffers for all agenda files."
20480 (interactive "sOrg-files matching: \np")
20481 (let* ((files (org-agenda-files))
20482 (tnames (mapcar 'file-truename files))
20483 (extra org-agenda-text-search-extra-files)
20485 (when (eq (car extra) 'agenda-archives)
20486 (setq extra (cdr extra))
20487 (setq files (org-add-archive-files files)))
20488 (while (setq f (pop extra))
20489 (unless (member (file-truename f) tnames)
20490 (add-to-list 'files f 'append)
20491 (add-to-list 'tnames (file-truename f) 'append)))
20492 (multi-occur
20493 (mapcar (lambda (x)
20494 (with-current-buffer
20495 (or (get-file-buffer x) (find-file-noselect x))
20496 (widen)
20497 (current-buffer)))
20498 files)
20499 regexp)))
20501 (if (boundp 'occur-mode-find-occurrence-hook)
20502 ;; Emacs 23
20503 (add-hook 'occur-mode-find-occurrence-hook
20504 (lambda ()
20505 (when (derived-mode-p 'org-mode)
20506 (org-reveal))))
20507 ;; Emacs 22
20508 (defadvice occur-mode-goto-occurrence
20509 (after org-occur-reveal activate)
20510 (and (derived-mode-p 'org-mode) (org-reveal)))
20511 (defadvice occur-mode-goto-occurrence-other-window
20512 (after org-occur-reveal activate)
20513 (and (derived-mode-p 'org-mode) (org-reveal)))
20514 (defadvice occur-mode-display-occurrence
20515 (after org-occur-reveal activate)
20516 (when (derived-mode-p 'org-mode)
20517 (let ((pos (occur-mode-find-occurrence)))
20518 (with-current-buffer (marker-buffer pos)
20519 (save-excursion
20520 (goto-char pos)
20521 (org-reveal)))))))
20523 (defun org-occur-link-in-agenda-files ()
20524 "Create a link and search for it in the agendas.
20525 The link is not stored in `org-stored-links', it is just created
20526 for the search purpose."
20527 (interactive)
20528 (let ((link (condition-case nil
20529 (org-store-link nil)
20530 (error "Unable to create a link to here"))))
20531 (org-occur-in-agenda-files (regexp-quote link))))
20533 (defun org-uniquify (list)
20534 "Remove duplicate elements from LIST."
20535 (let (res)
20536 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20537 res))
20539 (defun org-delete-all (elts list)
20540 "Remove all elements in ELTS from LIST."
20541 (while elts
20542 (setq list (delete (pop elts) list)))
20543 list)
20545 (defun org-count (cl-item cl-seq)
20546 "Count the number of occurrences of ITEM in SEQ.
20547 Taken from `count' in cl-seq.el with all keyword arguments removed."
20548 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20549 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20550 (while (< cl-start cl-end)
20551 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20552 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20553 (setq cl-start (1+ cl-start)))
20554 cl-count))
20556 (defun org-remove-if (predicate seq)
20557 "Remove everything from SEQ that fulfills PREDICATE."
20558 (let (res e)
20559 (while seq
20560 (setq e (pop seq))
20561 (if (not (funcall predicate e)) (push e res)))
20562 (nreverse res)))
20564 (defun org-remove-if-not (predicate seq)
20565 "Remove everything from SEQ that does not fulfill PREDICATE."
20566 (let (res e)
20567 (while seq
20568 (setq e (pop seq))
20569 (if (funcall predicate e) (push e res)))
20570 (nreverse res)))
20572 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20573 "Reduce two-argument FUNCTION across SEQ.
20574 Taken from `reduce' in cl-seq.el with all keyword arguments but
20575 \":initial-value\" removed."
20576 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20577 (cadr (memq :initial-value cl-keys)))
20578 (cl-seq (pop cl-seq))
20579 (t (funcall cl-func)))))
20580 (while cl-seq
20581 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20582 cl-accum))
20584 (defun org-back-over-empty-lines ()
20585 "Move backwards over whitespace, to the beginning of the first empty line.
20586 Returns the number of empty lines passed."
20587 (let ((pos (point)))
20588 (if (cdr (assoc 'heading org-blank-before-new-entry))
20589 (skip-chars-backward " \t\n\r")
20590 (unless (eobp)
20591 (forward-line -1)))
20592 (beginning-of-line 2)
20593 (goto-char (min (point) pos))
20594 (count-lines (point) pos)))
20596 (defun org-skip-whitespace ()
20597 (skip-chars-forward " \t\n\r"))
20599 (defun org-point-in-group (point group &optional context)
20600 "Check if POINT is in match-group GROUP.
20601 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20602 match. If the match group does not exist or point is not inside it,
20603 return nil."
20604 (and (match-beginning group)
20605 (>= point (match-beginning group))
20606 (<= point (match-end group))
20607 (if context
20608 (list context (match-beginning group) (match-end group))
20609 t)))
20611 (defun org-switch-to-buffer-other-window (&rest args)
20612 "Switch to buffer in a second window on the current frame.
20613 In particular, do not allow pop-up frames.
20614 Returns the newly created buffer."
20615 (org-no-popups
20616 (apply 'switch-to-buffer-other-window args)))
20618 (defun org-combine-plists (&rest plists)
20619 "Create a single property list from all plists in PLISTS.
20620 The process starts by copying the first list, and then setting properties
20621 from the other lists. Settings in the last list are the most significant
20622 ones and overrule settings in the other lists."
20623 (let ((rtn (copy-sequence (pop plists)))
20624 p v ls)
20625 (while plists
20626 (setq ls (pop plists))
20627 (while ls
20628 (setq p (pop ls) v (pop ls))
20629 (setq rtn (plist-put rtn p v))))
20630 rtn))
20632 (defun org-replace-escapes (string table)
20633 "Replace %-escapes in STRING with values in TABLE.
20634 TABLE is an association list with keys like \"%a\" and string values.
20635 The sequences in STRING may contain normal field width and padding information,
20636 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20637 so values can contain further %-escapes if they are define later in TABLE."
20638 (let ((tbl (copy-alist table))
20639 (case-fold-search nil)
20640 (pchg 0)
20641 e re rpl)
20642 (while (setq e (pop tbl))
20643 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20644 (when (and (cdr e) (string-match re (cdr e)))
20645 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20646 (safe "SREF"))
20647 (add-text-properties 0 3 (list 'sref sref) safe)
20648 (setcdr e (replace-match safe t t (cdr e)))))
20649 (while (string-match re string)
20650 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20651 (cdr e)))
20652 (setq string (replace-match rpl t t string))))
20653 (while (setq pchg (next-property-change pchg string))
20654 (let ((sref (get-text-property pchg 'sref string)))
20655 (when (and sref (string-match "SREF" string pchg))
20656 (setq string (replace-match sref t t string)))))
20657 string))
20659 (defun org-sublist (list start end)
20660 "Return a section of LIST, from START to END.
20661 Counting starts at 1."
20662 (let (rtn (c start))
20663 (setq list (nthcdr (1- start) list))
20664 (while (and list (<= c end))
20665 (push (pop list) rtn)
20666 (setq c (1+ c)))
20667 (nreverse rtn)))
20669 (defun org-find-base-buffer-visiting (file)
20670 "Like `find-buffer-visiting' but always return the base buffer and
20671 not an indirect buffer."
20672 (let ((buf (or (get-file-buffer file)
20673 (find-buffer-visiting file))))
20674 (if buf
20675 (or (buffer-base-buffer buf) buf)
20676 nil)))
20678 (defun org-image-file-name-regexp (&optional extensions)
20679 "Return regexp matching the file names of images.
20680 If EXTENSIONS is given, only match these."
20681 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20682 (image-file-name-regexp)
20683 (let ((image-file-name-extensions
20684 (or extensions
20685 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20686 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20687 (concat "\\."
20688 (regexp-opt (nconc (mapcar 'upcase
20689 image-file-name-extensions)
20690 image-file-name-extensions)
20692 "\\'"))))
20694 (defun org-file-image-p (file &optional extensions)
20695 "Return non-nil if FILE is an image."
20696 (save-match-data
20697 (string-match (org-image-file-name-regexp extensions) file)))
20699 (defun org-get-cursor-date ()
20700 "Return the date at cursor in as a time.
20701 This works in the calendar and in the agenda, anywhere else it just
20702 returns the current time."
20703 (let (date day defd)
20704 (cond
20705 ((eq major-mode 'calendar-mode)
20706 (setq date (calendar-cursor-to-date)
20707 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20708 ((eq major-mode 'org-agenda-mode)
20709 (setq day (get-text-property (point) 'day))
20710 (if day
20711 (setq date (calendar-gregorian-from-absolute day)
20712 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20713 (nth 2 date))))))
20714 (or defd (current-time))))
20716 (defun org-mark-subtree (&optional up)
20717 "Mark the current subtree.
20718 This puts point at the start of the current subtree, and mark at
20719 the end. If a numeric prefix UP is given, move up into the
20720 hierarchy of headlines by UP levels before marking the subtree."
20721 (interactive "P")
20722 (org-with-limited-levels
20723 (cond ((org-at-heading-p) (beginning-of-line))
20724 ((org-before-first-heading-p) (error "Not in a subtree"))
20725 (t (outline-previous-visible-heading 1))))
20726 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20727 (if (org-called-interactively-p 'any)
20728 (call-interactively 'org-mark-element)
20729 (org-mark-element)))
20731 ;;; Indentation
20733 (defun org-indent-line ()
20734 "Indent line depending on context."
20735 (interactive)
20736 (let* ((pos (point))
20737 (itemp (org-at-item-p))
20738 (case-fold-search t)
20739 (org-drawer-regexp (or org-drawer-regexp "\000"))
20740 (inline-task-p (and (featurep 'org-inlinetask)
20741 (org-inlinetask-in-task-p)))
20742 (inline-re (and inline-task-p
20743 (org-inlinetask-outline-regexp)))
20744 column)
20745 (if (and orgstruct-is-++ (eq pos (point)))
20746 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20747 (indent-according-to-mode))
20748 (beginning-of-line 1)
20749 (cond
20750 ;; Headings
20751 ((looking-at org-outline-regexp) (setq column 0))
20752 ;; Included files
20753 ((looking-at "#\\+include:") (setq column 0))
20754 ;; Footnote definition
20755 ((looking-at org-footnote-definition-re) (setq column 0))
20756 ;; Literal examples
20757 ((looking-at "[ \t]*:\\( \\|$\\)")
20758 (setq column (org-get-indentation))) ; do nothing
20759 ;; Lists
20760 ((ignore-errors (goto-char (org-in-item-p)))
20761 (setq column (if itemp
20762 (org-get-indentation)
20763 (org-list-item-body-column (point))))
20764 (goto-char pos))
20765 ;; Drawers
20766 ((and (looking-at "[ \t]*:END:")
20767 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20768 (save-excursion
20769 (goto-char (1- (match-beginning 1)))
20770 (setq column (current-column))))
20771 ;; Special blocks
20772 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20773 (save-excursion
20774 (re-search-backward
20775 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20776 (setq column (org-get-indentation (match-string 0))))
20777 ((and (not (looking-at "[ \t]*#\\+begin_"))
20778 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20779 (save-excursion
20780 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20781 (setq column
20782 (cond ((equal (downcase (match-string 1)) "src")
20783 ;; src blocks: let `org-edit-src-exit' handle them
20784 (org-get-indentation))
20785 ((equal (downcase (match-string 1)) "example")
20786 (max (org-get-indentation)
20787 (org-get-indentation (match-string 0))))
20789 (org-get-indentation (match-string 0))))))
20790 ;; This line has nothing special, look at the previous relevant
20791 ;; line to compute indentation
20793 (beginning-of-line 0)
20794 (while (and (not (bobp))
20795 (not (looking-at org-table-line-regexp))
20796 (not (looking-at org-drawer-regexp))
20797 ;; When point started in an inline task, do not move
20798 ;; above task starting line.
20799 (not (and inline-task-p (looking-at inline-re)))
20800 ;; Skip drawers, blocks, empty lines, verbatim,
20801 ;; comments, tables, footnotes definitions, lists,
20802 ;; inline tasks.
20803 (or (and (looking-at "[ \t]*:END:")
20804 (re-search-backward org-drawer-regexp nil t))
20805 (and (looking-at "[ \t]*#\\+end_")
20806 (re-search-backward "[ \t]*#\\+begin_"nil t))
20807 (looking-at "[ \t]*[\n:#|]")
20808 (looking-at org-footnote-definition-re)
20809 (and (ignore-errors (goto-char (org-in-item-p)))
20810 (goto-char
20811 (org-list-get-top-point (org-list-struct))))
20812 (and (not inline-task-p)
20813 (featurep 'org-inlinetask)
20814 (org-inlinetask-in-task-p)
20815 (or (org-inlinetask-goto-beginning) t))))
20816 (beginning-of-line 0))
20817 (cond
20818 ;; There was an heading above.
20819 ((looking-at "\\*+[ \t]+")
20820 (if (not org-adapt-indentation)
20821 (setq column 0)
20822 (goto-char (match-end 0))
20823 (setq column (current-column))))
20824 ;; A drawer had started and is unfinished
20825 ((looking-at org-drawer-regexp)
20826 (goto-char (1- (match-beginning 1)))
20827 (setq column (current-column)))
20828 ;; Else, nothing noticeable found: get indentation and go on.
20829 (t (setq column (org-get-indentation))))))
20830 ;; Now apply indentation and move cursor accordingly
20831 (goto-char pos)
20832 (if (<= (current-column) (current-indentation))
20833 (org-indent-line-to column)
20834 (save-excursion (org-indent-line-to column)))
20835 ;; Special polishing for properties, see `org-property-format'
20836 (setq column (current-column))
20837 (beginning-of-line 1)
20838 (if (looking-at
20839 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20840 (replace-match (concat (match-string 1)
20841 (format org-property-format
20842 (match-string 2) (match-string 3)))
20843 t t))
20844 (org-move-to-column column))))
20846 (defun org-indent-drawer ()
20847 "Indent the drawer at point."
20848 (interactive)
20849 (let ((p (point))
20850 (e (and (save-excursion (re-search-forward ":END:" nil t))
20851 (match-end 0)))
20852 (folded
20853 (save-excursion
20854 (end-of-line)
20855 (when (overlays-at (point))
20856 (member 'invisible (overlay-properties
20857 (car (overlays-at (point)))))))))
20858 (when folded (org-cycle))
20859 (indent-for-tab-command)
20860 (while (and (move-beginning-of-line 2) (< (point) e))
20861 (indent-for-tab-command))
20862 (goto-char p)
20863 (when folded (org-cycle)))
20864 (message "Drawer at point indented"))
20866 (defun org-indent-block ()
20867 "Indent the block at point."
20868 (interactive)
20869 (let ((p (point))
20870 (case-fold-search t)
20871 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20872 (match-end 0)))
20873 (folded
20874 (save-excursion
20875 (end-of-line)
20876 (when (overlays-at (point))
20877 (member 'invisible (overlay-properties
20878 (car (overlays-at (point)))))))))
20879 (when folded (org-cycle))
20880 (indent-for-tab-command)
20881 (while (and (move-beginning-of-line 2) (< (point) e))
20882 (indent-for-tab-command))
20883 (goto-char p)
20884 (when folded (org-cycle)))
20885 (message "Block at point indented"))
20887 (defun org-indent-region (start end)
20888 "Indent region."
20889 (interactive "r")
20890 (save-excursion
20891 (let ((line-end (org-current-line end)))
20892 (goto-char start)
20893 (while (< (org-current-line) line-end)
20894 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20895 (t (call-interactively 'org-indent-line)))
20896 (move-beginning-of-line 2)))))
20899 ;;; Filling
20901 ;; We use our own fill-paragraph and auto-fill functions.
20903 ;; `org-fill-paragraph' relies on adaptive filling and context
20904 ;; checking. Appropriate `fill-prefix' is computed with
20905 ;; `org-adaptive-fill-function'.
20907 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20908 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20909 ;; `org-adaptive-fill-function' value. Internally,
20910 ;; `org-comment-line-break-function' breaks the line.
20912 ;; `org-setup-filling' installs filling and auto-filling related
20913 ;; variables during `org-mode' initialization.
20915 (defun org-setup-filling ()
20916 (interactive)
20917 ;; Prevent auto-fill from inserting unwanted new items.
20918 (when (boundp 'fill-nobreak-predicate)
20919 (org-set-local
20920 'fill-nobreak-predicate
20921 (org-uniquify
20922 (append fill-nobreak-predicate
20923 '(org-fill-paragraph-separate-nobreak-p
20924 org-fill-line-break-nobreak-p)))))
20925 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20926 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20927 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20928 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20930 (defvar org-element-paragraph-separate) ; org-element.el
20931 (defun org-fill-paragraph-separate-nobreak-p ()
20932 "Non-nil when a line break at point would insert a new item."
20933 (looking-at (substring org-element-paragraph-separate 1)))
20935 (defun org-fill-line-break-nobreak-p ()
20936 "Non-nil when a line break at point would create an Org line break."
20937 (save-excursion
20938 (skip-chars-backward "[ \t]")
20939 (skip-chars-backward "\\\\")
20940 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20942 (declare-function message-in-body-p "message" ())
20943 (defvar org-element--affiliated-re) ; From org-element.el
20944 (defun org-adaptive-fill-function ()
20945 "Compute a fill prefix for the current line.
20946 Return fill prefix, as a string, or nil if current line isn't
20947 meant to be filled."
20948 (org-with-wide-buffer
20949 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
20950 ;; FIXME: This is really the job of orgstruct++-mode
20951 (let* ((p (line-beginning-position))
20952 (element (save-excursion (beginning-of-line)
20953 (org-element-at-point)))
20954 (type (org-element-type element))
20955 (post-affiliated
20956 (save-excursion
20957 (goto-char (org-element-property :begin element))
20958 (while (looking-at org-element--affiliated-re) (forward-line))
20959 (point))))
20960 (unless (< p post-affiliated)
20961 (case type
20962 (comment (looking-at "[ \t]*# ?") (match-string 0))
20963 (footnote-definition "")
20964 ((item plain-list)
20965 (make-string (org-list-item-body-column post-affiliated) ? ))
20966 (paragraph
20967 ;; Fill prefix is usually the same as the current line,
20968 ;; except if the paragraph is at the beginning of an item.
20969 (let ((parent (org-element-property :parent element)))
20970 (cond ((eq (org-element-type parent) 'item)
20971 (make-string (org-list-item-body-column
20972 (org-element-property :begin parent))
20973 ? ))
20974 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20975 (match-string 0))
20976 (t ""))))
20977 (comment-block
20978 ;; Only fill contents if P is within block boundaries.
20979 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20980 (forward-line)
20981 (point)))
20982 (cend (save-excursion
20983 (goto-char (org-element-property :end element))
20984 (skip-chars-backward " \r\t\n")
20985 (line-beginning-position))))
20986 (when (and (>= p cbeg) (< p cend))
20987 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20988 (match-string 0)
20989 ""))))))))))
20991 (declare-function message-goto-body "message" ())
20992 (defvar message-cite-prefix-regexp) ; From message.el
20993 (defvar org-element-all-objects) ; From org-element.el
20994 (defun org-fill-paragraph (&optional justify)
20995 "Fill element at point, when applicable.
20997 This function only applies to comment blocks, comments, example
20998 blocks and paragraphs. Also, as a special case, re-align table
20999 when point is at one.
21001 If JUSTIFY is non-nil (interactively, with prefix argument),
21002 justify as well. If `sentence-end-double-space' is non-nil, then
21003 period followed by one space does not end a sentence, so don't
21004 break a line there. The variable `fill-column' controls the
21005 width for filling.
21007 For convenience, when point is at a plain list, an item or
21008 a footnote definition, try to fill the first paragraph within."
21009 (interactive)
21010 (if (and (derived-mode-p 'message-mode)
21011 (or (not (message-in-body-p))
21012 (save-excursion (move-beginning-of-line 1)
21013 (looking-at message-cite-prefix-regexp))))
21014 ;; First ensure filling is correct in message-mode.
21015 (let ((fill-paragraph-function
21016 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21017 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21018 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21019 (paragraph-separate
21020 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21021 (fill-paragraph nil))
21022 (save-excursion
21023 ;; Move to end of line in order to get the first paragraph
21024 ;; within a plain list or a footnote definition.
21025 (end-of-line)
21026 (let ((element (org-element-at-point)))
21027 ;; First check if point is in a blank line at the beginning of
21028 ;; the buffer. In that case, ignore filling.
21029 (if (< (point) (org-element-property :begin element)) t
21030 (case (org-element-type element)
21031 ;; Use major mode filling function is src blocks.
21032 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21033 ;; Align Org tables, leave table.el tables as-is.
21034 (table-row (org-table-align) t)
21035 (table
21036 (when (eq (org-element-property :type element) 'org)
21037 (org-table-align))
21039 (paragraph
21040 ;; Paragraphs may contain `line-break' type objects.
21041 (let ((beg (max (point-min)
21042 (org-element-property :contents-begin element)))
21043 (end (min (point-max)
21044 (org-element-property :contents-end element))))
21045 ;; Do nothing if point is at an affiliated keyword.
21046 (if (< (point) beg) t
21047 (when (derived-mode-p 'message-mode)
21048 ;; In `message-mode', do not fill following
21049 ;; citation in current paragraph nor text before
21050 ;; message body.
21051 (let ((body-start (save-excursion (message-goto-body))))
21052 (when body-start (setq beg (max body-start beg))))
21053 (when (save-excursion
21054 (re-search-forward
21055 (concat "^" message-cite-prefix-regexp) end t))
21056 (setq end (match-beginning 0))))
21057 ;; Fill paragraph, taking line breaks into
21058 ;; consideration. For that, slice the paragraph
21059 ;; using line breaks as separators, and fill the
21060 ;; parts in reverse order to avoid messing with
21061 ;; markers.
21062 (save-excursion
21063 (goto-char end)
21064 (mapc
21065 (lambda (pos)
21066 (fill-region-as-paragraph pos (point) justify)
21067 (goto-char pos))
21068 ;; Find the list of ending positions for line
21069 ;; breaks in the current paragraph. Add paragraph
21070 ;; beginning to include first slice.
21071 (nreverse
21072 (cons
21074 (org-element-map
21075 (org-element--parse-objects
21076 beg end nil org-element-all-objects)
21077 'line-break
21078 (lambda (lb) (org-element-property :end lb)))))))
21079 t)))
21080 ;; Contents of `comment-block' type elements should be
21081 ;; filled as plain text, but only if point is within block
21082 ;; markers.
21083 (comment-block
21084 (let* ((case-fold-search t)
21085 (beg (save-excursion
21086 (goto-char (org-element-property :begin element))
21087 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21088 (forward-line)
21089 (point)))
21090 (end (save-excursion
21091 (goto-char (org-element-property :end element))
21092 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21093 (line-beginning-position))))
21094 (when (and (>= (point) beg) (< (point) end))
21095 (fill-region-as-paragraph
21096 (save-excursion
21097 (end-of-line)
21098 (re-search-backward "^[ \t]*$" beg 'move)
21099 (line-beginning-position))
21100 (save-excursion
21101 (beginning-of-line)
21102 (re-search-forward "^[ \t]*$" end 'move)
21103 (line-beginning-position))
21104 justify)))
21106 ;; Fill comments.
21107 (comment (fill-comment-paragraph justify))
21108 ;; Ignore every other element.
21109 (otherwise t)))))))
21111 (defun org-auto-fill-function ()
21112 "Auto-fill function."
21113 ;; Check if auto-filling is meaningful.
21114 (let ((fc (current-fill-column)))
21115 (when (and fc (> (current-column) fc))
21116 (let* ((fill-prefix (org-adaptive-fill-function))
21117 ;; Enforce empty fill prefix, if required. Otherwise, it
21118 ;; will be computed again.
21119 (adaptive-fill-mode (not (equal fill-prefix ""))))
21120 (when fill-prefix (do-auto-fill))))))
21122 (defun org-comment-line-break-function (&optional soft)
21123 "Break line at point and indent, continuing comment if within one.
21124 The inserted newline is marked hard if variable
21125 `use-hard-newlines' is true, unless optional argument SOFT is
21126 non-nil."
21127 (if soft (insert-and-inherit ?\n) (newline 1))
21128 (save-excursion (forward-char -1) (delete-horizontal-space))
21129 (delete-horizontal-space)
21130 (indent-to-left-margin)
21131 (insert-before-markers-and-inherit fill-prefix))
21134 ;;; Comments
21136 ;; Org comments syntax is quite complex. It requires the entire line
21137 ;; to be just a comment. Also, even with the right syntax at the
21138 ;; beginning of line, some some elements (i.e. verse-block or
21139 ;; example-block) don't accept comments. Usual Emacs comment commands
21140 ;; cannot cope with those requirements. Therefore, Org replaces them.
21142 ;; Org still relies on `comment-dwim', but cannot trust
21143 ;; `comment-only-p'. So, `comment-region-function' and
21144 ;; `uncomment-region-function' both point
21145 ;; to`org-comment-or-uncomment-region'. Eventually,
21146 ;; `org-insert-comment' takes care of insertion of comments at the
21147 ;; beginning of line.
21149 ;; `org-setup-comments-handling' install comments related variables
21150 ;; during `org-mode' initialization.
21152 (defun org-setup-comments-handling ()
21153 (interactive)
21154 (org-set-local 'comment-use-syntax nil)
21155 (org-set-local 'comment-start "# ")
21156 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21157 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21158 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21159 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21161 (defun org-insert-comment ()
21162 "Insert an empty comment above current line.
21163 If the line is empty, insert comment at its beginning."
21164 (beginning-of-line)
21165 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21166 (org-indent-line)
21167 (insert "# "))
21169 (defvar comment-empty-lines) ; From newcomment.el.
21170 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21171 "Comment or uncomment each non-blank line in the region.
21172 Uncomment each non-blank line between BEG and END if it only
21173 contains commented lines. Otherwise, comment them."
21174 (save-restriction
21175 ;; Restrict region
21176 (narrow-to-region (save-excursion (goto-char beg)
21177 (skip-chars-forward " \r\t\n" end)
21178 (line-beginning-position))
21179 (save-excursion (goto-char end)
21180 (skip-chars-backward " \r\t\n" beg)
21181 (line-end-position)))
21182 (let ((uncommentp
21183 ;; UNCOMMENTP is non-nil when every non blank line between
21184 ;; BEG and END is a comment.
21185 (save-excursion
21186 (goto-char (point-min))
21187 (while (and (not (eobp))
21188 (let ((element (org-element-at-point)))
21189 (and (eq (org-element-type element) 'comment)
21190 (goto-char (min (point-max)
21191 (org-element-property
21192 :end element)))))))
21193 (eobp))))
21194 (if uncommentp
21195 ;; Only blank lines and comments in region: uncomment it.
21196 (save-excursion
21197 (goto-char (point-min))
21198 (while (not (eobp))
21199 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21200 (replace-match "" nil nil nil 1))
21201 (forward-line)))
21202 ;; Comment each line in region.
21203 (let ((min-indent (point-max)))
21204 ;; First find the minimum indentation across all lines.
21205 (save-excursion
21206 (goto-char (point-min))
21207 (while (and (not (eobp)) (not (zerop min-indent)))
21208 (unless (looking-at "[ \t]*$")
21209 (setq min-indent (min min-indent (current-indentation))))
21210 (forward-line)))
21211 ;; Then loop over all lines.
21212 (save-excursion
21213 (goto-char (point-min))
21214 (while (not (eobp))
21215 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21216 (org-move-to-column min-indent t)
21217 (insert comment-start))
21218 (forward-line))))))))
21221 ;;; Other stuff.
21223 (defun org-toggle-fixed-width-section (arg)
21224 "Toggle the fixed-width export.
21225 If there is no active region, the QUOTE keyword at the current headline is
21226 inserted or removed. When present, it causes the text between this headline
21227 and the next to be exported as fixed-width text, and unmodified.
21228 If there is an active region, this command adds or removes a colon as the
21229 first character of this line. If the first character of a line is a colon,
21230 this line is also exported in fixed-width font."
21231 (interactive "P")
21232 (let* ((cc 0)
21233 (regionp (org-region-active-p))
21234 (beg (if regionp (region-beginning) (point)))
21235 (end (if regionp (region-end)))
21236 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21237 (case-fold-search nil)
21238 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21239 off)
21240 (if regionp
21241 (save-excursion
21242 (goto-char beg)
21243 (setq cc (current-column))
21244 (beginning-of-line 1)
21245 (setq off (looking-at re))
21246 (while (> nlines 0)
21247 (setq nlines (1- nlines))
21248 (beginning-of-line 1)
21249 (cond
21250 (arg
21251 (org-move-to-column cc t)
21252 (insert ": \n")
21253 (forward-line -1))
21254 ((and off (looking-at re))
21255 (replace-match "" t t nil 1))
21256 ((not off) (org-move-to-column cc t) (insert ": ")))
21257 (forward-line 1)))
21258 (save-excursion
21259 (org-back-to-heading)
21260 (cond
21261 ((looking-at (format org-heading-keyword-regexp-format
21262 org-quote-string))
21263 (goto-char (match-end 1))
21264 (looking-at (concat " +" org-quote-string))
21265 (replace-match "" t t)
21266 (when (eolp) (insert " ")))
21267 ((looking-at org-outline-regexp)
21268 (goto-char (match-end 0))
21269 (insert org-quote-string " ")))))))
21271 (defun org-reftex-citation ()
21272 "Use reftex-citation to insert a citation into the buffer.
21273 This looks for a line like
21275 #+BIBLIOGRAPHY: foo plain option:-d
21277 and derives from it that foo.bib is the bibliography file relevant
21278 for this document. It then installs the necessary environment for RefTeX
21279 to work in this buffer and calls `reftex-citation' to insert a citation
21280 into the buffer.
21282 Export of such citations to both LaTeX and HTML is handled by the contributed
21283 package org-exp-bibtex by Taru Karttunen."
21284 (interactive)
21285 (let ((reftex-docstruct-symbol 'rds)
21286 (reftex-cite-format "\\cite{%l}")
21287 rds bib)
21288 (save-excursion
21289 (save-restriction
21290 (widen)
21291 (let ((case-fold-search t)
21292 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21293 (if (not (save-excursion
21294 (or (re-search-forward re nil t)
21295 (re-search-backward re nil t))))
21296 (error "No bibliography defined in file")
21297 (setq bib (concat (match-string 1) ".bib")
21298 rds (list (list 'bib bib)))))))
21299 (call-interactively 'reftex-citation)))
21301 ;;;; Functions extending outline functionality
21303 (defun org-beginning-of-line (&optional arg)
21304 "Go to the beginning of the current line. If that is invisible, continue
21305 to a visible line beginning. This makes the function of C-a more intuitive.
21306 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21307 first attempt, and only move to after the tags when the cursor is already
21308 beyond the end of the headline."
21309 (interactive "P")
21310 (let ((pos (point))
21311 (special (if (consp org-special-ctrl-a/e)
21312 (car org-special-ctrl-a/e)
21313 org-special-ctrl-a/e))
21314 refpos)
21315 (if (org-bound-and-true-p visual-line-mode)
21316 (beginning-of-visual-line 1)
21317 (beginning-of-line 1))
21318 (if (and arg (fboundp 'move-beginning-of-line))
21319 (call-interactively 'move-beginning-of-line)
21320 (if (bobp)
21322 (backward-char 1)
21323 (if (org-truely-invisible-p)
21324 (while (and (not (bobp)) (org-truely-invisible-p))
21325 (backward-char 1)
21326 (beginning-of-line 1))
21327 (forward-char 1))))
21328 (when special
21329 (cond
21330 ((and (looking-at org-complex-heading-regexp)
21331 (= (char-after (match-end 1)) ?\ ))
21332 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21333 (point-at-eol)))
21334 (goto-char
21335 (if (eq special t)
21336 (cond ((> pos refpos) refpos)
21337 ((= pos (point)) refpos)
21338 (t (point)))
21339 (cond ((> pos (point)) (point))
21340 ((not (eq last-command this-command)) (point))
21341 (t refpos)))))
21342 ((org-at-item-p)
21343 ;; Being at an item and not looking at an the item means point
21344 ;; was previously moved to beginning of a visual line, which
21345 ;; doesn't contain the item. Therefore, do nothing special,
21346 ;; just stay here.
21347 (when (looking-at org-list-full-item-re)
21348 ;; Set special position at first white space character after
21349 ;; bullet, and check-box, if any.
21350 (let ((after-bullet
21351 (let ((box (match-end 3)))
21352 (if (not box) (match-end 1)
21353 (let ((after (char-after box)))
21354 (if (and after (= after ? )) (1+ box) box))))))
21355 ;; Special case: Move point to special position when
21356 ;; currently after it or at beginning of line.
21357 (if (eq special t)
21358 (when (or (> pos after-bullet) (= (point) pos))
21359 (goto-char after-bullet))
21360 ;; Reversed case: Move point to special position when
21361 ;; point was already at beginning of line and command is
21362 ;; repeated.
21363 (when (and (= (point) pos) (eq last-command this-command))
21364 (goto-char after-bullet))))))))
21365 (org-no-warnings
21366 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21368 (defun org-end-of-line (&optional arg)
21369 "Go to the end of the line.
21370 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21371 tags on the first attempt, and only move to after the tags when
21372 the cursor is already beyond the end of the headline."
21373 (interactive "P")
21374 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21375 org-special-ctrl-a/e))
21376 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21377 'end-of-visual-line)
21378 ((fboundp 'move-end-of-line) 'move-end-of-line)
21379 (t 'end-of-line))))
21380 (if (or (not special) arg) (call-interactively move-fun)
21381 (let* ((element (save-excursion (beginning-of-line)
21382 (org-element-at-point)))
21383 (type (org-element-type element)))
21384 (cond
21385 ((memq type '(headline inlinetask))
21386 (let ((pos (point)))
21387 (beginning-of-line 1)
21388 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21389 (if (eq special t)
21390 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21391 (goto-char (match-beginning 1))
21392 (goto-char (match-end 0)))
21393 (if (or (< pos (match-end 0))
21394 (not (eq this-command last-command)))
21395 (goto-char (match-end 0))
21396 (goto-char (match-beginning 1))))
21397 (call-interactively move-fun))))
21398 ((org-element-property :hiddenp element)
21399 ;; If element is hidden, `move-end-of-line' would put point
21400 ;; after it. Use `end-of-line' to stay on current line.
21401 (call-interactively 'end-of-line))
21402 (t (call-interactively move-fun)))))
21403 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21405 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21406 (define-key org-mode-map "\C-e" 'org-end-of-line)
21408 (defun org-backward-sentence (&optional arg)
21409 "Go to beginning of sentence, or beginning of table field.
21410 This will call `backward-sentence' or `org-table-beginning-of-field',
21411 depending on context."
21412 (interactive "P")
21413 (cond
21414 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21415 (t (call-interactively 'backward-sentence))))
21417 (defun org-forward-sentence (&optional arg)
21418 "Go to end of sentence, or end of table field.
21419 This will call `forward-sentence' or `org-table-end-of-field',
21420 depending on context."
21421 (interactive "P")
21422 (cond
21423 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21424 (t (call-interactively 'forward-sentence))))
21426 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21427 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21429 (defun org-kill-line (&optional arg)
21430 "Kill line, to tags or end of line."
21431 (interactive "P")
21432 (cond
21433 ((or (not org-special-ctrl-k)
21434 (bolp)
21435 (not (org-at-heading-p)))
21436 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21437 org-ctrl-k-protect-subtree)
21438 (if (or (eq org-ctrl-k-protect-subtree 'error)
21439 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21440 (error "C-k aborted - would kill hidden subtree")))
21441 (call-interactively
21442 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21443 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21444 (kill-region (point) (match-beginning 1))
21445 (org-set-tags nil t))
21446 (t (kill-region (point) (point-at-eol)))))
21448 (define-key org-mode-map "\C-k" 'org-kill-line)
21450 (defun org-yank (&optional arg)
21451 "Yank. If the kill is a subtree, treat it specially.
21452 This command will look at the current kill and check if is a single
21453 subtree, or a series of subtrees[1]. If it passes the test, and if the
21454 cursor is at the beginning of a line or after the stars of a currently
21455 empty headline, then the yank is handled specially. How exactly depends
21456 on the value of the following variables, both set by default.
21458 org-yank-folded-subtrees
21459 When set, the subtree(s) will be folded after insertion, but only
21460 if doing so would now swallow text after the yanked text.
21462 org-yank-adjusted-subtrees
21463 When set, the subtree will be promoted or demoted in order to
21464 fit into the local outline tree structure, which means that the level
21465 will be adjusted so that it becomes the smaller one of the two
21466 *visible* surrounding headings.
21468 Any prefix to this command will cause `yank' to be called directly with
21469 no special treatment. In particular, a simple \\[universal-argument] prefix \
21470 will just
21471 plainly yank the text as it is.
21473 \[1] The test checks if the first non-white line is a heading
21474 and if there are no other headings with fewer stars."
21475 (interactive "P")
21476 (org-yank-generic 'yank arg))
21478 (defun org-yank-generic (command arg)
21479 "Perform some yank-like command.
21481 This function implements the behavior described in the `org-yank'
21482 documentation. However, it has been generalized to work for any
21483 interactive command with similar behavior."
21485 ;; pretend to be command COMMAND
21486 (setq this-command command)
21488 (if arg
21489 (call-interactively command)
21491 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21492 (and (org-kill-is-subtree-p)
21493 (or (bolp)
21494 (and (looking-at "[ \t]*$")
21495 (string-match
21496 "\\`\\*+\\'"
21497 (buffer-substring (point-at-bol) (point)))))))
21498 swallowp)
21499 (cond
21500 ((and subtreep org-yank-folded-subtrees)
21501 (let ((beg (point))
21502 end)
21503 (if (and subtreep org-yank-adjusted-subtrees)
21504 (org-paste-subtree nil nil 'for-yank)
21505 (call-interactively command))
21507 (setq end (point))
21508 (goto-char beg)
21509 (when (and (bolp) subtreep
21510 (not (setq swallowp
21511 (org-yank-folding-would-swallow-text beg end))))
21512 (org-with-limited-levels
21513 (or (looking-at org-outline-regexp)
21514 (re-search-forward org-outline-regexp-bol end t))
21515 (while (and (< (point) end) (looking-at org-outline-regexp))
21516 (hide-subtree)
21517 (org-cycle-show-empty-lines 'folded)
21518 (condition-case nil
21519 (outline-forward-same-level 1)
21520 (error (goto-char end))))))
21521 (when swallowp
21522 (message
21523 "Inserted text not folded because that would swallow text"))
21525 (goto-char end)
21526 (skip-chars-forward " \t\n\r")
21527 (beginning-of-line 1)
21528 (push-mark beg 'nomsg)))
21529 ((and subtreep org-yank-adjusted-subtrees)
21530 (let ((beg (point-at-bol)))
21531 (org-paste-subtree nil nil 'for-yank)
21532 (push-mark beg 'nomsg)))
21534 (call-interactively command))))))
21536 (defun org-yank-folding-would-swallow-text (beg end)
21537 "Would hide-subtree at BEG swallow any text after END?"
21538 (let (level)
21539 (org-with-limited-levels
21540 (save-excursion
21541 (goto-char beg)
21542 (when (or (looking-at org-outline-regexp)
21543 (re-search-forward org-outline-regexp-bol end t))
21544 (setq level (org-outline-level)))
21545 (goto-char end)
21546 (skip-chars-forward " \t\r\n\v\f")
21547 (if (or (eobp)
21548 (and (bolp) (looking-at org-outline-regexp)
21549 (<= (org-outline-level) level)))
21550 nil ; Nothing would be swallowed
21551 t))))) ; something would swallow
21553 (define-key org-mode-map "\C-y" 'org-yank)
21555 (defun org-truely-invisible-p ()
21556 "Check if point is at a character currently not visible.
21557 This version does not only check the character property, but also
21558 `visible-mode'."
21559 ;; Early versions of noutline don't have `outline-invisible-p'.
21560 (if (org-bound-and-true-p visible-mode)
21562 (outline-invisible-p)))
21564 (defun org-invisible-p2 ()
21565 "Check if point is at a character currently not visible."
21566 (save-excursion
21567 (if (and (eolp) (not (bobp))) (backward-char 1))
21568 ;; Early versions of noutline don't have `outline-invisible-p'.
21569 (outline-invisible-p)))
21571 (defun org-back-to-heading (&optional invisible-ok)
21572 "Call `outline-back-to-heading', but provide a better error message."
21573 (condition-case nil
21574 (outline-back-to-heading invisible-ok)
21575 (error (error "Before first headline at position %d in buffer %s"
21576 (point) (current-buffer)))))
21578 (defun org-before-first-heading-p ()
21579 "Before first heading?"
21580 (save-excursion
21581 (end-of-line)
21582 (null (re-search-backward org-outline-regexp-bol nil t))))
21584 (defun org-at-heading-p (&optional ignored)
21585 (outline-on-heading-p t))
21586 ;; Compatibility alias with Org versions < 7.8.03
21587 (defalias 'org-on-heading-p 'org-at-heading-p)
21589 (defun org-at-comment-p nil
21590 "Is cursor in a line starting with a # character?"
21591 (save-excursion
21592 (beginning-of-line)
21593 (looking-at "^#")))
21595 (defun org-at-drawer-p nil
21596 "Is cursor at a drawer keyword?"
21597 (save-excursion
21598 (move-beginning-of-line 1)
21599 (looking-at org-drawer-regexp)))
21601 (defun org-at-block-p nil
21602 "Is cursor at a block keyword?"
21603 (save-excursion
21604 (move-beginning-of-line 1)
21605 (looking-at org-block-regexp)))
21607 (defun org-point-at-end-of-empty-headline ()
21608 "If point is at the end of an empty headline, return t, else nil.
21609 If the heading only contains a TODO keyword, it is still still considered
21610 empty."
21611 (and (looking-at "[ \t]*$")
21612 (when org-todo-line-regexp
21613 (save-excursion
21614 (beginning-of-line 1)
21615 (let ((case-fold-search nil))
21616 (looking-at org-todo-line-regexp)
21617 (string= (match-string 3) ""))))))
21619 (defun org-at-heading-or-item-p ()
21620 (or (org-at-heading-p) (org-at-item-p)))
21622 (defun org-at-target-p ()
21623 (or (org-in-regexp org-radio-target-regexp)
21624 (org-in-regexp org-target-regexp)))
21625 ;; Compatibility alias with Org versions < 7.8.03
21626 (defalias 'org-on-target-p 'org-at-target-p)
21628 (defun org-up-heading-all (arg)
21629 "Move to the heading line of which the present line is a subheading.
21630 This function considers both visible and invisible heading lines.
21631 With argument, move up ARG levels."
21632 (if (fboundp 'outline-up-heading-all)
21633 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21634 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21636 (defun org-up-heading-safe ()
21637 "Move to the heading line of which the present line is a subheading.
21638 This version will not throw an error. It will return the level of the
21639 headline found, or nil if no higher level is found.
21641 Also, this function will be a lot faster than `outline-up-heading',
21642 because it relies on stars being the outline starters. This can really
21643 make a significant difference in outlines with very many siblings."
21644 (let (start-level re)
21645 (org-back-to-heading t)
21646 (setq start-level (funcall outline-level))
21647 (if (equal start-level 1)
21649 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21650 (if (re-search-backward re nil t)
21651 (funcall outline-level)))))
21653 (defun org-first-sibling-p ()
21654 "Is this heading the first child of its parents?"
21655 (interactive)
21656 (let ((re org-outline-regexp-bol)
21657 level l)
21658 (unless (org-at-heading-p t)
21659 (error "Not at a heading"))
21660 (setq level (funcall outline-level))
21661 (save-excursion
21662 (if (not (re-search-backward re nil t))
21664 (setq l (funcall outline-level))
21665 (< l level)))))
21667 (defun org-goto-sibling (&optional previous)
21668 "Goto the next sibling, even if it is invisible.
21669 When PREVIOUS is set, go to the previous sibling instead. Returns t
21670 when a sibling was found. When none is found, return nil and don't
21671 move point."
21672 (let ((fun (if previous 're-search-backward 're-search-forward))
21673 (pos (point))
21674 (re org-outline-regexp-bol)
21675 level l)
21676 (when (condition-case nil (org-back-to-heading t) (error nil))
21677 (setq level (funcall outline-level))
21678 (catch 'exit
21679 (or previous (forward-char 1))
21680 (while (funcall fun re nil t)
21681 (setq l (funcall outline-level))
21682 (when (< l level) (goto-char pos) (throw 'exit nil))
21683 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21684 (goto-char pos)
21685 nil))))
21687 (defun org-show-siblings ()
21688 "Show all siblings of the current headline."
21689 (save-excursion
21690 (while (org-goto-sibling) (org-flag-heading nil)))
21691 (save-excursion
21692 (while (org-goto-sibling 'previous)
21693 (org-flag-heading nil))))
21695 (defun org-goto-first-child ()
21696 "Goto the first child, even if it is invisible.
21697 Return t when a child was found. Otherwise don't move point and
21698 return nil."
21699 (let (level (pos (point)) (re org-outline-regexp-bol))
21700 (when (condition-case nil (org-back-to-heading t) (error nil))
21701 (setq level (outline-level))
21702 (forward-char 1)
21703 (if (and (re-search-forward re nil t) (> (outline-level) level))
21704 (progn (goto-char (match-beginning 0)) t)
21705 (goto-char pos) nil))))
21707 (defun org-show-hidden-entry ()
21708 "Show an entry where even the heading is hidden."
21709 (save-excursion
21710 (org-show-entry)))
21712 (defun org-flag-heading (flag &optional entry)
21713 "Flag the current heading. FLAG non-nil means make invisible.
21714 When ENTRY is non-nil, show the entire entry."
21715 (save-excursion
21716 (org-back-to-heading t)
21717 ;; Check if we should show the entire entry
21718 (if entry
21719 (progn
21720 (org-show-entry)
21721 (save-excursion
21722 (and (outline-next-heading)
21723 (org-flag-heading nil))))
21724 (outline-flag-region (max (point-min) (1- (point)))
21725 (save-excursion (outline-end-of-heading) (point))
21726 flag))))
21728 (defun org-get-next-sibling ()
21729 "Move to next heading of the same level, and return point.
21730 If there is no such heading, return nil.
21731 This is like outline-next-sibling, but invisible headings are ok."
21732 (let ((level (funcall outline-level)))
21733 (outline-next-heading)
21734 (while (and (not (eobp)) (> (funcall outline-level) level))
21735 (outline-next-heading))
21736 (if (or (eobp) (< (funcall outline-level) level))
21738 (point))))
21740 (defun org-get-last-sibling ()
21741 "Move to previous heading of the same level, and return point.
21742 If there is no such heading, return nil."
21743 (let ((opoint (point))
21744 (level (funcall outline-level)))
21745 (outline-previous-heading)
21746 (when (and (/= (point) opoint) (outline-on-heading-p t))
21747 (while (and (> (funcall outline-level) level)
21748 (not (bobp)))
21749 (outline-previous-heading))
21750 (if (< (funcall outline-level) level)
21752 (point)))))
21754 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21755 "Goto to the end of a subtree."
21756 ;; This contains an exact copy of the original function, but it uses
21757 ;; `org-back-to-heading', to make it work also in invisible
21758 ;; trees. And is uses an invisible-ok argument.
21759 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21760 ;; Furthermore, when used inside Org, finding the end of a large subtree
21761 ;; with many children and grandchildren etc, this can be much faster
21762 ;; than the outline version.
21763 (org-back-to-heading invisible-ok)
21764 (let ((first t)
21765 (level (funcall outline-level)))
21766 (if (and (derived-mode-p 'org-mode) (< level 1000))
21767 ;; A true heading (not a plain list item), in Org-mode
21768 ;; This means we can easily find the end by looking
21769 ;; only for the right number of stars. Using a regexp to do
21770 ;; this is so much faster than using a Lisp loop.
21771 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21772 (forward-char 1)
21773 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21774 ;; something else, do it the slow way
21775 (while (and (not (eobp))
21776 (or first (> (funcall outline-level) level)))
21777 (setq first nil)
21778 (outline-next-heading)))
21779 (unless to-heading
21780 (if (memq (preceding-char) '(?\n ?\^M))
21781 (progn
21782 ;; Go to end of line before heading
21783 (forward-char -1)
21784 (if (memq (preceding-char) '(?\n ?\^M))
21785 ;; leave blank line before heading
21786 (forward-char -1))))))
21787 (point))
21789 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21790 "Use Org version in org-mode, for dramatic speed-up."
21791 (if (derived-mode-p 'org-mode)
21792 (progn
21793 (org-end-of-subtree nil t)
21794 (unless (eobp) (backward-char 1)))
21795 ad-do-it))
21797 (defun org-end-of-meta-data-and-drawers ()
21798 "Jump to the first text after meta data and drawers in the current entry.
21799 This will move over empty lines, lines with planning time stamps,
21800 clocking lines, and drawers."
21801 (org-back-to-heading t)
21802 (let ((end (save-excursion (outline-next-heading) (point)))
21803 (re (concat "\\(" org-drawer-regexp "\\)"
21804 "\\|" "[ \t]*" org-keyword-time-regexp)))
21805 (forward-line 1)
21806 (while (re-search-forward re end t)
21807 (if (not (match-end 1))
21808 ;; empty or planning line
21809 (forward-line 1)
21810 ;; a drawer, find the end
21811 (re-search-forward "^[ \t]*:END:" end 'move)
21812 (forward-line 1)))
21813 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21814 (point)))
21816 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21817 "Move forward to the arg'th subheading at same level as this one.
21818 Stop at the first and last subheadings of a superior heading.
21819 Normally this only looks at visible headings, but when INVISIBLE-OK is
21820 non-nil it will also look at invisible ones."
21821 (interactive "p")
21822 (org-back-to-heading invisible-ok)
21823 (org-at-heading-p)
21824 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21825 (re (format "^\\*\\{1,%d\\} " level))
21827 (forward-char 1)
21828 (while (> arg 0)
21829 (while (and (re-search-forward re nil 'move)
21830 (setq l (- (match-end 0) (match-beginning 0) 1))
21831 (= l level)
21832 (not invisible-ok)
21833 (progn (backward-char 1) (outline-invisible-p)))
21834 (if (< l level) (setq arg 1)))
21835 (setq arg (1- arg)))
21836 (beginning-of-line 1)))
21838 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21839 "Move backward to the arg'th subheading at same level as this one.
21840 Stop at the first and last subheadings of a superior heading."
21841 (interactive "p")
21842 (org-back-to-heading)
21843 (org-at-heading-p)
21844 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21845 (re (format "^\\*\\{1,%d\\} " level))
21847 (while (> arg 0)
21848 (while (and (re-search-backward re nil 'move)
21849 (setq l (- (match-end 0) (match-beginning 0) 1))
21850 (= l level)
21851 (not invisible-ok)
21852 (outline-invisible-p))
21853 (if (< l level) (setq arg 1)))
21854 (setq arg (1- arg)))))
21856 (defun org-forward-element ()
21857 "Move forward by one element.
21858 Move to the next element at the same level, when possible."
21859 (interactive)
21860 (cond ((eobp) (error "Cannot move further down"))
21861 ((org-with-limited-levels (org-at-heading-p))
21862 (let ((origin (point)))
21863 (org-forward-heading-same-level 1)
21864 (unless (org-with-limited-levels (org-at-heading-p))
21865 (goto-char origin)
21866 (error "Cannot move further down"))))
21868 (let* ((elem (org-element-at-point))
21869 (end (org-element-property :end elem))
21870 (parent (org-element-property :parent elem)))
21871 (if (and parent (= (org-element-property :contents-end parent) end))
21872 (goto-char (org-element-property :end parent))
21873 (goto-char end))))))
21875 (defun org-backward-element ()
21876 "Move backward by one element.
21877 Move to the previous element at the same level, when possible."
21878 (interactive)
21879 (cond ((bobp) (error "Cannot move further up"))
21880 ((org-with-limited-levels (org-at-heading-p))
21881 ;; At an headline, move to the previous one, if any, or stay
21882 ;; here.
21883 (let ((origin (point)))
21884 (org-backward-heading-same-level 1)
21885 (unless (org-with-limited-levels (org-at-heading-p))
21886 (goto-char origin)
21887 (error "Cannot move further up"))))
21889 (let* ((trail (org-element-at-point 'keep-trail))
21890 (elem (car trail))
21891 (prev-elem (nth 1 trail))
21892 (beg (org-element-property :begin elem)))
21893 (cond
21894 ;; Move to beginning of current element if point isn't
21895 ;; there already.
21896 ((/= (point) beg) (goto-char beg))
21897 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21898 ((org-before-first-heading-p) (goto-char (point-min)))
21899 (t (org-back-to-heading)))))))
21901 (defun org-up-element ()
21902 "Move to upper element."
21903 (interactive)
21904 (if (org-with-limited-levels (org-at-heading-p))
21905 (unless (org-up-heading-safe) (error "No surrounding element"))
21906 (let* ((elem (org-element-at-point))
21907 (parent (org-element-property :parent elem)))
21908 (if parent (goto-char (org-element-property :begin parent))
21909 (if (org-with-limited-levels (org-before-first-heading-p))
21910 (error "No surrounding element")
21911 (org-with-limited-levels (org-back-to-heading)))))))
21913 (defvar org-element-greater-elements)
21914 (defun org-down-element ()
21915 "Move to inner element."
21916 (interactive)
21917 (let ((element (org-element-at-point)))
21918 (cond
21919 ((memq (org-element-type element) '(plain-list table))
21920 (goto-char (org-element-property :contents-begin element))
21921 (forward-char))
21922 ((memq (org-element-type element) org-element-greater-elements)
21923 ;; If contents are hidden, first disclose them.
21924 (when (org-element-property :hiddenp element) (org-cycle))
21925 (goto-char (or (org-element-property :contents-begin element)
21926 (error "No content for this element"))))
21927 (t (error "No inner element")))))
21929 (defun org-drag-element-backward ()
21930 "Move backward element at point."
21931 (interactive)
21932 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21933 (let* ((trail (org-element-at-point 'keep-trail))
21934 (elem (car trail))
21935 (prev-elem (nth 1 trail)))
21936 ;; Error out if no previous element or previous element is
21937 ;; a parent of the current one.
21938 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21939 (error "Cannot drag element backward")
21940 (let ((pos (point)))
21941 (org-element-swap-A-B prev-elem elem)
21942 (goto-char (+ (org-element-property :begin prev-elem)
21943 (- pos (org-element-property :begin elem)))))))))
21945 (defun org-drag-element-forward ()
21946 "Move forward element at point."
21947 (interactive)
21948 (let* ((pos (point))
21949 (elem (org-element-at-point)))
21950 (when (= (point-max) (org-element-property :end elem))
21951 (error "Cannot drag element forward"))
21952 (goto-char (org-element-property :end elem))
21953 (let ((next-elem (org-element-at-point)))
21954 (when (or (org-element-nested-p elem next-elem)
21955 (and (eq (org-element-type next-elem) 'headline)
21956 (not (eq (org-element-type elem) 'headline))))
21957 (goto-char pos)
21958 (error "Cannot drag element forward"))
21959 ;; Compute new position of point: it's shifted by NEXT-ELEM
21960 ;; body's length (without final blanks) and by the length of
21961 ;; blanks between ELEM and NEXT-ELEM.
21962 (let ((size-next (- (save-excursion
21963 (goto-char (org-element-property :end next-elem))
21964 (skip-chars-backward " \r\t\n")
21965 (forward-line)
21966 ;; Small correction if buffer doesn't end
21967 ;; with a newline character.
21968 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
21969 (org-element-property :begin next-elem)))
21970 (size-blank (- (org-element-property :end elem)
21971 (save-excursion
21972 (goto-char (org-element-property :end elem))
21973 (skip-chars-backward " \r\t\n")
21974 (forward-line)
21975 (point)))))
21976 (org-element-swap-A-B elem next-elem)
21977 (goto-char (+ pos size-next size-blank))))))
21979 (defun org-mark-element ()
21980 "Put point at beginning of this element, mark at end.
21982 Interactively, if this command is repeated or (in Transient Mark
21983 mode) if the mark is active, it marks the next element after the
21984 ones already marked."
21985 (interactive)
21986 (let (deactivate-mark)
21987 (if (and (org-called-interactively-p 'any)
21988 (or (and (eq last-command this-command) (mark t))
21989 (and transient-mark-mode mark-active)))
21990 (set-mark
21991 (save-excursion
21992 (goto-char (mark))
21993 (goto-char (org-element-property :end (org-element-at-point)))))
21994 (let ((element (org-element-at-point)))
21995 (end-of-line)
21996 (push-mark (org-element-property :end element) t t)
21997 (goto-char (org-element-property :begin element))))))
21999 (defun org-narrow-to-element ()
22000 "Narrow buffer to current element."
22001 (interactive)
22002 (let ((elem (org-element-at-point)))
22003 (cond
22004 ((eq (car elem) 'headline)
22005 (narrow-to-region
22006 (org-element-property :begin elem)
22007 (org-element-property :end elem)))
22008 ((memq (car elem) org-element-greater-elements)
22009 (narrow-to-region
22010 (org-element-property :contents-begin elem)
22011 (org-element-property :contents-end elem)))
22013 (narrow-to-region
22014 (org-element-property :begin elem)
22015 (org-element-property :end elem))))))
22017 (defun org-transpose-element ()
22018 "Transpose current and previous elements, keeping blank lines between.
22019 Point is moved after both elements."
22020 (interactive)
22021 (org-skip-whitespace)
22022 (let ((end (org-element-property :end (org-element-at-point))))
22023 (org-drag-element-backward)
22024 (goto-char end)))
22026 (defun org-unindent-buffer ()
22027 "Un-indent the visible part of the buffer.
22028 Relative indentation (between items, inside blocks, etc.) isn't
22029 modified."
22030 (interactive)
22031 (unless (eq major-mode 'org-mode)
22032 (error "Cannot un-indent a buffer not in Org mode"))
22033 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22034 unindent-tree ; For byte-compiler.
22035 (unindent-tree
22036 (function
22037 (lambda (contents)
22038 (mapc
22039 (lambda (element)
22040 (if (memq (org-element-type element) '(headline section))
22041 (funcall unindent-tree (org-element-contents element))
22042 (save-excursion
22043 (save-restriction
22044 (narrow-to-region
22045 (org-element-property :begin element)
22046 (org-element-property :end element))
22047 (org-do-remove-indentation)))))
22048 (reverse contents))))))
22049 (funcall unindent-tree (org-element-contents parse-tree))))
22051 (defun org-show-subtree ()
22052 "Show everything after this heading at deeper levels."
22053 (interactive)
22054 (outline-flag-region
22055 (point)
22056 (save-excursion
22057 (org-end-of-subtree t t))
22058 nil))
22060 (defun org-show-entry ()
22061 "Show the body directly following this heading.
22062 Show the heading too, if it is currently invisible."
22063 (interactive)
22064 (save-excursion
22065 (condition-case nil
22066 (progn
22067 (org-back-to-heading t)
22068 (outline-flag-region
22069 (max (point-min) (1- (point)))
22070 (save-excursion
22071 (if (re-search-forward
22072 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22073 (match-beginning 1)
22074 (point-max)))
22075 nil)
22076 (org-cycle-hide-drawers 'children))
22077 (error nil))))
22079 (defun org-make-options-regexp (kwds &optional extra)
22080 "Make a regular expression for keyword lines."
22081 (concat
22082 "^#\\+\\("
22083 (mapconcat 'regexp-quote kwds "\\|")
22084 (if extra (concat "\\|" extra))
22085 "\\):[ \t]*\\(.*\\)"))
22087 ;; Make isearch reveal the necessary context
22088 (defun org-isearch-end ()
22089 "Reveal context after isearch exits."
22090 (when isearch-success ; only if search was successful
22091 (if (featurep 'xemacs)
22092 ;; Under XEmacs, the hook is run in the correct place,
22093 ;; we directly show the context.
22094 (org-show-context 'isearch)
22095 ;; In Emacs the hook runs *before* restoring the overlays.
22096 ;; So we have to use a one-time post-command-hook to do this.
22097 ;; (Emacs 22 has a special variable, see function `org-mode')
22098 (unless (and (boundp 'isearch-mode-end-hook-quit)
22099 isearch-mode-end-hook-quit)
22100 ;; Only when the isearch was not quitted.
22101 (org-add-hook 'post-command-hook 'org-isearch-post-command
22102 'append 'local)))))
22104 (defun org-isearch-post-command ()
22105 "Remove self from hook, and show context."
22106 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22107 (org-show-context 'isearch))
22110 ;;;; Integration with and fixes for other packages
22112 ;;; Imenu support
22114 (defvar org-imenu-markers nil
22115 "All markers currently used by Imenu.")
22116 (make-variable-buffer-local 'org-imenu-markers)
22118 (defun org-imenu-new-marker (&optional pos)
22119 "Return a new marker for use by Imenu, and remember the marker."
22120 (let ((m (make-marker)))
22121 (move-marker m (or pos (point)))
22122 (push m org-imenu-markers)
22125 (defun org-imenu-get-tree ()
22126 "Produce the index for Imenu."
22127 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22128 (setq org-imenu-markers nil)
22129 (let* ((n org-imenu-depth)
22130 (re (concat "^" (org-get-limited-outline-regexp)))
22131 (subs (make-vector (1+ n) nil))
22132 (last-level 0)
22133 m level head)
22134 (save-excursion
22135 (save-restriction
22136 (widen)
22137 (goto-char (point-max))
22138 (while (re-search-backward re nil t)
22139 (setq level (org-reduced-level (funcall outline-level)))
22140 (when (and (<= level n)
22141 (looking-at org-complex-heading-regexp))
22142 (setq head (org-link-display-format
22143 (org-match-string-no-properties 4))
22144 m (org-imenu-new-marker))
22145 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22146 (if (>= level last-level)
22147 (push (cons head m) (aref subs level))
22148 (push (cons head (aref subs (1+ level))) (aref subs level))
22149 (loop for i from (1+ level) to n do (aset subs i nil)))
22150 (setq last-level level)))))
22151 (aref subs 1)))
22153 (eval-after-load "imenu"
22154 '(progn
22155 (add-hook 'imenu-after-jump-hook
22156 (lambda ()
22157 (if (derived-mode-p 'org-mode)
22158 (org-show-context 'org-goto))))))
22160 (defun org-link-display-format (link)
22161 "Replace a link with either the description, or the link target
22162 if no description is present"
22163 (save-match-data
22164 (if (string-match org-bracket-link-analytic-regexp link)
22165 (replace-match (if (match-end 5)
22166 (match-string 5 link)
22167 (concat (match-string 1 link)
22168 (match-string 3 link)))
22169 nil t link)
22170 link)))
22172 (defun org-toggle-link-display ()
22173 "Toggle the literal or descriptive display of links."
22174 (interactive)
22175 (if org-descriptive-links
22176 (progn (org-remove-from-invisibility-spec '(org-link))
22177 (org-restart-font-lock)
22178 (setq org-descriptive-links nil))
22179 (progn (add-to-invisibility-spec '(org-link))
22180 (org-restart-font-lock)
22181 (setq org-descriptive-links t))))
22183 ;; Speedbar support
22185 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22186 "Overlay marking the agenda restriction line in speedbar.")
22187 (overlay-put org-speedbar-restriction-lock-overlay
22188 'face 'org-agenda-restriction-lock)
22189 (overlay-put org-speedbar-restriction-lock-overlay
22190 'help-echo "Agendas are currently limited to this item.")
22191 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22193 (defun org-speedbar-set-agenda-restriction ()
22194 "Restrict future agenda commands to the location at point in speedbar.
22195 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22196 (interactive)
22197 (require 'org-agenda)
22198 (let (p m tp np dir txt)
22199 (cond
22200 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22201 'org-imenu t))
22202 (setq m (get-text-property p 'org-imenu-marker))
22203 (with-current-buffer (marker-buffer m)
22204 (goto-char m)
22205 (org-agenda-set-restriction-lock 'subtree)))
22206 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22207 'speedbar-function 'speedbar-find-file))
22208 (setq tp (previous-single-property-change
22209 (1+ p) 'speedbar-function)
22210 np (next-single-property-change
22211 tp 'speedbar-function)
22212 dir (speedbar-line-directory)
22213 txt (buffer-substring-no-properties (or tp (point-min))
22214 (or np (point-max))))
22215 (with-current-buffer (find-file-noselect
22216 (let ((default-directory dir))
22217 (expand-file-name txt)))
22218 (unless (derived-mode-p 'org-mode)
22219 (error "Cannot restrict to non-Org-mode file"))
22220 (org-agenda-set-restriction-lock 'file)))
22221 (t (error "Don't know how to restrict Org-mode's agenda")))
22222 (move-overlay org-speedbar-restriction-lock-overlay
22223 (point-at-bol) (point-at-eol))
22224 (setq current-prefix-arg nil)
22225 (org-agenda-maybe-redo)))
22227 (eval-after-load "speedbar"
22228 '(progn
22229 (speedbar-add-supported-extension ".org")
22230 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22231 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22232 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22233 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22234 (add-hook 'speedbar-visiting-tag-hook
22235 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22237 ;;; Fixes and Hacks for problems with other packages
22239 ;; Make flyspell not check words in links, to not mess up our keymap
22240 (defun org-mode-flyspell-verify ()
22241 "Don't let flyspell put overlays at active buttons, or on
22242 {todo,all-time,additional-option-like}-keywords."
22243 (let ((pos (max (1- (point)) (point-min)))
22244 (word (thing-at-point 'word)))
22245 (and (not (get-text-property pos 'keymap))
22246 (not (get-text-property pos 'org-no-flyspell))
22247 (not (member word org-todo-keywords-1))
22248 (not (member word org-all-time-keywords))
22249 (not (member word org-options-keywords))
22250 (not (member word (mapcar 'car org-startup-options)))
22251 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22253 (defun org-remove-flyspell-overlays-in (beg end)
22254 "Remove flyspell overlays in region."
22255 (and (org-bound-and-true-p flyspell-mode)
22256 (fboundp 'flyspell-delete-region-overlays)
22257 (flyspell-delete-region-overlays beg end))
22258 (add-text-properties beg end '(org-no-flyspell t)))
22260 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22261 (eval-after-load "bookmark"
22262 '(if (boundp 'bookmark-after-jump-hook)
22263 ;; We can use the hook
22264 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22265 ;; Hook not available, use advice
22266 (defadvice bookmark-jump (after org-make-visible activate)
22267 "Make the position visible."
22268 (org-bookmark-jump-unhide))))
22270 ;; Make sure saveplace shows the location if it was hidden
22271 (eval-after-load "saveplace"
22272 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22273 "Make the position visible."
22274 (org-bookmark-jump-unhide)))
22276 ;; Make sure ecb shows the location if it was hidden
22277 (eval-after-load "ecb"
22278 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22279 "Make hierarchy visible when jumping into location from ECB tree buffer."
22280 (if (derived-mode-p 'org-mode)
22281 (org-show-context))))
22283 (defun org-bookmark-jump-unhide ()
22284 "Unhide the current position, to show the bookmark location."
22285 (and (derived-mode-p 'org-mode)
22286 (or (outline-invisible-p)
22287 (save-excursion (goto-char (max (point-min) (1- (point))))
22288 (outline-invisible-p)))
22289 (org-show-context 'bookmark-jump)))
22291 ;; Make session.el ignore our circular variable
22292 (eval-after-load "session"
22293 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22295 ;;;; Experimental code
22297 (defun org-closed-in-range ()
22298 "Sparse tree of items closed in a certain time range.
22299 Still experimental, may disappear in the future."
22300 (interactive)
22301 ;; Get the time interval from the user.
22302 (let* ((time1 (org-float-time
22303 (org-read-date nil 'to-time nil "Starting date: ")))
22304 (time2 (org-float-time
22305 (org-read-date nil 'to-time nil "End date:")))
22306 ;; callback function
22307 (callback (lambda ()
22308 (let ((time
22309 (org-float-time
22310 (apply 'encode-time
22311 (org-parse-time-string
22312 (match-string 1))))))
22313 ;; check if time in interval
22314 (and (>= time time1) (<= time time2))))))
22315 ;; make tree, check each match with the callback
22316 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22318 ;;;; Finish up
22320 (provide 'org)
22322 (run-hooks 'org-load-hook)
22324 ;;; org.el ends here