org-html.el (org-html-handle-links): Fix bug in setting the attribute for link with...
[org-mode.git] / lisp / org.el
blobca751a7d4f2b459e183ef0f92acebb85dd3c187f
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 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 When nil, you can use these keybindings to navigate the buffer:
1225 q Quit the org-goto interface
1226 n Go to the next visible heading
1227 p Go to the previous visible heading
1228 f Go one heading forward on same level
1229 b Go one heading backward on same level
1230 u Go one heading up"
1231 :group 'org-edit-structure
1232 :type 'boolean)
1234 (defgroup org-sparse-trees nil
1235 "Options concerning sparse trees in Org-mode."
1236 :tag "Org Sparse Trees"
1237 :group 'org-structure)
1239 (defcustom org-highlight-sparse-tree-matches t
1240 "Non-nil means highlight all matches that define a sparse tree.
1241 The highlights will automatically disappear the next time the buffer is
1242 changed by an edit command."
1243 :group 'org-sparse-trees
1244 :type 'boolean)
1246 (defcustom org-remove-highlights-with-change t
1247 "Non-nil means any change to the buffer will remove temporary highlights.
1248 Such highlights are created by `org-occur' and `org-clock-display'.
1249 When nil, `C-c C-c needs to be used to get rid of the highlights.
1250 The highlights created by `org-preview-latex-fragment' always need
1251 `C-c C-c' to be removed."
1252 :group 'org-sparse-trees
1253 :group 'org-time
1254 :type 'boolean)
1257 (defcustom org-occur-hook '(org-first-headline-recenter)
1258 "Hook that is run after `org-occur' has constructed a sparse tree.
1259 This can be used to recenter the window to show as much of the structure
1260 as possible."
1261 :group 'org-sparse-trees
1262 :type 'hook)
1264 (defgroup org-imenu-and-speedbar nil
1265 "Options concerning imenu and speedbar in Org-mode."
1266 :tag "Org Imenu and Speedbar"
1267 :group 'org-structure)
1269 (defcustom org-imenu-depth 2
1270 "The maximum level for Imenu access to Org-mode headlines.
1271 This also applied for speedbar access."
1272 :group 'org-imenu-and-speedbar
1273 :type 'integer)
1275 (defgroup org-table nil
1276 "Options concerning tables in Org-mode."
1277 :tag "Org Table"
1278 :group 'org)
1280 (defcustom org-enable-table-editor 'optimized
1281 "Non-nil means lines starting with \"|\" are handled by the table editor.
1282 When nil, such lines will be treated like ordinary lines.
1284 When equal to the symbol `optimized', the table editor will be optimized to
1285 do the following:
1286 - Automatic overwrite mode in front of whitespace in table fields.
1287 This makes the structure of the table stay in tact as long as the edited
1288 field does not exceed the column width.
1289 - Minimize the number of realigns. Normally, the table is aligned each time
1290 TAB or RET are pressed to move to another field. With optimization this
1291 happens only if changes to a field might have changed the column width.
1292 Optimization requires replacing the functions `self-insert-command',
1293 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1294 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1295 very good at guessing when a re-align will be necessary, but you can always
1296 force one with \\[org-ctrl-c-ctrl-c].
1298 If you would like to use the optimized version in Org-mode, but the
1299 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1301 This variable can be used to turn on and off the table editor during a session,
1302 but in order to toggle optimization, a restart is required.
1304 See also the variable `org-table-auto-blank-field'."
1305 :group 'org-table
1306 :type '(choice
1307 (const :tag "off" nil)
1308 (const :tag "on" t)
1309 (const :tag "on, optimized" optimized)))
1311 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1312 (version<= emacs-version "24.1"))
1313 "Non-nil means cluster self-insert commands for undo when possible.
1314 If this is set, then, like in the Emacs command loop, 20 consecutive
1315 characters will be undone together.
1316 This is configurable, because there is some impact on typing performance."
1317 :group 'org-table
1318 :type 'boolean)
1320 (defcustom org-table-tab-recognizes-table.el t
1321 "Non-nil means TAB will automatically notice a table.el table.
1322 When it sees such a table, it moves point into it and - if necessary -
1323 calls `table-recognize-table'."
1324 :group 'org-table-editing
1325 :type 'boolean)
1327 (defgroup org-link nil
1328 "Options concerning links in Org-mode."
1329 :tag "Org Link"
1330 :group 'org)
1332 (defvar org-link-abbrev-alist-local nil
1333 "Buffer-local version of `org-link-abbrev-alist', which see.
1334 The value of this is taken from the #+LINK lines.")
1335 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1337 (defcustom org-link-abbrev-alist nil
1338 "Alist of link abbreviations.
1339 The car of each element is a string, to be replaced at the start of a link.
1340 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1341 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1343 [[linkkey:tag][description]]
1345 The 'linkkey' must be a word word, starting with a letter, followed
1346 by letters, numbers, '-' or '_'.
1348 If REPLACE is a string, the tag will simply be appended to create the link.
1349 If the string contains \"%s\", the tag will be inserted there. If the string
1350 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1351 at that point (see the function `url-hexify-string'). If the string contains
1352 the specifier \"%(my-function)\", then the custom function `my-function' will
1353 be invoked: this function takes the tag as its only argument and must return
1354 a string.
1356 REPLACE may also be a function that will be called with the tag as the
1357 only argument to create the link, which should be returned as a string.
1359 See the manual for examples."
1360 :group 'org-link
1361 :type '(repeat
1362 (cons
1363 (string :tag "Protocol")
1364 (choice
1365 (string :tag "Format")
1366 (function)))))
1368 (defcustom org-descriptive-links t
1369 "Non-nil means Org will display descriptive links.
1370 E.g. [[http://orgmode.org][Org website]] will be displayed as
1371 \"Org Website\", hiding the link itself and just displaying its
1372 description. When set to `nil', Org will display the full links
1373 literally.
1375 You can interactively set the value of this variable by calling
1376 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1377 :group 'org-link
1378 :type 'boolean)
1380 (defcustom org-link-file-path-type 'adaptive
1381 "How the path name in file links should be stored.
1382 Valid values are:
1384 relative Relative to the current directory, i.e. the directory of the file
1385 into which the link is being inserted.
1386 absolute Absolute path, if possible with ~ for home directory.
1387 noabbrev Absolute path, no abbreviation of home directory.
1388 adaptive Use relative path for files in the current directory and sub-
1389 directories of it. For other files, use an absolute path."
1390 :group 'org-link
1391 :type '(choice
1392 (const relative)
1393 (const absolute)
1394 (const noabbrev)
1395 (const adaptive)))
1397 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1398 "Types of links that should be activated in Org-mode files.
1399 This is a list of symbols, each leading to the activation of a certain link
1400 type. In principle, it does not hurt to turn on most link types - there may
1401 be a small gain when turning off unused link types. The types are:
1403 bracket The recommended [[link][description]] or [[link]] links with hiding.
1404 angle Links in angular brackets that may contain whitespace like
1405 <bbdb:Carsten Dominik>.
1406 plain Plain links in normal text, no whitespace, like http://google.com.
1407 radio Text that is matched by a radio target, see manual for details.
1408 tag Tag settings in a headline (link to tag search).
1409 date Time stamps (link to calendar).
1410 footnote Footnote labels.
1412 Changing this variable requires a restart of Emacs to become effective."
1413 :group 'org-link
1414 :type '(set :greedy t
1415 (const :tag "Double bracket links" bracket)
1416 (const :tag "Angular bracket links" angle)
1417 (const :tag "Plain text links" plain)
1418 (const :tag "Radio target matches" radio)
1419 (const :tag "Tags" tag)
1420 (const :tag "Timestamps" date)
1421 (const :tag "Footnotes" footnote)))
1423 (defcustom org-make-link-description-function nil
1424 "Function to use for generating link descriptions from links.
1425 When nil, the link location will be used. This function must take
1426 two parameters: the first one is the link, the second one is the
1427 description generated by `org-insert-link'. The function should
1428 return the description to use."
1429 :group 'org-link
1430 :type 'function)
1432 (defgroup org-link-store nil
1433 "Options concerning storing links in Org-mode."
1434 :tag "Org Store Link"
1435 :group 'org-link)
1437 (defcustom org-url-hexify-p t
1438 "When non-nil, hexify URL when creating a link."
1439 :type 'boolean
1440 :version "24.3"
1441 :group 'org-link-store)
1443 (defcustom org-email-link-description-format "Email %c: %.30s"
1444 "Format of the description part of a link to an email or usenet message.
1445 The following %-escapes will be replaced by corresponding information:
1447 %F full \"From\" field
1448 %f name, taken from \"From\" field, address if no name
1449 %T full \"To\" field
1450 %t first name in \"To\" field, address if no name
1451 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1452 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1453 %s subject
1454 %d date
1455 %m message-id.
1457 You may use normal field width specification between the % and the letter.
1458 This is for example useful to limit the length of the subject.
1460 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1461 :group 'org-link-store
1462 :type 'string)
1464 (defcustom org-from-is-user-regexp
1465 (let (r1 r2)
1466 (when (and user-mail-address (not (string= user-mail-address "")))
1467 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1468 (when (and user-full-name (not (string= user-full-name "")))
1469 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1470 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1471 "Regexp matched against the \"From:\" header of an email or usenet message.
1472 It should match if the message is from the user him/herself."
1473 :group 'org-link-store
1474 :type 'regexp)
1476 (defcustom org-context-in-file-links t
1477 "Non-nil means file links from `org-store-link' contain context.
1478 A search string will be added to the file name with :: as separator and
1479 used to find the context when the link is activated by the command
1480 `org-open-at-point'. When this option is t, the entire active region
1481 will be placed in the search string of the file link. If set to a
1482 positive integer, only the first n lines of context will be stored.
1484 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1485 negates this setting for the duration of the command."
1486 :group 'org-link-store
1487 :type '(choice boolean integer))
1489 (defcustom org-keep-stored-link-after-insertion nil
1490 "Non-nil means keep link in list for entire session.
1492 The command `org-store-link' adds a link pointing to the current
1493 location to an internal list. These links accumulate during a session.
1494 The command `org-insert-link' can be used to insert links into any
1495 Org-mode file (offering completion for all stored links). When this
1496 option is nil, every link which has been inserted once using \\[org-insert-link]
1497 will be removed from the list, to make completing the unused links
1498 more efficient."
1499 :group 'org-link-store
1500 :type 'boolean)
1502 (defgroup org-link-follow nil
1503 "Options concerning following links in Org-mode."
1504 :tag "Org Follow Link"
1505 :group 'org-link)
1507 (defcustom org-link-translation-function nil
1508 "Function to translate links with different syntax to Org syntax.
1509 This can be used to translate links created for example by the Planner
1510 or emacs-wiki packages to Org syntax.
1511 The function must accept two parameters, a TYPE containing the link
1512 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1513 which is everything after the link protocol. It should return a cons
1514 with possibly modified values of type and path.
1515 Org contains a function for this, so if you set this variable to
1516 `org-translate-link-from-planner', you should be able follow many
1517 links created by planner."
1518 :group 'org-link-follow
1519 :type 'function)
1521 (defcustom org-follow-link-hook nil
1522 "Hook that is run after a link has been followed."
1523 :group 'org-link-follow
1524 :type 'hook)
1526 (defcustom org-tab-follows-link nil
1527 "Non-nil means on links TAB will follow the link.
1528 Needs to be set before org.el is loaded.
1529 This really should not be used, it does not make sense, and the
1530 implementation is bad."
1531 :group 'org-link-follow
1532 :type 'boolean)
1534 (defcustom org-return-follows-link nil
1535 "Non-nil means on links RET will follow the link."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mouse-1-follows-link
1540 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1541 "Non-nil means mouse-1 on a link will follow the link.
1542 A longer mouse click will still set point. Does not work on XEmacs.
1543 Needs to be set before org.el is loaded."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-mark-ring-length 4
1548 "Number of different positions to be recorded in the ring.
1549 Changing this requires a restart of Emacs to work correctly."
1550 :group 'org-link-follow
1551 :type 'integer)
1553 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1554 "Non-nil means internal links in Org files must exactly match a headline.
1555 When nil, the link search tries to match a phrase with all words
1556 in the search text."
1557 :group 'org-link-follow
1558 :version "24.1"
1559 :type '(choice
1560 (const :tag "Use fuzzy text search" nil)
1561 (const :tag "Match only exact headline" t)
1562 (const :tag "Match exact headline or query to create it"
1563 query-to-create)))
1565 (defcustom org-link-frame-setup
1566 '((vm . vm-visit-folder-other-frame)
1567 (vm-imap . vm-visit-imap-folder-other-frame)
1568 (gnus . org-gnus-no-new-news)
1569 (file . find-file-other-window)
1570 (wl . wl-other-frame))
1571 "Setup the frame configuration for following links.
1572 When following a link with Emacs, it may often be useful to display
1573 this link in another window or frame. This variable can be used to
1574 set this up for the different types of links.
1575 For VM, use any of
1576 `vm-visit-folder'
1577 `vm-visit-folder-other-window'
1578 `vm-visit-folder-other-frame'
1579 For Gnus, use any of
1580 `gnus'
1581 `gnus-other-frame'
1582 `org-gnus-no-new-news'
1583 For FILE, use any of
1584 `find-file'
1585 `find-file-other-window'
1586 `find-file-other-frame'
1587 For Wanderlust use any of
1588 `wl'
1589 `wl-other-frame'
1590 For the calendar, use the variable `calendar-setup'.
1591 For BBDB, it is currently only possible to display the matches in
1592 another window."
1593 :group 'org-link-follow
1594 :type '(list
1595 (cons (const vm)
1596 (choice
1597 (const vm-visit-folder)
1598 (const vm-visit-folder-other-window)
1599 (const vm-visit-folder-other-frame)))
1600 (cons (const gnus)
1601 (choice
1602 (const gnus)
1603 (const gnus-other-frame)
1604 (const org-gnus-no-new-news)))
1605 (cons (const file)
1606 (choice
1607 (const find-file)
1608 (const find-file-other-window)
1609 (const find-file-other-frame)))
1610 (cons (const wl)
1611 (choice
1612 (const wl)
1613 (const wl-other-frame)))))
1615 (defcustom org-display-internal-link-with-indirect-buffer nil
1616 "Non-nil means use indirect buffer to display infile links.
1617 Activating internal links (from one location in a file to another location
1618 in the same file) normally just jumps to the location. When the link is
1619 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1620 is displayed in
1621 another window. When this option is set, the other window actually displays
1622 an indirect buffer clone of the current buffer, to avoid any visibility
1623 changes to the current buffer."
1624 :group 'org-link-follow
1625 :type 'boolean)
1627 (defcustom org-open-non-existing-files nil
1628 "Non-nil means `org-open-file' will open non-existing files.
1629 When nil, an error will be generated.
1630 This variable applies only to external applications because they
1631 might choke on non-existing files. If the link is to a file that
1632 will be opened in Emacs, the variable is ignored."
1633 :group 'org-link-follow
1634 :type 'boolean)
1636 (defcustom org-open-directory-means-index-dot-org nil
1637 "Non-nil means a link to a directory really means to index.org.
1638 When nil, following a directory link will run dired or open a finder/explorer
1639 window on that directory."
1640 :group 'org-link-follow
1641 :type 'boolean)
1643 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1644 "Function and arguments to call for following mailto links.
1645 This is a list with the first element being a Lisp function, and the
1646 remaining elements being arguments to the function. In string arguments,
1647 %a will be replaced by the address, and %s will be replaced by the subject
1648 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1649 :group 'org-link-follow
1650 :type '(choice
1651 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1652 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1653 (const :tag "message-mail" (message-mail "%a" "%s"))
1654 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1656 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1657 "Non-nil means ask for confirmation before executing shell links.
1658 Shell links can be dangerous: just think about a link
1660 [[shell:rm -rf ~/*][Google Search]]
1662 This link would show up in your Org-mode document as \"Google Search\",
1663 but really it would remove your entire home directory.
1664 Therefore we advise against setting this variable to nil.
1665 Just change it to `y-or-n-p' if you want to confirm with a
1666 single keystroke rather than having to type \"yes\"."
1667 :group 'org-link-follow
1668 :type '(choice
1669 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1670 (const :tag "with y-or-n (faster)" y-or-n-p)
1671 (const :tag "no confirmation (dangerous)" nil)))
1672 (put 'org-confirm-shell-link-function
1673 'safe-local-variable
1674 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1676 (defcustom org-confirm-shell-link-not-regexp ""
1677 "A regexp to skip confirmation for shell links."
1678 :group 'org-link-follow
1679 :version "24.1"
1680 :type 'regexp)
1682 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1683 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1684 Elisp links can be dangerous: just think about a link
1686 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1688 This link would show up in your Org-mode document as \"Google Search\",
1689 but really it would remove your entire home directory.
1690 Therefore we advise against setting this variable to nil.
1691 Just change it to `y-or-n-p' if you want to confirm with a
1692 single keystroke rather than having to type \"yes\"."
1693 :group 'org-link-follow
1694 :type '(choice
1695 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1696 (const :tag "with y-or-n (faster)" y-or-n-p)
1697 (const :tag "no confirmation (dangerous)" nil)))
1698 (put 'org-confirm-shell-link-function
1699 'safe-local-variable
1700 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1702 (defcustom org-confirm-elisp-link-not-regexp ""
1703 "A regexp to skip confirmation for Elisp links."
1704 :group 'org-link-follow
1705 :version "24.1"
1706 :type 'regexp)
1708 (defconst org-file-apps-defaults-gnu
1709 '((remote . emacs)
1710 (system . mailcap)
1711 (t . mailcap))
1712 "Default file applications on a UNIX or GNU/Linux system.
1713 See `org-file-apps'.")
1715 (defconst org-file-apps-defaults-macosx
1716 '((remote . emacs)
1717 (t . "open %s")
1718 (system . "open %s")
1719 ("ps.gz" . "gv %s")
1720 ("eps.gz" . "gv %s")
1721 ("dvi" . "xdvi %s")
1722 ("fig" . "xfig %s"))
1723 "Default file applications on a MacOS X system.
1724 The system \"open\" is known as a default, but we use X11 applications
1725 for some files for which the OS does not have a good default.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-windowsnt
1729 (list
1730 '(remote . emacs)
1731 (cons t
1732 (list (if (featurep 'xemacs)
1733 'mswindows-shell-execute
1734 'w32-shell-execute)
1735 "open" 'file))
1736 (cons 'system
1737 (list (if (featurep 'xemacs)
1738 'mswindows-shell-execute
1739 'w32-shell-execute)
1740 "open" 'file)))
1741 "Default file applications on a Windows NT system.
1742 The system \"open\" is used for most files.
1743 See `org-file-apps'.")
1745 (defcustom org-file-apps
1747 (auto-mode . emacs)
1748 ("\\.mm\\'" . default)
1749 ("\\.x?html?\\'" . default)
1750 ("\\.pdf\\'" . default)
1752 "External applications for opening `file:path' items in a document.
1753 Org-mode uses system defaults for different file types, but
1754 you can use this variable to set the application for a given file
1755 extension. The entries in this list are cons cells where the car identifies
1756 files and the cdr the corresponding command. Possible values for the
1757 file identifier are
1758 \"string\" A string as a file identifier can be interpreted in different
1759 ways, depending on its contents:
1761 - Alphanumeric characters only:
1762 Match links with this file extension.
1763 Example: (\"pdf\" . \"evince %s\")
1764 to open PDFs with evince.
1766 - Regular expression: Match links where the
1767 filename matches the regexp. If you want to
1768 use groups here, use shy groups.
1770 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1771 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1772 to open *.html and *.xhtml with firefox.
1774 - Regular expression which contains (non-shy) groups:
1775 Match links where the whole link, including \"::\", and
1776 anything after that, matches the regexp.
1777 In a custom command string, %1, %2, etc. are replaced with
1778 the parts of the link that were matched by the groups.
1779 For backwards compatibility, if a command string is given
1780 that does not use any of the group matches, this case is
1781 handled identically to the second one (i.e. match against
1782 file name only).
1783 In a custom lisp form, you can access the group matches with
1784 (match-string n link).
1786 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1787 to open [[file:document.pdf::5]] with evince at page 5.
1789 `directory' Matches a directory
1790 `remote' Matches a remote file, accessible through tramp or efs.
1791 Remote files most likely should be visited through Emacs
1792 because external applications cannot handle such paths.
1793 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1794 so all files Emacs knows how to handle. Using this with
1795 command `emacs' will open most files in Emacs. Beware that this
1796 will also open html files inside Emacs, unless you add
1797 (\"html\" . default) to the list as well.
1798 t Default for files not matched by any of the other options.
1799 `system' The system command to open files, like `open' on Windows
1800 and Mac OS X, and mailcap under GNU/Linux. This is the command
1801 that will be selected if you call `C-c C-o' with a double
1802 \\[universal-argument] \\[universal-argument] prefix.
1804 Possible values for the command are:
1805 `emacs' The file will be visited by the current Emacs process.
1806 `default' Use the default application for this file type, which is the
1807 association for t in the list, most likely in the system-specific
1808 part.
1809 This can be used to overrule an unwanted setting in the
1810 system-specific variable.
1811 `system' Use the system command for opening files, like \"open\".
1812 This command is specified by the entry whose car is `system'.
1813 Most likely, the system-specific version of this variable
1814 does define this command, but you can overrule/replace it
1815 here.
1816 string A command to be executed by a shell; %s will be replaced
1817 by the path to the file.
1818 sexp A Lisp form which will be evaluated. The file path will
1819 be available in the Lisp variable `file'.
1820 For more examples, see the system specific constants
1821 `org-file-apps-defaults-macosx'
1822 `org-file-apps-defaults-windowsnt'
1823 `org-file-apps-defaults-gnu'."
1824 :group 'org-link-follow
1825 :type '(repeat
1826 (cons (choice :value ""
1827 (string :tag "Extension")
1828 (const :tag "System command to open files" system)
1829 (const :tag "Default for unrecognized files" t)
1830 (const :tag "Remote file" remote)
1831 (const :tag "Links to a directory" directory)
1832 (const :tag "Any files that have Emacs modes"
1833 auto-mode))
1834 (choice :value ""
1835 (const :tag "Visit with Emacs" emacs)
1836 (const :tag "Use default" default)
1837 (const :tag "Use the system command" system)
1838 (string :tag "Command")
1839 (sexp :tag "Lisp form")))))
1841 (defcustom org-doi-server-url "http://dx.doi.org/"
1842 "The URL of the DOI server."
1843 :type 'string
1844 :version "24.3"
1845 :group 'org-link-follow)
1847 (defgroup org-refile nil
1848 "Options concerning refiling entries in Org-mode."
1849 :tag "Org Refile"
1850 :group 'org)
1852 (defcustom org-directory "~/org"
1853 "Directory with org files.
1854 This is just a default location to look for Org files. There is no need
1855 at all to put your files into this directory. It is only used in the
1856 following situations:
1858 1. When a capture template specifies a target file that is not an
1859 absolute path. The path will then be interpreted relative to
1860 `org-directory'
1861 2. When a capture note is filed away in an interactive way (when exiting the
1862 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1863 with `org-directory' as the default path."
1864 :group 'org-refile
1865 :group 'org-remember
1866 :group 'org-capture
1867 :type 'directory)
1869 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1870 "Default target for storing notes.
1871 Used as a fall back file for org-remember.el and org-capture.el, for
1872 templates that do not specify a target file."
1873 :group 'org-refile
1874 :group 'org-remember
1875 :group 'org-capture
1876 :type '(choice
1877 (const :tag "Default from remember-data-file" nil)
1878 file))
1880 (defcustom org-goto-interface 'outline
1881 "The default interface to be used for `org-goto'.
1882 Allowed values are:
1883 outline The interface shows an outline of the relevant file
1884 and the correct heading is found by moving through
1885 the outline or by searching with incremental search.
1886 outline-path-completion Headlines in the current buffer are offered via
1887 completion. This is the interface also used by
1888 the refile command."
1889 :group 'org-refile
1890 :type '(choice
1891 (const :tag "Outline" outline)
1892 (const :tag "Outline-path-completion" outline-path-completion)))
1894 (defcustom org-goto-max-level 5
1895 "Maximum target level when running `org-goto' with refile interface."
1896 :group 'org-refile
1897 :type 'integer)
1899 (defcustom org-reverse-note-order nil
1900 "Non-nil means store new notes at the beginning of a file or entry.
1901 When nil, new notes will be filed to the end of a file or entry.
1902 This can also be a list with cons cells of regular expressions that
1903 are matched against file names, and values."
1904 :group 'org-remember
1905 :group 'org-capture
1906 :group 'org-refile
1907 :type '(choice
1908 (const :tag "Reverse always" t)
1909 (const :tag "Reverse never" nil)
1910 (repeat :tag "By file name regexp"
1911 (cons regexp boolean))))
1913 (defcustom org-log-refile nil
1914 "Information to record when a task is refiled.
1916 Possible values are:
1918 nil Don't add anything
1919 time Add a time stamp to the task
1920 note Prompt for a note and add it with template `org-log-note-headings'
1922 This option can also be set with on a per-file-basis with
1924 #+STARTUP: nologrefile
1925 #+STARTUP: logrefile
1926 #+STARTUP: lognoterefile
1928 You can have local logging settings for a subtree by setting the LOGGING
1929 property to one or more of these keywords.
1931 When bulk-refiling from the agenda, the value `note' is forbidden and
1932 will temporarily be changed to `time'."
1933 :group 'org-refile
1934 :group 'org-progress
1935 :version "24.1"
1936 :type '(choice
1937 (const :tag "No logging" nil)
1938 (const :tag "Record timestamp" time)
1939 (const :tag "Record timestamp with note." note)))
1941 (defcustom org-refile-targets nil
1942 "Targets for refiling entries with \\[org-refile].
1943 This is a list of cons cells. Each cell contains:
1944 - a specification of the files to be considered, either a list of files,
1945 or a symbol whose function or variable value will be used to retrieve
1946 a file name or a list of file names. If you use `org-agenda-files' for
1947 that, all agenda files will be scanned for targets. Nil means consider
1948 headings in the current buffer.
1949 - A specification of how to find candidate refile targets. This may be
1950 any of:
1951 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1952 This tag has to be present in all target headlines, inheritance will
1953 not be considered.
1954 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1955 todo keyword.
1956 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1957 headlines that are refiling targets.
1958 - a cons cell (:level . N). Any headline of level N is considered a target.
1959 Note that, when `org-odd-levels-only' is set, level corresponds to
1960 order in hierarchy, not to the number of stars.
1961 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1962 Note that, when `org-odd-levels-only' is set, level corresponds to
1963 order in hierarchy, not to the number of stars.
1965 Each element of this list generates a set of possible targets.
1966 The union of these sets is presented (with completion) to
1967 the user by `org-refile'.
1969 You can set the variable `org-refile-target-verify-function' to a function
1970 to verify each headline found by the simple criteria above.
1972 When this variable is nil, all top-level headlines in the current buffer
1973 are used, equivalent to the value `((nil . (:level . 1))'."
1974 :group 'org-refile
1975 :type '(repeat
1976 (cons
1977 (choice :value org-agenda-files
1978 (const :tag "All agenda files" org-agenda-files)
1979 (const :tag "Current buffer" nil)
1980 (function) (variable) (file))
1981 (choice :tag "Identify target headline by"
1982 (cons :tag "Specific tag" (const :value :tag) (string))
1983 (cons :tag "TODO keyword" (const :value :todo) (string))
1984 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1985 (cons :tag "Level number" (const :value :level) (integer))
1986 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1988 (defcustom org-refile-target-verify-function nil
1989 "Function to verify if the headline at point should be a refile target.
1990 The function will be called without arguments, with point at the
1991 beginning of the headline. It should return t and leave point
1992 where it is if the headline is a valid target for refiling.
1994 If the target should not be selected, the function must return nil.
1995 In addition to this, it may move point to a place from where the search
1996 should be continued. For example, the function may decide that the entire
1997 subtree of the current entry should be excluded and move point to the end
1998 of the subtree."
1999 :group 'org-refile
2000 :type 'function)
2002 (defcustom org-refile-use-cache nil
2003 "Non-nil means cache refile targets to speed up the process.
2004 The cache for a particular file will be updated automatically when
2005 the buffer has been killed, or when any of the marker used for flagging
2006 refile targets no longer points at a live buffer.
2007 If you have added new entries to a buffer that might themselves be targets,
2008 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2009 find that easier, `C-u C-u C-u C-c C-w'."
2010 :group 'org-refile
2011 :version "24.1"
2012 :type 'boolean)
2014 (defcustom org-refile-use-outline-path nil
2015 "Non-nil means provide refile targets as paths.
2016 So a level 3 headline will be available as level1/level2/level3.
2018 When the value is `file', also include the file name (without directory)
2019 into the path. In this case, you can also stop the completion after
2020 the file name, to get entries inserted as top level in the file.
2022 When `full-file-path', include the full file path."
2023 :group 'org-refile
2024 :type '(choice
2025 (const :tag "Not" nil)
2026 (const :tag "Yes" t)
2027 (const :tag "Start with file name" file)
2028 (const :tag "Start with full file path" full-file-path)))
2030 (defcustom org-outline-path-complete-in-steps t
2031 "Non-nil means complete the outline path in hierarchical steps.
2032 When Org-mode uses the refile interface to select an outline path
2033 \(see variable `org-refile-use-outline-path'), the completion of
2034 the path can be done is a single go, or if can be done in steps down
2035 the headline hierarchy. Going in steps is probably the best if you
2036 do not use a special completion package like `ido' or `icicles'.
2037 However, when using these packages, going in one step can be very
2038 fast, while still showing the whole path to the entry."
2039 :group 'org-refile
2040 :type 'boolean)
2042 (defcustom org-refile-allow-creating-parent-nodes nil
2043 "Non-nil means allow to create new nodes as refile targets.
2044 New nodes are then created by adding \"/new node name\" to the completion
2045 of an existing node. When the value of this variable is `confirm',
2046 new node creation must be confirmed by the user (recommended)
2047 When nil, the completion must match an existing entry.
2049 Note that, if the new heading is not seen by the criteria
2050 listed in `org-refile-targets', multiple instances of the same
2051 heading would be created by trying again to file under the new
2052 heading."
2053 :group 'org-refile
2054 :type '(choice
2055 (const :tag "Never" nil)
2056 (const :tag "Always" t)
2057 (const :tag "Prompt for confirmation" confirm)))
2059 (defcustom org-refile-active-region-within-subtree nil
2060 "Non-nil means also refile active region within a subtree.
2062 By default `org-refile' doesn't allow refiling regions if they
2063 don't contain a set of subtrees, but it might be convenient to
2064 do so sometimes: in that case, the first line of the region is
2065 converted to a headline before refiling."
2066 :group 'org-refile
2067 :version "24.1"
2068 :type 'boolean)
2070 (defgroup org-todo nil
2071 "Options concerning TODO items in Org-mode."
2072 :tag "Org TODO"
2073 :group 'org)
2075 (defgroup org-progress nil
2076 "Options concerning Progress logging in Org-mode."
2077 :tag "Org Progress"
2078 :group 'org-time)
2080 (defvar org-todo-interpretation-widgets
2081 '((:tag "Sequence (cycling hits every state)" sequence)
2082 (:tag "Type (cycling directly to DONE)" type))
2083 "The available interpretation symbols for customizing `org-todo-keywords'.
2084 Interested libraries should add to this list.")
2086 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2087 "List of TODO entry keyword sequences and their interpretation.
2088 \\<org-mode-map>This is a list of sequences.
2090 Each sequence starts with a symbol, either `sequence' or `type',
2091 indicating if the keywords should be interpreted as a sequence of
2092 action steps, or as different types of TODO items. The first
2093 keywords are states requiring action - these states will select a headline
2094 for inclusion into the global TODO list Org-mode produces. If one of
2095 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2096 signify that no further action is necessary. If \"|\" is not found,
2097 the last keyword is treated as the only DONE state of the sequence.
2099 The command \\[org-todo] cycles an entry through these states, and one
2100 additional state where no keyword is present. For details about this
2101 cycling, see the manual.
2103 TODO keywords and interpretation can also be set on a per-file basis with
2104 the special #+SEQ_TODO and #+TYP_TODO lines.
2106 Each keyword can optionally specify a character for fast state selection
2107 \(in combination with the variable `org-use-fast-todo-selection')
2108 and specifiers for state change logging, using the same syntax that
2109 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2110 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2111 indicates to record a time stamp each time this state is selected.
2113 Each keyword may also specify if a timestamp or a note should be
2114 recorded when entering or leaving the state, by adding additional
2115 characters in the parenthesis after the keyword. This looks like this:
2116 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2117 record only the time of the state change. With X and Y being either
2118 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2119 Y when leaving the state if and only if the *target* state does not
2120 define X. You may omit any of the fast-selection key or X or /Y,
2121 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2123 For backward compatibility, this variable may also be just a list
2124 of keywords. In this case the interpretation (sequence or type) will be
2125 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2126 :group 'org-todo
2127 :group 'org-keywords
2128 :type '(choice
2129 (repeat :tag "Old syntax, just keywords"
2130 (string :tag "Keyword"))
2131 (repeat :tag "New syntax"
2132 (cons
2133 (choice
2134 :tag "Interpretation"
2135 ;;Quick and dirty way to see
2136 ;;`org-todo-interpretations'. This takes the
2137 ;;place of item arguments
2138 :convert-widget
2139 (lambda (widget)
2140 (widget-put widget
2141 :args (mapcar
2142 #'(lambda (x)
2143 (widget-convert
2144 (cons 'const x)))
2145 org-todo-interpretation-widgets))
2146 widget))
2147 (repeat
2148 (string :tag "Keyword"))))))
2150 (defvar org-todo-keywords-1 nil
2151 "All TODO and DONE keywords active in a buffer.")
2152 (make-variable-buffer-local 'org-todo-keywords-1)
2153 (defvar org-todo-keywords-for-agenda nil)
2154 (defvar org-done-keywords-for-agenda nil)
2155 (defvar org-drawers-for-agenda nil)
2156 (defvar org-todo-keyword-alist-for-agenda nil)
2157 (defvar org-tag-alist-for-agenda nil)
2158 (defvar org-agenda-contributing-files nil)
2159 (defvar org-not-done-keywords nil)
2160 (make-variable-buffer-local 'org-not-done-keywords)
2161 (defvar org-done-keywords nil)
2162 (make-variable-buffer-local 'org-done-keywords)
2163 (defvar org-todo-heads nil)
2164 (make-variable-buffer-local 'org-todo-heads)
2165 (defvar org-todo-sets nil)
2166 (make-variable-buffer-local 'org-todo-sets)
2167 (defvar org-todo-log-states nil)
2168 (make-variable-buffer-local 'org-todo-log-states)
2169 (defvar org-todo-kwd-alist nil)
2170 (make-variable-buffer-local 'org-todo-kwd-alist)
2171 (defvar org-todo-key-alist nil)
2172 (make-variable-buffer-local 'org-todo-key-alist)
2173 (defvar org-todo-key-trigger nil)
2174 (make-variable-buffer-local 'org-todo-key-trigger)
2176 (defcustom org-todo-interpretation 'sequence
2177 "Controls how TODO keywords are interpreted.
2178 This variable is in principle obsolete and is only used for
2179 backward compatibility, if the interpretation of todo keywords is
2180 not given already in `org-todo-keywords'. See that variable for
2181 more information."
2182 :group 'org-todo
2183 :group 'org-keywords
2184 :type '(choice (const sequence)
2185 (const type)))
2187 (defcustom org-use-fast-todo-selection t
2188 "Non-nil means use the fast todo selection scheme with C-c C-t.
2189 This variable describes if and under what circumstances the cycling
2190 mechanism for TODO keywords will be replaced by a single-key, direct
2191 selection scheme.
2193 When nil, fast selection is never used.
2195 When the symbol `prefix', it will be used when `org-todo' is called
2196 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2197 `C-u t' in an agenda buffer.
2199 When t, fast selection is used by default. In this case, the prefix
2200 argument forces cycling instead.
2202 In all cases, the special interface is only used if access keys have
2203 actually been assigned by the user, i.e. if keywords in the configuration
2204 are followed by a letter in parenthesis, like TODO(t)."
2205 :group 'org-todo
2206 :type '(choice
2207 (const :tag "Never" nil)
2208 (const :tag "By default" t)
2209 (const :tag "Only with C-u C-c C-t" prefix)))
2211 (defcustom org-provide-todo-statistics t
2212 "Non-nil means update todo statistics after insert and toggle.
2213 ALL-HEADLINES means update todo statistics by including headlines
2214 with no TODO keyword as well, counting them as not done.
2215 A list of TODO keywords means the same, but skip keywords that are
2216 not in this list.
2218 When this is set, todo statistics is updated in the parent of the
2219 current entry each time a todo state is changed."
2220 :group 'org-todo
2221 :type '(choice
2222 (const :tag "Yes, only for TODO entries" t)
2223 (const :tag "Yes, including all entries" 'all-headlines)
2224 (repeat :tag "Yes, for TODOs in this list"
2225 (string :tag "TODO keyword"))
2226 (other :tag "No TODO statistics" nil)))
2228 (defcustom org-hierarchical-todo-statistics t
2229 "Non-nil means TODO statistics covers just direct children.
2230 When nil, all entries in the subtree are considered.
2231 This has only an effect if `org-provide-todo-statistics' is set.
2232 To set this to nil for only a single subtree, use a COOKIE_DATA
2233 property and include the word \"recursive\" into the value."
2234 :group 'org-todo
2235 :type 'boolean)
2237 (defcustom org-after-todo-state-change-hook nil
2238 "Hook which is run after the state of a TODO item was changed.
2239 The new state (a string with a TODO keyword, or nil) is available in the
2240 Lisp variable `org-state'."
2241 :group 'org-todo
2242 :type 'hook)
2244 (defvar org-blocker-hook nil
2245 "Hook for functions that are allowed to block a state change.
2247 Functions in this hook should not modify the buffer.
2248 Each function gets as its single argument a property list,
2249 see `org-trigger-hook' for more information about this list.
2251 If any of the functions in this hook returns nil, the state change
2252 is blocked.")
2254 (defvar org-trigger-hook nil
2255 "Hook for functions that are triggered by a state change.
2257 Each function gets as its single argument a property list with at
2258 least the following elements:
2260 (:type type-of-change :position pos-at-entry-start
2261 :from old-state :to new-state)
2263 Depending on the type, more properties may be present.
2265 This mechanism is currently implemented for:
2267 TODO state changes
2268 ------------------
2269 :type todo-state-change
2270 :from previous state (keyword as a string), or nil, or a symbol
2271 'todo' or 'done', to indicate the general type of state.
2272 :to new state, like in :from")
2274 (defcustom org-enforce-todo-dependencies nil
2275 "Non-nil means undone TODO entries will block switching the parent to DONE.
2276 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2277 be blocked if any prior sibling is not yet done.
2278 Finally, if the parent is blocked because of ordered siblings of its own,
2279 the child will also be blocked."
2280 :set (lambda (var val)
2281 (set var val)
2282 (if val
2283 (add-hook 'org-blocker-hook
2284 'org-block-todo-from-children-or-siblings-or-parent)
2285 (remove-hook 'org-blocker-hook
2286 'org-block-todo-from-children-or-siblings-or-parent)))
2287 :group 'org-todo
2288 :type 'boolean)
2290 (defcustom org-enforce-todo-checkbox-dependencies nil
2291 "Non-nil means unchecked boxes will block switching the parent to DONE.
2292 When this is nil, checkboxes have no influence on switching TODO states.
2293 When non-nil, you first need to check off all check boxes before the TODO
2294 entry can be switched to DONE.
2295 This variable needs to be set before org.el is loaded, and you need to
2296 restart Emacs after a change to make the change effective. The only way
2297 to change is while Emacs is running is through the customize interface."
2298 :set (lambda (var val)
2299 (set var val)
2300 (if val
2301 (add-hook 'org-blocker-hook
2302 'org-block-todo-from-checkboxes)
2303 (remove-hook 'org-blocker-hook
2304 'org-block-todo-from-checkboxes)))
2305 :group 'org-todo
2306 :type 'boolean)
2308 (defcustom org-treat-insert-todo-heading-as-state-change nil
2309 "Non-nil means inserting a TODO heading is treated as state change.
2310 So when the command \\[org-insert-todo-heading] is used, state change
2311 logging will apply if appropriate. When nil, the new TODO item will
2312 be inserted directly, and no logging will take place."
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2317 "Non-nil means switching TODO states with S-cursor counts as state change.
2318 This is the default behavior. However, setting this to nil allows a
2319 convenient way to select a TODO state and bypass any logging associated
2320 with that."
2321 :group 'org-todo
2322 :type 'boolean)
2324 (defcustom org-todo-state-tags-triggers nil
2325 "Tag changes that should be triggered by TODO state changes.
2326 This is a list. Each entry is
2328 (state-change (tag . flag) .......)
2330 State-change can be a string with a state, and empty string to indicate the
2331 state that has no TODO keyword, or it can be one of the symbols `todo'
2332 or `done', meaning any not-done or done state, respectively."
2333 :group 'org-todo
2334 :group 'org-tags
2335 :type '(repeat
2336 (cons (choice :tag "When changing to"
2337 (const :tag "Not-done state" todo)
2338 (const :tag "Done state" done)
2339 (string :tag "State"))
2340 (repeat
2341 (cons :tag "Tag action"
2342 (string :tag "Tag")
2343 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2345 (defcustom org-log-done nil
2346 "Information to record when a task moves to the DONE state.
2348 Possible values are:
2350 nil Don't add anything, just change the keyword
2351 time Add a time stamp to the task
2352 note Prompt for a note and add it with template `org-log-note-headings'
2354 This option can also be set with on a per-file-basis with
2356 #+STARTUP: nologdone
2357 #+STARTUP: logdone
2358 #+STARTUP: lognotedone
2360 You can have local logging settings for a subtree by setting the LOGGING
2361 property to one or more of these keywords."
2362 :group 'org-todo
2363 :group 'org-progress
2364 :type '(choice
2365 (const :tag "No logging" nil)
2366 (const :tag "Record CLOSED timestamp" time)
2367 (const :tag "Record CLOSED timestamp with note." note)))
2369 ;; Normalize old uses of org-log-done.
2370 (cond
2371 ((eq org-log-done t) (setq org-log-done 'time))
2372 ((and (listp org-log-done) (memq 'done org-log-done))
2373 (setq org-log-done 'note)))
2375 (defcustom org-log-reschedule nil
2376 "Information to record when the scheduling date of a tasks is modified.
2378 Possible values are:
2380 nil Don't add anything, just change the date
2381 time Add a time stamp to the task
2382 note Prompt for a note and add it with template `org-log-note-headings'
2384 This option can also be set with on a per-file-basis with
2386 #+STARTUP: nologreschedule
2387 #+STARTUP: logreschedule
2388 #+STARTUP: lognotereschedule"
2389 :group 'org-todo
2390 :group 'org-progress
2391 :type '(choice
2392 (const :tag "No logging" nil)
2393 (const :tag "Record timestamp" time)
2394 (const :tag "Record timestamp with note." note)))
2396 (defcustom org-log-redeadline nil
2397 "Information to record when the deadline date of a tasks is modified.
2399 Possible values are:
2401 nil Don't add anything, just change the date
2402 time Add a time stamp to the task
2403 note Prompt for a note and add it with template `org-log-note-headings'
2405 This option can also be set with on a per-file-basis with
2407 #+STARTUP: nologredeadline
2408 #+STARTUP: logredeadline
2409 #+STARTUP: lognoteredeadline
2411 You can have local logging settings for a subtree by setting the LOGGING
2412 property to one or more of these keywords."
2413 :group 'org-todo
2414 :group 'org-progress
2415 :type '(choice
2416 (const :tag "No logging" nil)
2417 (const :tag "Record timestamp" time)
2418 (const :tag "Record timestamp with note." note)))
2420 (defcustom org-log-note-clock-out nil
2421 "Non-nil means record a note when clocking out of an item.
2422 This can also be configured on a per-file basis by adding one of
2423 the following lines anywhere in the buffer:
2425 #+STARTUP: lognoteclock-out
2426 #+STARTUP: nolognoteclock-out"
2427 :group 'org-todo
2428 :group 'org-progress
2429 :type 'boolean)
2431 (defcustom org-log-done-with-time t
2432 "Non-nil means the CLOSED time stamp will contain date and time.
2433 When nil, only the date will be recorded."
2434 :group 'org-progress
2435 :type 'boolean)
2437 (defcustom org-log-note-headings
2438 '((done . "CLOSING NOTE %t")
2439 (state . "State %-12s from %-12S %t")
2440 (note . "Note taken on %t")
2441 (reschedule . "Rescheduled from %S on %t")
2442 (delschedule . "Not scheduled, was %S on %t")
2443 (redeadline . "New deadline from %S on %t")
2444 (deldeadline . "Removed deadline, was %S on %t")
2445 (refile . "Refiled on %t")
2446 (clock-out . ""))
2447 "Headings for notes added to entries.
2448 The value is an alist, with the car being a symbol indicating the note
2449 context, and the cdr is the heading to be used. The heading may also be the
2450 empty string.
2451 %t in the heading will be replaced by a time stamp.
2452 %T will be an active time stamp instead the default inactive one
2453 %d will be replaced by a short-format time stamp.
2454 %D will be replaced by an active short-format time stamp.
2455 %s will be replaced by the new TODO state, in double quotes.
2456 %S will be replaced by the old TODO state, in double quotes.
2457 %u will be replaced by the user name.
2458 %U will be replaced by the full user name.
2460 In fact, it is not a good idea to change the `state' entry, because
2461 agenda log mode depends on the format of these entries."
2462 :group 'org-todo
2463 :group 'org-progress
2464 :type '(list :greedy t
2465 (cons (const :tag "Heading when closing an item" done) string)
2466 (cons (const :tag
2467 "Heading when changing todo state (todo sequence only)"
2468 state) string)
2469 (cons (const :tag "Heading when just taking a note" note) string)
2470 (cons (const :tag "Heading when clocking out" clock-out) string)
2471 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2472 (cons (const :tag "Heading when rescheduling" reschedule) string)
2473 (cons (const :tag "Heading when changing deadline" redeadline) string)
2474 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2475 (cons (const :tag "Heading when refiling" refile) string)))
2477 (unless (assq 'note org-log-note-headings)
2478 (push '(note . "%t") org-log-note-headings))
2480 (defcustom org-log-into-drawer nil
2481 "Non-nil means insert state change notes and time stamps into a drawer.
2482 When nil, state changes notes will be inserted after the headline and
2483 any scheduling and clock lines, but not inside a drawer.
2485 The value of this variable should be the name of the drawer to use.
2486 LOGBOOK is proposed as the default drawer for this purpose, you can
2487 also set this to a string to define the drawer of your choice.
2489 A value of t is also allowed, representing \"LOGBOOK\".
2491 If this variable is set, `org-log-state-notes-insert-after-drawers'
2492 will be ignored.
2494 You can set the property LOG_INTO_DRAWER to overrule this setting for
2495 a subtree."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "Not into a drawer" nil)
2500 (const :tag "LOGBOOK" t)
2501 (string :tag "Other")))
2503 (if (fboundp 'defvaralias)
2504 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2506 (defun org-log-into-drawer ()
2507 "Return the value of `org-log-into-drawer', but let properties overrule.
2508 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2509 used instead of the default value."
2510 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2511 (cond
2512 ((not p) org-log-into-drawer)
2513 ((equal p "nil") nil)
2514 ((equal p "t") "LOGBOOK")
2515 (t p))))
2517 (defcustom org-log-state-notes-insert-after-drawers nil
2518 "Non-nil means insert state change notes after any drawers in entry.
2519 Only the drawers that *immediately* follow the headline and the
2520 deadline/scheduled line are skipped.
2521 When nil, insert notes right after the heading and perhaps the line
2522 with deadline/scheduling if present.
2524 This variable will have no effect if `org-log-into-drawer' is
2525 set."
2526 :group 'org-todo
2527 :group 'org-progress
2528 :type 'boolean)
2530 (defcustom org-log-states-order-reversed t
2531 "Non-nil means the latest state note will be directly after heading.
2532 When nil, the state change notes will be ordered according to time."
2533 :group 'org-todo
2534 :group 'org-progress
2535 :type 'boolean)
2537 (defcustom org-todo-repeat-to-state nil
2538 "The TODO state to which a repeater should return the repeating task.
2539 By default this is the first task in a TODO sequence, or the previous state
2540 in a TODO_TYP set. But you can specify another task here.
2541 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2542 :group 'org-todo
2543 :version "24.1"
2544 :type '(choice (const :tag "Head of sequence" nil)
2545 (string :tag "Specific state")))
2547 (defcustom org-log-repeat 'time
2548 "Non-nil means record moving through the DONE state when triggering repeat.
2549 An auto-repeating task is immediately switched back to TODO when
2550 marked DONE. If you are not logging state changes (by adding \"@\"
2551 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2552 record a closing note, there will be no record of the task moving
2553 through DONE. This variable forces taking a note anyway.
2555 nil Don't force a record
2556 time Record a time stamp
2557 note Prompt for a note and add it with template `org-log-note-headings'
2559 This option can also be set with on a per-file-basis with
2561 #+STARTUP: nologrepeat
2562 #+STARTUP: logrepeat
2563 #+STARTUP: lognoterepeat
2565 You can have local logging settings for a subtree by setting the LOGGING
2566 property to one or more of these keywords."
2567 :group 'org-todo
2568 :group 'org-progress
2569 :type '(choice
2570 (const :tag "Don't force a record" nil)
2571 (const :tag "Force recording the DONE state" time)
2572 (const :tag "Force recording a note with the DONE state" note)))
2575 (defgroup org-priorities nil
2576 "Priorities in Org-mode."
2577 :tag "Org Priorities"
2578 :group 'org-todo)
2580 (defcustom org-enable-priority-commands t
2581 "Non-nil means priority commands are active.
2582 When nil, these commands will be disabled, so that you never accidentally
2583 set a priority."
2584 :group 'org-priorities
2585 :type 'boolean)
2587 (defcustom org-highest-priority ?A
2588 "The highest priority of TODO items. A character like ?A, ?B etc.
2589 Must have a smaller ASCII number than `org-lowest-priority'."
2590 :group 'org-priorities
2591 :type 'character)
2593 (defcustom org-lowest-priority ?C
2594 "The lowest priority of TODO items. A character like ?A, ?B etc.
2595 Must have a larger ASCII number than `org-highest-priority'."
2596 :group 'org-priorities
2597 :type 'character)
2599 (defcustom org-default-priority ?B
2600 "The default priority of TODO items.
2601 This is the priority an item gets if no explicit priority is given.
2602 When starting to cycle on an empty priority the first step in the cycle
2603 depends on `org-priority-start-cycle-with-default'. The resulting first
2604 step priority must not exceed the range from `org-highest-priority' to
2605 `org-lowest-priority' which means that `org-default-priority' has to be
2606 in this range exclusive or inclusive the range boundaries. Else the
2607 first step refuses to set the default and the second will fall back
2608 to (depending on the command used) the highest or lowest priority."
2609 :group 'org-priorities
2610 :type 'character)
2612 (defcustom org-priority-start-cycle-with-default t
2613 "Non-nil means start with default priority when starting to cycle.
2614 When this is nil, the first step in the cycle will be (depending on the
2615 command used) one higher or lower than the default priority.
2616 See also `org-default-priority'."
2617 :group 'org-priorities
2618 :type 'boolean)
2620 (defcustom org-get-priority-function nil
2621 "Function to extract the priority from a string.
2622 The string is normally the headline. If this is nil Org computes the
2623 priority from the priority cookie like [#A] in the headline. It returns
2624 an integer, increasing by 1000 for each priority level.
2625 The user can set a different function here, which should take a string
2626 as an argument and return the numeric priority."
2627 :group 'org-priorities
2628 :version "24.1"
2629 :type 'function)
2631 (defgroup org-time nil
2632 "Options concerning time stamps and deadlines in Org-mode."
2633 :tag "Org Time"
2634 :group 'org)
2636 (defcustom org-insert-labeled-timestamps-at-point nil
2637 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2638 When nil, these labeled time stamps are forces into the second line of an
2639 entry, just after the headline. When scheduling from the global TODO list,
2640 the time stamp will always be forced into the second line."
2641 :group 'org-time
2642 :type 'boolean)
2644 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2645 "Formats for `format-time-string' which are used for time stamps.
2646 It is not recommended to change this constant.")
2648 (defcustom org-time-stamp-rounding-minutes '(0 5)
2649 "Number of minutes to round time stamps to.
2650 These are two values, the first applies when first creating a time stamp.
2651 The second applies when changing it with the commands `S-up' and `S-down'.
2652 When changing the time stamp, this means that it will change in steps
2653 of N minutes, as given by the second value.
2655 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2656 numbers should be factors of 60, so for example 5, 10, 15.
2658 When this is larger than 1, you can still force an exact time stamp by using
2659 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2660 and by using a prefix arg to `S-up/down' to specify the exact number
2661 of minutes to shift."
2662 :group 'org-time
2663 :get #'(lambda (var) ; Make sure both elements are there
2664 (if (integerp (default-value var))
2665 (list (default-value var) 5)
2666 (default-value var)))
2667 :type '(list
2668 (integer :tag "when inserting times")
2669 (integer :tag "when modifying times")))
2671 ;; Normalize old customizations of this variable.
2672 (when (integerp org-time-stamp-rounding-minutes)
2673 (setq org-time-stamp-rounding-minutes
2674 (list org-time-stamp-rounding-minutes
2675 org-time-stamp-rounding-minutes)))
2677 (defcustom org-display-custom-times nil
2678 "Non-nil means overlay custom formats over all time stamps.
2679 The formats are defined through the variable `org-time-stamp-custom-formats'.
2680 To turn this on on a per-file basis, insert anywhere in the file:
2681 #+STARTUP: customtime"
2682 :group 'org-time
2683 :set 'set-default
2684 :type 'sexp)
2685 (make-variable-buffer-local 'org-display-custom-times)
2687 (defcustom org-time-stamp-custom-formats
2688 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2689 "Custom formats for time stamps. See `format-time-string' for the syntax.
2690 These are overlaid over the default ISO format if the variable
2691 `org-display-custom-times' is set. Time like %H:%M should be at the
2692 end of the second format. The custom formats are also honored by export
2693 commands, if custom time display is turned on at the time of export."
2694 :group 'org-time
2695 :type 'sexp)
2697 (defun org-time-stamp-format (&optional long inactive)
2698 "Get the right format for a time string."
2699 (let ((f (if long (cdr org-time-stamp-formats)
2700 (car org-time-stamp-formats))))
2701 (if inactive
2702 (concat "[" (substring f 1 -1) "]")
2703 f)))
2705 (defcustom org-time-clocksum-format "%d:%02d"
2706 "The format string used when creating CLOCKSUM lines.
2707 This is also used when org-mode generates a time duration."
2708 :group 'org-time
2709 :type 'string)
2711 (defcustom org-time-clocksum-use-fractional nil
2712 "If non-nil, \\[org-clock-display] uses fractional times.
2713 org-mode generates a time duration."
2714 :group 'org-time
2715 :type 'boolean)
2717 (defcustom org-time-clocksum-fractional-format "%.2f"
2718 "The format string used when creating CLOCKSUM lines, or when
2719 org-mode generates a time duration."
2720 :group 'org-time
2721 :type 'string)
2723 (defcustom org-deadline-warning-days 14
2724 "No. of days before expiration during which a deadline becomes active.
2725 This variable governs the display in sparse trees and in the agenda.
2726 When 0 or negative, it means use this number (the absolute value of it)
2727 even if a deadline has a different individual lead time specified.
2729 Custom commands can set this variable in the options section."
2730 :group 'org-time
2731 :group 'org-agenda-daily/weekly
2732 :type 'integer)
2734 (defcustom org-read-date-prefer-future t
2735 "Non-nil means assume future for incomplete date input from user.
2736 This affects the following situations:
2737 1. The user gives a month but not a year.
2738 For example, if it is April and you enter \"feb 2\", this will be read
2739 as Feb 2, *next* year. \"May 5\", however, will be this year.
2740 2. The user gives a day, but no month.
2741 For example, if today is the 15th, and you enter \"3\", Org-mode will
2742 read this as the third of *next* month. However, if you enter \"17\",
2743 it will be considered as *this* month.
2745 If you set this variable to the symbol `time', then also the following
2746 will work:
2748 3. If the user gives a time.
2749 If the time is before now, it will be interpreted as tomorrow.
2751 Currently none of this works for ISO week specifications.
2753 When this option is nil, the current day, month and year will always be
2754 used as defaults.
2756 See also `org-agenda-jump-prefer-future'."
2757 :group 'org-time
2758 :type '(choice
2759 (const :tag "Never" nil)
2760 (const :tag "Check month and day" t)
2761 (const :tag "Check month, day, and time" time)))
2763 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2764 "Should the agenda jump command prefer the future for incomplete dates?
2765 The default is to do the same as configured in `org-read-date-prefer-future'.
2766 But you can also set a deviating value here.
2767 This may t or nil, or the symbol `org-read-date-prefer-future'."
2768 :group 'org-agenda
2769 :group 'org-time
2770 :version "24.1"
2771 :type '(choice
2772 (const :tag "Use org-read-date-prefer-future"
2773 org-read-date-prefer-future)
2774 (const :tag "Never" nil)
2775 (const :tag "Always" t)))
2777 (defcustom org-read-date-force-compatible-dates t
2778 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2780 Depending on the system Emacs is running on, certain dates cannot
2781 be represented with the type used internally to represent time.
2782 Dates between 1970-1-1 and 2038-1-1 can always be represented
2783 correctly. Some systems allow for earlier dates, some for later,
2784 some for both. One way to find out it to insert any date into an
2785 Org buffer, putting the cursor on the year and hitting S-up and
2786 S-down to test the range.
2788 When this variable is set to t, the date/time prompt will not let
2789 you specify dates outside the 1970-2037 range, so it is certain that
2790 these dates will work in whatever version of Emacs you are
2791 running, and also that you can move a file from one Emacs implementation
2792 to another. WHenever Org is forcing the year for you, it will display
2793 a message and beep.
2795 When this variable is nil, Org will check if the date is
2796 representable in the specific Emacs implementation you are using.
2797 If not, it will force a year, usually the current year, and beep
2798 to remind you. Currently this setting is not recommended because
2799 the likelihood that you will open your Org files in an Emacs that
2800 has limited date range is not negligible.
2802 A workaround for this problem is to use diary sexp dates for time
2803 stamps outside of this range."
2804 :group 'org-time
2805 :version "24.1"
2806 :type 'boolean)
2808 (defcustom org-read-date-display-live t
2809 "Non-nil means display current interpretation of date prompt live.
2810 This display will be in an overlay, in the minibuffer."
2811 :group 'org-time
2812 :type 'boolean)
2814 (defcustom org-read-date-popup-calendar t
2815 "Non-nil means pop up a calendar when prompting for a date.
2816 In the calendar, the date can be selected with mouse-1. However, the
2817 minibuffer will also be active, and you can simply enter the date as well.
2818 When nil, only the minibuffer will be available."
2819 :group 'org-time
2820 :type 'boolean)
2821 (if (fboundp 'defvaralias)
2822 (defvaralias 'org-popup-calendar-for-date-prompt
2823 'org-read-date-popup-calendar))
2825 (defcustom org-read-date-minibuffer-setup-hook nil
2826 "Hook to be used to set up keys for the date/time interface.
2827 Add key definitions to `minibuffer-local-map', which will be a temporary
2828 copy."
2829 :group 'org-time
2830 :type 'hook)
2832 (defcustom org-extend-today-until 0
2833 "The hour when your day really ends. Must be an integer.
2834 This has influence for the following applications:
2835 - When switching the agenda to \"today\". It it is still earlier than
2836 the time given here, the day recognized as TODAY is actually yesterday.
2837 - When a date is read from the user and it is still before the time given
2838 here, the current date and time will be assumed to be yesterday, 23:59.
2839 Also, timestamps inserted in capture templates follow this rule.
2841 IMPORTANT: This is a feature whose implementation is and likely will
2842 remain incomplete. Really, it is only here because past midnight seems to
2843 be the favorite working time of John Wiegley :-)"
2844 :group 'org-time
2845 :type 'integer)
2847 (defcustom org-use-effective-time nil
2848 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2849 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2850 \"effective time\" of any timestamps between midnight and 8am will be
2851 23:59 of the previous day."
2852 :group 'org-time
2853 :version "24.1"
2854 :type 'boolean)
2856 (defcustom org-edit-timestamp-down-means-later nil
2857 "Non-nil means S-down will increase the time in a time stamp.
2858 When nil, S-up will increase."
2859 :group 'org-time
2860 :type 'boolean)
2862 (defcustom org-calendar-follow-timestamp-change t
2863 "Non-nil means make the calendar window follow timestamp changes.
2864 When a timestamp is modified and the calendar window is visible, it will be
2865 moved to the new date."
2866 :group 'org-time
2867 :type 'boolean)
2869 (defgroup org-tags nil
2870 "Options concerning tags in Org-mode."
2871 :tag "Org Tags"
2872 :group 'org)
2874 (defcustom org-tag-alist nil
2875 "List of tags allowed in Org-mode files.
2876 When this list is nil, Org-mode will base TAG input on what is already in the
2877 buffer.
2878 The value of this variable is an alist, the car of each entry must be a
2879 keyword as a string, the cdr may be a character that is used to select
2880 that tag through the fast-tag-selection interface.
2881 See the manual for details."
2882 :group 'org-tags
2883 :type '(repeat
2884 (choice
2885 (cons (string :tag "Tag name")
2886 (character :tag "Access char"))
2887 (list :tag "Start radio group"
2888 (const :startgroup)
2889 (option (string :tag "Group description")))
2890 (list :tag "End radio group"
2891 (const :endgroup)
2892 (option (string :tag "Group description")))
2893 (const :tag "New line" (:newline)))))
2895 (defcustom org-tag-persistent-alist nil
2896 "List of tags that will always appear in all Org-mode files.
2897 This is in addition to any in buffer settings or customizations
2898 of `org-tag-alist'.
2899 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2900 The value of this variable is an alist, the car of each entry must be a
2901 keyword as a string, the cdr may be a character that is used to select
2902 that tag through the fast-tag-selection interface.
2903 See the manual for details.
2904 To disable these tags on a per-file basis, insert anywhere in the file:
2905 #+STARTUP: noptag"
2906 :group 'org-tags
2907 :type '(repeat
2908 (choice
2909 (cons (string :tag "Tag name")
2910 (character :tag "Access char"))
2911 (const :tag "Start radio group" (:startgroup))
2912 (const :tag "End radio group" (:endgroup))
2913 (const :tag "New line" (:newline)))))
2915 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2916 "If non-nil, always offer completion for all tags of all agenda files.
2917 Instead of customizing this variable directly, you might want to
2918 set it locally for capture buffers, because there no list of
2919 tags in that file can be created dynamically (there are none).
2921 (add-hook 'org-capture-mode-hook
2922 (lambda ()
2923 (set (make-local-variable
2924 'org-complete-tags-always-offer-all-agenda-tags)
2925 t)))"
2926 :group 'org-tags
2927 :version "24.1"
2928 :type 'boolean)
2930 (defvar org-file-tags nil
2931 "List of tags that can be inherited by all entries in the file.
2932 The tags will be inherited if the variable `org-use-tag-inheritance'
2933 says they should be.
2934 This variable is populated from #+FILETAGS lines.")
2936 (defcustom org-use-fast-tag-selection 'auto
2937 "Non-nil means use fast tag selection scheme.
2938 This is a special interface to select and deselect tags with single keys.
2939 When nil, fast selection is never used.
2940 When the symbol `auto', fast selection is used if and only if selection
2941 characters for tags have been configured, either through the variable
2942 `org-tag-alist' or through a #+TAGS line in the buffer.
2943 When t, fast selection is always used and selection keys are assigned
2944 automatically if necessary."
2945 :group 'org-tags
2946 :type '(choice
2947 (const :tag "Always" t)
2948 (const :tag "Never" nil)
2949 (const :tag "When selection characters are configured" 'auto)))
2951 (defcustom org-fast-tag-selection-single-key nil
2952 "Non-nil means fast tag selection exits after first change.
2953 When nil, you have to press RET to exit it.
2954 During fast tag selection, you can toggle this flag with `C-c'.
2955 This variable can also have the value `expert'. In this case, the window
2956 displaying the tags menu is not even shown, until you press C-c again."
2957 :group 'org-tags
2958 :type '(choice
2959 (const :tag "No" nil)
2960 (const :tag "Yes" t)
2961 (const :tag "Expert" expert)))
2963 (defvar org-fast-tag-selection-include-todo nil
2964 "Non-nil means fast tags selection interface will also offer TODO states.
2965 This is an undocumented feature, you should not rely on it.")
2967 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2968 "The column to which tags should be indented in a headline.
2969 If this number is positive, it specifies the column. If it is negative,
2970 it means that the tags should be flushright to that column. For example,
2971 -80 works well for a normal 80 character screen.
2972 When 0, place tags directly after headline text, with only one space in
2973 between."
2974 :group 'org-tags
2975 :type 'integer)
2977 (defcustom org-auto-align-tags t
2978 "Non-nil keeps tags aligned when modifying headlines.
2979 Some operations (i.e. demoting) change the length of a headline and
2980 therefore shift the tags around. With this option turned on, after
2981 each such operation the tags are again aligned to `org-tags-column'."
2982 :group 'org-tags
2983 :type 'boolean)
2985 (defcustom org-use-tag-inheritance t
2986 "Non-nil means tags in levels apply also for sublevels.
2987 When nil, only the tags directly given in a specific line apply there.
2988 This may also be a list of tags that should be inherited, or a regexp that
2989 matches tags that should be inherited. Additional control is possible
2990 with the variable `org-tags-exclude-from-inheritance' which gives an
2991 explicit list of tags to be excluded from inheritance, even if the value of
2992 `org-use-tag-inheritance' would select it for inheritance.
2994 If this option is t, a match early-on in a tree can lead to a large
2995 number of matches in the subtree when constructing the agenda or creating
2996 a sparse tree. If you only want to see the first match in a tree during
2997 a search, check out the variable `org-tags-match-list-sublevels'."
2998 :group 'org-tags
2999 :type '(choice
3000 (const :tag "Not" nil)
3001 (const :tag "Always" t)
3002 (repeat :tag "Specific tags" (string :tag "Tag"))
3003 (regexp :tag "Tags matched by regexp")))
3005 (defcustom org-tags-exclude-from-inheritance nil
3006 "List of tags that should never be inherited.
3007 This is a way to exclude a few tags from inheritance. For way to do
3008 the opposite, to actively allow inheritance for selected tags,
3009 see the variable `org-use-tag-inheritance'."
3010 :group 'org-tags
3011 :type '(repeat (string :tag "Tag")))
3013 (defun org-tag-inherit-p (tag)
3014 "Check if TAG is one that should be inherited."
3015 (cond
3016 ((member tag org-tags-exclude-from-inheritance) nil)
3017 ((eq org-use-tag-inheritance t) t)
3018 ((not org-use-tag-inheritance) nil)
3019 ((stringp org-use-tag-inheritance)
3020 (string-match org-use-tag-inheritance tag))
3021 ((listp org-use-tag-inheritance)
3022 (member tag org-use-tag-inheritance))
3023 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3025 (defcustom org-tags-match-list-sublevels t
3026 "Non-nil means list also sublevels of headlines matching a search.
3027 This variable applies to tags/property searches, and also to stuck
3028 projects because this search is based on a tags match as well.
3030 When set to the symbol `indented', sublevels are indented with
3031 leading dots.
3033 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3034 the sublevels of a headline matching a tag search often also match
3035 the same search. Listing all of them can create very long lists.
3036 Setting this variable to nil causes subtrees of a match to be skipped.
3038 This variable is semi-obsolete and probably should always be true. It
3039 is better to limit inheritance to certain tags using the variables
3040 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3041 :group 'org-tags
3042 :type '(choice
3043 (const :tag "No, don't list them" nil)
3044 (const :tag "Yes, do list them" t)
3045 (const :tag "List them, indented with leading dots" indented)))
3047 (defcustom org-tags-sort-function nil
3048 "When set, tags are sorted using this function as a comparator."
3049 :group 'org-tags
3050 :type '(choice
3051 (const :tag "No sorting" nil)
3052 (const :tag "Alphabetical" string<)
3053 (const :tag "Reverse alphabetical" string>)
3054 (function :tag "Custom function" nil)))
3056 (defvar org-tags-history nil
3057 "History of minibuffer reads for tags.")
3058 (defvar org-last-tags-completion-table nil
3059 "The last used completion table for tags.")
3060 (defvar org-after-tags-change-hook nil
3061 "Hook that is run after the tags in a line have changed.")
3063 (defgroup org-properties nil
3064 "Options concerning properties in Org-mode."
3065 :tag "Org Properties"
3066 :group 'org)
3068 (defcustom org-property-format "%-10s %s"
3069 "How property key/value pairs should be formatted by `indent-line'.
3070 When `indent-line' hits a property definition, it will format the line
3071 according to this format, mainly to make sure that the values are
3072 lined-up with respect to each other."
3073 :group 'org-properties
3074 :type 'string)
3076 (defcustom org-properties-postprocess-alist nil
3077 "Alist of properties and functions to adjust inserted values.
3078 Elements of this alist must be of the form
3080 ([string] [function])
3082 where [string] must be a property name and [function] must be a
3083 lambda expression: this lambda expression must take one argument,
3084 the value to adjust, and return the new value as a string.
3086 For example, this element will allow the property \"Remaining\"
3087 to be updated wrt the relation between the \"Effort\" property
3088 and the clock summary:
3090 ((\"Remaining\" (lambda(value)
3091 (let ((clocksum (org-clock-sum-current-item))
3092 (effort (org-duration-string-to-minutes
3093 (org-entry-get (point) \"Effort\"))))
3094 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3095 :group 'org-properties
3096 :version "24.1"
3097 :type '(alist :key-type (string :tag "Property")
3098 :value-type (function :tag "Function")))
3100 (defcustom org-use-property-inheritance nil
3101 "Non-nil means properties apply also for sublevels.
3103 This setting is chiefly used during property searches. Turning it on can
3104 cause significant overhead when doing a search, which is why it is not
3105 on by default.
3107 When nil, only the properties directly given in the current entry count.
3108 When t, every property is inherited. The value may also be a list of
3109 properties that should have inheritance, or a regular expression matching
3110 properties that should be inherited.
3112 However, note that some special properties use inheritance under special
3113 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3114 and the properties ending in \"_ALL\" when they are used as descriptor
3115 for valid values of a property.
3117 Note for programmers:
3118 When querying an entry with `org-entry-get', you can control if inheritance
3119 should be used. By default, `org-entry-get' looks only at the local
3120 properties. You can request inheritance by setting the inherit argument
3121 to t (to force inheritance) or to `selective' (to respect the setting
3122 in this variable)."
3123 :group 'org-properties
3124 :type '(choice
3125 (const :tag "Not" nil)
3126 (const :tag "Always" t)
3127 (repeat :tag "Specific properties" (string :tag "Property"))
3128 (regexp :tag "Properties matched by regexp")))
3130 (defun org-property-inherit-p (property)
3131 "Check if PROPERTY is one that should be inherited."
3132 (cond
3133 ((eq org-use-property-inheritance t) t)
3134 ((not org-use-property-inheritance) nil)
3135 ((stringp org-use-property-inheritance)
3136 (string-match org-use-property-inheritance property))
3137 ((listp org-use-property-inheritance)
3138 (member property org-use-property-inheritance))
3139 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3141 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3142 "The default column format, if no other format has been defined.
3143 This variable can be set on the per-file basis by inserting a line
3145 #+COLUMNS: %25ITEM ....."
3146 :group 'org-properties
3147 :type 'string)
3149 (defcustom org-columns-ellipses ".."
3150 "The ellipses to be used when a field in column view is truncated.
3151 When this is the empty string, as many characters as possible are shown,
3152 but then there will be no visual indication that the field has been truncated.
3153 When this is a string of length N, the last N characters of a truncated
3154 field are replaced by this string. If the column is narrower than the
3155 ellipses string, only part of the ellipses string will be shown."
3156 :group 'org-properties
3157 :type 'string)
3159 (defcustom org-columns-modify-value-for-display-function nil
3160 "Function that modifies values for display in column view.
3161 For example, it can be used to cut out a certain part from a time stamp.
3162 The function must take 2 arguments:
3164 column-title The title of the column (*not* the property name)
3165 value The value that should be modified.
3167 The function should return the value that should be displayed,
3168 or nil if the normal value should be used."
3169 :group 'org-properties
3170 :type 'function)
3172 (defcustom org-effort-property "Effort"
3173 "The property that is being used to keep track of effort estimates.
3174 Effort estimates given in this property need to have the format H:MM."
3175 :group 'org-properties
3176 :group 'org-progress
3177 :type '(string :tag "Property"))
3179 (defconst org-global-properties-fixed
3180 '(("VISIBILITY_ALL" . "folded children content all")
3181 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3182 "List of property/value pairs that can be inherited by any entry.
3184 These are fixed values, for the preset properties. The user variable
3185 that can be used to add to this list is `org-global-properties'.
3187 The entries in this list are cons cells where the car is a property
3188 name and cdr is a string with the value. If the value represents
3189 multiple items like an \"_ALL\" property, separate the items by
3190 spaces.")
3192 (defcustom org-global-properties nil
3193 "List of property/value pairs that can be inherited by any entry.
3195 This list will be combined with the constant `org-global-properties-fixed'.
3197 The entries in this list are cons cells where the car is a property
3198 name and cdr is a string with the value.
3200 You can set buffer-local values for the same purpose in the variable
3201 `org-file-properties' this by adding lines like
3203 #+PROPERTY: NAME VALUE"
3204 :group 'org-properties
3205 :type '(repeat
3206 (cons (string :tag "Property")
3207 (string :tag "Value"))))
3209 (defvar org-file-properties nil
3210 "List of property/value pairs that can be inherited by any entry.
3211 Valid for the current buffer.
3212 This variable is populated from #+PROPERTY lines.")
3213 (make-variable-buffer-local 'org-file-properties)
3215 (defgroup org-agenda nil
3216 "Options concerning agenda views in Org-mode."
3217 :tag "Org Agenda"
3218 :group 'org)
3220 (defvar org-category nil
3221 "Variable used by org files to set a category for agenda display.
3222 Such files should use a file variable to set it, for example
3224 # -*- mode: org; org-category: \"ELisp\"
3226 or contain a special line
3228 #+CATEGORY: ELisp
3230 If the file does not specify a category, then file's base name
3231 is used instead.")
3232 (make-variable-buffer-local 'org-category)
3233 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3235 (defcustom org-agenda-files nil
3236 "The files to be used for agenda display.
3237 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3238 \\[org-remove-file]. You can also use customize to edit the list.
3240 If an entry is a directory, all files in that directory that are matched by
3241 `org-agenda-file-regexp' will be part of the file list.
3243 If the value of the variable is not a list but a single file name, then
3244 the list of agenda files is actually stored and maintained in that file, one
3245 agenda file per line. In this file paths can be given relative to
3246 `org-directory'. Tilde expansion and environment variable substitution
3247 are also made."
3248 :group 'org-agenda
3249 :type '(choice
3250 (repeat :tag "List of files and directories" file)
3251 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3253 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3254 "Regular expression to match files for `org-agenda-files'.
3255 If any element in the list in that variable contains a directory instead
3256 of a normal file, all files in that directory that are matched by this
3257 regular expression will be included."
3258 :group 'org-agenda
3259 :type 'regexp)
3261 (defcustom org-agenda-text-search-extra-files nil
3262 "List of extra files to be searched by text search commands.
3263 These files will be search in addition to the agenda files by the
3264 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3265 Note that these files will only be searched for text search commands,
3266 not for the other agenda views like todo lists, tag searches or the weekly
3267 agenda. This variable is intended to list notes and possibly archive files
3268 that should also be searched by these two commands.
3269 In fact, if the first element in the list is the symbol `agenda-archives',
3270 than all archive files of all agenda files will be added to the search
3271 scope."
3272 :group 'org-agenda
3273 :type '(set :greedy t
3274 (const :tag "Agenda Archives" agenda-archives)
3275 (repeat :inline t (file))))
3277 (if (fboundp 'defvaralias)
3278 (defvaralias 'org-agenda-multi-occur-extra-files
3279 'org-agenda-text-search-extra-files))
3281 (defcustom org-agenda-skip-unavailable-files nil
3282 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3283 A nil value means to remove them, after a query, from the list."
3284 :group 'org-agenda
3285 :type 'boolean)
3287 (defcustom org-calendar-to-agenda-key [?c]
3288 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3289 The command `org-calendar-goto-agenda' will be bound to this key. The
3290 default is the character `c' because then `c' can be used to switch back and
3291 forth between agenda and calendar."
3292 :group 'org-agenda
3293 :type 'sexp)
3295 (defcustom org-calendar-insert-diary-entry-key [?i]
3296 "The key to be installed in `calendar-mode-map' for adding diary entries.
3297 This option is irrelevant until `org-agenda-diary-file' has been configured
3298 to point to an Org-mode file. When that is the case, the command
3299 `org-agenda-diary-entry' will be bound to the key given here, by default
3300 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3301 if you want to continue doing this, you need to change this to a different
3302 key."
3303 :group 'org-agenda
3304 :type 'sexp)
3306 (defcustom org-agenda-diary-file 'diary-file
3307 "File to which to add new entries with the `i' key in agenda and calendar.
3308 When this is the symbol `diary-file', the functionality in the Emacs
3309 calendar will be used to add entries to the `diary-file'. But when this
3310 points to a file, `org-agenda-diary-entry' will be used instead."
3311 :group 'org-agenda
3312 :type '(choice
3313 (const :tag "The standard Emacs diary file" diary-file)
3314 (file :tag "Special Org file diary entries")))
3316 (eval-after-load "calendar"
3317 '(progn
3318 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3319 'org-calendar-goto-agenda)
3320 (add-hook 'calendar-mode-hook
3321 (lambda ()
3322 (unless (eq org-agenda-diary-file 'diary-file)
3323 (define-key calendar-mode-map
3324 org-calendar-insert-diary-entry-key
3325 'org-agenda-diary-entry))))))
3327 (defgroup org-latex nil
3328 "Options for embedding LaTeX code into Org-mode."
3329 :tag "Org LaTeX"
3330 :group 'org)
3332 (defcustom org-format-latex-options
3333 '(:foreground default :background default :scale 1.0
3334 :html-foreground "Black" :html-background "Transparent"
3335 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3336 "Options for creating images from LaTeX fragments.
3337 This is a property list with the following properties:
3338 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3339 `default' means use the foreground of the default face.
3340 :background the background color, or \"Transparent\".
3341 `default' means use the background of the default face.
3342 :scale a scaling factor for the size of the images, to get more pixels
3343 :html-foreground, :html-background, :html-scale
3344 the same numbers for HTML export.
3345 :matchers a list indicating which matchers should be used to
3346 find LaTeX fragments. Valid members of this list are:
3347 \"begin\" find environments
3348 \"$1\" find single characters surrounded by $.$
3349 \"$\" find math expressions surrounded by $...$
3350 \"$$\" find math expressions surrounded by $$....$$
3351 \"\\(\" find math expressions surrounded by \\(...\\)
3352 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3353 :group 'org-latex
3354 :type 'plist)
3356 (defcustom org-format-latex-signal-error t
3357 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3358 When nil, just push out a message."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type 'boolean)
3363 (defcustom org-latex-to-mathml-jar-file nil
3364 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3365 Use this to specify additional executable file say a jar file.
3367 When using MathToWeb as the converter, specify the full-path to
3368 your mathtoweb.jar file."
3369 :group 'org-latex
3370 :version "24.1"
3371 :type '(choice
3372 (const :tag "None" nil)
3373 (file :tag "JAR file" :must-match t)))
3375 (defcustom org-latex-to-mathml-convert-command nil
3376 "Command to convert LaTeX fragments to MathML.
3377 Replace format-specifiers in the command as noted below and use
3378 `shell-command' to convert LaTeX to MathML.
3379 %j: Executable file in fully expanded form as specified by
3380 `org-latex-to-mathml-jar-file'.
3381 %I: Input LaTeX file in fully expanded form
3382 %o: Output MathML file
3383 This command is used by `org-create-math-formula'.
3385 When using MathToWeb as the converter, set this to
3386 \"java -jar %j -unicode -force -df %o %I\"."
3387 :group 'org-latex
3388 :version "24.1"
3389 :type '(choice
3390 (const :tag "None" nil)
3391 (string :tag "\nShell command")))
3393 (defcustom org-latex-create-formula-image-program 'dvipng
3394 "Program to convert LaTeX fragments with.
3396 dvipng Process the LaTeX fragments to dvi file, then convert
3397 dvi files to png files using dvipng.
3398 This will also include processing of non-math environments.
3399 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3400 to convert pdf files to png files"
3401 :group 'org-latex
3402 :version "24.1"
3403 :type '(choice
3404 (const :tag "dvipng" dvipng)
3405 (const :tag "imagemagick" imagemagick)))
3407 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3408 "Path to store latex preview images. A relative path here creates many
3409 directories relative to the processed org files paths. An absolute path
3410 puts all preview images at the same place."
3411 :group 'org-latex
3412 :version "24.3"
3413 :type 'string)
3415 (defun org-format-latex-mathml-available-p ()
3416 "Return t if `org-latex-to-mathml-convert-command' is usable."
3417 (save-match-data
3418 (when (and (boundp 'org-latex-to-mathml-convert-command)
3419 org-latex-to-mathml-convert-command)
3420 (let ((executable (car (split-string
3421 org-latex-to-mathml-convert-command))))
3422 (when (executable-find executable)
3423 (if (string-match
3424 "%j" org-latex-to-mathml-convert-command)
3425 (file-readable-p org-latex-to-mathml-jar-file)
3426 t))))))
3428 (defcustom org-format-latex-header "\\documentclass{article}
3429 \\usepackage[usenames]{color}
3430 \\usepackage{amsmath}
3431 \\usepackage[mathscr]{eucal}
3432 \\pagestyle{empty} % do not remove
3433 \[PACKAGES]
3434 \[DEFAULT-PACKAGES]
3435 % The settings below are copied from fullpage.sty
3436 \\setlength{\\textwidth}{\\paperwidth}
3437 \\addtolength{\\textwidth}{-3cm}
3438 \\setlength{\\oddsidemargin}{1.5cm}
3439 \\addtolength{\\oddsidemargin}{-2.54cm}
3440 \\setlength{\\evensidemargin}{\\oddsidemargin}
3441 \\setlength{\\textheight}{\\paperheight}
3442 \\addtolength{\\textheight}{-\\headheight}
3443 \\addtolength{\\textheight}{-\\headsep}
3444 \\addtolength{\\textheight}{-\\footskip}
3445 \\addtolength{\\textheight}{-3cm}
3446 \\setlength{\\topmargin}{1.5cm}
3447 \\addtolength{\\topmargin}{-2.54cm}"
3448 "The document header used for processing LaTeX fragments.
3449 It is imperative that this header make sure that no page number
3450 appears on the page. The package defined in the variables
3451 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3452 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3453 will be appended."
3454 :group 'org-latex
3455 :type 'string)
3457 (defvar org-format-latex-header-extra nil)
3459 (defun org-set-packages-alist (var val)
3460 "Set the packages alist and make sure it has 3 elements per entry."
3461 (set var (mapcar (lambda (x)
3462 (if (and (consp x) (= (length x) 2))
3463 (list (car x) (nth 1 x) t)
3465 val)))
3467 (defun org-get-packages-alist (var)
3469 "Get the packages alist and make sure it has 3 elements per entry."
3470 (mapcar (lambda (x)
3471 (if (and (consp x) (= (length x) 2))
3472 (list (car x) (nth 1 x) t)
3474 (default-value var)))
3476 ;; The following variables are defined here because is it also used
3477 ;; when formatting latex fragments. Originally it was part of the
3478 ;; LaTeX exporter, which is why the name includes "export".
3479 (defcustom org-export-latex-default-packages-alist
3480 '(("AUTO" "inputenc" t)
3481 ("T1" "fontenc" t)
3482 ("" "fixltx2e" nil)
3483 ("" "graphicx" t)
3484 ("" "longtable" nil)
3485 ("" "float" nil)
3486 ("" "wrapfig" nil)
3487 ("" "soul" t)
3488 ("" "textcomp" t)
3489 ("" "marvosym" t)
3490 ("" "wasysym" t)
3491 ("" "latexsym" t)
3492 ("" "amssymb" t)
3493 ("" "hyperref" nil)
3494 "\\tolerance=1000"
3496 "Alist of default packages to be inserted in the header.
3497 Change this only if one of the packages here causes an incompatibility
3498 with another package you are using.
3499 The packages in this list are needed by one part or another of Org-mode
3500 to function properly.
3502 - inputenc, fontenc: for basic font and character selection
3503 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3504 for interpreting the entities in `org-entities'. You can skip some of these
3505 packages if you don't use any of the symbols in it.
3506 - graphicx: for including images
3507 - float, wrapfig: for figure placement
3508 - longtable: for long tables
3509 - hyperref: for cross references
3511 Therefore you should not modify this variable unless you know what you
3512 are doing. The one reason to change it anyway is that you might be loading
3513 some other package that conflicts with one of the default packages.
3514 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3515 If SNIPPET-FLAG is t, the package also needs to be included when
3516 compiling LaTeX snippets into images for inclusion into HTML."
3517 :group 'org-export-latex
3518 :set 'org-set-packages-alist
3519 :get 'org-get-packages-alist
3520 :version "24.1"
3521 :type '(repeat
3522 (choice
3523 (list :tag "options/package pair"
3524 (string :tag "options")
3525 (string :tag "package")
3526 (boolean :tag "Snippet"))
3527 (string :tag "A line of LaTeX"))))
3529 (defcustom org-export-latex-packages-alist nil
3530 "Alist of packages to be inserted in every LaTeX header.
3531 These will be inserted after `org-export-latex-default-packages-alist'.
3532 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3533 SNIPPET-FLAG, when t, indicates that this package is also needed when
3534 turning LaTeX snippets into images for inclusion into HTML.
3535 Make sure that you only list packages here which:
3536 - you want in every file
3537 - do not conflict with the default packages in
3538 `org-export-latex-default-packages-alist'
3539 - do not conflict with the setup in `org-format-latex-header'."
3540 :group 'org-export-latex
3541 :set 'org-set-packages-alist
3542 :get 'org-get-packages-alist
3543 :type '(repeat
3544 (choice
3545 (list :tag "options/package pair"
3546 (string :tag "options")
3547 (string :tag "package")
3548 (boolean :tag "Snippet"))
3549 (string :tag "A line of LaTeX"))))
3552 (defgroup org-appearance nil
3553 "Settings for Org-mode appearance."
3554 :tag "Org Appearance"
3555 :group 'org)
3557 (defcustom org-level-color-stars-only nil
3558 "Non-nil means fontify only the stars in each headline.
3559 When nil, the entire headline is fontified.
3560 Changing it requires restart of `font-lock-mode' to become effective
3561 also in regions already fontified."
3562 :group 'org-appearance
3563 :type 'boolean)
3565 (defcustom org-hide-leading-stars nil
3566 "Non-nil means hide the first N-1 stars in a headline.
3567 This works by using the face `org-hide' for these stars. This
3568 face is white for a light background, and black for a dark
3569 background. You may have to customize the face `org-hide' to
3570 make this work.
3571 Changing it requires restart of `font-lock-mode' to become effective
3572 also in regions already fontified.
3573 You may also set this on a per-file basis by adding one of the following
3574 lines to the buffer:
3576 #+STARTUP: hidestars
3577 #+STARTUP: showstars"
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-hidden-keywords nil
3582 "List of symbols corresponding to keywords to be hidden the org buffer.
3583 For example, a value '(title) for this list will make the document's title
3584 appear in the buffer without the initial #+TITLE: keyword."
3585 :group 'org-appearance
3586 :version "24.1"
3587 :type '(set (const :tag "#+AUTHOR" author)
3588 (const :tag "#+DATE" date)
3589 (const :tag "#+EMAIL" email)
3590 (const :tag "#+TITLE" title)))
3592 (defcustom org-custom-properties nil
3593 "List of properties (as strings) with a special meaning.
3594 The default use of these custom properties is to let the user
3595 hide them with `org-toggle-custom-properties-visibility'."
3596 :group 'org-properties
3597 :group 'org-appearance
3598 :version "24.3"
3599 :type '(repeat (string :tag "Property Name")))
3601 (defcustom org-fontify-done-headline nil
3602 "Non-nil means change the face of a headline if it is marked DONE.
3603 Normally, only the TODO/DONE keyword indicates the state of a headline.
3604 When this is non-nil, the headline after the keyword is set to the
3605 `org-headline-done' as an additional indication."
3606 :group 'org-appearance
3607 :type 'boolean)
3609 (defcustom org-fontify-emphasized-text t
3610 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3611 Changing this variable requires a restart of Emacs to take effect."
3612 :group 'org-appearance
3613 :type 'boolean)
3615 (defcustom org-fontify-whole-heading-line nil
3616 "Non-nil means fontify the whole line for headings.
3617 This is useful when setting a background color for the
3618 org-level-* faces."
3619 :group 'org-appearance
3620 :type 'boolean)
3622 (defcustom org-highlight-latex-fragments-and-specials nil
3623 "Non-nil means fontify what is treated specially by the exporters."
3624 :group 'org-appearance
3625 :type 'boolean)
3627 (defcustom org-hide-emphasis-markers nil
3628 "Non-nil mean font-lock should hide the emphasis marker characters."
3629 :group 'org-appearance
3630 :type 'boolean)
3632 (defcustom org-pretty-entities nil
3633 "Non-nil means show entities as UTF8 characters.
3634 When nil, the \\name form remains in the buffer."
3635 :group 'org-appearance
3636 :version "24.1"
3637 :type 'boolean)
3639 (defcustom org-pretty-entities-include-sub-superscripts t
3640 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3641 :group 'org-appearance
3642 :version "24.1"
3643 :type 'boolean)
3645 (defvar org-emph-re nil
3646 "Regular expression for matching emphasis.
3647 After a match, the match groups contain these elements:
3648 0 The match of the full regular expression, including the characters
3649 before and after the proper match
3650 1 The character before the proper match, or empty at beginning of line
3651 2 The proper match, including the leading and trailing markers
3652 3 The leading marker like * or /, indicating the type of highlighting
3653 4 The text between the emphasis markers, not including the markers
3654 5 The character after the match, empty at the end of a line")
3655 (defvar org-verbatim-re nil
3656 "Regular expression for matching verbatim text.")
3657 (defvar org-emphasis-regexp-components) ; defined just below
3658 (defvar org-emphasis-alist) ; defined just below
3659 (defun org-set-emph-re (var val)
3660 "Set variable and compute the emphasis regular expression."
3661 (set var val)
3662 (when (and (boundp 'org-emphasis-alist)
3663 (boundp 'org-emphasis-regexp-components)
3664 org-emphasis-alist org-emphasis-regexp-components)
3665 (let* ((e org-emphasis-regexp-components)
3666 (pre (car e))
3667 (post (nth 1 e))
3668 (border (nth 2 e))
3669 (body (nth 3 e))
3670 (nl (nth 4 e))
3671 (body1 (concat body "*?"))
3672 (markers (mapconcat 'car org-emphasis-alist ""))
3673 (vmarkers (mapconcat
3674 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3675 org-emphasis-alist "")))
3676 ;; make sure special characters appear at the right position in the class
3677 (if (string-match "\\^" markers)
3678 (setq markers (concat (replace-match "" t t markers) "^")))
3679 (if (string-match "-" markers)
3680 (setq markers (concat (replace-match "" t t markers) "-")))
3681 (if (string-match "\\^" vmarkers)
3682 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3683 (if (string-match "-" vmarkers)
3684 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3685 (if (> nl 0)
3686 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3687 (int-to-string nl) "\\}")))
3688 ;; Make the regexp
3689 (setq org-emph-re
3690 (concat "\\([" pre "]\\|^\\)"
3691 "\\("
3692 "\\([" markers "]\\)"
3693 "\\("
3694 "[^" border "]\\|"
3695 "[^" border "]"
3696 body1
3697 "[^" border "]"
3698 "\\)"
3699 "\\3\\)"
3700 "\\([" post "]\\|$\\)"))
3701 (setq org-verbatim-re
3702 (concat "\\([" pre "]\\|^\\)"
3703 "\\("
3704 "\\([" vmarkers "]\\)"
3705 "\\("
3706 "[^" border "]\\|"
3707 "[^" border "]"
3708 body1
3709 "[^" border "]"
3710 "\\)"
3711 "\\3\\)"
3712 "\\([" post "]\\|$\\)")))))
3714 (defcustom org-emphasis-regexp-components
3715 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3716 "Components used to build the regular expression for emphasis.
3717 This is a list with five entries. Terminology: In an emphasis string
3718 like \" *strong word* \", we call the initial space PREMATCH, the final
3719 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3720 and \"trong wor\" is the body. The different components in this variable
3721 specify what is allowed/forbidden in each part:
3723 pre Chars allowed as prematch. Beginning of line will be allowed too.
3724 post Chars allowed as postmatch. End of line will be allowed too.
3725 border The chars *forbidden* as border characters.
3726 body-regexp A regexp like \".\" to match a body character. Don't use
3727 non-shy groups here, and don't allow newline here.
3728 newline The maximum number of newlines allowed in an emphasis exp.
3730 Use customize to modify this, or restart Emacs after changing it."
3731 :group 'org-appearance
3732 :set 'org-set-emph-re
3733 :type '(list
3734 (sexp :tag "Allowed chars in pre ")
3735 (sexp :tag "Allowed chars in post ")
3736 (sexp :tag "Forbidden chars in border ")
3737 (sexp :tag "Regexp for body ")
3738 (integer :tag "number of newlines allowed")
3739 (option (boolean :tag "Please ignore this button"))))
3741 (defcustom org-emphasis-alist
3742 `(("*" bold "<b>" "</b>")
3743 ("/" italic "<i>" "</i>")
3744 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3745 ("=" org-code "<code>" "</code>" verbatim)
3746 ("~" org-verbatim "<code>" "</code>" verbatim)
3747 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3748 "<del>" "</del>")
3750 "Special syntax for emphasized text.
3751 Text starting and ending with a special character will be emphasized, for
3752 example *bold*, _underlined_ and /italic/. This variable sets the marker
3753 characters, the face to be used by font-lock for highlighting in Org-mode
3754 Emacs buffers, and the HTML tags to be used for this.
3755 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3756 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3757 Use customize to modify this, or restart Emacs after changing it."
3758 :group 'org-appearance
3759 :set 'org-set-emph-re
3760 :type '(repeat
3761 (list
3762 (string :tag "Marker character")
3763 (choice
3764 (face :tag "Font-lock-face")
3765 (plist :tag "Face property list"))
3766 (string :tag "HTML start tag")
3767 (string :tag "HTML end tag")
3768 (option (const verbatim)))))
3770 (defvar org-protecting-blocks
3771 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3772 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3773 This is needed for font-lock setup.")
3775 ;;; Miscellaneous options
3777 (defgroup org-completion nil
3778 "Completion in Org-mode."
3779 :tag "Org Completion"
3780 :group 'org)
3782 (defcustom org-completion-use-ido nil
3783 "Non-nil means use ido completion wherever possible.
3784 Note that `ido-mode' must be active for this variable to be relevant.
3785 If you decide to turn this variable on, you might well want to turn off
3786 `org-outline-path-complete-in-steps'.
3787 See also `org-completion-use-iswitchb'."
3788 :group 'org-completion
3789 :type 'boolean)
3791 (defcustom org-completion-use-iswitchb nil
3792 "Non-nil means use iswitchb completion wherever possible.
3793 Note that `iswitchb-mode' must be active for this variable to be relevant.
3794 If you decide to turn this variable on, you might well want to turn off
3795 `org-outline-path-complete-in-steps'.
3796 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3797 :group 'org-completion
3798 :type 'boolean)
3800 (defcustom org-completion-fallback-command 'hippie-expand
3801 "The expansion command called by \\[pcomplete] in normal context.
3802 Normal means, no org-mode-specific context."
3803 :group 'org-completion
3804 :type 'function)
3806 ;;; Functions and variables from their packages
3807 ;; Declared here to avoid compiler warnings
3809 ;; XEmacs only
3810 (defvar outline-mode-menu-heading)
3811 (defvar outline-mode-menu-show)
3812 (defvar outline-mode-menu-hide)
3813 (defvar zmacs-regions) ; XEmacs regions
3815 ;; Emacs only
3816 (defvar mark-active)
3818 ;; Various packages
3819 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3820 (declare-function calendar-forward-day "cal-move" (arg))
3821 (declare-function calendar-goto-date "cal-move" (date))
3822 (declare-function calendar-goto-today "cal-move" ())
3823 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3824 (defvar calc-embedded-close-formula)
3825 (defvar calc-embedded-open-formula)
3826 (declare-function cdlatex-tab "ext:cdlatex" ())
3827 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3828 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3829 (defvar font-lock-unfontify-region-function)
3830 (declare-function iswitchb-read-buffer "iswitchb"
3831 (prompt &optional default require-match start matches-set))
3832 (defvar iswitchb-temp-buflist)
3833 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3834 (defvar org-agenda-tags-todo-honor-ignore-options)
3835 (declare-function org-agenda-skip "org-agenda" ())
3836 (declare-function
3837 org-agenda-format-item "org-agenda"
3838 (extra txt &optional category tags dotime noprefix remove-re habitp))
3839 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3840 (declare-function org-agenda-change-all-lines "org-agenda"
3841 (newhead hdmarker &optional fixface just-this))
3842 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3843 (declare-function org-agenda-maybe-redo "org-agenda" ())
3844 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3845 (beg end))
3846 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3847 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3848 "org-agenda" (&optional end))
3849 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3850 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3851 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3852 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3853 (declare-function org-indent-mode "org-indent" (&optional arg))
3854 (declare-function parse-time-string "parse-time" (string))
3855 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3856 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3857 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3858 (defvar remember-data-file)
3859 (defvar texmathp-why)
3860 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3861 (declare-function table--at-cell-p "table" (position &optional object at-column))
3863 (defvar w3m-current-url)
3864 (defvar w3m-current-title)
3866 (defvar org-latex-regexps)
3868 ;;; Autoload and prepare some org modules
3870 ;; Some table stuff that needs to be defined here, because it is used
3871 ;; by the functions setting up org-mode or checking for table context.
3873 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3874 "Detect an org-type or table-type table.")
3875 (defconst org-table-line-regexp "^[ \t]*|"
3876 "Detect an org-type table line.")
3877 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3878 "Detect an org-type table line.")
3879 (defconst org-table-hline-regexp "^[ \t]*|-"
3880 "Detect an org-type table hline.")
3881 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3882 "Detect a table-type table hline.")
3883 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3884 "Detect the first line outside a table when searching from within it.
3885 This works for both table types.")
3887 ;; Autoload the functions in org-table.el that are needed by functions here.
3889 (eval-and-compile
3890 (org-autoload "org-table"
3891 '(org-table-begin org-table-blank-field org-table-end)))
3893 ;;;###autoload
3894 (defun turn-on-orgtbl ()
3895 "Unconditionally turn on `orgtbl-mode'."
3896 (require 'org-table)
3897 (orgtbl-mode 1))
3899 (defun org-at-table-p (&optional table-type)
3900 "Return t if the cursor is inside an org-type table.
3901 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3902 (if org-enable-table-editor
3903 (save-excursion
3904 (beginning-of-line 1)
3905 (looking-at (if table-type org-table-any-line-regexp
3906 org-table-line-regexp)))
3907 nil))
3908 (defsubst org-table-p () (org-at-table-p))
3910 (defun org-at-table.el-p ()
3911 "Return t if and only if we are at a table.el table."
3912 (and (org-at-table-p 'any)
3913 (save-excursion
3914 (goto-char (org-table-begin 'any))
3915 (looking-at org-table1-hline-regexp))))
3916 (defun org-table-recognize-table.el ()
3917 "If there is a table.el table nearby, recognize it and move into it."
3918 (if org-table-tab-recognizes-table.el
3919 (if (org-at-table.el-p)
3920 (progn
3921 (beginning-of-line 1)
3922 (if (looking-at org-table-dataline-regexp)
3924 (if (looking-at org-table1-hline-regexp)
3925 (progn
3926 (beginning-of-line 2)
3927 (if (looking-at org-table-any-border-regexp)
3928 (beginning-of-line -1)))))
3929 (if (re-search-forward "|" (org-table-end t) t)
3930 (progn
3931 (require 'table)
3932 (if (table--at-cell-p (point))
3934 (message "recognizing table.el table...")
3935 (table-recognize-table)
3936 (message "recognizing table.el table...done")))
3937 (error "This should not happen"))
3939 nil)
3940 nil))
3942 (defun org-at-table-hline-p ()
3943 "Return t if the cursor is inside a hline in a table."
3944 (if org-enable-table-editor
3945 (save-excursion
3946 (beginning-of-line 1)
3947 (looking-at org-table-hline-regexp))
3948 nil))
3950 (defvar org-table-clean-did-remove-column nil)
3952 (defun org-table-map-tables (function &optional quietly)
3953 "Apply FUNCTION to the start of all tables in the buffer."
3954 (save-excursion
3955 (save-restriction
3956 (widen)
3957 (goto-char (point-min))
3958 (while (re-search-forward org-table-any-line-regexp nil t)
3959 (unless quietly
3960 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3961 (beginning-of-line 1)
3962 (when (and (looking-at org-table-line-regexp)
3963 ;; Exclude tables in src/example/verbatim/clocktable blocks
3964 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
3965 (save-excursion (funcall function))
3966 (or (looking-at org-table-line-regexp)
3967 (forward-char 1)))
3968 (re-search-forward org-table-any-border-regexp nil 1))))
3969 (unless quietly (message "Mapping tables: done")))
3971 ;; Declare and autoload functions from org-exp.el & Co
3973 (declare-function org-default-export-plist "org-exp")
3974 (declare-function org-infile-export-plist "org-exp")
3975 (declare-function org-get-current-options "org-exp")
3977 ;; Declare and autoload functions from org-agenda.el
3979 (eval-and-compile
3980 (org-autoload "org-agenda"
3981 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3983 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3984 (declare-function org-clock-update-mode-line "org-clock" ())
3985 (declare-function org-resolve-clocks "org-clock"
3986 (&optional also-non-dangling-p prompt last-valid))
3987 (defvar org-clock-start-time)
3988 (defvar org-clock-marker (make-marker)
3989 "Marker recording the last clock-in.")
3990 (defvar org-clock-hd-marker (make-marker)
3991 "Marker recording the last clock-in, but the headline position.")
3992 (defvar org-clock-heading ""
3993 "The heading of the current clock entry.")
3994 (defun org-clock-is-active ()
3995 "Return non-nil if clock is currently running.
3996 The return value is actually the clock marker."
3997 (marker-buffer org-clock-marker))
3999 (eval-and-compile
4000 (org-autoload "org-clock" '(org-clock-remove-overlays
4001 org-clock-update-time-maybe
4002 org-clocktable-shift)))
4004 (defun org-check-running-clock ()
4005 "Check if the current buffer contains the running clock.
4006 If yes, offer to stop it and to save the buffer with the changes."
4007 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4008 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4009 (buffer-name))))
4010 (org-clock-out)
4011 (when (y-or-n-p "Save changed buffer?")
4012 (save-buffer))))
4014 (defun org-clocktable-try-shift (dir n)
4015 "Check if this line starts a clock table, if yes, shift the time block."
4016 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4017 (org-clocktable-shift dir n)))
4019 ;;;###autoload
4020 (defun org-clock-persistence-insinuate ()
4021 "Set up hooks for clock persistence."
4022 (require 'org-clock)
4023 (add-hook 'org-mode-hook 'org-clock-load)
4024 (add-hook 'kill-emacs-hook 'org-clock-save))
4026 ;; Define the variable already here, to make sure we have it.
4027 (defvar org-indent-mode nil
4028 "Non-nil if Org-Indent mode is enabled.
4029 Use the command `org-indent-mode' to change this variable.")
4031 ;; Autoload archiving code
4032 ;; The stuff that is needed for cycling and tags has to be defined here.
4034 (defgroup org-archive nil
4035 "Options concerning archiving in Org-mode."
4036 :tag "Org Archive"
4037 :group 'org-structure)
4039 (defcustom org-archive-location "%s_archive::"
4040 "The location where subtrees should be archived.
4042 The value of this variable is a string, consisting of two parts,
4043 separated by a double-colon. The first part is a filename and
4044 the second part is a headline.
4046 When the filename is omitted, archiving happens in the same file.
4047 %s in the filename will be replaced by the current file
4048 name (without the directory part). Archiving to a different file
4049 is useful to keep archived entries from contributing to the
4050 Org-mode Agenda.
4052 The archived entries will be filed as subtrees of the specified
4053 headline. When the headline is omitted, the subtrees are simply
4054 filed away at the end of the file, as top-level entries. Also in
4055 the heading you can use %s to represent the file name, this can be
4056 useful when using the same archive for a number of different files.
4058 Here are a few examples:
4059 \"%s_archive::\"
4060 If the current file is Projects.org, archive in file
4061 Projects.org_archive, as top-level trees. This is the default.
4063 \"::* Archived Tasks\"
4064 Archive in the current file, under the top-level headline
4065 \"* Archived Tasks\".
4067 \"~/org/archive.org::\"
4068 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4070 \"~/org/archive.org::* From %s\"
4071 Archive in file ~/org/archive.org (absolute path), under headlines
4072 \"From FILENAME\" where file name is the current file name.
4074 \"~/org/datetree.org::datetree/* Finished Tasks\"
4075 The \"datetree/\" string is special, signifying to archive
4076 items to the datetree. Items are placed in either the CLOSED
4077 date of the item, or the current date if there is no CLOSED date.
4078 The heading will be a subentry to the current date. There doesn't
4079 need to be a heading, but there always needs to be a slash after
4080 datetree. For example, to store archived items directly in the
4081 datetree, use \"~/org/datetree.org::datetree/\".
4083 \"basement::** Finished Tasks\"
4084 Archive in file ./basement (relative path), as level 3 trees
4085 below the level 2 heading \"** Finished Tasks\".
4087 You may set this option on a per-file basis by adding to the buffer a
4088 line like
4090 #+ARCHIVE: basement::** Finished Tasks
4092 You may also define it locally for a subtree by setting an ARCHIVE property
4093 in the entry. If such a property is found in an entry, or anywhere up
4094 the hierarchy, it will be used."
4095 :group 'org-archive
4096 :type 'string)
4098 (defcustom org-archive-tag "ARCHIVE"
4099 "The tag that marks a subtree as archived.
4100 An archived subtree does not open during visibility cycling, and does
4101 not contribute to the agenda listings.
4102 After changing this, font-lock must be restarted in the relevant buffers to
4103 get the proper fontification."
4104 :group 'org-archive
4105 :group 'org-keywords
4106 :type 'string)
4108 (defcustom org-agenda-skip-archived-trees t
4109 "Non-nil means the agenda will skip any items located in archived trees.
4110 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4111 variable is no longer recommended, you should leave it at the value t.
4112 Instead, use the key `v' to cycle the archives-mode in the agenda."
4113 :group 'org-archive
4114 :group 'org-agenda-skip
4115 :type 'boolean)
4117 (defcustom org-columns-skip-archived-trees t
4118 "Non-nil means ignore archived trees when creating column view."
4119 :group 'org-archive
4120 :group 'org-properties
4121 :type 'boolean)
4123 (defcustom org-cycle-open-archived-trees nil
4124 "Non-nil means `org-cycle' will open archived trees.
4125 An archived tree is a tree marked with the tag ARCHIVE.
4126 When nil, archived trees will stay folded. You can still open them with
4127 normal outline commands like `show-all', but not with the cycling commands."
4128 :group 'org-archive
4129 :group 'org-cycle
4130 :type 'boolean)
4132 (defcustom org-sparse-tree-open-archived-trees nil
4133 "Non-nil means sparse tree construction shows matches in archived trees.
4134 When nil, matches in these trees are highlighted, but the trees are kept in
4135 collapsed state."
4136 :group 'org-archive
4137 :group 'org-sparse-trees
4138 :type 'boolean)
4140 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4141 "The default date type when building a sparse tree.
4142 When this is nil, a date is a scheduled or a deadline timestamp.
4143 Otherwise, these types are allowed:
4145 all: all timestamps
4146 active: only active timestamps (<...>)
4147 inactive: only inactive timestamps (<...)
4148 scheduled: only scheduled timestamps
4149 deadline: only deadline timestamps"
4150 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4151 (const :tag "All timestamps" all)
4152 (const :tag "Only active timestamps" active)
4153 (const :tag "Only inactive timestamps" inactive)
4154 (const :tag "Only scheduled timestamps" scheduled)
4155 (const :tag "Only deadline timestamps" deadline))
4156 :version "24.3"
4157 :group 'org-sparse-trees)
4159 (defun org-cycle-hide-archived-subtrees (state)
4160 "Re-hide all archived subtrees after a visibility state change."
4161 (when (and (not org-cycle-open-archived-trees)
4162 (not (memq state '(overview folded))))
4163 (save-excursion
4164 (let* ((globalp (memq state '(contents all)))
4165 (beg (if globalp (point-min) (point)))
4166 (end (if globalp (point-max) (org-end-of-subtree t))))
4167 (org-hide-archived-subtrees beg end)
4168 (goto-char beg)
4169 (if (looking-at (concat ".*:" org-archive-tag ":"))
4170 (message "%s" (substitute-command-keys
4171 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4173 (defun org-force-cycle-archived ()
4174 "Cycle subtree even if it is archived."
4175 (interactive)
4176 (setq this-command 'org-cycle)
4177 (let ((org-cycle-open-archived-trees t))
4178 (call-interactively 'org-cycle)))
4180 (defun org-hide-archived-subtrees (beg end)
4181 "Re-hide all archived subtrees after a visibility state change."
4182 (save-excursion
4183 (let* ((re (concat ":" org-archive-tag ":")))
4184 (goto-char beg)
4185 (while (re-search-forward re end t)
4186 (when (org-at-heading-p)
4187 (org-flag-subtree t)
4188 (org-end-of-subtree t))))))
4190 (declare-function outline-end-of-heading "outline" ())
4191 (declare-function outline-flag-region "outline" (from to flag))
4192 (defun org-flag-subtree (flag)
4193 (save-excursion
4194 (org-back-to-heading t)
4195 (outline-end-of-heading)
4196 (outline-flag-region (point)
4197 (progn (org-end-of-subtree t) (point))
4198 flag)))
4200 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4202 (eval-and-compile
4203 (org-autoload "org-archive"
4204 '(org-add-archive-files)))
4206 ;; Autoload Column View Code
4208 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4209 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4210 (declare-function org-columns-compute "org-colview" (property))
4212 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4213 '(org-columns-number-to-string
4214 org-columns-get-format-and-top-level
4215 org-columns-compute
4216 org-columns-remove-overlays))
4218 ;; Autoload ID code
4220 (declare-function org-id-store-link "org-id")
4221 (declare-function org-id-locations-load "org-id")
4222 (declare-function org-id-locations-save "org-id")
4223 (defvar org-id-track-globally)
4224 (org-autoload "org-id"
4225 '(org-id-new
4226 org-id-copy
4227 org-id-get-with-outline-path-completion
4228 org-id-get-with-outline-drilling))
4230 ;;; Variables for pre-computed regular expressions, all buffer local
4232 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4233 "Matches first line of a hidden block.")
4234 (make-variable-buffer-local 'org-drawer-regexp)
4235 (defvar org-todo-regexp nil
4236 "Matches any of the TODO state keywords.")
4237 (make-variable-buffer-local 'org-todo-regexp)
4238 (defvar org-not-done-regexp nil
4239 "Matches any of the TODO state keywords except the last one.")
4240 (make-variable-buffer-local 'org-not-done-regexp)
4241 (defvar org-not-done-heading-regexp nil
4242 "Matches a TODO headline that is not done.")
4243 (make-variable-buffer-local 'org-not-done-regexp)
4244 (defvar org-todo-line-regexp nil
4245 "Matches a headline and puts TODO state into group 2 if present.")
4246 (make-variable-buffer-local 'org-todo-line-regexp)
4247 (defvar org-complex-heading-regexp nil
4248 "Matches a headline and puts everything into groups:
4249 group 1: the stars
4250 group 2: The todo keyword, maybe
4251 group 3: Priority cookie
4252 group 4: True headline
4253 group 5: Tags")
4254 (make-variable-buffer-local 'org-complex-heading-regexp)
4255 (defvar org-complex-heading-regexp-format nil
4256 "Printf format to make regexp to match an exact headline.
4257 This regexp will match the headline of any node which has the
4258 exact headline text that is put into the format, but may have any
4259 TODO state, priority and tags.")
4260 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4261 (defvar org-todo-line-tags-regexp nil
4262 "Matches a headline and puts TODO state into group 2 if present.
4263 Also put tags into group 4 if tags are present.")
4264 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4265 (defvar org-ds-keyword-length 12
4266 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4267 (make-variable-buffer-local 'org-ds-keyword-length)
4268 (defvar org-deadline-regexp nil
4269 "Matches the DEADLINE keyword.")
4270 (make-variable-buffer-local 'org-deadline-regexp)
4271 (defvar org-deadline-time-regexp nil
4272 "Matches the DEADLINE keyword together with a time stamp.")
4273 (make-variable-buffer-local 'org-deadline-time-regexp)
4274 (defvar org-deadline-line-regexp nil
4275 "Matches the DEADLINE keyword and the rest of the line.")
4276 (make-variable-buffer-local 'org-deadline-line-regexp)
4277 (defvar org-scheduled-regexp nil
4278 "Matches the SCHEDULED keyword.")
4279 (make-variable-buffer-local 'org-scheduled-regexp)
4280 (defvar org-scheduled-time-regexp nil
4281 "Matches the SCHEDULED keyword together with a time stamp.")
4282 (make-variable-buffer-local 'org-scheduled-time-regexp)
4283 (defvar org-closed-time-regexp nil
4284 "Matches the CLOSED keyword together with a time stamp.")
4285 (make-variable-buffer-local 'org-closed-time-regexp)
4287 (defvar org-keyword-time-regexp nil
4288 "Matches any of the 4 keywords, together with the time stamp.")
4289 (make-variable-buffer-local 'org-keyword-time-regexp)
4290 (defvar org-keyword-time-not-clock-regexp nil
4291 "Matches any of the 3 keywords, together with the time stamp.")
4292 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4293 (defvar org-maybe-keyword-time-regexp nil
4294 "Matches a timestamp, possibly preceded by a keyword.")
4295 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4296 (defvar org-all-time-keywords nil
4297 "List of time keywords.")
4298 (make-variable-buffer-local 'org-all-time-keywords)
4300 (defconst org-plain-time-of-day-regexp
4301 (concat
4302 "\\(\\<[012]?[0-9]"
4303 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4304 "\\(--?"
4305 "\\(\\<[012]?[0-9]"
4306 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4307 "\\)?")
4308 "Regular expression to match a plain time or time range.
4309 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4310 groups carry important information:
4311 0 the full match
4312 1 the first time, range or not
4313 8 the second time, if it is a range.")
4315 (defconst org-plain-time-extension-regexp
4316 (concat
4317 "\\(\\<[012]?[0-9]"
4318 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4319 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4320 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4321 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4322 groups carry important information:
4323 0 the full match
4324 7 hours of duration
4325 9 minutes of duration")
4327 (defconst org-stamp-time-of-day-regexp
4328 (concat
4329 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4330 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4331 "\\(--?"
4332 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4333 "Regular expression to match a timestamp time or time range.
4334 After a match, the following groups carry important information:
4335 0 the full match
4336 1 date plus weekday, for back referencing to make sure both times are on the same day
4337 2 the first time, range or not
4338 4 the second time, if it is a range.")
4340 (defconst org-startup-options
4341 '(("fold" org-startup-folded t)
4342 ("overview" org-startup-folded t)
4343 ("nofold" org-startup-folded nil)
4344 ("showall" org-startup-folded nil)
4345 ("showeverything" org-startup-folded showeverything)
4346 ("content" org-startup-folded content)
4347 ("indent" org-startup-indented t)
4348 ("noindent" org-startup-indented nil)
4349 ("hidestars" org-hide-leading-stars t)
4350 ("showstars" org-hide-leading-stars nil)
4351 ("odd" org-odd-levels-only t)
4352 ("oddeven" org-odd-levels-only nil)
4353 ("align" org-startup-align-all-tables t)
4354 ("noalign" org-startup-align-all-tables nil)
4355 ("inlineimages" org-startup-with-inline-images t)
4356 ("noinlineimages" org-startup-with-inline-images nil)
4357 ("customtime" org-display-custom-times t)
4358 ("logdone" org-log-done time)
4359 ("lognotedone" org-log-done note)
4360 ("nologdone" org-log-done nil)
4361 ("lognoteclock-out" org-log-note-clock-out t)
4362 ("nolognoteclock-out" org-log-note-clock-out nil)
4363 ("logrepeat" org-log-repeat state)
4364 ("lognoterepeat" org-log-repeat note)
4365 ("nologrepeat" org-log-repeat nil)
4366 ("logreschedule" org-log-reschedule time)
4367 ("lognotereschedule" org-log-reschedule note)
4368 ("nologreschedule" org-log-reschedule nil)
4369 ("logredeadline" org-log-redeadline time)
4370 ("lognoteredeadline" org-log-redeadline note)
4371 ("nologredeadline" org-log-redeadline nil)
4372 ("logrefile" org-log-refile time)
4373 ("lognoterefile" org-log-refile note)
4374 ("nologrefile" org-log-refile nil)
4375 ("fninline" org-footnote-define-inline t)
4376 ("nofninline" org-footnote-define-inline nil)
4377 ("fnlocal" org-footnote-section nil)
4378 ("fnauto" org-footnote-auto-label t)
4379 ("fnprompt" org-footnote-auto-label nil)
4380 ("fnconfirm" org-footnote-auto-label confirm)
4381 ("fnplain" org-footnote-auto-label plain)
4382 ("fnadjust" org-footnote-auto-adjust t)
4383 ("nofnadjust" org-footnote-auto-adjust nil)
4384 ("constcgs" constants-unit-system cgs)
4385 ("constSI" constants-unit-system SI)
4386 ("noptag" org-tag-persistent-alist nil)
4387 ("hideblocks" org-hide-block-startup t)
4388 ("nohideblocks" org-hide-block-startup nil)
4389 ("beamer" org-startup-with-beamer-mode t)
4390 ("entitiespretty" org-pretty-entities t)
4391 ("entitiesplain" org-pretty-entities nil))
4392 "Variable associated with STARTUP options for org-mode.
4393 Each element is a list of three items: the startup options (as written
4394 in the #+STARTUP line), the corresponding variable, and the value to set
4395 this variable to if the option is found. An optional forth element PUSH
4396 means to push this value onto the list in the variable.")
4398 (defun org-update-property-plist (key val props)
4399 "Update PROPS with KEY and VAL."
4400 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4401 (key (if appending (substring key 0 (- (length key) 1)) key))
4402 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4403 (previous (cdr (assoc key props))))
4404 (if appending
4405 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4406 (cons (cons key val) remainder))))
4408 (defconst org-block-regexp
4409 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4410 "Regular expression for hiding blocks.")
4411 (defconst org-heading-keyword-regexp-format
4412 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4413 "Printf format for a regexp matching an headline with some keyword.
4414 This regexp will match the headline of any node which has the
4415 exact keyword that is put into the format. The keyword isn't in
4416 any group by default, but the stars and the body are.")
4417 (defconst org-heading-keyword-maybe-regexp-format
4418 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4419 "Printf format for a regexp matching an headline, possibly with some keyword.
4420 This regexp can match any headline with the specified keyword, or
4421 without a keyword. The keyword isn't in any group by default,
4422 but the stars and the body are.")
4424 (defun org-set-regexps-and-options ()
4425 "Precompute regular expressions for current buffer."
4426 (when (derived-mode-p 'org-mode)
4427 (org-set-local 'org-todo-kwd-alist nil)
4428 (org-set-local 'org-todo-key-alist nil)
4429 (org-set-local 'org-todo-key-trigger nil)
4430 (org-set-local 'org-todo-keywords-1 nil)
4431 (org-set-local 'org-done-keywords nil)
4432 (org-set-local 'org-todo-heads nil)
4433 (org-set-local 'org-todo-sets nil)
4434 (org-set-local 'org-todo-log-states nil)
4435 (org-set-local 'org-file-properties nil)
4436 (org-set-local 'org-file-tags nil)
4437 (let ((re (org-make-options-regexp
4438 '("CATEGORY" "TODO" "COLUMNS"
4439 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4440 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4441 "OPTIONS")
4442 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4443 (splitre "[ \t]+")
4444 (scripts org-use-sub-superscripts)
4445 kwds kws0 kwsa key log value cat arch tags const links hw dws
4446 tail sep kws1 prio props ftags drawers beamer-p
4447 ext-setup-or-nil setup-contents (start 0))
4448 (save-excursion
4449 (save-restriction
4450 (widen)
4451 (goto-char (point-min))
4452 (while (or (and ext-setup-or-nil
4453 (string-match re ext-setup-or-nil start)
4454 (setq start (match-end 0)))
4455 (and (setq ext-setup-or-nil nil start 0)
4456 (re-search-forward re nil t)))
4457 (setq key (upcase (match-string 1 ext-setup-or-nil))
4458 value (org-match-string-no-properties 2 ext-setup-or-nil))
4459 (if (stringp value) (setq value (org-trim value)))
4460 (cond
4461 ((equal key "CATEGORY")
4462 (setq cat value))
4463 ((member key '("SEQ_TODO" "TODO"))
4464 (push (cons 'sequence (org-split-string value splitre)) kwds))
4465 ((equal key "TYP_TODO")
4466 (push (cons 'type (org-split-string value splitre)) kwds))
4467 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4468 ;; general TODO-like setup
4469 (push (cons (intern (downcase (match-string 1 key)))
4470 (org-split-string value splitre)) kwds))
4471 ((equal key "TAGS")
4472 (setq tags (append tags (if tags '("\\n") nil)
4473 (org-split-string value splitre))))
4474 ((equal key "COLUMNS")
4475 (org-set-local 'org-columns-default-format value))
4476 ((equal key "LINK")
4477 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4478 (push (cons (match-string 1 value)
4479 (org-trim (match-string 2 value)))
4480 links)))
4481 ((equal key "PRIORITIES")
4482 (setq prio (org-split-string value " +")))
4483 ((equal key "PROPERTY")
4484 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4485 (setq props (org-update-property-plist (match-string 1 value)
4486 (match-string 2 value)
4487 props))))
4488 ((equal key "FILETAGS")
4489 (when (string-match "\\S-" value)
4490 (setq ftags
4491 (append
4492 ftags
4493 (apply 'append
4494 (mapcar (lambda (x) (org-split-string x ":"))
4495 (org-split-string value)))))))
4496 ((equal key "DRAWERS")
4497 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4498 ((equal key "CONSTANTS")
4499 (setq const (append const (org-split-string value splitre))))
4500 ((equal key "STARTUP")
4501 (let ((opts (org-split-string value splitre))
4502 l var val)
4503 (while (setq l (pop opts))
4504 (when (setq l (assoc l org-startup-options))
4505 (setq var (nth 1 l) val (nth 2 l))
4506 (if (not (nth 3 l))
4507 (set (make-local-variable var) val)
4508 (if (not (listp (symbol-value var)))
4509 (set (make-local-variable var) nil))
4510 (set (make-local-variable var) (symbol-value var))
4511 (add-to-list var val))))))
4512 ((equal key "ARCHIVE")
4513 (setq arch value)
4514 (remove-text-properties 0 (length arch)
4515 '(face t fontified t) arch))
4516 ((equal key "LATEX_CLASS")
4517 (setq beamer-p (equal value "beamer")))
4518 ((equal key "OPTIONS")
4519 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4520 (setq scripts (read (match-string 2 value)))))
4521 ((equal key "SETUPFILE")
4522 (setq setup-contents (org-file-contents
4523 (expand-file-name
4524 (org-remove-double-quotes value))
4525 'noerror))
4526 (if (not ext-setup-or-nil)
4527 (setq ext-setup-or-nil setup-contents start 0)
4528 (setq ext-setup-or-nil
4529 (concat (substring ext-setup-or-nil 0 start)
4530 "\n" setup-contents "\n"
4531 (substring ext-setup-or-nil start)))))))
4532 ;; search for property blocks
4533 (goto-char (point-min))
4534 (while (re-search-forward org-block-regexp nil t)
4535 (when (equal "PROPERTY" (upcase (match-string 1)))
4536 (setq value (replace-regexp-in-string
4537 "[\n\r]" " " (match-string 4)))
4538 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4539 (setq props (org-update-property-plist (match-string 1 value)
4540 (match-string 2 value)
4541 props)))))))
4542 (org-set-local 'org-use-sub-superscripts scripts)
4543 (when cat
4544 (org-set-local 'org-category (intern cat))
4545 (push (cons "CATEGORY" cat) props))
4546 (when prio
4547 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4548 (setq prio (mapcar 'string-to-char prio))
4549 (org-set-local 'org-highest-priority (nth 0 prio))
4550 (org-set-local 'org-lowest-priority (nth 1 prio))
4551 (org-set-local 'org-default-priority (nth 2 prio)))
4552 (and props (org-set-local 'org-file-properties (nreverse props)))
4553 (and ftags (org-set-local 'org-file-tags
4554 (mapcar 'org-add-prop-inherited ftags)))
4555 (and drawers (org-set-local 'org-drawers drawers))
4556 (and arch (org-set-local 'org-archive-location arch))
4557 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4558 ;; Process the TODO keywords
4559 (unless kwds
4560 ;; Use the global values as if they had been given locally.
4561 (setq kwds (default-value 'org-todo-keywords))
4562 (if (stringp (car kwds))
4563 (setq kwds (list (cons org-todo-interpretation
4564 (default-value 'org-todo-keywords)))))
4565 (setq kwds (reverse kwds)))
4566 (setq kwds (nreverse kwds))
4567 (let (inter kws kw)
4568 (while (setq kws (pop kwds))
4569 (let ((kws (or
4570 (run-hook-with-args-until-success
4571 'org-todo-setup-filter-hook kws)
4572 kws)))
4573 (setq inter (pop kws) sep (member "|" kws)
4574 kws0 (delete "|" (copy-sequence kws))
4575 kwsa nil
4576 kws1 (mapcar
4577 (lambda (x)
4578 ;; 1 2
4579 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4580 (progn
4581 (setq kw (match-string 1 x)
4582 key (and (match-end 2) (match-string 2 x))
4583 log (org-extract-log-state-settings x))
4584 (push (cons kw (and key (string-to-char key))) kwsa)
4585 (and log (push log org-todo-log-states))
4587 (error "Invalid TODO keyword %s" x)))
4588 kws0)
4589 kwsa (if kwsa (append '((:startgroup))
4590 (nreverse kwsa)
4591 '((:endgroup))))
4592 hw (car kws1)
4593 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4594 tail (list inter hw (car dws) (org-last dws))))
4595 (add-to-list 'org-todo-heads hw 'append)
4596 (push kws1 org-todo-sets)
4597 (setq org-done-keywords (append org-done-keywords dws nil))
4598 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4599 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4600 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4601 (setq org-todo-sets (nreverse org-todo-sets)
4602 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4603 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4604 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4605 ;; Process the constants
4606 (when const
4607 (let (e cst)
4608 (while (setq e (pop const))
4609 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4610 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4611 (setq org-table-formula-constants-local cst)))
4613 ;; Process the tags.
4614 (when tags
4615 (let (e tgs)
4616 (while (setq e (pop tags))
4617 (cond
4618 ((equal e "{") (push '(:startgroup) tgs))
4619 ((equal e "}") (push '(:endgroup) tgs))
4620 ((equal e "\\n") (push '(:newline) tgs))
4621 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4622 (push (cons (match-string 1 e)
4623 (string-to-char (match-string 2 e)))
4624 tgs))
4625 (t (push (list e) tgs))))
4626 (org-set-local 'org-tag-alist nil)
4627 (while (setq e (pop tgs))
4628 (or (and (stringp (car e))
4629 (assoc (car e) org-tag-alist))
4630 (push e org-tag-alist)))))
4632 ;; Compute the regular expressions and other local variables.
4633 ;; Using `org-outline-regexp-bol' would complicate them much,
4634 ;; because of the fixed white space at the end of that string.
4635 (if (not org-done-keywords)
4636 (setq org-done-keywords (and org-todo-keywords-1
4637 (list (org-last org-todo-keywords-1)))))
4638 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4639 (length org-scheduled-string)
4640 (length org-clock-string)
4641 (length org-closed-string)))
4642 org-drawer-regexp
4643 (concat "^[ \t]*:\\("
4644 (mapconcat 'regexp-quote org-drawers "\\|")
4645 "\\):[ \t]*$")
4646 org-not-done-keywords
4647 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4648 org-todo-regexp
4649 (concat "\\("
4650 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4651 "\\)")
4652 org-not-done-regexp
4653 (concat "\\("
4654 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4655 "\\)")
4656 org-not-done-heading-regexp
4657 (format org-heading-keyword-regexp-format org-not-done-regexp)
4658 org-todo-line-regexp
4659 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4660 org-complex-heading-regexp
4661 (concat "^\\(\\*+\\)"
4662 "\\(?: +" org-todo-regexp "\\)?"
4663 "\\(?: +\\(\\[#.\\]\\)\\)?"
4664 "\\(?: +\\(.*?\\)\\)??"
4665 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4666 "[ \t]*$")
4667 org-complex-heading-regexp-format
4668 (concat "^\\(\\*+\\)"
4669 "\\(?: +" org-todo-regexp "\\)?"
4670 "\\(?: +\\(\\[#.\\]\\)\\)?"
4671 "\\(?: +"
4672 ;; Stats cookies can be stuck to body.
4673 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4674 "\\(%s\\)"
4675 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4676 "\\)"
4677 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4678 "[ \t]*$")
4679 org-todo-line-tags-regexp
4680 (concat "^\\(\\*+\\)"
4681 "\\(?: +" org-todo-regexp "\\)?"
4682 "\\(?: +\\(.*?\\)\\)??"
4683 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4684 "[ \t]*$")
4685 org-deadline-regexp (concat "\\<" org-deadline-string)
4686 org-deadline-time-regexp
4687 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4688 org-deadline-line-regexp
4689 (concat "\\<\\(" org-deadline-string "\\).*")
4690 org-scheduled-regexp
4691 (concat "\\<" org-scheduled-string)
4692 org-scheduled-time-regexp
4693 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4694 org-closed-time-regexp
4695 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4696 org-keyword-time-regexp
4697 (concat "\\<\\(" org-scheduled-string
4698 "\\|" org-deadline-string
4699 "\\|" org-closed-string
4700 "\\|" org-clock-string "\\)"
4701 " *[[<]\\([^]>]+\\)[]>]")
4702 org-keyword-time-not-clock-regexp
4703 (concat "\\<\\(" org-scheduled-string
4704 "\\|" org-deadline-string
4705 "\\|" org-closed-string
4706 "\\)"
4707 " *[[<]\\([^]>]+\\)[]>]")
4708 org-maybe-keyword-time-regexp
4709 (concat "\\(\\<\\(" org-scheduled-string
4710 "\\|" org-deadline-string
4711 "\\|" org-closed-string
4712 "\\|" org-clock-string "\\)\\)?"
4713 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4714 org-all-time-keywords
4715 (mapcar (lambda (w) (substring w 0 -1))
4716 (list org-scheduled-string org-deadline-string
4717 org-clock-string org-closed-string))
4719 (org-compute-latex-and-specials-regexp)
4720 (org-set-font-lock-defaults))))
4722 (defun org-file-contents (file &optional noerror)
4723 "Return the contents of FILE, as a string."
4724 (if (or (not file)
4725 (not (file-readable-p file)))
4726 (if noerror
4727 (progn
4728 (message "Cannot read file \"%s\"" file)
4729 (ding) (sit-for 2)
4731 (error "Cannot read file \"%s\"" file))
4732 (with-temp-buffer
4733 (insert-file-contents file)
4734 (buffer-string))))
4736 (defun org-extract-log-state-settings (x)
4737 "Extract the log state setting from a TODO keyword string.
4738 This will extract info from a string like \"WAIT(w@/!)\"."
4739 (let (kw key log1 log2)
4740 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4741 (setq kw (match-string 1 x)
4742 key (and (match-end 2) (match-string 2 x))
4743 log1 (and (match-end 3) (match-string 3 x))
4744 log2 (and (match-end 4) (match-string 4 x)))
4745 (and (or log1 log2)
4746 (list kw
4747 (and log1 (if (equal log1 "!") 'time 'note))
4748 (and log2 (if (equal log2 "!") 'time 'note)))))))
4750 (defun org-remove-keyword-keys (list)
4751 "Remove a pair of parenthesis at the end of each string in LIST."
4752 (mapcar (lambda (x)
4753 (if (string-match "(.*)$" x)
4754 (substring x 0 (match-beginning 0))
4756 list))
4758 (defun org-assign-fast-keys (alist)
4759 "Assign fast keys to a keyword-key alist.
4760 Respect keys that are already there."
4761 (let (new e (alt ?0))
4762 (while (setq e (pop alist))
4763 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4764 (cdr e)) ;; Key already assigned.
4765 (push e new)
4766 (let ((clist (string-to-list (downcase (car e))))
4767 (used (append new alist)))
4768 (when (= (car clist) ?@)
4769 (pop clist))
4770 (while (and clist (rassoc (car clist) used))
4771 (pop clist))
4772 (unless clist
4773 (while (rassoc alt used)
4774 (incf alt)))
4775 (push (cons (car e) (or (car clist) alt)) new))))
4776 (nreverse new)))
4778 ;;; Some variables used in various places
4780 (defvar org-window-configuration nil
4781 "Used in various places to store a window configuration.")
4782 (defvar org-selected-window nil
4783 "Used in various places to store a window configuration.")
4784 (defvar org-finish-function nil
4785 "Function to be called when `C-c C-c' is used.
4786 This is for getting out of special buffers like capture.")
4789 ;; FIXME: Occasionally check by commenting these, to make sure
4790 ;; no other functions uses these, forgetting to let-bind them.
4791 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4792 (defvar org-last-state)
4793 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4795 ;; Defined somewhere in this file, but used before definition.
4796 (defvar org-entities) ;; defined in org-entities.el
4797 (defvar org-struct-menu)
4798 (defvar org-org-menu)
4799 (defvar org-tbl-menu)
4801 ;;;; Define the Org-mode
4803 ;; We use a before-change function to check if a table might need
4804 ;; an update.
4805 (defvar org-table-may-need-update t
4806 "Indicates that a table might need an update.
4807 This variable is set by `org-before-change-function'.
4808 `org-table-align' sets it back to nil.")
4809 (defun org-before-change-function (beg end)
4810 "Every change indicates that a table might need an update."
4811 (setq org-table-may-need-update t))
4812 (defvar org-mode-map)
4813 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4814 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4815 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4816 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4817 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4818 (defvar org-table-buffer-is-an nil)
4820 (defvar bidi-paragraph-direction)
4821 (defvar buffer-face-mode-face)
4823 (require 'outline)
4824 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4825 (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"))
4826 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4828 ;; Other stuff we need.
4829 (require 'time-date)
4830 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4831 (require 'easymenu)
4832 (require 'overlay)
4834 (require 'org-macs)
4835 (require 'org-entities)
4836 ;; (require 'org-compat) moved higher up in the file before it is first used
4837 (require 'org-faces)
4838 (require 'org-list)
4839 (require 'org-pcomplete)
4840 (require 'org-src)
4841 (require 'org-footnote)
4843 ;; babel
4844 (require 'ob)
4845 (require 'ob-table)
4846 (require 'ob-lob)
4847 (require 'ob-ref)
4848 (require 'ob-tangle)
4849 (require 'ob-comint)
4850 (require 'ob-keys)
4852 ;;;###autoload
4853 (define-derived-mode org-mode outline-mode "Org"
4854 "Outline-based notes management and organizer, alias
4855 \"Carsten's outline-mode for keeping track of everything.\"
4857 Org-mode develops organizational tasks around a NOTES file which
4858 contains information about projects as plain text. Org-mode is
4859 implemented on top of outline-mode, which is ideal to keep the content
4860 of large files well structured. It supports ToDo items, deadlines and
4861 time stamps, which magically appear in the diary listing of the Emacs
4862 calendar. Tables are easily created with a built-in table editor.
4863 Plain text URL-like links connect to websites, emails (VM), Usenet
4864 messages (Gnus), BBDB entries, and any files related to the project.
4865 For printing and sharing of notes, an Org-mode file (or a part of it)
4866 can be exported as a structured ASCII or HTML file.
4868 The following commands are available:
4870 \\{org-mode-map}"
4872 ;; Get rid of Outline menus, they are not needed
4873 ;; Need to do this here because define-derived-mode sets up
4874 ;; the keymap so late. Still, it is a waste to call this each time
4875 ;; we switch another buffer into org-mode.
4876 (if (featurep 'xemacs)
4877 (when (boundp 'outline-mode-menu-heading)
4878 ;; Assume this is Greg's port, it uses easymenu
4879 (easy-menu-remove outline-mode-menu-heading)
4880 (easy-menu-remove outline-mode-menu-show)
4881 (easy-menu-remove outline-mode-menu-hide))
4882 (define-key org-mode-map [menu-bar headings] 'undefined)
4883 (define-key org-mode-map [menu-bar hide] 'undefined)
4884 (define-key org-mode-map [menu-bar show] 'undefined))
4886 (org-load-modules-maybe)
4887 (easy-menu-add org-org-menu)
4888 (easy-menu-add org-tbl-menu)
4889 (org-install-agenda-files-menu)
4890 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4891 (add-to-invisibility-spec '(org-cwidth))
4892 (add-to-invisibility-spec '(org-hide-block . t))
4893 (when (featurep 'xemacs)
4894 (org-set-local 'line-move-ignore-invisible t))
4895 (org-set-local 'outline-regexp org-outline-regexp)
4896 (org-set-local 'outline-level 'org-outline-level)
4897 (setq bidi-paragraph-direction 'left-to-right)
4898 (when (and org-ellipsis
4899 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4900 (fboundp 'make-glyph-code))
4901 (unless org-display-table
4902 (setq org-display-table (make-display-table)))
4903 (set-display-table-slot
4904 org-display-table 4
4905 (vconcat (mapcar
4906 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4907 org-ellipsis)))
4908 (if (stringp org-ellipsis) org-ellipsis "..."))))
4909 (setq buffer-display-table org-display-table))
4910 (org-set-regexps-and-options)
4911 (when (and org-tag-faces (not org-tags-special-faces-re))
4912 ;; tag faces set outside customize.... force initialization.
4913 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4914 ;; Calc embedded
4915 (org-set-local 'calc-embedded-open-mode "# ")
4916 (modify-syntax-entry ?@ "w")
4917 (if org-startup-truncated (setq truncate-lines t))
4918 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
4919 (org-set-local 'font-lock-unfontify-region-function
4920 'org-unfontify-region)
4921 ;; Activate before-change-function
4922 (org-set-local 'org-table-may-need-update t)
4923 (org-add-hook 'before-change-functions 'org-before-change-function nil
4924 'local)
4925 ;; Check for running clock before killing a buffer
4926 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4927 ;; Indentation.
4928 (org-set-local 'indent-line-function 'org-indent-line)
4929 (org-set-local 'indent-region-function 'org-indent-region)
4930 ;; Initialize radio targets.
4931 (org-update-radio-target-regexp)
4932 ;; Filling and auto-filling.
4933 (org-setup-filling)
4934 ;; Comments.
4935 (org-setup-comments-handling)
4936 ;; Beginning/end of defun
4937 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4938 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4939 ;; Next error for sparse trees
4940 (org-set-local 'next-error-function 'org-occur-next-match)
4941 ;; Make sure dependence stuff works reliably, even for users who set it
4942 ;; too late :-(
4943 (if org-enforce-todo-dependencies
4944 (add-hook 'org-blocker-hook
4945 'org-block-todo-from-children-or-siblings-or-parent)
4946 (remove-hook 'org-blocker-hook
4947 'org-block-todo-from-children-or-siblings-or-parent))
4948 (if org-enforce-todo-checkbox-dependencies
4949 (add-hook 'org-blocker-hook
4950 'org-block-todo-from-checkboxes)
4951 (remove-hook 'org-blocker-hook
4952 'org-block-todo-from-checkboxes))
4954 ;; Align options lines
4955 (org-set-local
4956 'align-mode-rules-list
4957 '((org-in-buffer-settings
4958 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4959 (modes . '(org-mode)))))
4961 ;; Imenu
4962 (org-set-local 'imenu-create-index-function
4963 'org-imenu-get-tree)
4965 ;; Make isearch reveal context
4966 (if (or (featurep 'xemacs)
4967 (not (boundp 'outline-isearch-open-invisible-function)))
4968 ;; Emacs 21 and XEmacs make use of the hook
4969 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4970 ;; Emacs 22 deals with this through a special variable
4971 (org-set-local 'outline-isearch-open-invisible-function
4972 (lambda (&rest ignore) (org-show-context 'isearch))))
4974 ;; Setup the pcomplete hooks
4975 (set (make-local-variable 'pcomplete-command-completion-function)
4976 'org-pcomplete-initial)
4977 (set (make-local-variable 'pcomplete-command-name-function)
4978 'org-command-at-point)
4979 (set (make-local-variable 'pcomplete-default-completion-function)
4980 'ignore)
4981 (set (make-local-variable 'pcomplete-parse-arguments-function)
4982 'org-parse-arguments)
4983 (set (make-local-variable 'pcomplete-termination-string) "")
4984 (when (>= emacs-major-version 23)
4985 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4987 ;; If empty file that did not turn on org-mode automatically, make it to.
4988 (if (and org-insert-mode-line-in-empty-file
4989 (org-called-interactively-p 'any)
4990 (= (point-min) (point-max)))
4991 (insert "# -*- mode: org -*-\n\n"))
4992 (unless org-inhibit-startup
4993 (and org-startup-with-beamer-mode (org-beamer-mode))
4994 (when org-startup-align-all-tables
4995 (let ((bmp (buffer-modified-p)))
4996 (org-table-map-tables 'org-table-align 'quietly)
4997 (set-buffer-modified-p bmp)))
4998 (when org-startup-with-inline-images
4999 (org-display-inline-images))
5000 (unless org-inhibit-startup-visibility-stuff
5001 (org-set-startup-visibility)))
5002 ;; Try to set org-hide correctly
5003 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5005 (when (fboundp 'abbrev-table-put)
5006 (abbrev-table-put org-mode-abbrev-table
5007 :parents (list text-mode-abbrev-table)))
5009 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5012 (defun org-find-invisible-foreground ()
5013 (let ((candidates (remove
5014 "unspecified-bg"
5015 (nconc
5016 (list (face-background 'default)
5017 (face-background 'org-default))
5018 (mapcar
5019 (lambda (alist)
5020 (when (boundp alist)
5021 (cdr (assoc 'background-color (symbol-value alist)))))
5022 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5023 (list (face-foreground 'org-hide))))))
5024 (car (remove nil candidates))))
5026 (defun org-current-time ()
5027 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5028 (if (> (car org-time-stamp-rounding-minutes) 1)
5029 (let ((r (car org-time-stamp-rounding-minutes))
5030 (time (decode-time)))
5031 (apply 'encode-time
5032 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5033 (nthcdr 2 time))))
5034 (current-time)))
5036 (defun org-today ()
5037 "Return today date, considering `org-extend-today-until'."
5038 (time-to-days
5039 (time-subtract (current-time)
5040 (list 0 (* 3600 org-extend-today-until) 0))))
5042 ;;;; Font-Lock stuff, including the activators
5044 (defvar org-mouse-map (make-sparse-keymap))
5045 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5046 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5047 (when org-mouse-1-follows-link
5048 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5049 (when org-tab-follows-link
5050 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5051 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5053 (require 'font-lock)
5055 (defconst org-non-link-chars "]\t\n\r<>")
5056 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5057 "shell" "elisp" "doi" "message"))
5058 (defvar org-link-types-re nil
5059 "Matches a link that has a url-like prefix like \"http:\"")
5060 (defvar org-link-re-with-space nil
5061 "Matches a link with spaces, optional angular brackets around it.")
5062 (defvar org-link-re-with-space2 nil
5063 "Matches a link with spaces, optional angular brackets around it.")
5064 (defvar org-link-re-with-space3 nil
5065 "Matches a link with spaces, only for internal part in bracket links.")
5066 (defvar org-angle-link-re nil
5067 "Matches link with angular brackets, spaces are allowed.")
5068 (defvar org-plain-link-re nil
5069 "Matches plain link, without spaces.")
5070 (defvar org-bracket-link-regexp nil
5071 "Matches a link in double brackets.")
5072 (defvar org-bracket-link-analytic-regexp nil
5073 "Regular expression used to analyze links.
5074 Here is what the match groups contain after a match:
5075 1: http:
5076 2: http
5077 3: path
5078 4: [desc]
5079 5: desc")
5080 (defvar org-bracket-link-analytic-regexp++ nil
5081 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5082 (defvar org-any-link-re nil
5083 "Regular expression matching any link.")
5085 (defcustom org-match-sexp-depth 3
5086 "Number of stacked braces for sub/superscript matching.
5087 This has to be set before loading org.el to be effective."
5088 :group 'org-export-translation ; ??????????????????????????/
5089 :type 'integer)
5091 (defun org-create-multibrace-regexp (left right n)
5092 "Create a regular expression which will match a balanced sexp.
5093 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5094 as single character strings.
5095 The regexp returned will match the entire expression including the
5096 delimiters. It will also define a single group which contains the
5097 match except for the outermost delimiters. The maximum depth of
5098 stacked delimiters is N. Escaping delimiters is not possible."
5099 (let* ((nothing (concat "[^" left right "]*?"))
5100 (or "\\|")
5101 (re nothing)
5102 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5103 (while (> n 1)
5104 (setq n (1- n)
5105 re (concat re or next)
5106 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5107 (concat left "\\(" re "\\)" right)))
5109 (defvar org-match-substring-regexp
5110 (concat
5111 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5112 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5113 "\\|"
5114 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5115 "\\|"
5116 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5117 "The regular expression matching a sub- or superscript.")
5119 (defvar org-match-substring-with-braces-regexp
5120 (concat
5121 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5122 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5123 "\\)")
5124 "The regular expression matching a sub- or superscript, forcing braces.")
5126 (defun org-make-link-regexps ()
5127 "Update the link regular expressions.
5128 This should be called after the variable `org-link-types' has changed."
5129 (setq org-link-types-re
5130 (concat
5131 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5132 org-link-re-with-space
5133 (concat
5134 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5135 "\\([^" org-non-link-chars " ]"
5136 "[^" org-non-link-chars "]*"
5137 "[^" org-non-link-chars " ]\\)>?")
5138 org-link-re-with-space2
5139 (concat
5140 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5141 "\\([^" org-non-link-chars " ]"
5142 "[^\t\n\r]*"
5143 "[^" org-non-link-chars " ]\\)>?")
5144 org-link-re-with-space3
5145 (concat
5146 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5147 "\\([^" org-non-link-chars " ]"
5148 "[^\t\n\r]*\\)")
5149 org-angle-link-re
5150 (concat
5151 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5152 "\\([^" org-non-link-chars " ]"
5153 "[^" org-non-link-chars "]*"
5154 "\\)>")
5155 org-plain-link-re
5156 (concat
5157 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5158 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5159 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5160 org-bracket-link-regexp
5161 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5162 org-bracket-link-analytic-regexp
5163 (concat
5164 "\\[\\["
5165 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5166 "\\([^]]+\\)"
5167 "\\]"
5168 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5169 "\\]")
5170 org-bracket-link-analytic-regexp++
5171 (concat
5172 "\\[\\["
5173 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5174 "\\([^]]+\\)"
5175 "\\]"
5176 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5177 "\\]")
5178 org-any-link-re
5179 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5180 org-angle-link-re "\\)\\|\\("
5181 org-plain-link-re "\\)")))
5183 (org-make-link-regexps)
5185 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5186 "Regular expression for fast time stamp matching.")
5187 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5188 "Regular expression for fast time stamp matching.")
5189 (defconst org-ts-regexp0
5190 "\\(\\([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 This one does not require the space after the date, so it can be used
5193 on a string that terminates immediately after the date.")
5194 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5195 "Regular expression matching time strings for analysis.")
5196 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5197 "Regular expression matching time stamps, with groups.")
5198 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5199 "Regular expression matching time stamps (also [..]), with groups.")
5200 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5201 "Regular expression matching a time stamp range.")
5202 (defconst org-tr-regexp-both
5203 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5204 "Regular expression matching a time stamp range.")
5205 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5206 org-ts-regexp "\\)?")
5207 "Regular expression matching a time stamp or time stamp range.")
5208 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5209 org-ts-regexp-both "\\)?")
5210 "Regular expression matching a time stamp or time stamp range.
5211 The time stamps may be either active or inactive.")
5213 (defvar org-emph-face nil)
5215 (defun org-do-emphasis-faces (limit)
5216 "Run through the buffer and add overlays to emphasized strings."
5217 (let (rtn a)
5218 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5219 (if (not (= (char-after (match-beginning 3))
5220 (char-after (match-beginning 4))))
5221 (progn
5222 (setq rtn t)
5223 (setq a (assoc (match-string 3) org-emphasis-alist))
5224 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5225 'face
5226 (nth 1 a))
5227 (and (nth 4 a)
5228 (org-remove-flyspell-overlays-in
5229 (match-beginning 0) (match-end 0)))
5230 (add-text-properties (match-beginning 2) (match-end 2)
5231 '(font-lock-multiline t org-emphasis t))
5232 (when org-hide-emphasis-markers
5233 (add-text-properties (match-end 4) (match-beginning 5)
5234 '(invisible org-link))
5235 (add-text-properties (match-beginning 3) (match-end 3)
5236 '(invisible org-link)))))
5237 (backward-char 1))
5238 rtn))
5240 (defun org-emphasize (&optional char)
5241 "Insert or change an emphasis, i.e. a font like bold or italic.
5242 If there is an active region, change that region to a new emphasis.
5243 If there is no region, just insert the marker characters and position
5244 the cursor between them.
5245 CHAR should be either the marker character, or the first character of the
5246 HTML tag associated with that emphasis. If CHAR is a space, the means
5247 to remove the emphasis of the selected region.
5248 If char is not given (for example in an interactive call) it
5249 will be prompted for."
5250 (interactive)
5251 (let ((eal org-emphasis-alist) e det
5252 (erc org-emphasis-regexp-components)
5253 (prompt "")
5254 (string "") beg end move tag c s)
5255 (if (org-region-active-p)
5256 (setq beg (region-beginning) end (region-end)
5257 string (buffer-substring beg end))
5258 (setq move t))
5260 (while (setq e (pop eal))
5261 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5262 c (aref tag 0))
5263 (push (cons c (string-to-char (car e))) det)
5264 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5265 (substring tag 1)))))
5266 (setq det (nreverse det))
5267 (unless char
5268 (message "%s" (concat "Emphasis marker or tag:" prompt))
5269 (setq char (read-char-exclusive)))
5270 (setq char (or (cdr (assoc char det)) char))
5271 (if (equal char ?\ )
5272 (setq s "" move nil)
5273 (unless (assoc (char-to-string char) org-emphasis-alist)
5274 (error "No such emphasis marker: \"%c\"" char))
5275 (setq s (char-to-string char)))
5276 (while (and (> (length string) 1)
5277 (equal (substring string 0 1) (substring string -1))
5278 (assoc (substring string 0 1) org-emphasis-alist))
5279 (setq string (substring string 1 -1)))
5280 (setq string (concat s string s))
5281 (if beg (delete-region beg end))
5282 (unless (or (bolp)
5283 (string-match (concat "[" (nth 0 erc) "\n]")
5284 (char-to-string (char-before (point)))))
5285 (insert " "))
5286 (unless (or (eobp)
5287 (string-match (concat "[" (nth 1 erc) "\n]")
5288 (char-to-string (char-after (point)))))
5289 (insert " ") (backward-char 1))
5290 (insert string)
5291 (and move (backward-char 1))))
5293 (defconst org-nonsticky-props
5294 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5296 (defsubst org-rear-nonsticky-at (pos)
5297 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5299 (defun org-activate-plain-links (limit)
5300 "Run through the buffer and add overlays to links."
5301 (catch 'exit
5302 (let (f)
5303 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5304 (not (org-in-src-block-p)))
5305 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5306 (setq f (get-text-property (match-beginning 0) 'face))
5307 (unless (or (org-in-src-block-p)
5308 (eq f 'org-tag)
5309 (and (listp f) (memq 'org-tag f)))
5310 (add-text-properties (match-beginning 0) (match-end 0)
5311 (list 'mouse-face 'highlight
5312 'face 'org-link
5313 'keymap org-mouse-map))
5314 (org-rear-nonsticky-at (match-end 0)))
5315 t))))
5317 (defun org-activate-code (limit)
5318 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5319 (progn
5320 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5321 (remove-text-properties (match-beginning 0) (match-end 0)
5322 '(display t invisible t intangible t))
5323 t)))
5325 (defcustom org-src-fontify-natively nil
5326 "When non-nil, fontify code in code blocks."
5327 :type 'boolean
5328 :version "24.1"
5329 :group 'org-appearance
5330 :group 'org-babel)
5332 (defcustom org-allow-promoting-top-level-subtree nil
5333 "When non-nil, allow promoting a top level subtree.
5334 The leading star of the top level headline will be replaced
5335 by a #."
5336 :type 'boolean
5337 :version "24.1"
5338 :group 'org-appearance)
5340 (defun org-fontify-meta-lines-and-blocks (limit)
5341 (condition-case nil
5342 (org-fontify-meta-lines-and-blocks-1 limit)
5343 (error (message "org-mode fontification error"))))
5345 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5346 "Fontify #+ lines and blocks, in the correct ways."
5347 (let ((case-fold-search t))
5348 (if (re-search-forward
5349 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5350 limit t)
5351 (let ((beg (match-beginning 0))
5352 (block-start (match-end 0))
5353 (block-end nil)
5354 (lang (match-string 7))
5355 (beg1 (line-beginning-position 2))
5356 (dc1 (downcase (match-string 2)))
5357 (dc3 (downcase (match-string 3)))
5358 end end1 quoting block-type ovl)
5359 (cond
5360 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5361 ;; a single line of backend-specific content
5362 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5363 (remove-text-properties (match-beginning 0) (match-end 0)
5364 '(display t invisible t intangible t))
5365 (add-text-properties (match-beginning 1) (match-end 3)
5366 '(font-lock-fontified t face org-meta-line))
5367 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5368 '(font-lock-fontified t face org-block))
5369 ; for backend-specific code
5371 ((and (match-end 4) (equal dc3 "+begin"))
5372 ;; Truly a block
5373 (setq block-type (downcase (match-string 5))
5374 quoting (member block-type org-protecting-blocks))
5375 (when (re-search-forward
5376 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5377 nil t) ;; on purpose, we look further than LIMIT
5378 (setq end (min (point-max) (match-end 0))
5379 end1 (min (point-max) (1- (match-beginning 0))))
5380 (setq block-end (match-beginning 0))
5381 (when quoting
5382 (remove-text-properties beg end
5383 '(display t invisible t intangible t)))
5384 (add-text-properties
5385 beg end
5386 '(font-lock-fontified t font-lock-multiline t))
5387 (add-text-properties beg beg1 '(face org-meta-line))
5388 (add-text-properties end1 (min (point-max) (1+ end))
5389 '(face org-meta-line)) ; for end_src
5390 (cond
5391 ((and lang (not (string= lang "")) org-src-fontify-natively)
5392 (org-src-font-lock-fontify-block lang block-start block-end)
5393 ;; remove old background overlays
5394 (mapc (lambda (ov)
5395 (if (eq (overlay-get ov 'face) 'org-block-background)
5396 (delete-overlay ov)))
5397 (overlays-at (/ (+ beg1 block-end) 2)))
5398 ;; add a background overlay
5399 (setq ovl (make-overlay beg1 block-end))
5400 (overlay-put ovl 'face 'org-block-background)
5401 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5402 (quoting
5403 (add-text-properties beg1 (min (point-max) (1+ end1))
5404 '(face org-block))) ; end of source block
5405 ((not org-fontify-quote-and-verse-blocks))
5406 ((string= block-type "quote")
5407 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5408 ((string= block-type "verse")
5409 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5410 (add-text-properties beg beg1 '(face org-block-begin-line))
5411 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5412 '(face org-block-end-line))
5414 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5415 (add-text-properties
5416 beg (match-end 3)
5417 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5418 '(font-lock-fontified t invisible t)
5419 '(font-lock-fontified t face org-document-info-keyword)))
5420 (add-text-properties
5421 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5422 (if (string-equal dc1 "+title:")
5423 '(font-lock-fontified t face org-document-title)
5424 '(font-lock-fontified t face org-document-info))))
5425 ((or (equal dc1 "+results")
5426 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5427 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5428 "+call:" "+header:" "+headers:" "+name:"))
5429 (and (match-end 4) (equal dc3 "+attr")))
5430 (add-text-properties
5431 beg (match-end 0)
5432 '(font-lock-fontified t face org-meta-line))
5434 ((member dc3 '(" " ""))
5435 (add-text-properties
5436 beg (match-end 0)
5437 '(font-lock-fontified t face font-lock-comment-face)))
5438 ((not (member (char-after beg) '(?\ ?\t)))
5439 ;; just any other in-buffer setting, but not indented
5440 (add-text-properties
5441 beg (match-end 0)
5442 '(font-lock-fontified t face org-meta-line))
5444 (t nil))))))
5446 (defun org-activate-angle-links (limit)
5447 "Run through the buffer and add overlays to links."
5448 (if (and (re-search-forward org-angle-link-re limit t)
5449 (not (org-in-src-block-p)))
5450 (progn
5451 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5452 (add-text-properties (match-beginning 0) (match-end 0)
5453 (list 'mouse-face 'highlight
5454 'keymap org-mouse-map))
5455 (org-rear-nonsticky-at (match-end 0))
5456 t)))
5458 (defun org-activate-footnote-links (limit)
5459 "Run through the buffer and add overlays to footnotes."
5460 (let ((fn (org-footnote-next-reference-or-definition limit)))
5461 (when fn
5462 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5463 (org-remove-flyspell-overlays-in beg end)
5464 (add-text-properties beg end
5465 (list 'mouse-face 'highlight
5466 'keymap org-mouse-map
5467 'help-echo
5468 (if (= (point-at-bol) beg)
5469 "Footnote definition"
5470 "Footnote reference")
5471 'font-lock-fontified t
5472 'font-lock-multiline t
5473 'face 'org-footnote))))))
5475 (defun org-activate-bracket-links (limit)
5476 "Run through the buffer and add overlays to bracketed links."
5477 (if (and (re-search-forward org-bracket-link-regexp limit t)
5478 (not (org-in-src-block-p)))
5479 (let* ((help (concat "LINK: "
5480 (org-match-string-no-properties 1)))
5481 ;; FIXME: above we should remove the escapes.
5482 ;; but that requires another match, protecting match data,
5483 ;; a lot of overhead for font-lock.
5484 (ip (org-maybe-intangible
5485 (list 'invisible 'org-link
5486 'keymap org-mouse-map 'mouse-face 'highlight
5487 'font-lock-multiline t 'help-echo help)))
5488 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5489 'font-lock-multiline t 'help-echo help)))
5490 ;; We need to remove the invisible property here. Table narrowing
5491 ;; may have made some of this invisible.
5492 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5493 (remove-text-properties (match-beginning 0) (match-end 0)
5494 '(invisible nil))
5495 (if (match-end 3)
5496 (progn
5497 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5498 (org-rear-nonsticky-at (match-beginning 3))
5499 (add-text-properties (match-beginning 3) (match-end 3) vp)
5500 (org-rear-nonsticky-at (match-end 3))
5501 (add-text-properties (match-end 3) (match-end 0) ip)
5502 (org-rear-nonsticky-at (match-end 0)))
5503 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5504 (org-rear-nonsticky-at (match-beginning 1))
5505 (add-text-properties (match-beginning 1) (match-end 1) vp)
5506 (org-rear-nonsticky-at (match-end 1))
5507 (add-text-properties (match-end 1) (match-end 0) ip)
5508 (org-rear-nonsticky-at (match-end 0)))
5509 t)))
5511 (defun org-activate-dates (limit)
5512 "Run through the buffer and add overlays to dates."
5513 (if (re-search-forward org-tsr-regexp-both limit t)
5514 (progn
5515 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5516 (add-text-properties (match-beginning 0) (match-end 0)
5517 (list 'mouse-face 'highlight
5518 'keymap org-mouse-map))
5519 (org-rear-nonsticky-at (match-end 0))
5520 (when org-display-custom-times
5521 (if (match-end 3)
5522 (org-display-custom-time (match-beginning 3) (match-end 3)))
5523 (org-display-custom-time (match-beginning 1) (match-end 1)))
5524 t)))
5526 (defvar org-target-link-regexp nil
5527 "Regular expression matching radio targets in plain text.")
5528 (make-variable-buffer-local 'org-target-link-regexp)
5529 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5530 "Regular expression matching a link target.")
5531 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5532 "Regular expression matching a radio target.")
5533 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5534 "Regular expression matching any target.")
5536 (defun org-activate-target-links (limit)
5537 "Run through the buffer and add overlays to target matches."
5538 (when org-target-link-regexp
5539 (let ((case-fold-search t))
5540 (if (re-search-forward org-target-link-regexp limit t)
5541 (progn
5542 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5543 (add-text-properties (match-beginning 0) (match-end 0)
5544 (list 'mouse-face 'highlight
5545 'keymap org-mouse-map
5546 'help-echo "Radio target link"
5547 'org-linked-text t))
5548 (org-rear-nonsticky-at (match-end 0))
5549 t)))))
5551 (defun org-update-radio-target-regexp ()
5552 "Find all radio targets in this file and update the regular expression."
5553 (interactive)
5554 (when (memq 'radio org-activate-links)
5555 (setq org-target-link-regexp
5556 (org-make-target-link-regexp (org-all-targets 'radio)))
5557 (org-restart-font-lock)))
5559 (defun org-hide-wide-columns (limit)
5560 (let (s e)
5561 (setq s (text-property-any (point) (or limit (point-max))
5562 'org-cwidth t))
5563 (when s
5564 (setq e (next-single-property-change s 'org-cwidth))
5565 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5566 (goto-char e)
5567 t)))
5569 (defvar org-latex-and-specials-regexp nil
5570 "Regular expression for highlighting export special stuff.")
5571 (defvar org-match-substring-regexp)
5572 (defvar org-match-substring-with-braces-regexp)
5574 ;; This should be with the exporter code, but we also use if for font-locking
5575 (defconst org-export-html-special-string-regexps
5576 '(("\\\\-" . "&shy;")
5577 ("---\\([^-]\\)" . "&mdash;\\1")
5578 ("--\\([^-]\\)" . "&ndash;\\1")
5579 ("\\.\\.\\." . "&hellip;"))
5580 "Regular expressions for special string conversion.")
5583 (defun org-compute-latex-and-specials-regexp ()
5584 "Compute regular expression for stuff treated specially by exporters."
5585 (if (not org-highlight-latex-fragments-and-specials)
5586 (org-set-local 'org-latex-and-specials-regexp nil)
5587 (require 'org-exp)
5588 (let*
5589 ((matchers (plist-get org-format-latex-options :matchers))
5590 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5591 org-latex-regexps)))
5592 (org-export-allow-BIND nil)
5593 (options (org-combine-plists (org-default-export-plist)
5594 (org-infile-export-plist)))
5595 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5596 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5597 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5598 (org-export-html-expand (plist-get options :expand-quoted-html))
5599 (org-export-with-special-strings (plist-get options :special-strings))
5600 (re-sub
5601 (cond
5602 ((equal org-export-with-sub-superscripts '{})
5603 (list org-match-substring-with-braces-regexp))
5604 (org-export-with-sub-superscripts
5605 (list org-match-substring-regexp))))
5606 (re-latex
5607 (if org-export-with-LaTeX-fragments
5608 (mapcar (lambda (x) (nth 1 x)) latexs)))
5609 (re-macros
5610 (if org-export-with-TeX-macros
5611 (list (concat "\\\\"
5612 (regexp-opt
5613 (append
5615 (delq nil
5616 (mapcar 'car-safe
5617 (append org-entities-user
5618 org-entities)))
5619 (if (boundp 'org-latex-entities)
5620 (mapcar (lambda (x)
5621 (or (car-safe x) x))
5622 org-latex-entities)
5623 nil))
5624 'words))) ; FIXME
5626 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5627 (re-special (if org-export-with-special-strings
5628 (mapcar (lambda (x) (car x))
5629 org-export-html-special-string-regexps)))
5630 (re-rest
5631 (delq nil
5632 (list
5633 (if org-export-html-expand "@<[^>\n]+>")
5634 ))))
5635 (org-set-local
5636 'org-latex-and-specials-regexp
5637 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5638 re-rest) "\\|")))))
5640 (defun org-do-latex-and-special-faces (limit)
5641 "Run through the buffer and add overlays to links."
5642 (when org-latex-and-specials-regexp
5643 (let (rtn d)
5644 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5645 limit t))
5646 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5647 'face))
5648 '(org-code org-verbatim underline)))
5649 (progn
5650 (setq rtn t
5651 d (cond ((member (char-after (1+ (match-beginning 0)))
5652 '(?_ ?^)) 1)
5653 (t 0)))
5654 (font-lock-prepend-text-property
5655 (+ d (match-beginning 0)) (match-end 0)
5656 'face 'org-latex-and-export-specials)
5657 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5658 '(font-lock-multiline t)))))
5659 rtn)))
5661 (defun org-restart-font-lock ()
5662 "Restart `font-lock-mode', to force refontification."
5663 (when (and (boundp 'font-lock-mode) font-lock-mode)
5664 (font-lock-mode -1)
5665 (font-lock-mode 1)))
5667 (defun org-all-targets (&optional radio)
5668 "Return a list of all targets in this file.
5669 With optional argument RADIO, only find radio targets."
5670 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5671 rtn)
5672 (save-excursion
5673 (goto-char (point-min))
5674 (while (re-search-forward re nil t)
5675 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5676 rtn)))
5678 (defun org-make-target-link-regexp (targets)
5679 "Make regular expression matching all strings in TARGETS.
5680 The regular expression finds the targets also if there is a line break
5681 between words."
5682 (and targets
5683 (concat
5684 "\\<\\("
5685 (mapconcat
5686 (lambda (x)
5687 (setq x (regexp-quote x))
5688 (while (string-match " +" x)
5689 (setq x (replace-match "\\s-+" t t x)))
5691 targets
5692 "\\|")
5693 "\\)\\>")))
5695 (defun org-activate-tags (limit)
5696 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5697 (progn
5698 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5699 (add-text-properties (match-beginning 1) (match-end 1)
5700 (list 'mouse-face 'highlight
5701 'keymap org-mouse-map))
5702 (org-rear-nonsticky-at (match-end 1))
5703 t)))
5705 (defun org-outline-level ()
5706 "Compute the outline level of the heading at point.
5707 This function assumes that the cursor is at the beginning of a line matched
5708 by `outline-regexp'. Otherwise it returns garbage.
5709 If this is called at a normal headline, the level is the number of stars.
5710 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5711 (save-excursion
5712 (looking-at org-outline-regexp)
5713 (1- (- (match-end 0) (match-beginning 0)))))
5715 (defvar org-font-lock-keywords nil)
5717 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5718 "Regular expression matching a property line.")
5720 (defvar org-font-lock-hook nil
5721 "Functions to be called for special font lock stuff.")
5723 (defvar org-font-lock-set-keywords-hook nil
5724 "Functions that can manipulate `org-font-lock-extra-keywords'.
5725 This is called after `org-font-lock-extra-keywords' is defined, but before
5726 it is installed to be used by font lock. This can be useful if something
5727 needs to be inserted at a specific position in the font-lock sequence.")
5729 (defun org-font-lock-hook (limit)
5730 "Run `org-font-lock-hook' within LIMIT."
5731 (run-hook-with-args 'org-font-lock-hook limit))
5733 (defun org-set-font-lock-defaults ()
5734 "Set font lock defaults for the current buffer."
5735 (let* ((em org-fontify-emphasized-text)
5736 (lk org-activate-links)
5737 (org-font-lock-extra-keywords
5738 (list
5739 ;; Call the hook
5740 '(org-font-lock-hook)
5741 ;; Headlines
5742 `(,(if org-fontify-whole-heading-line
5743 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5744 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5745 (1 (org-get-level-face 1))
5746 (2 (org-get-level-face 2))
5747 (3 (org-get-level-face 3)))
5748 ;; Table lines
5749 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5750 (1 'org-table t))
5751 ;; Table internals
5752 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5753 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5754 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5755 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5756 ;; Drawers
5757 (list org-drawer-regexp '(0 'org-special-keyword t))
5758 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5759 ;; Properties
5760 (list org-property-re
5761 '(1 'org-special-keyword t)
5762 '(3 'org-property-value t))
5763 ;; Links
5764 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5765 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5766 (if (memq 'plain lk) '(org-activate-plain-links))
5767 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5768 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5769 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5770 (if (memq 'footnote lk) '(org-activate-footnote-links))
5771 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5772 '(org-hide-wide-columns (0 nil append))
5773 ;; TODO keyword
5774 (list (format org-heading-keyword-regexp-format
5775 org-todo-regexp)
5776 '(2 (org-get-todo-face 2) t))
5777 ;; DONE
5778 (if org-fontify-done-headline
5779 (list (format org-heading-keyword-regexp-format
5780 (concat
5781 "\\(?:"
5782 (mapconcat 'regexp-quote org-done-keywords "\\|")
5783 "\\)"))
5784 '(2 'org-headline-done t))
5785 nil)
5786 ;; Priorities
5787 '(org-font-lock-add-priority-faces)
5788 ;; Tags
5789 '(org-font-lock-add-tag-faces)
5790 ;; Special keywords
5791 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5792 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5793 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5794 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5795 ;; Emphasis
5796 (if em
5797 (if (featurep 'xemacs)
5798 '(org-do-emphasis-faces (0 nil append))
5799 '(org-do-emphasis-faces)))
5800 ;; Checkboxes
5801 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5802 1 'org-checkbox prepend)
5803 (if (cdr (assq 'checkbox org-list-automatic-rules))
5804 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5805 (0 (org-get-checkbox-statistics-face) t)))
5806 ;; Description list items
5807 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5808 1 'org-list-dt prepend)
5809 ;; ARCHIVEd headings
5810 (list (concat
5811 org-outline-regexp-bol
5812 "\\(.*:" org-archive-tag ":.*\\)")
5813 '(1 'org-archived prepend))
5814 ;; Specials
5815 '(org-do-latex-and-special-faces)
5816 '(org-fontify-entities)
5817 '(org-raise-scripts)
5818 ;; Code
5819 '(org-activate-code (1 'org-code t))
5820 ;; COMMENT
5821 (list (format org-heading-keyword-regexp-format
5822 (concat "\\("
5823 org-comment-string "\\|" org-quote-string
5824 "\\)"))
5825 '(2 'org-special-keyword t))
5826 ;; Blocks and meta lines
5827 '(org-fontify-meta-lines-and-blocks)
5829 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5830 (run-hooks 'org-font-lock-set-keywords-hook)
5831 ;; Now set the full font-lock-keywords
5832 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5833 (org-set-local 'font-lock-defaults
5834 '(org-font-lock-keywords t nil nil backward-paragraph))
5835 (kill-local-variable 'font-lock-keywords) nil))
5837 (defun org-toggle-pretty-entities ()
5838 "Toggle the composition display of entities as UTF8 characters."
5839 (interactive)
5840 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5841 (org-restart-font-lock)
5842 (if org-pretty-entities
5843 (message "Entities are displayed as UTF8 characters")
5844 (save-restriction
5845 (widen)
5846 (org-decompose-region (point-min) (point-max))
5847 (message "Entities are displayed plain"))))
5849 (defvar org-custom-properties-overlays nil
5850 "List of overlays used for custom properties.")
5851 (make-variable-buffer-local 'org-custom-properties-overlays)
5853 (defun org-toggle-custom-properties-visibility ()
5854 "Display or hide properties in `org-custom-properties'."
5855 (interactive)
5856 (if org-custom-properties-overlays
5857 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5858 (setq org-custom-properties-overlays nil))
5859 (unless (not org-custom-properties)
5860 (save-excursion
5861 (save-restriction
5862 (widen)
5863 (goto-char (point-min))
5864 (while (re-search-forward org-property-re nil t)
5865 (mapc (lambda(p)
5866 (when (equal p (substring (match-string 1) 1 -1))
5867 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5868 (overlay-put o 'invisible t)
5869 (overlay-put o 'org-custom-property t)
5870 (push o org-custom-properties-overlays))))
5871 org-custom-properties)))))))
5873 (defun org-fontify-entities (limit)
5874 "Find an entity to fontify."
5875 (let (ee)
5876 (when org-pretty-entities
5877 (catch 'match
5878 (while (re-search-forward
5879 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5880 limit t)
5881 (if (and (not (org-in-indented-comment-line))
5882 (setq ee (org-entity-get (match-string 1)))
5883 (= (length (nth 6 ee)) 1))
5884 (let*
5885 ((end (if (equal (match-string 2) "{}")
5886 (match-end 2)
5887 (match-end 1))))
5888 (add-text-properties
5889 (match-beginning 0) end
5890 (list 'font-lock-fontified t))
5891 (compose-region (match-beginning 0) end
5892 (nth 6 ee) nil)
5893 (backward-char 1)
5894 (throw 'match t))))
5895 nil))))
5897 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5898 "Fontify string S like in Org-mode."
5899 (with-temp-buffer
5900 (insert s)
5901 (let ((org-odd-levels-only odd-levels))
5902 (org-mode)
5903 (font-lock-fontify-buffer)
5904 (buffer-string))))
5906 (defvar org-m nil)
5907 (defvar org-l nil)
5908 (defvar org-f nil)
5909 (defun org-get-level-face (n)
5910 "Get the right face for match N in font-lock matching of headlines."
5911 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5912 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5913 (if org-cycle-level-faces
5914 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5915 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5916 (cond
5917 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5918 ((eq n 2) org-f)
5919 (t (if org-level-color-stars-only nil org-f))))
5922 (defun org-get-todo-face (kwd)
5923 "Get the right face for a TODO keyword KWD.
5924 If KWD is a number, get the corresponding match group."
5925 (if (numberp kwd) (setq kwd (match-string kwd)))
5926 (or (org-face-from-face-or-color
5927 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5928 (and (member kwd org-done-keywords) 'org-done)
5929 'org-todo))
5931 (defun org-face-from-face-or-color (context inherit face-or-color)
5932 "Create a face list that inherits INHERIT, but sets the foreground color.
5933 When FACE-OR-COLOR is not a string, just return it."
5934 (if (stringp face-or-color)
5935 (list :inherit inherit
5936 (cdr (assoc context org-faces-easy-properties))
5937 face-or-color)
5938 face-or-color))
5940 (defun org-font-lock-add-tag-faces (limit)
5941 "Add the special tag faces."
5942 (when (and org-tag-faces org-tags-special-faces-re)
5943 (while (re-search-forward org-tags-special-faces-re limit t)
5944 (add-text-properties (match-beginning 1) (match-end 1)
5945 (list 'face (org-get-tag-face 1)
5946 'font-lock-fontified t))
5947 (backward-char 1))))
5949 (defun org-font-lock-add-priority-faces (limit)
5950 "Add the special priority faces."
5951 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5952 (when (save-match-data (org-at-heading-p))
5953 (add-text-properties
5954 (match-beginning 0) (match-end 0)
5955 (list 'face (or (org-face-from-face-or-color
5956 'priority 'org-special-keyword
5957 (cdr (assoc (char-after (match-beginning 1))
5958 org-priority-faces)))
5959 'org-special-keyword)
5960 'font-lock-fontified t)))))
5962 (defun org-get-tag-face (kwd)
5963 "Get the right face for a TODO keyword KWD.
5964 If KWD is a number, get the corresponding match group."
5965 (if (numberp kwd) (setq kwd (match-string kwd)))
5966 (or (org-face-from-face-or-color
5967 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5968 'org-tag))
5970 (defun org-unfontify-region (beg end &optional maybe_loudly)
5971 "Remove fontification and activation overlays from links."
5972 (font-lock-default-unfontify-region beg end)
5973 (let* ((buffer-undo-list t)
5974 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5975 (inhibit-modification-hooks t)
5976 deactivate-mark buffer-file-name buffer-file-truename)
5977 (org-decompose-region beg end)
5978 (remove-text-properties beg end
5979 '(mouse-face t keymap t org-linked-text t
5980 invisible t intangible t
5981 org-no-flyspell t org-emphasis t))
5982 (org-remove-font-lock-display-properties beg end)))
5984 (defconst org-script-display '(((raise -0.3) (height 0.7))
5985 ((raise 0.3) (height 0.7))
5986 ((raise -0.5))
5987 ((raise 0.5)))
5988 "Display properties for showing superscripts and subscripts.")
5990 (defun org-remove-font-lock-display-properties (beg end)
5991 "Remove specific display properties that have been added by font lock.
5992 The will remove the raise properties that are used to show superscripts
5993 and subscripts."
5994 (let (next prop)
5995 (while (< beg end)
5996 (setq next (next-single-property-change beg 'display nil end)
5997 prop (get-text-property beg 'display))
5998 (if (member prop org-script-display)
5999 (put-text-property beg next 'display nil))
6000 (setq beg next))))
6002 (defun org-raise-scripts (limit)
6003 "Add raise properties to sub/superscripts."
6004 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6005 (if (re-search-forward
6006 (if (eq org-use-sub-superscripts t)
6007 org-match-substring-regexp
6008 org-match-substring-with-braces-regexp)
6009 limit t)
6010 (let* ((pos (point)) table-p comment-p
6011 (mpos (match-beginning 3))
6012 (emph-p (get-text-property mpos 'org-emphasis))
6013 (link-p (get-text-property mpos 'mouse-face))
6014 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6015 (goto-char (point-at-bol))
6016 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6017 comment-p (org-looking-at-p "[ \t]*#"))
6018 (goto-char pos)
6019 ;; FIXME: Should we go back one character here, for a_b^c
6020 ;; (goto-char (1- pos)) ;????????????????????
6021 (if (or comment-p emph-p link-p keyw-p)
6023 (put-text-property (match-beginning 3) (match-end 0)
6024 'display
6025 (if (equal (char-after (match-beginning 2)) ?^)
6026 (nth (if table-p 3 1) org-script-display)
6027 (nth (if table-p 2 0) org-script-display)))
6028 (add-text-properties (match-beginning 2) (match-end 2)
6029 (list 'invisible t
6030 'org-dwidth t 'org-dwidth-n 1))
6031 (if (and (eq (char-after (match-beginning 3)) ?{)
6032 (eq (char-before (match-end 3)) ?}))
6033 (progn
6034 (add-text-properties
6035 (match-beginning 3) (1+ (match-beginning 3))
6036 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6037 (add-text-properties
6038 (1- (match-end 3)) (match-end 3)
6039 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6040 t)))))
6042 ;;;; Visibility cycling, including org-goto and indirect buffer
6044 ;;; Cycling
6046 (defvar org-cycle-global-status nil)
6047 (make-variable-buffer-local 'org-cycle-global-status)
6048 (defvar org-cycle-subtree-status nil)
6049 (make-variable-buffer-local 'org-cycle-subtree-status)
6051 (defvar org-inlinetask-min-level)
6053 ;;;###autoload
6054 (defun org-cycle (&optional arg)
6055 "TAB-action and visibility cycling for Org-mode.
6057 This is the command invoked in Org-mode by the TAB key. Its main purpose
6058 is outline visibility cycling, but it also invokes other actions
6059 in special contexts.
6061 - When this function is called with a prefix argument, rotate the entire
6062 buffer through 3 states (global cycling)
6063 1. OVERVIEW: Show only top-level headlines.
6064 2. CONTENTS: Show all headlines of all levels, but no body text.
6065 3. SHOW ALL: Show everything.
6066 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6067 determined by the variable `org-startup-folded', and by any VISIBILITY
6068 properties in the buffer.
6069 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6070 including any drawers.
6072 - When inside a table, re-align the table and move to the next field.
6074 - When point is at the beginning of a headline, rotate the subtree started
6075 by this line through 3 different states (local cycling)
6076 1. FOLDED: Only the main headline is shown.
6077 2. CHILDREN: The main headline and the direct children are shown.
6078 From this state, you can move to one of the children
6079 and zoom in further.
6080 3. SUBTREE: Show the entire subtree, including body text.
6081 If there is no subtree, switch directly from CHILDREN to FOLDED.
6083 - When point is at the beginning of an empty headline and the variable
6084 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6085 of the headline by demoting and promoting it to likely levels. This
6086 speeds up creation document structure by pressing TAB once or several
6087 times right after creating a new headline.
6089 - When there is a numeric prefix, go up to a heading with level ARG, do
6090 a `show-subtree' and return to the previous cursor position. If ARG
6091 is negative, go up that many levels.
6093 - When point is not at the beginning of a headline, execute the global
6094 binding for TAB, which is re-indenting the line. See the option
6095 `org-cycle-emulate-tab' for details.
6097 - Special case: if point is at the beginning of the buffer and there is
6098 no headline in line 1, this function will act as if called with prefix arg
6099 (C-u TAB, same as S-TAB) also when called without prefix arg.
6100 But only if also the variable `org-cycle-global-at-bob' is t."
6101 (interactive "P")
6102 (org-load-modules-maybe)
6103 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6104 (and org-cycle-level-after-item/entry-creation
6105 (or (org-cycle-level)
6106 (org-cycle-item-indentation))))
6107 (let* ((limit-level
6108 (or org-cycle-max-level
6109 (and (boundp 'org-inlinetask-min-level)
6110 org-inlinetask-min-level
6111 (1- org-inlinetask-min-level))))
6112 (nstars (and limit-level
6113 (if org-odd-levels-only
6114 (and limit-level (1- (* limit-level 2)))
6115 limit-level)))
6116 (org-outline-regexp
6117 (if (not (derived-mode-p 'org-mode))
6118 outline-regexp
6119 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6120 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6121 (not (looking-at org-outline-regexp))))
6122 (org-cycle-hook
6123 (if bob-special
6124 (delq 'org-optimize-window-after-visibility-change
6125 (copy-sequence org-cycle-hook))
6126 org-cycle-hook))
6127 (pos (point)))
6129 (if (or bob-special (equal arg '(4)))
6130 ;; special case: use global cycling
6131 (setq arg t))
6133 (cond
6135 ((equal arg '(16))
6136 (setq last-command 'dummy)
6137 (org-set-startup-visibility)
6138 (message "Startup visibility, plus VISIBILITY properties"))
6140 ((equal arg '(64))
6141 (show-all)
6142 (message "Entire buffer visible, including drawers"))
6144 ;; Table: enter it or move to the next field.
6145 ((org-at-table-p 'any)
6146 (if (org-at-table.el-p)
6147 (message "Use C-c ' to edit table.el tables")
6148 (if arg (org-table-edit-field t)
6149 (org-table-justify-field-maybe)
6150 (call-interactively 'org-table-next-field))))
6152 ((run-hook-with-args-until-success
6153 'org-tab-after-check-for-table-hook))
6155 ;; Global cycling: delegate to `org-cycle-internal-global'.
6156 ((eq arg t) (org-cycle-internal-global))
6158 ;; Drawers: delegate to `org-flag-drawer'.
6159 ((and org-drawers org-drawer-regexp
6160 (save-excursion
6161 (beginning-of-line 1)
6162 (looking-at org-drawer-regexp)))
6163 (org-flag-drawer ; toggle block visibility
6164 (not (get-char-property (match-end 0) 'invisible))))
6166 ;; Show-subtree, ARG levels up from here.
6167 ((integerp arg)
6168 (save-excursion
6169 (org-back-to-heading)
6170 (outline-up-heading (if (< arg 0) (- arg)
6171 (- (funcall outline-level) arg)))
6172 (org-show-subtree)))
6174 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6175 ((and (featurep 'org-inlinetask)
6176 (org-inlinetask-at-task-p)
6177 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6178 (org-inlinetask-toggle-visibility))
6180 ((org-try-cdlatex-tab))
6182 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6183 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6184 (save-excursion (beginning-of-line 1)
6185 (looking-at org-outline-regexp)))
6186 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6187 (org-cycle-internal-local))
6189 ;; From there: TAB emulation and template completion.
6190 (buffer-read-only (org-back-to-heading))
6192 ((run-hook-with-args-until-success
6193 'org-tab-after-check-for-cycling-hook))
6195 ((org-try-structure-completion))
6197 ((run-hook-with-args-until-success
6198 'org-tab-before-tab-emulation-hook))
6200 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6201 (or (not (bolp))
6202 (not (looking-at org-outline-regexp))))
6203 (call-interactively (global-key-binding "\t")))
6205 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6206 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6207 (or (and (eq org-cycle-emulate-tab 'white)
6208 (= (match-end 0) (point-at-eol)))
6209 (and (eq org-cycle-emulate-tab 'whitestart)
6210 (>= (match-end 0) pos))))
6212 (eq org-cycle-emulate-tab t))
6213 (call-interactively (global-key-binding "\t")))
6215 (t (save-excursion
6216 (org-back-to-heading)
6217 (org-cycle)))))))
6219 (defun org-cycle-internal-global ()
6220 "Do the global cycling action."
6221 ;; Hack to avoid display of messages for .org attachments in Gnus
6222 (let ((ga (string-match "\\*fontification" (buffer-name))))
6223 (cond
6224 ((and (eq last-command this-command)
6225 (eq org-cycle-global-status 'overview))
6226 ;; We just created the overview - now do table of contents
6227 ;; This can be slow in very large buffers, so indicate action
6228 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6229 (unless ga (message "CONTENTS..."))
6230 (org-content)
6231 (unless ga (message "CONTENTS...done"))
6232 (setq org-cycle-global-status 'contents)
6233 (run-hook-with-args 'org-cycle-hook 'contents))
6235 ((and (eq last-command this-command)
6236 (eq org-cycle-global-status 'contents))
6237 ;; We just showed the table of contents - now show everything
6238 (run-hook-with-args 'org-pre-cycle-hook 'all)
6239 (show-all)
6240 (unless ga (message "SHOW ALL"))
6241 (setq org-cycle-global-status 'all)
6242 (run-hook-with-args 'org-cycle-hook 'all))
6245 ;; Default action: go to overview
6246 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6247 (org-overview)
6248 (unless ga (message "OVERVIEW"))
6249 (setq org-cycle-global-status 'overview)
6250 (run-hook-with-args 'org-cycle-hook 'overview)))))
6252 (defun org-cycle-internal-local ()
6253 "Do the local cycling action."
6254 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6255 ;; First, determine end of headline (EOH), end of subtree or item
6256 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6257 (save-excursion
6258 (if (org-at-item-p)
6259 (progn
6260 (beginning-of-line)
6261 (setq struct (org-list-struct))
6262 (setq eoh (point-at-eol))
6263 (setq eos (org-list-get-item-end-before-blank (point) struct))
6264 (setq has-children (org-list-has-child-p (point) struct)))
6265 (org-back-to-heading)
6266 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6267 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6268 (setq has-children
6269 (or (save-excursion
6270 (let ((level (funcall outline-level)))
6271 (outline-next-heading)
6272 (and (org-at-heading-p t)
6273 (> (funcall outline-level) level))))
6274 (save-excursion
6275 (org-list-search-forward (org-item-beginning-re) eos t)))))
6276 ;; Determine end invisible part of buffer (EOL)
6277 (beginning-of-line 2)
6278 ;; XEmacs doesn't have `next-single-char-property-change'
6279 (if (featurep 'xemacs)
6280 (while (and (not (eobp)) ;; this is like `next-line'
6281 (get-char-property (1- (point)) 'invisible))
6282 (beginning-of-line 2))
6283 (while (and (not (eobp)) ;; this is like `next-line'
6284 (get-char-property (1- (point)) 'invisible))
6285 (goto-char (next-single-char-property-change (point) 'invisible))
6286 (and (eolp) (beginning-of-line 2))))
6287 (setq eol (point)))
6288 ;; Find out what to do next and set `this-command'
6289 (cond
6290 ((= eos eoh)
6291 ;; Nothing is hidden behind this heading
6292 (unless (org-before-first-heading-p)
6293 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6294 (message "EMPTY ENTRY")
6295 (setq org-cycle-subtree-status nil)
6296 (save-excursion
6297 (goto-char eos)
6298 (outline-next-heading)
6299 (if (outline-invisible-p) (org-flag-heading nil))))
6300 ((and (or (>= eol eos)
6301 (not (string-match "\\S-" (buffer-substring eol eos))))
6302 (or has-children
6303 (not (setq children-skipped
6304 org-cycle-skip-children-state-if-no-children))))
6305 ;; Entire subtree is hidden in one line: children view
6306 (unless (org-before-first-heading-p)
6307 (run-hook-with-args 'org-pre-cycle-hook 'children))
6308 (if (org-at-item-p)
6309 (org-list-set-item-visibility (point-at-bol) struct 'children)
6310 (org-show-entry)
6311 (org-with-limited-levels (show-children))
6312 ;; FIXME: This slows down the func way too much.
6313 ;; How keep drawers hidden in subtree anyway?
6314 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6315 ;; (org-cycle-hide-drawers 'subtree))
6317 ;; Fold every list in subtree to top-level items.
6318 (when (eq org-cycle-include-plain-lists 'integrate)
6319 (save-excursion
6320 (org-back-to-heading)
6321 (while (org-list-search-forward (org-item-beginning-re) eos t)
6322 (beginning-of-line 1)
6323 (let* ((struct (org-list-struct))
6324 (prevs (org-list-prevs-alist struct))
6325 (end (org-list-get-bottom-point struct)))
6326 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6327 (org-list-get-all-items (point) struct prevs))
6328 (goto-char end))))))
6329 (message "CHILDREN")
6330 (save-excursion
6331 (goto-char eos)
6332 (outline-next-heading)
6333 (if (outline-invisible-p) (org-flag-heading nil)))
6334 (setq org-cycle-subtree-status 'children)
6335 (unless (org-before-first-heading-p)
6336 (run-hook-with-args 'org-cycle-hook 'children)))
6337 ((or children-skipped
6338 (and (eq last-command this-command)
6339 (eq org-cycle-subtree-status 'children)))
6340 ;; We just showed the children, or no children are there,
6341 ;; now show everything.
6342 (unless (org-before-first-heading-p)
6343 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6344 (outline-flag-region eoh eos nil)
6345 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6346 (setq org-cycle-subtree-status 'subtree)
6347 (unless (org-before-first-heading-p)
6348 (run-hook-with-args 'org-cycle-hook 'subtree)))
6350 ;; Default action: hide the subtree.
6351 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6352 (outline-flag-region eoh eos t)
6353 (message "FOLDED")
6354 (setq org-cycle-subtree-status 'folded)
6355 (unless (org-before-first-heading-p)
6356 (run-hook-with-args 'org-cycle-hook 'folded))))))
6358 ;;;###autoload
6359 (defun org-global-cycle (&optional arg)
6360 "Cycle the global visibility. For details see `org-cycle'.
6361 With \\[universal-argument] prefix arg, switch to startup visibility.
6362 With a numeric prefix, show all headlines up to that level."
6363 (interactive "P")
6364 (let ((org-cycle-include-plain-lists
6365 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6366 (cond
6367 ((integerp arg)
6368 (show-all)
6369 (hide-sublevels arg)
6370 (setq org-cycle-global-status 'contents))
6371 ((equal arg '(4))
6372 (org-set-startup-visibility)
6373 (message "Startup visibility, plus VISIBILITY properties."))
6375 (org-cycle '(4))))))
6377 (defun org-set-startup-visibility ()
6378 "Set the visibility required by startup options and properties."
6379 (cond
6380 ((eq org-startup-folded t)
6381 (org-cycle '(4)))
6382 ((eq org-startup-folded 'content)
6383 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6384 (org-cycle '(4)) (org-cycle '(4)))))
6385 (unless (eq org-startup-folded 'showeverything)
6386 (if org-hide-block-startup (org-hide-block-all))
6387 (org-set-visibility-according-to-property 'no-cleanup)
6388 (org-cycle-hide-archived-subtrees 'all)
6389 (org-cycle-hide-drawers 'all)
6390 (org-cycle-show-empty-lines t)))
6392 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6393 "Switch subtree visibilities according to :VISIBILITY: property."
6394 (interactive)
6395 (let (org-show-entry-below state)
6396 (save-excursion
6397 (goto-char (point-min))
6398 (while (re-search-forward
6399 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6400 nil t)
6401 (setq state (match-string 1))
6402 (save-excursion
6403 (org-back-to-heading t)
6404 (hide-subtree)
6405 (org-reveal)
6406 (cond
6407 ((equal state '("fold" "folded"))
6408 (hide-subtree))
6409 ((equal state "children")
6410 (org-show-hidden-entry)
6411 (show-children))
6412 ((equal state "content")
6413 (save-excursion
6414 (save-restriction
6415 (org-narrow-to-subtree)
6416 (org-content))))
6417 ((member state '("all" "showall"))
6418 (show-subtree)))))
6419 (unless no-cleanup
6420 (org-cycle-hide-archived-subtrees 'all)
6421 (org-cycle-hide-drawers 'all)
6422 (org-cycle-show-empty-lines 'all)))))
6424 ;; This function uses outline-regexp instead of the more fundamental
6425 ;; org-outline-regexp so that org-cycle-global works outside of Org
6426 ;; buffers, where outline-regexp is needed.
6427 (defun org-overview ()
6428 "Switch to overview mode, showing only top-level headlines.
6429 Really, this shows all headlines with level equal or greater than the level
6430 of the first headline in the buffer. This is important, because if the
6431 first headline is not level one, then (hide-sublevels 1) gives confusing
6432 results."
6433 (interactive)
6434 (let ((level (save-excursion
6435 (goto-char (point-min))
6436 (if (re-search-forward (concat "^" outline-regexp) nil t)
6437 (progn
6438 (goto-char (match-beginning 0))
6439 (funcall outline-level))))))
6440 (and level (hide-sublevels level))))
6442 (defun org-content (&optional arg)
6443 "Show all headlines in the buffer, like a table of contents.
6444 With numerical argument N, show content up to level N."
6445 (interactive "P")
6446 (save-excursion
6447 ;; Visit all headings and show their offspring
6448 (and (integerp arg) (org-overview))
6449 (goto-char (point-max))
6450 (catch 'exit
6451 (while (and (progn (condition-case nil
6452 (outline-previous-visible-heading 1)
6453 (error (goto-char (point-min))))
6455 (looking-at org-outline-regexp))
6456 (if (integerp arg)
6457 (show-children (1- arg))
6458 (show-branches))
6459 (if (bobp) (throw 'exit nil))))))
6462 (defun org-optimize-window-after-visibility-change (state)
6463 "Adjust the window after a change in outline visibility.
6464 This function is the default value of the hook `org-cycle-hook'."
6465 (when (get-buffer-window (current-buffer))
6466 (cond
6467 ((eq state 'content) nil)
6468 ((eq state 'all) nil)
6469 ((eq state 'folded) nil)
6470 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6471 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6473 (defun org-remove-empty-overlays-at (pos)
6474 "Remove outline overlays that do not contain non-white stuff."
6475 (mapc
6476 (lambda (o)
6477 (and (eq 'outline (overlay-get o 'invisible))
6478 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6479 (overlay-end o))))
6480 (delete-overlay o)))
6481 (overlays-at pos)))
6483 (defun org-clean-visibility-after-subtree-move ()
6484 "Fix visibility issues after moving a subtree."
6485 ;; First, find a reasonable region to look at:
6486 ;; Start two siblings above, end three below
6487 (let* ((beg (save-excursion
6488 (and (org-get-last-sibling)
6489 (org-get-last-sibling))
6490 (point)))
6491 (end (save-excursion
6492 (and (org-get-next-sibling)
6493 (org-get-next-sibling)
6494 (org-get-next-sibling))
6495 (if (org-at-heading-p)
6496 (point-at-eol)
6497 (point))))
6498 (level (looking-at "\\*+"))
6499 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6500 (save-excursion
6501 (save-restriction
6502 (narrow-to-region beg end)
6503 (when re
6504 ;; Properly fold already folded siblings
6505 (goto-char (point-min))
6506 (while (re-search-forward re nil t)
6507 (if (and (not (outline-invisible-p))
6508 (save-excursion
6509 (goto-char (point-at-eol)) (outline-invisible-p)))
6510 (hide-entry))))
6511 (org-cycle-show-empty-lines 'overview)
6512 (org-cycle-hide-drawers 'overview)))))
6514 (defun org-cycle-show-empty-lines (state)
6515 "Show empty lines above all visible headlines.
6516 The region to be covered depends on STATE when called through
6517 `org-cycle-hook'. Lisp program can use t for STATE to get the
6518 entire buffer covered. Note that an empty line is only shown if there
6519 are at least `org-cycle-separator-lines' empty lines before the headline."
6520 (when (not (= org-cycle-separator-lines 0))
6521 (save-excursion
6522 (let* ((n (abs org-cycle-separator-lines))
6523 (re (cond
6524 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6525 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6526 (t (let ((ns (number-to-string (- n 2))))
6527 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6528 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6529 beg end b e)
6530 (cond
6531 ((memq state '(overview contents t))
6532 (setq beg (point-min) end (point-max)))
6533 ((memq state '(children folded))
6534 (setq beg (point) end (progn (org-end-of-subtree t t)
6535 (beginning-of-line 2)
6536 (point)))))
6537 (when beg
6538 (goto-char beg)
6539 (while (re-search-forward re end t)
6540 (unless (get-char-property (match-end 1) 'invisible)
6541 (setq e (match-end 1))
6542 (if (< org-cycle-separator-lines 0)
6543 (setq b (save-excursion
6544 (goto-char (match-beginning 0))
6545 (org-back-over-empty-lines)
6546 (if (save-excursion
6547 (goto-char (max (point-min) (1- (point))))
6548 (org-at-heading-p))
6549 (1- (point))
6550 (point))))
6551 (setq b (match-beginning 1)))
6552 (outline-flag-region b e nil)))))))
6553 ;; Never hide empty lines at the end of the file.
6554 (save-excursion
6555 (goto-char (point-max))
6556 (outline-previous-heading)
6557 (outline-end-of-heading)
6558 (if (and (looking-at "[ \t\n]+")
6559 (= (match-end 0) (point-max)))
6560 (outline-flag-region (point) (match-end 0) nil))))
6562 (defun org-show-empty-lines-in-parent ()
6563 "Move to the parent and re-show empty lines before visible headlines."
6564 (save-excursion
6565 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6566 (org-cycle-show-empty-lines context))))
6568 (defun org-files-list ()
6569 "Return `org-agenda-files' list, plus all open org-mode files.
6570 This is useful for operations that need to scan all of a user's
6571 open and agenda-wise Org files."
6572 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6573 (dolist (buf (buffer-list))
6574 (with-current-buffer buf
6575 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6576 (let ((file (expand-file-name (buffer-file-name))))
6577 (unless (member file files)
6578 (push file files))))))
6579 files))
6581 (defsubst org-entry-beginning-position ()
6582 "Return the beginning position of the current entry."
6583 (save-excursion (outline-back-to-heading t) (point)))
6585 (defsubst org-entry-end-position ()
6586 "Return the end position of the current entry."
6587 (save-excursion (outline-next-heading) (point)))
6589 (defun org-cycle-hide-drawers (state)
6590 "Re-hide all drawers after a visibility state change."
6591 (when (and (derived-mode-p 'org-mode)
6592 (not (memq state '(overview folded contents))))
6593 (save-excursion
6594 (let* ((globalp (memq state '(contents all)))
6595 (beg (if globalp (point-min) (point)))
6596 (end (if globalp (point-max)
6597 (if (eq state 'children)
6598 (save-excursion (outline-next-heading) (point))
6599 (org-end-of-subtree t)))))
6600 (goto-char beg)
6601 (while (re-search-forward org-drawer-regexp end t)
6602 (org-flag-drawer t))))))
6604 (defun org-flag-drawer (flag)
6605 "When FLAG is non-nil, hide the drawer we are within.
6606 Otherwise make it visible."
6607 (save-excursion
6608 (beginning-of-line 1)
6609 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6610 (let ((b (match-end 0)))
6611 (if (re-search-forward
6612 "^[ \t]*:END:"
6613 (save-excursion (outline-next-heading) (point)) t)
6614 (outline-flag-region b (point-at-eol) flag)
6615 (error ":END: line missing at position %s" b))))))
6617 (defun org-subtree-end-visible-p ()
6618 "Is the end of the current subtree visible?"
6619 (pos-visible-in-window-p
6620 (save-excursion (org-end-of-subtree t) (point))))
6622 (defun org-first-headline-recenter (&optional N)
6623 "Move cursor to the first headline and recenter the headline.
6624 Optional argument N means put the headline into the Nth line of the window."
6625 (goto-char (point-min))
6626 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6627 (beginning-of-line)
6628 (recenter (prefix-numeric-value N))))
6630 ;;; Saving and restoring visibility
6632 (defun org-outline-overlay-data (&optional use-markers)
6633 "Return a list of the locations of all outline overlays.
6634 These are overlays with the `invisible' property value `outline'.
6635 The return value is a list of cons cells, with start and stop
6636 positions for each overlay.
6637 If USE-MARKERS is set, return the positions as markers."
6638 (let (beg end)
6639 (save-excursion
6640 (save-restriction
6641 (widen)
6642 (delq nil
6643 (mapcar (lambda (o)
6644 (when (eq (overlay-get o 'invisible) 'outline)
6645 (setq beg (overlay-start o)
6646 end (overlay-end o))
6647 (and beg end (> end beg)
6648 (if use-markers
6649 (cons (move-marker (make-marker) beg)
6650 (move-marker (make-marker) end))
6651 (cons beg end)))))
6652 (overlays-in (point-min) (point-max))))))))
6654 (defun org-set-outline-overlay-data (data)
6655 "Create visibility overlays for all positions in DATA.
6656 DATA should have been made by `org-outline-overlay-data'."
6657 (let (o)
6658 (save-excursion
6659 (save-restriction
6660 (widen)
6661 (show-all)
6662 (mapc (lambda (c)
6663 (outline-flag-region (car c) (cdr c) t))
6664 data)))))
6666 ;;; Folding of blocks
6668 (defvar org-hide-block-overlays nil
6669 "Overlays hiding blocks.")
6670 (make-variable-buffer-local 'org-hide-block-overlays)
6672 (defun org-block-map (function &optional start end)
6673 "Call FUNCTION at the head of all source blocks in the current buffer.
6674 Optional arguments START and END can be used to limit the range."
6675 (let ((start (or start (point-min)))
6676 (end (or end (point-max))))
6677 (save-excursion
6678 (goto-char start)
6679 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6680 (save-excursion
6681 (save-match-data
6682 (goto-char (match-beginning 0))
6683 (funcall function)))))))
6685 (defun org-hide-block-toggle-all ()
6686 "Toggle the visibility of all blocks in the current buffer."
6687 (org-block-map #'org-hide-block-toggle))
6689 (defun org-hide-block-all ()
6690 "Fold all blocks in the current buffer."
6691 (interactive)
6692 (org-show-block-all)
6693 (org-block-map #'org-hide-block-toggle-maybe))
6695 (defun org-show-block-all ()
6696 "Unfold all blocks in the current buffer."
6697 (interactive)
6698 (mapc 'delete-overlay org-hide-block-overlays)
6699 (setq org-hide-block-overlays nil))
6701 (defun org-hide-block-toggle-maybe ()
6702 "Toggle visibility of block at point."
6703 (interactive)
6704 (let ((case-fold-search t))
6705 (if (save-excursion
6706 (beginning-of-line 1)
6707 (looking-at org-block-regexp))
6708 (progn (org-hide-block-toggle)
6709 t) ;; to signal that we took action
6710 nil))) ;; to signal that we did not
6712 (defun org-hide-block-toggle (&optional force)
6713 "Toggle the visibility of the current block."
6714 (interactive)
6715 (save-excursion
6716 (beginning-of-line)
6717 (if (re-search-forward org-block-regexp nil t)
6718 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6719 (end (match-end 0)) ;; end of entire body
6721 (if (memq t (mapcar (lambda (overlay)
6722 (eq (overlay-get overlay 'invisible)
6723 'org-hide-block))
6724 (overlays-at start)))
6725 (if (or (not force) (eq force 'off))
6726 (mapc (lambda (ov)
6727 (when (member ov org-hide-block-overlays)
6728 (setq org-hide-block-overlays
6729 (delq ov org-hide-block-overlays)))
6730 (when (eq (overlay-get ov 'invisible)
6731 'org-hide-block)
6732 (delete-overlay ov)))
6733 (overlays-at start)))
6734 (setq ov (make-overlay start end))
6735 (overlay-put ov 'invisible 'org-hide-block)
6736 ;; make the block accessible to isearch
6737 (overlay-put
6738 ov 'isearch-open-invisible
6739 (lambda (ov)
6740 (when (member ov org-hide-block-overlays)
6741 (setq org-hide-block-overlays
6742 (delq ov org-hide-block-overlays)))
6743 (when (eq (overlay-get ov 'invisible)
6744 'org-hide-block)
6745 (delete-overlay ov))))
6746 (push ov org-hide-block-overlays)))
6747 (error "Not looking at a source block"))))
6749 ;; org-tab-after-check-for-cycling-hook
6750 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6751 ;; Remove overlays when changing major mode
6752 (add-hook 'org-mode-hook
6753 (lambda () (org-add-hook 'change-major-mode-hook
6754 'org-show-block-all 'append 'local)))
6756 ;;; Org-goto
6758 (defvar org-goto-window-configuration nil)
6759 (defvar org-goto-marker nil)
6760 (defvar org-goto-map)
6761 (defun org-goto-map ()
6762 "Set the keymap `org-goto'."
6763 (setq org-goto-map
6764 (let ((map (make-sparse-keymap)))
6765 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6766 mouse-drag-region universal-argument org-occur))
6767 cmd)
6768 (while (setq cmd (pop cmds))
6769 (substitute-key-definition cmd cmd map global-map)))
6770 (suppress-keymap map)
6771 (org-defkey map "\C-m" 'org-goto-ret)
6772 (org-defkey map [(return)] 'org-goto-ret)
6773 (org-defkey map [(left)] 'org-goto-left)
6774 (org-defkey map [(right)] 'org-goto-right)
6775 (org-defkey map [(control ?g)] 'org-goto-quit)
6776 (org-defkey map "\C-i" 'org-cycle)
6777 (org-defkey map [(tab)] 'org-cycle)
6778 (org-defkey map [(down)] 'outline-next-visible-heading)
6779 (org-defkey map [(up)] 'outline-previous-visible-heading)
6780 (if org-goto-auto-isearch
6781 (if (fboundp 'define-key-after)
6782 (define-key-after map [t] 'org-goto-local-auto-isearch)
6783 nil)
6784 (org-defkey map "q" 'org-goto-quit)
6785 (org-defkey map "n" 'outline-next-visible-heading)
6786 (org-defkey map "p" 'outline-previous-visible-heading)
6787 (org-defkey map "f" 'outline-forward-same-level)
6788 (org-defkey map "b" 'outline-backward-same-level)
6789 (org-defkey map "u" 'outline-up-heading))
6790 (org-defkey map "/" 'org-occur)
6791 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6792 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6793 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6794 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6795 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6796 map)))
6798 (defconst org-goto-help
6799 "Browse buffer copy, to find location or copy text.%s
6800 RET=jump to location C-g=quit and return to previous location
6801 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6803 (defvar org-goto-start-pos) ; dynamically scoped parameter
6805 ;; FIXME: Docstring does not mention both interfaces
6806 (defun org-goto (&optional alternative-interface)
6807 "Look up a different location in the current file, keeping current visibility.
6809 When you want look-up or go to a different location in a
6810 document, the fastest way is often to fold the entire buffer and
6811 then dive into the tree. This method has the disadvantage, that
6812 the previous location will be folded, which may not be what you
6813 want.
6815 This command works around this by showing a copy of the current
6816 buffer in an indirect buffer, in overview mode. You can dive
6817 into the tree in that copy, use org-occur and incremental search
6818 to find a location. When pressing RET or `Q', the command
6819 returns to the original buffer in which the visibility is still
6820 unchanged. After RET it will also jump to the location selected
6821 in the indirect buffer and expose the headline hierarchy above.
6823 With a prefix argument, use the alternative interface: e.g. if
6824 `org-goto-interface' is 'outline use 'outline-path-completion."
6825 (interactive "P")
6826 (org-goto-map)
6827 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6828 (org-refile-use-outline-path t)
6829 (org-refile-target-verify-function nil)
6830 (interface
6831 (if (not alternative-interface)
6832 org-goto-interface
6833 (if (eq org-goto-interface 'outline)
6834 'outline-path-completion
6835 'outline)))
6836 (org-goto-start-pos (point))
6837 (selected-point
6838 (if (eq interface 'outline)
6839 (car (org-get-location (current-buffer) org-goto-help))
6840 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6841 (org-refile-check-position pa)
6842 (nth 3 pa)))))
6843 (if selected-point
6844 (progn
6845 (org-mark-ring-push org-goto-start-pos)
6846 (goto-char selected-point)
6847 (if (or (outline-invisible-p) (org-invisible-p2))
6848 (org-show-context 'org-goto)))
6849 (message "Quit"))))
6851 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6852 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6853 (defvar org-goto-local-auto-isearch-map) ; defined below
6855 (defun org-get-location (buf help)
6856 "Let the user select a location in the Org-mode buffer BUF.
6857 This function uses a recursive edit. It returns the selected position
6858 or nil."
6859 (org-no-popups
6860 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6861 (isearch-hide-immediately nil)
6862 (isearch-search-fun-function
6863 (lambda () 'org-goto-local-search-headings))
6864 (org-goto-selected-point org-goto-exit-command))
6865 (save-excursion
6866 (save-window-excursion
6867 (delete-other-windows)
6868 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6869 (org-pop-to-buffer-same-window
6870 (condition-case nil
6871 (make-indirect-buffer (current-buffer) "*org-goto*")
6872 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6873 (with-output-to-temp-buffer "*Org Help*"
6874 (princ (format help (if org-goto-auto-isearch
6875 " Just type for auto-isearch."
6876 " n/p/f/b/u to navigate, q to quit."))))
6877 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
6878 (setq buffer-read-only nil)
6879 (let ((org-startup-truncated t)
6880 (org-startup-folded nil)
6881 (org-startup-align-all-tables nil))
6882 (org-mode)
6883 (org-overview))
6884 (setq buffer-read-only t)
6885 (if (and (boundp 'org-goto-start-pos)
6886 (integer-or-marker-p org-goto-start-pos))
6887 (let ((org-show-hierarchy-above t)
6888 (org-show-siblings t)
6889 (org-show-following-heading t))
6890 (goto-char org-goto-start-pos)
6891 (and (outline-invisible-p) (org-show-context)))
6892 (goto-char (point-min)))
6893 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6894 (message "Select location and press RET")
6895 (use-local-map org-goto-map)
6896 (recursive-edit)))
6897 (kill-buffer "*org-goto*")
6898 (cons org-goto-selected-point org-goto-exit-command))))
6900 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6901 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6902 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6903 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6905 (defun org-goto-local-search-headings (string bound noerror)
6906 "Search and make sure that any matches are in headlines."
6907 (catch 'return
6908 (while (if isearch-forward
6909 (search-forward string bound noerror)
6910 (search-backward string bound noerror))
6911 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6912 (and (member :headline context)
6913 (not (member :tags context))))
6914 (throw 'return (point))))))
6916 (defun org-goto-local-auto-isearch ()
6917 "Start isearch."
6918 (interactive)
6919 (goto-char (point-min))
6920 (let ((keys (this-command-keys)))
6921 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6922 (isearch-mode t)
6923 (isearch-process-search-char (string-to-char keys)))))
6925 (defun org-goto-ret (&optional arg)
6926 "Finish `org-goto' by going to the new location."
6927 (interactive "P")
6928 (setq org-goto-selected-point (point)
6929 org-goto-exit-command 'return)
6930 (throw 'exit nil))
6932 (defun org-goto-left ()
6933 "Finish `org-goto' by going to the new location."
6934 (interactive)
6935 (if (org-at-heading-p)
6936 (progn
6937 (beginning-of-line 1)
6938 (setq org-goto-selected-point (point)
6939 org-goto-exit-command 'left)
6940 (throw 'exit nil))
6941 (error "Not on a heading")))
6943 (defun org-goto-right ()
6944 "Finish `org-goto' by going to the new location."
6945 (interactive)
6946 (if (org-at-heading-p)
6947 (progn
6948 (setq org-goto-selected-point (point)
6949 org-goto-exit-command 'right)
6950 (throw 'exit nil))
6951 (error "Not on a heading")))
6953 (defun org-goto-quit ()
6954 "Finish `org-goto' without cursor motion."
6955 (interactive)
6956 (setq org-goto-selected-point nil)
6957 (setq org-goto-exit-command 'quit)
6958 (throw 'exit nil))
6960 ;;; Indirect buffer display of subtrees
6962 (defvar org-indirect-dedicated-frame nil
6963 "This is the frame being used for indirect tree display.")
6964 (defvar org-last-indirect-buffer nil)
6966 (defun org-tree-to-indirect-buffer (&optional arg)
6967 "Create indirect buffer and narrow it to current subtree.
6968 With a numerical prefix ARG, go up to this level and then take that tree.
6969 If ARG is negative, go up that many levels.
6971 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6972 indirect buffer previously made with this command, to avoid proliferation of
6973 indirect buffers. However, when you call the command with a \
6974 \\[universal-argument] prefix, or
6975 when `org-indirect-buffer-display' is `new-frame', the last buffer
6976 is kept so that you can work with several indirect buffers at the same time.
6977 If `org-indirect-buffer-display' is `dedicated-frame', the \
6978 \\[universal-argument] prefix also
6979 requests that a new frame be made for the new buffer, so that the dedicated
6980 frame is not changed."
6981 (interactive "P")
6982 (let ((cbuf (current-buffer))
6983 (cwin (selected-window))
6984 (pos (point))
6985 beg end level heading ibuf)
6986 (save-excursion
6987 (org-back-to-heading t)
6988 (when (numberp arg)
6989 (setq level (org-outline-level))
6990 (if (< arg 0) (setq arg (+ level arg)))
6991 (while (> (setq level (org-outline-level)) arg)
6992 (org-up-heading-safe)))
6993 (setq beg (point)
6994 heading (org-get-heading))
6995 (org-end-of-subtree t t)
6996 (if (org-at-heading-p) (backward-char 1))
6997 (setq end (point)))
6998 (if (and (buffer-live-p org-last-indirect-buffer)
6999 (not (eq org-indirect-buffer-display 'new-frame))
7000 (not arg))
7001 (kill-buffer org-last-indirect-buffer))
7002 (setq ibuf (org-get-indirect-buffer cbuf)
7003 org-last-indirect-buffer ibuf)
7004 (cond
7005 ((or (eq org-indirect-buffer-display 'new-frame)
7006 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7007 (select-frame (make-frame))
7008 (delete-other-windows)
7009 (org-pop-to-buffer-same-window ibuf)
7010 (org-set-frame-title heading))
7011 ((eq org-indirect-buffer-display 'dedicated-frame)
7012 (raise-frame
7013 (select-frame (or (and org-indirect-dedicated-frame
7014 (frame-live-p org-indirect-dedicated-frame)
7015 org-indirect-dedicated-frame)
7016 (setq org-indirect-dedicated-frame (make-frame)))))
7017 (delete-other-windows)
7018 (org-pop-to-buffer-same-window ibuf)
7019 (org-set-frame-title (concat "Indirect: " heading)))
7020 ((eq org-indirect-buffer-display 'current-window)
7021 (org-pop-to-buffer-same-window ibuf))
7022 ((eq org-indirect-buffer-display 'other-window)
7023 (pop-to-buffer ibuf))
7024 (t (error "Invalid value")))
7025 (if (featurep 'xemacs)
7026 (save-excursion (org-mode) (turn-on-font-lock)))
7027 (narrow-to-region beg end)
7028 (show-all)
7029 (goto-char pos)
7030 (run-hook-with-args 'org-cycle-hook 'all)
7031 (and (window-live-p cwin) (select-window cwin))))
7033 (defun org-get-indirect-buffer (&optional buffer)
7034 (setq buffer (or buffer (current-buffer)))
7035 (let ((n 1) (base (buffer-name buffer)) bname)
7036 (while (buffer-live-p
7037 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7038 (setq n (1+ n)))
7039 (condition-case nil
7040 (make-indirect-buffer buffer bname 'clone)
7041 (error (make-indirect-buffer buffer bname)))))
7043 (defun org-set-frame-title (title)
7044 "Set the title of the current frame to the string TITLE."
7045 ;; FIXME: how to name a single frame in XEmacs???
7046 (unless (featurep 'xemacs)
7047 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7049 ;;;; Structure editing
7051 ;;; Inserting headlines
7053 (defun org-previous-line-empty-p ()
7054 (save-excursion
7055 (and (not (bobp))
7056 (or (beginning-of-line 0) t)
7057 (save-match-data
7058 (looking-at "[ \t]*$")))))
7060 (defun org-insert-heading (&optional force-heading invisible-ok)
7061 "Insert a new heading or item with same depth at point.
7062 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7063 If point is at the beginning of a headline, insert a sibling before the
7064 current headline. If point is not at the beginning, split the line,
7065 create the new headline with the text in the current line after point
7066 \(but see also the variable `org-M-RET-may-split-line').
7068 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7069 This is important for non-interactive uses of the command."
7070 (interactive "P")
7071 (if (or (= (buffer-size) 0)
7072 (and (not (save-excursion
7073 (and (ignore-errors (org-back-to-heading invisible-ok))
7074 (org-at-heading-p))))
7075 (or force-heading (not (org-in-item-p)))))
7076 (progn
7077 (insert "\n* ")
7078 (run-hooks 'org-insert-heading-hook))
7079 (when (or force-heading (not (org-insert-item)))
7080 (let* ((empty-line-p nil)
7081 (level nil)
7082 (on-heading (org-at-heading-p))
7083 (head (save-excursion
7084 (condition-case nil
7085 (progn
7086 (org-back-to-heading invisible-ok)
7087 (when (and (not on-heading)
7088 (featurep 'org-inlinetask)
7089 (integerp org-inlinetask-min-level)
7090 (>= (length (match-string 0))
7091 org-inlinetask-min-level))
7092 ;; Find a heading level before the inline task
7093 (while (and (setq level (org-up-heading-safe))
7094 (>= level org-inlinetask-min-level)))
7095 (if (org-at-heading-p)
7096 (org-back-to-heading invisible-ok)
7097 (error "This should not happen")))
7098 (setq empty-line-p (org-previous-line-empty-p))
7099 (match-string 0))
7100 (error "*"))))
7101 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7102 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7103 pos hide-previous previous-pos)
7104 (cond
7105 ((and (org-at-heading-p) (bolp)
7106 (or (bobp)
7107 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7108 ;; insert before the current line
7109 (open-line (if blank 2 1)))
7110 ((and (bolp)
7111 (not org-insert-heading-respect-content)
7112 (or (bobp)
7113 (save-excursion
7114 (backward-char 1) (not (outline-invisible-p)))))
7115 ;; insert right here
7116 nil)
7118 ;; somewhere in the line
7119 (save-excursion
7120 (setq previous-pos (point-at-bol))
7121 (end-of-line)
7122 (setq hide-previous (outline-invisible-p)))
7123 (and org-insert-heading-respect-content (org-show-subtree))
7124 (let ((split
7125 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7126 (save-excursion
7127 (let ((p (point)))
7128 (goto-char (point-at-bol))
7129 (and (looking-at org-complex-heading-regexp)
7130 (match-beginning 4)
7131 (> p (match-beginning 4)))))))
7132 tags pos)
7133 (cond
7134 (org-insert-heading-respect-content
7135 (org-end-of-subtree nil t)
7136 (when (featurep 'org-inlinetask)
7137 (while (and (not (eobp))
7138 (looking-at "\\(\\*+\\)[ \t]+")
7139 (>= (length (match-string 1))
7140 org-inlinetask-min-level))
7141 (org-end-of-subtree nil t)))
7142 (or (bolp) (newline))
7143 (or (org-previous-line-empty-p)
7144 (and blank (newline)))
7145 (open-line 1))
7146 ((org-at-heading-p)
7147 (when hide-previous
7148 (show-children)
7149 (org-show-entry))
7150 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7151 (setq tags (and (match-end 2) (match-string 2)))
7152 (and (match-end 1)
7153 (delete-region (match-beginning 1) (match-end 1)))
7154 (setq pos (point-at-bol))
7155 (or split (end-of-line 1))
7156 (delete-horizontal-space)
7157 (if (string-match "\\`\\*+\\'"
7158 (buffer-substring (point-at-bol) (point)))
7159 (insert " "))
7160 (newline (if blank 2 1))
7161 (when tags
7162 (save-excursion
7163 (goto-char pos)
7164 (end-of-line 1)
7165 (insert " " tags)
7166 (org-set-tags nil 'align))))
7168 (or split (end-of-line 1))
7169 (newline (if blank 2 1)))))))
7170 (insert head) (just-one-space)
7171 (setq pos (point))
7172 (end-of-line 1)
7173 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7174 (when (and org-insert-heading-respect-content hide-previous)
7175 (save-excursion
7176 (goto-char previous-pos)
7177 (hide-subtree)))
7178 (run-hooks 'org-insert-heading-hook)))))
7180 (defun org-get-heading (&optional no-tags no-todo)
7181 "Return the heading of the current entry, without the stars.
7182 When NO-TAGS is non-nil, don't include tags.
7183 When NO-TODO is non-nil, don't include TODO keywords."
7184 (save-excursion
7185 (org-back-to-heading t)
7186 (cond
7187 ((and no-tags no-todo)
7188 (looking-at org-complex-heading-regexp)
7189 (match-string 4))
7190 (no-tags
7191 (looking-at (concat org-outline-regexp
7192 "\\(.*?\\)"
7193 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7194 (match-string 1))
7195 (no-todo
7196 (looking-at org-todo-line-regexp)
7197 (match-string 3))
7198 (t (looking-at org-heading-regexp)
7199 (match-string 2)))))
7201 (defun org-heading-components ()
7202 "Return the components of the current heading.
7203 This is a list with the following elements:
7204 - the level as an integer
7205 - the reduced level, different if `org-odd-levels-only' is set.
7206 - the TODO keyword, or nil
7207 - the priority character, like ?A, or nil if no priority is given
7208 - the headline text itself, or the tags string if no headline text
7209 - the tags string, or nil."
7210 (save-excursion
7211 (org-back-to-heading t)
7212 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7213 (list (length (match-string 1))
7214 (org-reduced-level (length (match-string 1)))
7215 (org-match-string-no-properties 2)
7216 (and (match-end 3) (aref (match-string 3) 2))
7217 (org-match-string-no-properties 4)
7218 (org-match-string-no-properties 5)))))
7220 (defun org-get-entry ()
7221 "Get the entry text, after heading, entire subtree."
7222 (save-excursion
7223 (org-back-to-heading t)
7224 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7226 (defun org-insert-heading-after-current ()
7227 "Insert a new heading with same level as current, after current subtree."
7228 (interactive)
7229 (org-back-to-heading)
7230 (org-insert-heading)
7231 (org-move-subtree-down)
7232 (end-of-line 1))
7234 (defun org-insert-heading-respect-content ()
7235 (interactive)
7236 (let ((org-insert-heading-respect-content t))
7237 (org-insert-heading t)))
7239 (defun org-insert-todo-heading-respect-content (&optional force-state)
7240 (interactive "P")
7241 (let ((org-insert-heading-respect-content t))
7242 (org-insert-todo-heading force-state t)))
7244 (defun org-insert-todo-heading (arg &optional force-heading)
7245 "Insert a new heading with the same level and TODO state as current heading.
7246 If the heading has no TODO state, or if the state is DONE, use the first
7247 state (TODO by default). Also with prefix arg, force first state."
7248 (interactive "P")
7249 (when (or force-heading (not (org-insert-item 'checkbox)))
7250 (org-insert-heading force-heading)
7251 (save-excursion
7252 (org-back-to-heading)
7253 (outline-previous-heading)
7254 (looking-at org-todo-line-regexp))
7255 (let*
7256 ((new-mark-x
7257 (if (or arg
7258 (not (match-beginning 2))
7259 (member (match-string 2) org-done-keywords))
7260 (car org-todo-keywords-1)
7261 (match-string 2)))
7262 (new-mark
7264 (run-hook-with-args-until-success
7265 'org-todo-get-default-hook new-mark-x nil)
7266 new-mark-x)))
7267 (beginning-of-line 1)
7268 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7269 (if org-treat-insert-todo-heading-as-state-change
7270 (org-todo new-mark)
7271 (insert new-mark " "))))
7272 (when org-provide-todo-statistics
7273 (org-update-parent-todo-statistics))))
7275 (defun org-insert-subheading (arg)
7276 "Insert a new subheading and demote it.
7277 Works for outline headings and for plain lists alike."
7278 (interactive "P")
7279 (org-insert-heading arg)
7280 (cond
7281 ((org-at-heading-p) (org-do-demote))
7282 ((org-at-item-p) (org-indent-item))))
7284 (defun org-insert-todo-subheading (arg)
7285 "Insert a new subheading with TODO keyword or checkbox and demote it.
7286 Works for outline headings and for plain lists alike."
7287 (interactive "P")
7288 (org-insert-todo-heading arg)
7289 (cond
7290 ((org-at-heading-p) (org-do-demote))
7291 ((org-at-item-p) (org-indent-item))))
7293 ;;; Promotion and Demotion
7295 (defvar org-after-demote-entry-hook nil
7296 "Hook run after an entry has been demoted.
7297 The cursor will be at the beginning of the entry.
7298 When a subtree is being demoted, the hook will be called for each node.")
7300 (defvar org-after-promote-entry-hook nil
7301 "Hook run after an entry has been promoted.
7302 The cursor will be at the beginning of the entry.
7303 When a subtree is being promoted, the hook will be called for each node.")
7305 (defun org-promote-subtree ()
7306 "Promote the entire subtree.
7307 See also `org-promote'."
7308 (interactive)
7309 (save-excursion
7310 (org-with-limited-levels (org-map-tree 'org-promote)))
7311 (org-fix-position-after-promote))
7313 (defun org-demote-subtree ()
7314 "Demote the entire subtree. See `org-demote'.
7315 See also `org-promote'."
7316 (interactive)
7317 (save-excursion
7318 (org-with-limited-levels (org-map-tree 'org-demote)))
7319 (org-fix-position-after-promote))
7322 (defun org-do-promote ()
7323 "Promote the current heading higher up the tree.
7324 If the region is active in `transient-mark-mode', promote all headings
7325 in the region."
7326 (interactive)
7327 (save-excursion
7328 (if (org-region-active-p)
7329 (org-map-region 'org-promote (region-beginning) (region-end))
7330 (org-promote)))
7331 (org-fix-position-after-promote))
7333 (defun org-do-demote ()
7334 "Demote the current heading lower down the tree.
7335 If the region is active in `transient-mark-mode', demote all headings
7336 in the region."
7337 (interactive)
7338 (save-excursion
7339 (if (org-region-active-p)
7340 (org-map-region 'org-demote (region-beginning) (region-end))
7341 (org-demote)))
7342 (org-fix-position-after-promote))
7344 (defun org-fix-position-after-promote ()
7345 "Make sure that after pro/demotion cursor position is right."
7346 (let ((pos (point)))
7347 (when (save-excursion
7348 (beginning-of-line 1)
7349 (looking-at org-todo-line-regexp)
7350 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7351 (cond ((eobp) (insert " "))
7352 ((eolp) (insert " "))
7353 ((equal (char-after) ?\ ) (forward-char 1))))))
7355 (defun org-current-level ()
7356 "Return the level of the current entry, or nil if before the first headline.
7357 The level is the number of stars at the beginning of the headline."
7358 (save-excursion
7359 (org-with-limited-levels
7360 (if (ignore-errors (org-back-to-heading t))
7361 (funcall outline-level)))))
7363 (defun org-get-previous-line-level ()
7364 "Return the outline depth of the last headline before the current line.
7365 Returns 0 for the first headline in the buffer, and nil if before the
7366 first headline."
7367 (let ((current-level (org-current-level))
7368 (prev-level (when (> (line-number-at-pos) 1)
7369 (save-excursion
7370 (beginning-of-line 0)
7371 (org-current-level)))))
7372 (cond ((null current-level) nil) ; Before first headline
7373 ((null prev-level) 0) ; At first headline
7374 (prev-level))))
7376 (defun org-reduced-level (l)
7377 "Compute the effective level of a heading.
7378 This takes into account the setting of `org-odd-levels-only'."
7379 (cond
7380 ((zerop l) 0)
7381 (org-odd-levels-only (1+ (floor (/ l 2))))
7382 (t l)))
7384 (defun org-level-increment ()
7385 "Return the number of stars that will be added or removed at a
7386 time to headlines when structure editing, based on the value of
7387 `org-odd-levels-only'."
7388 (if org-odd-levels-only 2 1))
7390 (defun org-get-valid-level (level &optional change)
7391 "Rectify a level change under the influence of `org-odd-levels-only'
7392 LEVEL is a current level, CHANGE is by how much the level should be
7393 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7394 even level numbers will become the next higher odd number."
7395 (if org-odd-levels-only
7396 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7397 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7398 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7399 (max 1 (+ level (or change 0)))))
7401 (if (boundp 'define-obsolete-function-alias)
7402 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7403 (define-obsolete-function-alias 'org-get-legal-level
7404 'org-get-valid-level)
7405 (define-obsolete-function-alias 'org-get-legal-level
7406 'org-get-valid-level "23.1")))
7408 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7409 ;; ̀org-with-limited-levels'
7410 (defun org-promote ()
7411 "Promote the current heading higher up the tree.
7412 If the region is active in `transient-mark-mode', promote all headings
7413 in the region."
7414 (org-back-to-heading t)
7415 (let* ((level (save-match-data (funcall outline-level)))
7416 (after-change-functions (remove 'flyspell-after-change-function
7417 after-change-functions))
7418 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7419 (diff (abs (- level (length up-head) -1))))
7420 (cond ((and (= level 1) org-called-with-limited-levels
7421 org-allow-promoting-top-level-subtree)
7422 (replace-match "# " nil t))
7423 ((= level 1)
7424 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7425 (t (replace-match up-head nil t)))
7426 ;; Fixup tag positioning
7427 (unless (= level 1)
7428 (and org-auto-align-tags (org-set-tags nil t))
7429 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7430 (run-hooks 'org-after-promote-entry-hook)))
7432 (defun org-demote ()
7433 "Demote the current heading lower down the tree.
7434 If the region is active in `transient-mark-mode', demote all headings
7435 in the region."
7436 (org-back-to-heading t)
7437 (let* ((level (save-match-data (funcall outline-level)))
7438 (after-change-functions (remove 'flyspell-after-change-function
7439 after-change-functions))
7440 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7441 (diff (abs (- level (length down-head) -1))))
7442 (replace-match down-head nil t)
7443 ;; Fixup tag positioning
7444 (and org-auto-align-tags (org-set-tags nil t))
7445 (if org-adapt-indentation (org-fixup-indentation diff))
7446 (run-hooks 'org-after-demote-entry-hook)))
7448 (defun org-cycle-level ()
7449 "Cycle the level of an empty headline through possible states.
7450 This goes first to child, then to parent, level, then up the hierarchy.
7451 After top level, it switches back to sibling level."
7452 (interactive)
7453 (let ((org-adapt-indentation nil))
7454 (when (org-point-at-end-of-empty-headline)
7455 (setq this-command 'org-cycle-level) ; Only needed for caching
7456 (let ((cur-level (org-current-level))
7457 (prev-level (org-get-previous-line-level)))
7458 (cond
7459 ;; If first headline in file, promote to top-level.
7460 ((= prev-level 0)
7461 (loop repeat (/ (- cur-level 1) (org-level-increment))
7462 do (org-do-promote)))
7463 ;; If same level as prev, demote one.
7464 ((= prev-level cur-level)
7465 (org-do-demote))
7466 ;; If parent is top-level, promote to top level if not already.
7467 ((= prev-level 1)
7468 (loop repeat (/ (- cur-level 1) (org-level-increment))
7469 do (org-do-promote)))
7470 ;; If top-level, return to prev-level.
7471 ((= cur-level 1)
7472 (loop repeat (/ (- prev-level 1) (org-level-increment))
7473 do (org-do-demote)))
7474 ;; If less than prev-level, promote one.
7475 ((< cur-level prev-level)
7476 (org-do-promote))
7477 ;; If deeper than prev-level, promote until higher than
7478 ;; prev-level.
7479 ((> cur-level prev-level)
7480 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7481 do (org-do-promote))))
7482 t))))
7484 (defun org-map-tree (fun)
7485 "Call FUN for every heading underneath the current one."
7486 (org-back-to-heading)
7487 (let ((level (funcall outline-level)))
7488 (save-excursion
7489 (funcall fun)
7490 (while (and (progn
7491 (outline-next-heading)
7492 (> (funcall outline-level) level))
7493 (not (eobp)))
7494 (funcall fun)))))
7496 (defun org-map-region (fun beg end)
7497 "Call FUN for every heading between BEG and END."
7498 (let ((org-ignore-region t))
7499 (save-excursion
7500 (setq end (copy-marker end))
7501 (goto-char beg)
7502 (if (and (re-search-forward org-outline-regexp-bol nil t)
7503 (< (point) end))
7504 (funcall fun))
7505 (while (and (progn
7506 (outline-next-heading)
7507 (< (point) end))
7508 (not (eobp)))
7509 (funcall fun)))))
7511 (defvar org-property-end-re) ; silence byte-compiler
7512 (defun org-fixup-indentation (diff)
7513 "Change the indentation in the current entry by DIFF.
7514 However, if any line in the current entry has no indentation, or if it
7515 would end up with no indentation after the change, nothing at all is done."
7516 (save-excursion
7517 (let ((end (save-excursion (outline-next-heading)
7518 (point-marker)))
7519 (prohibit (if (> diff 0)
7520 "^\\S-"
7521 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7522 col)
7523 (unless (save-excursion (end-of-line 1)
7524 (re-search-forward prohibit end t))
7525 (while (and (< (point) end)
7526 (re-search-forward "^[ \t]+" end t))
7527 (goto-char (match-end 0))
7528 (setq col (current-column))
7529 (if (< diff 0) (replace-match ""))
7530 (org-indent-to-column (+ diff col))))
7531 (move-marker end nil))))
7533 (defun org-convert-to-odd-levels ()
7534 "Convert an org-mode file with all levels allowed to one with odd levels.
7535 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7536 level 5 etc."
7537 (interactive)
7538 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7539 (let ((outline-level 'org-outline-level)
7540 (org-odd-levels-only nil) n)
7541 (save-excursion
7542 (goto-char (point-min))
7543 (while (re-search-forward "^\\*\\*+ " nil t)
7544 (setq n (- (length (match-string 0)) 2))
7545 (while (>= (setq n (1- n)) 0)
7546 (org-demote))
7547 (end-of-line 1))))))
7549 (defun org-convert-to-oddeven-levels ()
7550 "Convert an org-mode file with only odd levels to one with odd/even levels.
7551 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7552 file contains a section with an even level, conversion would
7553 destroy the structure of the file. An error is signaled in this
7554 case."
7555 (interactive)
7556 (goto-char (point-min))
7557 ;; First check if there are no even levels
7558 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7559 (org-show-context t)
7560 (error "Not all levels are odd in this file. Conversion not possible"))
7561 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7562 (let ((outline-regexp org-outline-regexp)
7563 (outline-level 'org-outline-level)
7564 (org-odd-levels-only nil) n)
7565 (save-excursion
7566 (goto-char (point-min))
7567 (while (re-search-forward "^\\*\\*+ " nil t)
7568 (setq n (/ (1- (length (match-string 0))) 2))
7569 (while (>= (setq n (1- n)) 0)
7570 (org-promote))
7571 (end-of-line 1))))))
7573 (defun org-tr-level (n)
7574 "Make N odd if required."
7575 (if org-odd-levels-only (1+ (/ n 2)) n))
7577 ;;; Vertical tree motion, cutting and pasting of subtrees
7579 (defun org-move-subtree-up (&optional arg)
7580 "Move the current subtree up past ARG headlines of the same level."
7581 (interactive "p")
7582 (org-move-subtree-down (- (prefix-numeric-value arg))))
7584 (defun org-move-subtree-down (&optional arg)
7585 "Move the current subtree down past ARG headlines of the same level."
7586 (interactive "p")
7587 (setq arg (prefix-numeric-value arg))
7588 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7589 'org-get-last-sibling))
7590 (ins-point (make-marker))
7591 (cnt (abs arg))
7592 (col (current-column))
7593 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7594 ;; Select the tree
7595 (org-back-to-heading)
7596 (setq beg0 (point))
7597 (save-excursion
7598 (setq ne-beg (org-back-over-empty-lines))
7599 (setq beg (point)))
7600 (save-match-data
7601 (save-excursion (outline-end-of-heading)
7602 (setq folded (outline-invisible-p)))
7603 (outline-end-of-subtree))
7604 (outline-next-heading)
7605 (setq ne-end (org-back-over-empty-lines))
7606 (setq end (point))
7607 (goto-char beg0)
7608 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7609 ;; include less whitespace
7610 (save-excursion
7611 (goto-char beg)
7612 (forward-line (- ne-beg ne-end))
7613 (setq beg (point))))
7614 ;; Find insertion point, with error handling
7615 (while (> cnt 0)
7616 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7617 (progn (goto-char beg0)
7618 (error "Cannot move past superior level or buffer limit")))
7619 (setq cnt (1- cnt)))
7620 (if (> arg 0)
7621 ;; Moving forward - still need to move over subtree
7622 (progn (org-end-of-subtree t t)
7623 (save-excursion
7624 (org-back-over-empty-lines)
7625 (or (bolp) (newline)))))
7626 (setq ne-ins (org-back-over-empty-lines))
7627 (move-marker ins-point (point))
7628 (setq txt (buffer-substring beg end))
7629 (org-save-markers-in-region beg end)
7630 (delete-region beg end)
7631 (org-remove-empty-overlays-at beg)
7632 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7633 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7634 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7635 (let ((bbb (point)))
7636 (insert-before-markers txt)
7637 (org-reinstall-markers-in-region bbb)
7638 (move-marker ins-point bbb))
7639 (or (bolp) (insert "\n"))
7640 (setq ins-end (point))
7641 (goto-char ins-point)
7642 (org-skip-whitespace)
7643 (when (and (< arg 0)
7644 (org-first-sibling-p)
7645 (> ne-ins ne-beg))
7646 ;; Move whitespace back to beginning
7647 (save-excursion
7648 (goto-char ins-end)
7649 (let ((kill-whole-line t))
7650 (kill-line (- ne-ins ne-beg)) (point)))
7651 (insert (make-string (- ne-ins ne-beg) ?\n)))
7652 (move-marker ins-point nil)
7653 (if folded
7654 (hide-subtree)
7655 (org-show-entry)
7656 (show-children)
7657 (org-cycle-hide-drawers 'children))
7658 (org-clean-visibility-after-subtree-move)
7659 ;; move back to the initial column we were at
7660 (move-to-column col)))
7662 (defvar org-subtree-clip ""
7663 "Clipboard for cut and paste of subtrees.
7664 This is actually only a copy of the kill, because we use the normal kill
7665 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7667 (defvar org-subtree-clip-folded nil
7668 "Was the last copied subtree folded?
7669 This is used to fold the tree back after pasting.")
7671 (defun org-cut-subtree (&optional n)
7672 "Cut the current subtree into the clipboard.
7673 With prefix arg N, cut this many sequential subtrees.
7674 This is a short-hand for marking the subtree and then cutting it."
7675 (interactive "p")
7676 (org-copy-subtree n 'cut))
7678 (defun org-copy-subtree (&optional n cut force-store-markers)
7679 "Cut the current subtree into the clipboard.
7680 With prefix arg N, cut this many sequential subtrees.
7681 This is a short-hand for marking the subtree and then copying it.
7682 If CUT is non-nil, actually cut the subtree.
7683 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7684 of some markers in the region, even if CUT is non-nil. This is
7685 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7686 (interactive "p")
7687 (let (beg end folded (beg0 (point)))
7688 (if (org-called-interactively-p 'any)
7689 (org-back-to-heading nil) ; take what looks like a subtree
7690 (org-back-to-heading t)) ; take what is really there
7691 (setq beg (point))
7692 (skip-chars-forward " \t\r\n")
7693 (save-match-data
7694 (save-excursion (outline-end-of-heading)
7695 (setq folded (outline-invisible-p)))
7696 (condition-case nil
7697 (org-forward-heading-same-level (1- n) t)
7698 (error nil))
7699 (org-end-of-subtree t t))
7700 (setq end (point))
7701 (goto-char beg0)
7702 (when (> end beg)
7703 (setq org-subtree-clip-folded folded)
7704 (when (or cut force-store-markers)
7705 (org-save-markers-in-region beg end))
7706 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7707 (setq org-subtree-clip (current-kill 0))
7708 (message "%s: Subtree(s) with %d characters"
7709 (if cut "Cut" "Copied")
7710 (length org-subtree-clip)))))
7712 (defun org-paste-subtree (&optional level tree for-yank)
7713 "Paste the clipboard as a subtree, with modification of headline level.
7714 The entire subtree is promoted or demoted in order to match a new headline
7715 level.
7717 If the cursor is at the beginning of a headline, the same level as
7718 that headline is used to paste the tree
7720 If not, the new level is derived from the *visible* headings
7721 before and after the insertion point, and taken to be the inferior headline
7722 level of the two. So if the previous visible heading is level 3 and the
7723 next is level 4 (or vice versa), level 4 will be used for insertion.
7724 This makes sure that the subtree remains an independent subtree and does
7725 not swallow low level entries.
7727 You can also force a different level, either by using a numeric prefix
7728 argument, or by inserting the heading marker by hand. For example, if the
7729 cursor is after \"*****\", then the tree will be shifted to level 5.
7731 If optional TREE is given, use this text instead of the kill ring.
7733 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7734 move back over whitespace before inserting, and move point to the end of
7735 the inserted text when done."
7736 (interactive "P")
7737 (setq tree (or tree (and kill-ring (current-kill 0))))
7738 (unless (org-kill-is-subtree-p tree)
7739 (error "%s"
7740 (substitute-command-keys
7741 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7742 (org-with-limited-levels
7743 (let* ((visp (not (outline-invisible-p)))
7744 (txt tree)
7745 (^re_ "\\(\\*+\\)[ \t]*")
7746 (old-level (if (string-match org-outline-regexp-bol txt)
7747 (- (match-end 0) (match-beginning 0) 1)
7748 -1))
7749 (force-level (cond (level (prefix-numeric-value level))
7750 ((and (looking-at "[ \t]*$")
7751 (string-match
7752 "^\\*+$" (buffer-substring
7753 (point-at-bol) (point))))
7754 (- (match-end 1) (match-beginning 1)))
7755 ((and (bolp)
7756 (looking-at org-outline-regexp))
7757 (- (match-end 0) (point) 1))))
7758 (previous-level (save-excursion
7759 (condition-case nil
7760 (progn
7761 (outline-previous-visible-heading 1)
7762 (if (looking-at ^re_)
7763 (- (match-end 0) (match-beginning 0) 1)
7765 (error 1))))
7766 (next-level (save-excursion
7767 (condition-case nil
7768 (progn
7769 (or (looking-at org-outline-regexp)
7770 (outline-next-visible-heading 1))
7771 (if (looking-at ^re_)
7772 (- (match-end 0) (match-beginning 0) 1)
7774 (error 1))))
7775 (new-level (or force-level (max previous-level next-level)))
7776 (shift (if (or (= old-level -1)
7777 (= new-level -1)
7778 (= old-level new-level))
7780 (- new-level old-level)))
7781 (delta (if (> shift 0) -1 1))
7782 (func (if (> shift 0) 'org-demote 'org-promote))
7783 (org-odd-levels-only nil)
7784 beg end newend)
7785 ;; Remove the forced level indicator
7786 (if force-level
7787 (delete-region (point-at-bol) (point)))
7788 ;; Paste
7789 (beginning-of-line (if (bolp) 1 2))
7790 (setq beg (point))
7791 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7792 (insert-before-markers txt)
7793 (unless (string-match "\n\\'" txt) (insert "\n"))
7794 (setq newend (point))
7795 (org-reinstall-markers-in-region beg)
7796 (setq end (point))
7797 (goto-char beg)
7798 (skip-chars-forward " \t\n\r")
7799 (setq beg (point))
7800 (if (and (outline-invisible-p) visp)
7801 (save-excursion (outline-show-heading)))
7802 ;; Shift if necessary
7803 (unless (= shift 0)
7804 (save-restriction
7805 (narrow-to-region beg end)
7806 (while (not (= shift 0))
7807 (org-map-region func (point-min) (point-max))
7808 (setq shift (+ delta shift)))
7809 (goto-char (point-min))
7810 (setq newend (point-max))))
7811 (when (or (org-called-interactively-p 'interactive) for-yank)
7812 (message "Clipboard pasted as level %d subtree" new-level))
7813 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7814 kill-ring
7815 (eq org-subtree-clip (current-kill 0))
7816 org-subtree-clip-folded)
7817 ;; The tree was folded before it was killed/copied
7818 (hide-subtree))
7819 (and for-yank (goto-char newend)))))
7821 (defun org-kill-is-subtree-p (&optional txt)
7822 "Check if the current kill is an outline subtree, or a set of trees.
7823 Returns nil if kill does not start with a headline, or if the first
7824 headline level is not the largest headline level in the tree.
7825 So this will actually accept several entries of equal levels as well,
7826 which is OK for `org-paste-subtree'.
7827 If optional TXT is given, check this string instead of the current kill."
7828 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7829 (re (org-get-limited-outline-regexp))
7830 (^re (concat "^" re))
7831 (start-level (and kill
7832 (string-match
7833 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7834 kill)
7835 (- (match-end 2) (match-beginning 2) 1)))
7836 (start (1+ (or (match-beginning 2) -1))))
7837 (if (not start-level)
7838 (progn
7839 nil) ;; does not even start with a heading
7840 (catch 'exit
7841 (while (setq start (string-match ^re kill (1+ start)))
7842 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7843 (throw 'exit nil)))
7844 t))))
7846 (defvar org-markers-to-move nil
7847 "Markers that should be moved with a cut-and-paste operation.
7848 Those markers are stored together with their positions relative to
7849 the start of the region.")
7851 (defun org-save-markers-in-region (beg end)
7852 "Check markers in region.
7853 If these markers are between BEG and END, record their position relative
7854 to BEG, so that after moving the block of text, we can put the markers back
7855 into place.
7856 This function gets called just before an entry or tree gets cut from the
7857 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7858 called immediately, to move the markers with the entries."
7859 (setq org-markers-to-move nil)
7860 (when (featurep 'org-clock)
7861 (org-clock-save-markers-for-cut-and-paste beg end))
7862 (when (featurep 'org-agenda)
7863 (org-agenda-save-markers-for-cut-and-paste beg end)))
7865 (defun org-check-and-save-marker (marker beg end)
7866 "Check if MARKER is between BEG and END.
7867 If yes, remember the marker and the distance to BEG."
7868 (when (and (marker-buffer marker)
7869 (equal (marker-buffer marker) (current-buffer)))
7870 (if (and (>= marker beg) (< marker end))
7871 (push (cons marker (- marker beg)) org-markers-to-move))))
7873 (defun org-reinstall-markers-in-region (beg)
7874 "Move all remembered markers to their position relative to BEG."
7875 (mapc (lambda (x)
7876 (move-marker (car x) (+ beg (cdr x))))
7877 org-markers-to-move)
7878 (setq org-markers-to-move nil))
7880 (defun org-narrow-to-subtree ()
7881 "Narrow buffer to the current subtree."
7882 (interactive)
7883 (save-excursion
7884 (save-match-data
7885 (org-with-limited-levels
7886 (narrow-to-region
7887 (progn (org-back-to-heading t) (point))
7888 (progn (org-end-of-subtree t t)
7889 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7890 (point)))))))
7892 (defun org-narrow-to-block ()
7893 "Narrow buffer to the current block."
7894 (interactive)
7895 (let* ((case-fold-search t)
7896 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7897 "^[ \t]*#\\+end_.*")))
7898 (if blockp
7899 (narrow-to-region (car blockp) (cdr blockp))
7900 (error "Not in a block"))))
7902 (eval-when-compile
7903 (defvar org-property-drawer-re))
7905 (defvar org-property-start-re) ;; defined below
7906 (defun org-clone-subtree-with-time-shift (n &optional shift)
7907 "Clone the task (subtree) at point N times.
7908 The clones will be inserted as siblings.
7910 In interactive use, the user will be prompted for the number of
7911 clones to be produced, and for a time SHIFT, which may be a
7912 repeater as used in time stamps, for example `+3d'.
7914 When a valid repeater is given and the entry contains any time
7915 stamps, the clones will become a sequence in time, with time
7916 stamps in the subtree shifted for each clone produced. If SHIFT
7917 is nil or the empty string, time stamps will be left alone. The
7918 ID property of the original subtree is removed.
7920 If the original subtree did contain time stamps with a repeater,
7921 the following will happen:
7922 - the repeater will be removed in each clone
7923 - an additional clone will be produced, with the current, unshifted
7924 date(s) in the entry.
7925 - the original entry will be placed *after* all the clones, with
7926 repeater intact.
7927 - the start days in the repeater in the original entry will be shifted
7928 to past the last clone.
7929 In this way you can spell out a number of instances of a repeating task,
7930 and still retain the repeater to cover future instances of the task."
7931 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7932 (let (beg end template task idprop
7933 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7934 (drawer-re org-drawer-regexp))
7935 (if (not (and (integerp n) (> n 0)))
7936 (error "Invalid number of replications %s" n))
7937 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7938 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7939 shift)))
7940 (error "Invalid shift specification %s" shift))
7941 (when doshift
7942 (setq shift-n (string-to-number (match-string 1 shift))
7943 shift-what (cdr (assoc (match-string 2 shift)
7944 '(("d" . day) ("w" . week)
7945 ("m" . month) ("y" . year))))))
7946 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7947 (setq nmin 1 nmax n)
7948 (org-back-to-heading t)
7949 (setq beg (point))
7950 (setq idprop (org-entry-get nil "ID"))
7951 (org-end-of-subtree t t)
7952 (or (bolp) (insert "\n"))
7953 (setq end (point))
7954 (setq template (buffer-substring beg end))
7955 (when (and doshift
7956 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7957 (delete-region beg end)
7958 (setq end beg)
7959 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7960 (goto-char end)
7961 (loop for n from nmin to nmax do
7962 ;; prepare clone
7963 (with-temp-buffer
7964 (insert template)
7965 (org-mode)
7966 (goto-char (point-min))
7967 (org-show-subtree)
7968 (and idprop (if org-clone-delete-id
7969 (org-entry-delete nil "ID")
7970 (org-id-get-create t)))
7971 (unless (= n 0)
7972 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7973 (kill-whole-line))
7974 (goto-char (point-min))
7975 (while (re-search-forward drawer-re nil t)
7976 (mapc (lambda (d)
7977 (org-remove-empty-drawer-at d (point))) org-drawers)))
7978 (goto-char (point-min))
7979 (when doshift
7980 (while (re-search-forward org-ts-regexp-both nil t)
7981 (org-timestamp-change (* n shift-n) shift-what))
7982 (unless (= n n-no-remove)
7983 (goto-char (point-min))
7984 (while (re-search-forward org-ts-regexp nil t)
7985 (save-excursion
7986 (goto-char (match-beginning 0))
7987 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7988 (delete-region (match-beginning 1) (match-end 1)))))))
7989 (setq task (buffer-string)))
7990 (insert task))
7991 (goto-char beg)))
7993 ;;; Outline Sorting
7995 (defun org-sort (with-case)
7996 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7997 Optional argument WITH-CASE means sort case-sensitively."
7998 (interactive "P")
7999 (cond
8000 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8001 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8003 (org-call-with-arg 'org-sort-entries with-case))))
8005 (defun org-sort-remove-invisible (s)
8006 (remove-text-properties 0 (length s) org-rm-props s)
8007 (while (string-match org-bracket-link-regexp s)
8008 (setq s (replace-match (if (match-end 2)
8009 (match-string 3 s)
8010 (match-string 1 s)) t t s)))
8013 (defvar org-priority-regexp) ; defined later in the file
8015 (defvar org-after-sorting-entries-or-items-hook nil
8016 "Hook that is run after a bunch of entries or items have been sorted.
8017 When children are sorted, the cursor is in the parent line when this
8018 hook gets called. When a region or a plain list is sorted, the cursor
8019 will be in the first entry of the sorted region/list.")
8021 (defun org-sort-entries
8022 (&optional with-case sorting-type getkey-func compare-func property)
8023 "Sort entries on a certain level of an outline tree.
8024 If there is an active region, the entries in the region are sorted.
8025 Else, if the cursor is before the first entry, sort the top-level items.
8026 Else, the children of the entry at point are sorted.
8028 Sorting can be alphabetically, numerically, by date/time as given by
8029 a time stamp, by a property or by priority.
8031 The command prompts for the sorting type unless it has been given to the
8032 function through the SORTING-TYPE argument, which needs to be a character,
8033 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8034 precise meaning of each character:
8036 n Numerically, by converting the beginning of the entry/item to a number.
8037 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8038 o By order of TODO keywords.
8039 t By date/time, either the first active time stamp in the entry, or, if
8040 none exist, by the first inactive one.
8041 s By the scheduled date/time.
8042 d By deadline date/time.
8043 c By creation time, which is assumed to be the first inactive time stamp
8044 at the beginning of a line.
8045 p By priority according to the cookie.
8046 r By the value of a property.
8048 Capital letters will reverse the sort order.
8050 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8051 called with point at the beginning of the record. It must return either
8052 a string or a number that should serve as the sorting key for that record.
8054 Comparing entries ignores case by default. However, with an optional argument
8055 WITH-CASE, the sorting considers case as well."
8056 (interactive "P")
8057 (let ((case-func (if with-case 'identity 'downcase))
8058 (cmstr
8059 ;; The clock marker is lost when using `sort-subr', let's
8060 ;; store the clocking string.
8061 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8062 (save-excursion
8063 (goto-char org-clock-marker)
8064 (looking-back "^.*") (match-string-no-properties 0))))
8065 start beg end stars re re2
8066 txt what tmp)
8067 ;; Find beginning and end of region to sort
8068 (cond
8069 ((org-region-active-p)
8070 ;; we will sort the region
8071 (setq end (region-end)
8072 what "region")
8073 (goto-char (region-beginning))
8074 (if (not (org-at-heading-p)) (outline-next-heading))
8075 (setq start (point)))
8076 ((or (org-at-heading-p)
8077 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8078 ;; we will sort the children of the current headline
8079 (org-back-to-heading)
8080 (setq start (point)
8081 end (progn (org-end-of-subtree t t)
8082 (or (bolp) (insert "\n"))
8083 (org-back-over-empty-lines)
8084 (point))
8085 what "children")
8086 (goto-char start)
8087 (show-subtree)
8088 (outline-next-heading))
8090 ;; we will sort the top-level entries in this file
8091 (goto-char (point-min))
8092 (or (org-at-heading-p) (outline-next-heading))
8093 (setq start (point))
8094 (goto-char (point-max))
8095 (beginning-of-line 1)
8096 (when (looking-at ".*?\\S-")
8097 ;; File ends in a non-white line
8098 (end-of-line 1)
8099 (insert "\n"))
8100 (setq end (point-max))
8101 (setq what "top-level")
8102 (goto-char start)
8103 (show-all)))
8105 (setq beg (point))
8106 (if (>= beg end) (error "Nothing to sort"))
8108 (looking-at "\\(\\*+\\)")
8109 (setq stars (match-string 1)
8110 re (concat "^" (regexp-quote stars) " +")
8111 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8112 txt (buffer-substring beg end))
8113 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8114 (if (and (not (equal stars "*")) (string-match re2 txt))
8115 (error "Region to sort contains a level above the first entry"))
8117 (unless sorting-type
8118 (message
8119 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8120 [t]ime [s]cheduled [d]eadline [c]reated
8121 A/N/P/R/O/F/T/S/D/C means reversed:"
8122 what)
8123 (setq sorting-type (read-char-exclusive))
8125 (and (= (downcase sorting-type) ?f)
8126 (setq getkey-func
8127 (org-icompleting-read "Sort using function: "
8128 obarray 'fboundp t nil nil))
8129 (setq getkey-func (intern getkey-func)))
8131 (and (= (downcase sorting-type) ?r)
8132 (setq property
8133 (org-icompleting-read "Property: "
8134 (mapcar 'list (org-buffer-property-keys t))
8135 nil t))))
8137 (message "Sorting entries...")
8139 (save-restriction
8140 (narrow-to-region start end)
8141 (let ((dcst (downcase sorting-type))
8142 (case-fold-search nil)
8143 (now (current-time)))
8144 (sort-subr
8145 (/= dcst sorting-type)
8146 ;; This function moves to the beginning character of the "record" to
8147 ;; be sorted.
8148 (lambda nil
8149 (if (re-search-forward re nil t)
8150 (goto-char (match-beginning 0))
8151 (goto-char (point-max))))
8152 ;; This function moves to the last character of the "record" being
8153 ;; sorted.
8154 (lambda nil
8155 (save-match-data
8156 (condition-case nil
8157 (outline-forward-same-level 1)
8158 (error
8159 (goto-char (point-max))))))
8160 ;; This function returns the value that gets sorted against.
8161 (lambda nil
8162 (cond
8163 ((= dcst ?n)
8164 (if (looking-at org-complex-heading-regexp)
8165 (string-to-number (match-string 4))
8166 nil))
8167 ((= dcst ?a)
8168 (if (looking-at org-complex-heading-regexp)
8169 (funcall case-func (match-string 4))
8170 nil))
8171 ((= dcst ?t)
8172 (let ((end (save-excursion (outline-next-heading) (point))))
8173 (if (or (re-search-forward org-ts-regexp end t)
8174 (re-search-forward org-ts-regexp-both end t))
8175 (org-time-string-to-seconds (match-string 0))
8176 (org-float-time now))))
8177 ((= dcst ?c)
8178 (let ((end (save-excursion (outline-next-heading) (point))))
8179 (if (re-search-forward
8180 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8181 end t)
8182 (org-time-string-to-seconds (match-string 0))
8183 (org-float-time now))))
8184 ((= dcst ?s)
8185 (let ((end (save-excursion (outline-next-heading) (point))))
8186 (if (re-search-forward org-scheduled-time-regexp end t)
8187 (org-time-string-to-seconds (match-string 1))
8188 (org-float-time now))))
8189 ((= dcst ?d)
8190 (let ((end (save-excursion (outline-next-heading) (point))))
8191 (if (re-search-forward org-deadline-time-regexp end t)
8192 (org-time-string-to-seconds (match-string 1))
8193 (org-float-time now))))
8194 ((= dcst ?p)
8195 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8196 (string-to-char (match-string 2))
8197 org-default-priority))
8198 ((= dcst ?r)
8199 (or (org-entry-get nil property) ""))
8200 ((= dcst ?o)
8201 (if (looking-at org-complex-heading-regexp)
8202 (- 9999 (length (member (match-string 2)
8203 org-todo-keywords-1)))))
8204 ((= dcst ?f)
8205 (if getkey-func
8206 (progn
8207 (setq tmp (funcall getkey-func))
8208 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8209 tmp)
8210 (error "Invalid key function `%s'" getkey-func)))
8211 (t (error "Invalid sorting type `%c'" sorting-type))))
8213 (cond
8214 ((= dcst ?a) 'string<)
8215 ((= dcst ?f) compare-func)
8216 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8217 (run-hooks 'org-after-sorting-entries-or-items-hook)
8218 ;; Reset the clock marker if needed
8219 (when cmstr
8220 (save-excursion
8221 (goto-char start)
8222 (search-forward cmstr nil t)
8223 (move-marker org-clock-marker (point))))
8224 (message "Sorting entries...done")))
8226 (defun org-do-sort (table what &optional with-case sorting-type)
8227 "Sort TABLE of WHAT according to SORTING-TYPE.
8228 The user will be prompted for the SORTING-TYPE if the call to this
8229 function does not specify it. WHAT is only for the prompt, to indicate
8230 what is being sorted. The sorting key will be extracted from
8231 the car of the elements of the table.
8232 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8233 (unless sorting-type
8234 (message
8235 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8236 what)
8237 (setq sorting-type (read-char-exclusive)))
8238 (let ((dcst (downcase sorting-type))
8239 extractfun comparefun)
8240 ;; Define the appropriate functions
8241 (cond
8242 ((= dcst ?n)
8243 (setq extractfun 'string-to-number
8244 comparefun (if (= dcst sorting-type) '< '>)))
8245 ((= dcst ?a)
8246 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8247 (lambda(x) (downcase (org-sort-remove-invisible x))))
8248 comparefun (if (= dcst sorting-type)
8249 'string<
8250 (lambda (a b) (and (not (string< a b))
8251 (not (string= a b)))))))
8252 ((= dcst ?t)
8253 (setq extractfun
8254 (lambda (x)
8255 (if (or (string-match org-ts-regexp x)
8256 (string-match org-ts-regexp-both x))
8257 (org-float-time
8258 (org-time-string-to-time (match-string 0 x)))
8260 comparefun (if (= dcst sorting-type) '< '>)))
8261 (t (error "Invalid sorting type `%c'" sorting-type)))
8263 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8264 table)
8265 (lambda (a b) (funcall comparefun (car a) (car b))))))
8268 ;;; The orgstruct minor mode
8270 ;; Define a minor mode which can be used in other modes in order to
8271 ;; integrate the org-mode structure editing commands.
8273 ;; This is really a hack, because the org-mode structure commands use
8274 ;; keys which normally belong to the major mode. Here is how it
8275 ;; works: The minor mode defines all the keys necessary to operate the
8276 ;; structure commands, but wraps the commands into a function which
8277 ;; tests if the cursor is currently at a headline or a plain list
8278 ;; item. If that is the case, the structure command is used,
8279 ;; temporarily setting many Org-mode variables like regular
8280 ;; expressions for filling etc. However, when any of those keys is
8281 ;; used at a different location, function uses `key-binding' to look
8282 ;; up if the key has an associated command in another currently active
8283 ;; keymap (minor modes, major mode, global), and executes that
8284 ;; command. There might be problems if any of the keys is otherwise
8285 ;; used as a prefix key.
8287 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8288 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8289 ;; addresses this by checking explicitly for both bindings.
8291 (defvar orgstruct-mode-map (make-sparse-keymap)
8292 "Keymap for the minor `orgstruct-mode'.")
8294 (defvar org-local-vars nil
8295 "List of local variables, for use by `orgstruct-mode'.")
8297 ;;;###autoload
8298 (define-minor-mode orgstruct-mode
8299 "Toggle the minor mode `orgstruct-mode'.
8300 This mode is for using Org-mode structure commands in other
8301 modes. The following keys behave as if Org-mode were active, if
8302 the cursor is on a headline, or on a plain list item (both as
8303 defined by Org-mode).
8305 M-up Move entry/item up
8306 M-down Move entry/item down
8307 M-left Promote
8308 M-right Demote
8309 M-S-up Move entry/item up
8310 M-S-down Move entry/item down
8311 M-S-left Promote subtree
8312 M-S-right Demote subtree
8313 M-q Fill paragraph and items like in Org-mode
8314 C-c ^ Sort entries
8315 C-c - Cycle list bullet
8316 TAB Cycle item visibility
8317 M-RET Insert new heading/item
8318 S-M-RET Insert new TODO heading / Checkbox item
8319 C-c C-c Set tags / toggle checkbox"
8320 nil " OrgStruct" nil
8321 (org-load-modules-maybe)
8322 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8324 ;;;###autoload
8325 (defun turn-on-orgstruct ()
8326 "Unconditionally turn on `orgstruct-mode'."
8327 (orgstruct-mode 1))
8329 (defvar org-fb-vars nil)
8330 (make-variable-buffer-local 'org-fb-vars)
8331 (defun orgstruct++-mode (&optional arg)
8332 "Toggle `orgstruct-mode', the enhanced version of it.
8333 In addition to setting orgstruct-mode, this also exports all
8334 indentation and autofilling variables from org-mode into the
8335 buffer. It will also recognize item context in multiline items."
8336 (interactive "P")
8337 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8338 (if (< arg 1)
8339 (progn (orgstruct-mode -1)
8340 (mapc (lambda(v)
8341 (org-set-local (car v)
8342 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8343 org-fb-vars))
8344 (orgstruct-mode 1)
8345 (setq org-fb-vars nil)
8346 (let (var val)
8347 (mapc
8348 (lambda (x)
8349 (when (string-match
8350 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8351 (symbol-name (car x)))
8352 (setq var (car x) val (nth 1 x))
8353 (push (list var `(quote ,(eval var))) org-fb-vars)
8354 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8355 org-local-vars)
8356 (org-set-local 'orgstruct-is-++ t))))
8358 (defvar orgstruct-is-++ nil
8359 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8360 (make-variable-buffer-local 'orgstruct-is-++)
8362 ;;;###autoload
8363 (defun turn-on-orgstruct++ ()
8364 "Unconditionally turn on `orgstruct++-mode'."
8365 (orgstruct++-mode 1))
8367 (defun orgstruct-error ()
8368 "Error when there is no default binding for a structure key."
8369 (interactive)
8370 (error "This key has no function outside structure elements"))
8372 (defun orgstruct-setup ()
8373 "Setup orgstruct keymaps."
8374 (let ((nfunc 0)
8375 (bindings
8376 (list
8377 '([(meta up)] org-metaup)
8378 '([(meta down)] org-metadown)
8379 '([(meta left)] org-metaleft)
8380 '([(meta right)] org-metaright)
8381 '([(meta shift up)] org-shiftmetaup)
8382 '([(meta shift down)] org-shiftmetadown)
8383 '([(meta shift left)] org-shiftmetaleft)
8384 '([(meta shift right)] org-shiftmetaright)
8385 '([?\e (up)] org-metaup)
8386 '([?\e (down)] org-metadown)
8387 '([?\e (left)] org-metaleft)
8388 '([?\e (right)] org-metaright)
8389 '([?\e (shift up)] org-shiftmetaup)
8390 '([?\e (shift down)] org-shiftmetadown)
8391 '([?\e (shift left)] org-shiftmetaleft)
8392 '([?\e (shift right)] org-shiftmetaright)
8393 '([(shift up)] org-shiftup)
8394 '([(shift down)] org-shiftdown)
8395 '([(shift left)] org-shiftleft)
8396 '([(shift right)] org-shiftright)
8397 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8398 '("\M-q" fill-paragraph)
8399 '("\C-c^" org-sort)
8400 '("\C-c-" org-cycle-list-bullet)))
8401 elt key fun cmd)
8402 (while (setq elt (pop bindings))
8403 (setq nfunc (1+ nfunc))
8404 (setq key (org-key (car elt))
8405 fun (nth 1 elt)
8406 cmd (orgstruct-make-binding fun nfunc key))
8407 (org-defkey orgstruct-mode-map key cmd))
8409 ;; Prevent an error for users who forgot to make autoloads
8410 (require 'org-element)
8412 ;; Special treatment needed for TAB and RET
8413 (org-defkey orgstruct-mode-map [(tab)]
8414 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8415 (org-defkey orgstruct-mode-map "\C-i"
8416 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8418 (org-defkey orgstruct-mode-map "\M-\C-m"
8419 (orgstruct-make-binding 'org-insert-heading 105
8420 "\M-\C-m" [(meta return)]))
8421 (org-defkey orgstruct-mode-map [(meta return)]
8422 (orgstruct-make-binding 'org-insert-heading 106
8423 [(meta return)] "\M-\C-m"))
8425 (org-defkey orgstruct-mode-map [(shift meta return)]
8426 (orgstruct-make-binding 'org-insert-todo-heading 107
8427 [(meta return)] "\M-\C-m"))
8429 (org-defkey orgstruct-mode-map "\e\C-m"
8430 (orgstruct-make-binding 'org-insert-heading 108
8431 "\e\C-m" [?\e (return)]))
8432 (org-defkey orgstruct-mode-map [?\e (return)]
8433 (orgstruct-make-binding 'org-insert-heading 109
8434 [?\e (return)] "\e\C-m"))
8435 (org-defkey orgstruct-mode-map [?\e (shift return)]
8436 (orgstruct-make-binding 'org-insert-todo-heading 110
8437 [?\e (return)] "\e\C-m"))
8439 (unless org-local-vars
8440 (setq org-local-vars (org-get-local-variables)))
8444 (defun orgstruct-make-binding (fun n &rest keys)
8445 "Create a function for binding in the structure minor mode.
8446 FUN is the command to call inside a table. N is used to create a unique
8447 command name. KEYS are keys that should be checked in for a command
8448 to execute outside of tables."
8449 (eval
8450 (list 'defun
8451 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8452 '(arg)
8453 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8454 "Outside of structure, run the binding of `"
8455 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8456 "'.")
8457 '(interactive "p")
8458 (list 'if
8459 `(org-context-p 'headline 'item
8460 (and orgstruct-is-++
8461 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8462 'item-body))
8463 (list 'org-run-like-in-org-mode (list 'quote fun))
8464 (list 'let '(orgstruct-mode)
8465 (list 'call-interactively
8466 (append '(or)
8467 (mapcar (lambda (k)
8468 (list 'key-binding k))
8469 keys)
8470 '('orgstruct-error))))))))
8472 (defun org-contextualize-keys (alist contexts)
8473 "Return valid elements in ALIST depending on CONTEXTS.
8475 `org-agenda-custom-commands' or `org-capture-templates' are the
8476 values used for ALIST, and `org-agenda-custom-commands-contexts'
8477 or `org-capture-templates-contexts' are the associated contexts
8478 definitions."
8479 (let ((contexts
8480 ;; normalize contexts
8481 (mapcar
8482 (lambda(c) (cond ((listp (cadr c))
8483 (list (car c) (car c) (cadr c)))
8484 ((string= "" (cadr c))
8485 (list (car c) (car c) (caddr c)))
8486 (t c))) contexts))
8487 (a alist) c r s)
8488 ;; loop over all commands or templates
8489 (while (setq c (pop a))
8490 (let (vrules repl)
8491 (cond
8492 ((not (assoc (car c) contexts))
8493 (push c r))
8494 ((and (assoc (car c) contexts)
8495 (setq vrules (org-contextualize-validate-key
8496 (car c) contexts)))
8497 (mapc (lambda (vr)
8498 (when (not (equal (car vr) (cadr vr)))
8499 (setq repl vr))) vrules)
8500 (if (not repl) (push c r)
8501 (push (cadr repl) s)
8502 (push
8503 (cons (car c)
8504 (cdr (or (assoc (cadr repl) alist)
8505 (error "Undefined key `%s' as contextual replacement for `%s'"
8506 (cadr repl) (car c)))))
8507 r))))))
8508 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8509 (delq
8511 (delete-dups
8512 (mapcar (lambda (x)
8513 (let ((tpl (car x)))
8514 (when (not (delq
8516 (mapcar (lambda(y)
8517 (equal y tpl)) s))) x)))
8518 (reverse r))))))
8520 (defun org-contextualize-validate-key (key contexts)
8521 "Check CONTEXTS for agenda or capture KEY."
8522 (let (r rr res)
8523 (while (setq r (pop contexts))
8524 (mapc
8525 (lambda (rr)
8526 (when
8527 (and (equal key (car r))
8528 (if (functionp rr) (funcall rr)
8529 (or (and (eq (car rr) 'in-file)
8530 (buffer-file-name)
8531 (string-match (cdr rr) (buffer-file-name)))
8532 (and (eq (car rr) 'in-mode)
8533 (string-match (cdr rr) (symbol-name major-mode)))
8534 (when (and (eq (car rr) 'not-in-file)
8535 (buffer-file-name))
8536 (not (string-match (cdr rr) (buffer-file-name))))
8537 (when (eq (car rr) 'not-in-mode)
8538 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8539 (push r res)))
8540 (car (last r))))
8541 (delete-dups (delq nil res))))
8543 (defun org-context-p (&rest contexts)
8544 "Check if local context is any of CONTEXTS.
8545 Possible values in the list of contexts are `table', `headline', and `item'."
8546 (let ((pos (point)))
8547 (goto-char (point-at-bol))
8548 (prog1 (or (and (memq 'table contexts)
8549 (looking-at "[ \t]*|"))
8550 (and (memq 'headline contexts)
8551 (looking-at org-outline-regexp))
8552 (and (memq 'item contexts)
8553 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8554 (and (memq 'item-body contexts)
8555 (org-in-item-p)))
8556 (goto-char pos))))
8558 (defun org-get-local-variables ()
8559 "Return a list of all local variables in an Org mode buffer."
8560 (let (varlist)
8561 (with-current-buffer (get-buffer-create "*Org tmp*")
8562 (erase-buffer)
8563 (org-mode)
8564 (setq varlist (buffer-local-variables)))
8565 (kill-buffer "*Org tmp*")
8566 (delq nil
8567 (mapcar
8568 (lambda (x)
8569 (setq x
8570 (if (symbolp x)
8571 (list x)
8572 (list (car x) (list 'quote (cdr x)))))
8573 (if (string-match
8574 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8575 (symbol-name (car x)))
8576 x nil))
8577 varlist))))
8579 (defun org-clone-local-variables (from-buffer &optional regexp)
8580 "Clone local variables from FROM-BUFFER.
8581 Optional argument REGEXP selects variables to clone."
8582 (mapc
8583 (lambda (pair)
8584 (and (symbolp (car pair))
8585 (or (null regexp)
8586 (string-match regexp (symbol-name (car pair))))
8587 (set (make-local-variable (car pair))
8588 (cdr pair))))
8589 (buffer-local-variables from-buffer)))
8591 ;;;###autoload
8592 (defun org-run-like-in-org-mode (cmd)
8593 "Run a command, pretending that the current buffer is in Org-mode.
8594 This will temporarily bind local variables that are typically bound in
8595 Org-mode to the values they have in Org-mode, and then interactively
8596 call CMD."
8597 (org-load-modules-maybe)
8598 (unless org-local-vars
8599 (setq org-local-vars (org-get-local-variables)))
8600 (eval (list 'let org-local-vars
8601 (list 'call-interactively (list 'quote cmd)))))
8603 ;;;; Archiving
8605 (defun org-get-category (&optional pos force-refresh)
8606 "Get the category applying to position POS."
8607 (save-match-data
8608 (if force-refresh (org-refresh-category-properties))
8609 (let ((pos (or pos (point))))
8610 (or (get-text-property pos 'org-category)
8611 (progn (org-refresh-category-properties)
8612 (get-text-property pos 'org-category))))))
8614 (defun org-refresh-category-properties ()
8615 "Refresh category text properties in the buffer."
8616 (let ((case-fold-search t)
8617 (inhibit-read-only t)
8618 (def-cat (cond
8619 ((null org-category)
8620 (if buffer-file-name
8621 (file-name-sans-extension
8622 (file-name-nondirectory buffer-file-name))
8623 "???"))
8624 ((symbolp org-category) (symbol-name org-category))
8625 (t org-category)))
8626 beg end cat pos optionp)
8627 (org-unmodified
8628 (save-excursion
8629 (save-restriction
8630 (widen)
8631 (goto-char (point-min))
8632 (put-text-property (point) (point-max) 'org-category def-cat)
8633 (while (re-search-forward
8634 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8635 (setq pos (match-end 0)
8636 optionp (equal (char-after (match-beginning 0)) ?#)
8637 cat (org-trim (match-string 2)))
8638 (if optionp
8639 (setq beg (point-at-bol) end (point-max))
8640 (org-back-to-heading t)
8641 (setq beg (point) end (org-end-of-subtree t t)))
8642 (put-text-property beg end 'org-category cat)
8643 (put-text-property beg end 'org-category-position beg)
8644 (goto-char pos)))))))
8646 (defun org-refresh-properties (dprop tprop)
8647 "Refresh buffer text properties.
8648 DPROP is the drawer property and TPROP is the corresponding text
8649 property to set."
8650 (let ((case-fold-search t)
8651 (inhibit-read-only t) p)
8652 (org-unmodified
8653 (save-excursion
8654 (save-restriction
8655 (widen)
8656 (goto-char (point-min))
8657 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8658 (setq p (org-match-string-no-properties 1))
8659 (save-excursion
8660 (org-back-to-heading t)
8661 (put-text-property
8662 (point-at-bol) (point-at-eol) tprop p))))))))
8665 ;;;; Link Stuff
8667 ;;; Link abbreviations
8669 (defun org-link-expand-abbrev (link)
8670 "Apply replacements as defined in `org-link-abbrev-alist'."
8671 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8672 (let* ((key (match-string 1 link))
8673 (as (or (assoc key org-link-abbrev-alist-local)
8674 (assoc key org-link-abbrev-alist)))
8675 (tag (and (match-end 2) (match-string 3 link)))
8676 rpl)
8677 (if (not as)
8678 link
8679 (setq rpl (cdr as))
8680 (cond
8681 ((symbolp rpl) (funcall rpl tag))
8682 ((string-match "%(\\([^)]+\\))" rpl)
8683 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8684 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8685 ((string-match "%h" rpl)
8686 (replace-match (url-hexify-string (or tag "")) t t rpl))
8687 (t (concat rpl tag)))))
8688 link))
8690 ;;; Storing and inserting links
8692 (defvar org-insert-link-history nil
8693 "Minibuffer history for links inserted with `org-insert-link'.")
8695 (defvar org-stored-links nil
8696 "Contains the links stored with `org-store-link'.")
8698 (defvar org-store-link-plist nil
8699 "Plist with info about the most recently link created with `org-store-link'.")
8701 (defvar org-link-protocols nil
8702 "Link protocols added to Org-mode using `org-add-link-type'.")
8704 (defvar org-store-link-functions nil
8705 "List of functions that are called to create and store a link.
8706 Each function will be called in turn until one returns a non-nil
8707 value. Each function should check if it is responsible for creating
8708 this link (for example by looking at the major mode).
8709 If not, it must exit and return nil.
8710 If yes, it should return a non-nil value after a calling
8711 `org-store-link-props' with a list of properties and values.
8712 Special properties are:
8714 :type The link prefix, like \"http\". This must be given.
8715 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8716 This is obligatory as well.
8717 :description Optional default description for the second pair
8718 of brackets in an Org-mode link. The user can still change
8719 this when inserting this link into an Org-mode buffer.
8721 In addition to these, any additional properties can be specified
8722 and then used in capture templates.")
8724 (defun org-add-link-type (type &optional follow export)
8725 "Add TYPE to the list of `org-link-types'.
8726 Re-compute all regular expressions depending on `org-link-types'
8728 FOLLOW and EXPORT are two functions.
8730 FOLLOW should take the link path as the single argument and do whatever
8731 is necessary to follow the link, for example find a file or display
8732 a mail message.
8734 EXPORT should format the link path for export to one of the export formats.
8735 It should be a function accepting three arguments:
8737 path the path of the link, the text after the prefix (like \"http:\")
8738 desc the description of the link, if any, or a description added by
8739 org-export-normalize-links if there is none
8740 format the export format, a symbol like `html' or `latex' or `ascii'..
8742 The function may use the FORMAT information to return different values
8743 depending on the format. The return value will be put literally into
8744 the exported file. If the return value is nil, this means Org should
8745 do what it normally does with links which do not have EXPORT defined.
8747 Org-mode has a built-in default for exporting links. If you are happy with
8748 this default, there is no need to define an export function for the link
8749 type. For a simple example of an export function, see `org-bbdb.el'."
8750 (add-to-list 'org-link-types type t)
8751 (org-make-link-regexps)
8752 (if (assoc type org-link-protocols)
8753 (setcdr (assoc type org-link-protocols) (list follow export))
8754 (push (list type follow export) org-link-protocols)))
8756 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8757 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8759 ;;;###autoload
8760 (defun org-store-link (arg)
8761 "\\<org-mode-map>Store an org-link to the current location.
8762 This link is added to `org-stored-links' and can later be inserted
8763 into an org-buffer with \\[org-insert-link].
8765 For some link types, a prefix arg is interpreted:
8766 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8767 For file links, arg negates `org-context-in-file-links'."
8768 (interactive "P")
8769 (org-load-modules-maybe)
8770 (setq org-store-link-plist nil) ; reset
8771 (org-with-limited-levels
8772 (let (link cpltxt desc description search txt custom-id agenda-link)
8773 (cond
8775 ((run-hook-with-args-until-success 'org-store-link-functions)
8776 (setq link (plist-get org-store-link-plist :link)
8777 desc (or (plist-get org-store-link-plist :description) link)))
8779 ((org-src-edit-buffer-p)
8780 (let (label gc)
8781 (while (or (not label)
8782 (save-excursion
8783 (save-restriction
8784 (widen)
8785 (goto-char (point-min))
8786 (re-search-forward
8787 (regexp-quote (format org-coderef-label-format label))
8788 nil t))))
8789 (when label (message "Label exists already") (sit-for 2))
8790 (setq label (read-string "Code line label: " label)))
8791 (end-of-line 1)
8792 (setq link (format org-coderef-label-format label))
8793 (setq gc (- 79 (length link)))
8794 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8795 (insert link)
8796 (setq link (concat "(" label ")") desc nil)))
8798 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8799 ;; We are in the agenda, link to referenced location
8800 (let ((m (or (get-text-property (point) 'org-hd-marker)
8801 (get-text-property (point) 'org-marker))))
8802 (when m
8803 (org-with-point-at m
8804 (setq agenda-link
8805 (if (org-called-interactively-p 'any)
8806 (call-interactively 'org-store-link)
8807 (org-store-link nil)))))))
8809 ((eq major-mode 'calendar-mode)
8810 (let ((cd (calendar-cursor-to-date)))
8811 (setq link
8812 (format-time-string
8813 (car org-time-stamp-formats)
8814 (apply 'encode-time
8815 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8816 nil nil nil))))
8817 (org-store-link-props :type "calendar" :date cd)))
8819 ((eq major-mode 'help-mode)
8820 (setq link (concat "help:" (save-excursion
8821 (goto-char (point-min))
8822 (looking-at "^[^ ]+")
8823 (match-string 0))))
8824 (org-store-link-props :type "help"))
8826 ((eq major-mode 'w3-mode)
8827 (setq cpltxt (if (and (buffer-name)
8828 (not (string-match "Untitled" (buffer-name))))
8829 (buffer-name)
8830 (url-view-url t))
8831 link (url-view-url t))
8832 (org-store-link-props :type "w3" :url (url-view-url t)))
8834 ((eq major-mode 'w3m-mode)
8835 (setq cpltxt (or w3m-current-title w3m-current-url)
8836 link w3m-current-url)
8837 (org-store-link-props :type "w3m" :url (url-view-url t)))
8839 ((setq search (run-hook-with-args-until-success
8840 'org-create-file-search-functions))
8841 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8842 "::" search))
8843 (setq cpltxt (or description link)))
8845 ((eq major-mode 'image-mode)
8846 (setq cpltxt (concat "file:"
8847 (abbreviate-file-name buffer-file-name))
8848 link cpltxt)
8849 (org-store-link-props :type "image" :file buffer-file-name))
8851 ((eq major-mode 'dired-mode)
8852 ;; link to the file in the current line
8853 (let ((file (dired-get-filename nil t)))
8854 (setq file (if file
8855 (abbreviate-file-name
8856 (expand-file-name (dired-get-filename nil t)))
8857 ;; otherwise, no file so use current directory.
8858 default-directory))
8859 (setq cpltxt (concat "file:" file)
8860 link cpltxt)))
8862 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8863 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8864 (cond
8865 ((org-in-regexp "<<\\(.*?\\)>>")
8866 (setq cpltxt
8867 (concat "file:"
8868 (abbreviate-file-name
8869 (buffer-file-name (buffer-base-buffer)))
8870 "::" (match-string 1))
8871 link cpltxt))
8872 ((and (featurep 'org-id)
8873 (or (eq org-id-link-to-org-use-id t)
8874 (and (org-called-interactively-p 'any)
8875 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
8876 (and (eq org-id-link-to-org-use-id
8877 'create-if-interactive-and-no-custom-id)
8878 (not custom-id))))
8879 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
8880 ;; We can make a link using the ID.
8881 (setq link (condition-case nil
8882 (prog1 (org-id-store-link)
8883 (setq desc (plist-get org-store-link-plist :description)))
8884 (error
8885 ;; probably before first headline, link to file only
8886 (concat "file:"
8887 (abbreviate-file-name
8888 (buffer-file-name (buffer-base-buffer))))))))
8890 ;; Just link to current headline
8891 (setq cpltxt (concat "file:"
8892 (abbreviate-file-name
8893 (buffer-file-name (buffer-base-buffer)))))
8894 ;; Add a context search string
8895 (when (org-xor org-context-in-file-links arg)
8896 (setq txt (cond
8897 ((org-at-heading-p) nil)
8898 ((org-region-active-p)
8899 (buffer-substring (region-beginning) (region-end)))))
8900 (when (or (null txt) (string-match "\\S-" txt))
8901 (setq cpltxt
8902 (concat cpltxt "::"
8903 (condition-case nil
8904 (org-make-org-heading-search-string txt)
8905 (error "")))
8906 desc (or (nth 4 (ignore-errors
8907 (org-heading-components))) "NONE"))))
8908 (if (string-match "::\\'" cpltxt)
8909 (setq cpltxt (substring cpltxt 0 -2)))
8910 (setq link cpltxt))))
8912 ((buffer-file-name (buffer-base-buffer))
8913 ;; Just link to this file here.
8914 (setq cpltxt (concat "file:"
8915 (abbreviate-file-name
8916 (buffer-file-name (buffer-base-buffer)))))
8917 ;; Add a context string
8918 (when (org-xor org-context-in-file-links arg)
8919 (setq txt (if (org-region-active-p)
8920 (buffer-substring (region-beginning) (region-end))
8921 (buffer-substring (point-at-bol) (point-at-eol))))
8922 ;; Only use search option if there is some text.
8923 (when (string-match "\\S-" txt)
8924 (setq cpltxt
8925 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8926 desc "NONE")))
8927 (setq link cpltxt))
8929 ((org-called-interactively-p 'interactive)
8930 (error "Cannot link to a buffer which is not visiting a file"))
8932 (t (setq link nil)))
8934 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8935 (setq link (or link cpltxt)
8936 desc (or desc cpltxt))
8937 (if (equal desc "NONE") (setq desc nil))
8939 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8940 (progn
8941 (setq org-stored-links
8942 (cons (list link desc) org-stored-links))
8943 (message "Stored: %s" (or desc link))
8944 (when custom-id
8945 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8946 "::#" custom-id))
8947 (setq org-stored-links
8948 (cons (list link desc) org-stored-links))))
8949 (or agenda-link (and link (org-make-link-string link desc)))))))
8951 (defun org-store-link-props (&rest plist)
8952 "Store link properties, extract names and addresses."
8953 (let (x adr)
8954 (when (setq x (plist-get plist :from))
8955 (setq adr (mail-extract-address-components x))
8956 (setq plist (plist-put plist :fromname (car adr)))
8957 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8958 (when (setq x (plist-get plist :to))
8959 (setq adr (mail-extract-address-components x))
8960 (setq plist (plist-put plist :toname (car adr)))
8961 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8962 (let ((from (plist-get plist :from))
8963 (to (plist-get plist :to)))
8964 (when (and from to org-from-is-user-regexp)
8965 (setq plist
8966 (plist-put plist :fromto
8967 (if (string-match org-from-is-user-regexp from)
8968 (concat "to %t")
8969 (concat "from %f"))))))
8970 (setq org-store-link-plist plist))
8972 (defun org-add-link-props (&rest plist)
8973 "Add these properties to the link property list."
8974 (let (key value)
8975 (while plist
8976 (setq key (pop plist) value (pop plist))
8977 (setq org-store-link-plist
8978 (plist-put org-store-link-plist key value)))))
8980 (defun org-email-link-description (&optional fmt)
8981 "Return the description part of an email link.
8982 This takes information from `org-store-link-plist' and formats it
8983 according to FMT (default from `org-email-link-description-format')."
8984 (setq fmt (or fmt org-email-link-description-format))
8985 (let* ((p org-store-link-plist)
8986 (to (plist-get p :toaddress))
8987 (from (plist-get p :fromaddress))
8988 (table
8989 (list
8990 (cons "%c" (plist-get p :fromto))
8991 (cons "%F" (plist-get p :from))
8992 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8993 (cons "%T" (plist-get p :to))
8994 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8995 (cons "%s" (plist-get p :subject))
8996 (cons "%d" (plist-get p :date))
8997 (cons "%m" (plist-get p :message-id)))))
8998 (when (string-match "%c" fmt)
8999 ;; Check if the user wrote this message
9000 (if (and org-from-is-user-regexp from to
9001 (save-match-data (string-match org-from-is-user-regexp from)))
9002 (setq fmt (replace-match "to %t" t t fmt))
9003 (setq fmt (replace-match "from %f" t t fmt))))
9004 (org-replace-escapes fmt table)))
9006 (defun org-make-org-heading-search-string (&optional string heading)
9007 "Make search string for STRING or current headline."
9008 (interactive)
9009 (let ((s (or string (org-get-heading)))
9010 (lines org-context-in-file-links))
9011 (unless (and string (not heading))
9012 ;; We are using a headline, clean up garbage in there.
9013 (if (string-match org-todo-regexp s)
9014 (setq s (replace-match "" t t s)))
9015 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9016 (setq s (replace-match "" t t s)))
9017 (setq s (org-trim s))
9018 (if (string-match (concat "^\\(" org-quote-string "\\|"
9019 org-comment-string "\\)") s)
9020 (setq s (replace-match "" t t s)))
9021 (while (string-match org-ts-regexp s)
9022 (setq s (replace-match "" t t s))))
9023 (or string (setq s (concat "*" s))) ; Add * for headlines
9024 (when (and string (integerp lines) (> lines 0))
9025 (let ((slines (org-split-string s "\n")))
9026 (when (< lines (length slines))
9027 (setq s (mapconcat
9028 'identity
9029 (reverse (nthcdr (- (length slines) lines)
9030 (reverse slines))) "\n")))))
9031 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9033 (defun org-make-link-string (link &optional description)
9034 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9035 (unless (string-match "\\S-" link)
9036 (error "Empty link"))
9037 (when (and description
9038 (stringp description)
9039 (not (string-match "\\S-" description)))
9040 (setq description nil))
9041 (when (stringp description)
9042 ;; Remove brackets from the description, they are fatal.
9043 (while (string-match "\\[" description)
9044 (setq description (replace-match "{" t t description)))
9045 (while (string-match "\\]" description)
9046 (setq description (replace-match "}" t t description))))
9047 (when (equal link description)
9048 ;; No description needed, it is identical
9049 (setq description nil))
9050 (when (and (not description)
9051 (not (string-match (org-image-file-name-regexp) link))
9052 (not (equal link (org-link-escape link))))
9053 (setq description (org-extract-attributes link)))
9054 (setq link
9055 (cond ((string-match (org-image-file-name-regexp) link) link)
9056 ((string-match org-link-types-re link)
9057 (concat (match-string 1 link)
9058 (org-link-escape (substring link (match-end 1)))))
9059 (t (org-link-escape link))))
9060 (concat "[[" link "]"
9061 (if description (concat "[" description "]") "")
9062 "]"))
9064 (defconst org-link-escape-chars
9065 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9066 "List of characters that should be escaped in link.
9067 This is the list that is used for internal purposes.")
9069 (defconst org-link-escape-chars-browser
9070 '(?\ )
9071 "List of escapes for characters that are problematic in links.
9072 This is the list that is used before handing over to the browser.")
9074 (defun org-link-escape (text &optional table merge)
9075 "Return percent escaped representation of TEXT.
9076 TEXT is a string with the text to escape.
9077 Optional argument TABLE is a list with characters that should be
9078 escaped. When nil, `org-link-escape-chars' is used.
9079 If optional argument MERGE is set, merge TABLE into
9080 `org-link-escape-chars'."
9081 (cond
9082 ((and table merge)
9083 (mapc (lambda (defchr)
9084 (unless (member defchr table)
9085 (setq table (cons defchr table)))) org-link-escape-chars))
9086 ((null table)
9087 (setq table org-link-escape-chars)))
9088 (mapconcat
9089 (lambda (char)
9090 (if (or (member char table)
9091 (and (or (< char 32) (= char 37) (> char 126))
9092 org-url-hexify-p))
9093 (mapconcat (lambda (sequence-element)
9094 (format "%%%.2X" sequence-element))
9095 (or (encode-coding-char char 'utf-8)
9096 (error "Unable to percent escape character: %s"
9097 (char-to-string char))) "")
9098 (char-to-string char))) text ""))
9100 (defun org-link-unescape (str)
9101 "Unhex hexified Unicode strings as returned from the JavaScript function
9102 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9103 (unless (and (null str) (string= "" str))
9104 (let ((pos 0) (case-fold-search t) unhexed)
9105 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9106 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9107 (setq str (replace-match unhexed t t str))
9108 (setq pos (+ pos (length unhexed))))))
9109 str)
9111 (defun org-link-unescape-compound (hex)
9112 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9113 Note: this function also decodes single byte encodings like
9114 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9115 (save-match-data
9116 (let* ((bytes (cdr (split-string hex "%")))
9117 (ret "")
9118 (eat 0)
9119 (sum 0))
9120 (while bytes
9121 (let* ((val (string-to-number (pop bytes) 16))
9122 (shift-xor
9123 (if (= 0 eat)
9124 (cond
9125 ((>= val 252) (cons 6 252))
9126 ((>= val 248) (cons 5 248))
9127 ((>= val 240) (cons 4 240))
9128 ((>= val 224) (cons 3 224))
9129 ((>= val 192) (cons 2 192))
9130 (t (cons 0 0)))
9131 (cons 6 128))))
9132 (if (>= val 192) (setq eat (car shift-xor)))
9133 (setq val (logxor val (cdr shift-xor)))
9134 (setq sum (+ (lsh sum (car shift-xor)) val))
9135 (if (> eat 0) (setq eat (- eat 1)))
9136 (cond
9137 ((= 0 eat) ;multi byte
9138 (setq ret (concat ret (org-char-to-string sum)))
9139 (setq sum 0))
9140 ((not bytes) ; single byte(s)
9141 (setq ret (org-link-unescape-single-byte-sequence hex))))
9142 )) ;; end (while bytes
9143 ret )))
9145 (defun org-link-unescape-single-byte-sequence (hex)
9146 "Unhexify hex-encoded single byte character sequences."
9147 (mapconcat (lambda (byte)
9148 (char-to-string (string-to-number byte 16)))
9149 (cdr (split-string hex "%")) ""))
9151 (defun org-xor (a b)
9152 "Exclusive or."
9153 (if a (not b) b))
9155 (defun org-fixup-message-id-for-http (s)
9156 "Replace special characters in a message id, so it can be used in an http query."
9157 (when (string-match "%" s)
9158 (setq s (mapconcat (lambda (c)
9159 (if (eq c ?%)
9160 "%25"
9161 (char-to-string c)))
9162 s "")))
9163 (while (string-match "<" s)
9164 (setq s (replace-match "%3C" t t s)))
9165 (while (string-match ">" s)
9166 (setq s (replace-match "%3E" t t s)))
9167 (while (string-match "@" s)
9168 (setq s (replace-match "%40" t t s)))
9171 (defun org-link-prettify (link)
9172 "Return a human-readable representation of LINK.
9173 The car of LINK must be a raw link the cdr of LINK must be either
9174 a link description or nil."
9175 (let ((desc (or (cadr link) "<no description>")))
9176 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9177 "<" (car link) ">")))
9179 ;;;###autoload
9180 (defun org-insert-link-global ()
9181 "Insert a link like Org-mode does.
9182 This command can be called in any mode to insert a link in Org-mode syntax."
9183 (interactive)
9184 (org-load-modules-maybe)
9185 (org-run-like-in-org-mode 'org-insert-link))
9187 (defun org-insert-all-links (&optional keep)
9188 "Insert all links in `org-stored-links'."
9189 (interactive "P")
9190 (let ((links (copy-sequence org-stored-links)) l)
9191 (while (setq l (if keep (pop links) (pop org-stored-links)))
9192 (insert "- ")
9193 (org-insert-link nil (car l) (cadr l))
9194 (insert "\n"))))
9196 (defun org-link-fontify-links-to-this-file ()
9197 "Fontify links to the current file in `org-stored-links'."
9198 (let ((f (buffer-file-name)) a b)
9199 (setq a (mapcar (lambda(l)
9200 (let ((ll (car l)))
9201 (when (and (string-match "^file:\\(.+\\)::" ll)
9202 (equal f (expand-file-name (match-string 1 ll))))
9203 ll)))
9204 org-stored-links))
9205 (when (featurep 'org-id)
9206 (setq b (mapcar (lambda(l)
9207 (let ((ll (car l)))
9208 (when (and (string-match "^id:\\(.+\\)$" ll)
9209 (equal f (expand-file-name
9210 (or (org-id-find-id-file
9211 (match-string 1 ll)) ""))))
9212 ll)))
9213 org-stored-links)))
9214 (mapcar (lambda(l)
9215 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9216 (delq nil (append a b)))))
9218 (defvar org-link-links-in-this-file nil)
9219 (defun org-insert-link (&optional complete-file link-location default-description)
9220 "Insert a link. At the prompt, enter the link.
9222 Completion can be used to insert any of the link protocol prefixes like
9223 http or ftp in use.
9225 The history can be used to select a link previously stored with
9226 `org-store-link'. When the empty string is entered (i.e. if you just
9227 press RET at the prompt), the link defaults to the most recently
9228 stored link. As SPC triggers completion in the minibuffer, you need to
9229 use M-SPC or C-q SPC to force the insertion of a space character.
9231 You will also be prompted for a description, and if one is given, it will
9232 be displayed in the buffer instead of the link.
9234 If there is already a link at point, this command will allow you to edit link
9235 and description parts.
9237 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9238 be selected using completion. The path to the file will be relative to the
9239 current directory if the file is in the current directory or a subdirectory.
9240 Otherwise, the link will be the absolute path as completed in the minibuffer
9241 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9242 option `org-link-file-path-type'.
9244 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9245 the current directory or below.
9247 With three \\[universal-argument] prefixes, negate the meaning of
9248 `org-keep-stored-link-after-insertion'.
9250 If `org-make-link-description-function' is non-nil, this function will be
9251 called with the link target, and the result will be the default
9252 link description.
9254 If the LINK-LOCATION parameter is non-nil, this value will be
9255 used as the link location instead of reading one interactively.
9257 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9258 be used as the default description."
9259 (interactive "P")
9260 (let* ((wcf (current-window-configuration))
9261 (region (if (org-region-active-p)
9262 (buffer-substring (region-beginning) (region-end))))
9263 (remove (and region (list (region-beginning) (region-end))))
9264 (desc region)
9265 tmphist ; byte-compile incorrectly complains about this
9266 (link link-location)
9267 (abbrevs org-link-abbrev-alist-local)
9268 entry file all-prefixes auto-desc)
9269 (cond
9270 (link-location) ; specified by arg, just use it.
9271 ((org-in-regexp org-bracket-link-regexp 1)
9272 ;; We do have a link at point, and we are going to edit it.
9273 (setq remove (list (match-beginning 0) (match-end 0)))
9274 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9275 (setq link (read-string "Link: "
9276 (org-link-unescape
9277 (org-match-string-no-properties 1)))))
9278 ((or (org-in-regexp org-angle-link-re)
9279 (org-in-regexp org-plain-link-re))
9280 ;; Convert to bracket link
9281 (setq remove (list (match-beginning 0) (match-end 0))
9282 link (read-string "Link: "
9283 (org-remove-angle-brackets (match-string 0)))))
9284 ((member complete-file '((4) (16)))
9285 ;; Completing read for file names.
9286 (setq link (org-file-complete-link complete-file)))
9288 ;; Read link, with completion for stored links.
9289 (org-link-fontify-links-to-this-file)
9290 (org-switch-to-buffer-other-window "*Org Links*")
9291 (with-current-buffer "*Org Links*"
9292 (erase-buffer)
9293 (insert "Insert a link.
9294 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9295 (when org-stored-links
9296 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9297 (insert (mapconcat 'org-link-prettify
9298 (reverse org-stored-links) "\n")))
9299 (goto-char (point-min)))
9300 (let ((cw (selected-window)))
9301 (select-window (get-buffer-window "*Org Links*" 'visible))
9302 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9303 (unless (pos-visible-in-window-p (point-max))
9304 (org-fit-window-to-buffer))
9305 (and (window-live-p cw) (select-window cw)))
9306 ;; Fake a link history, containing the stored links.
9307 (setq tmphist (append (mapcar 'car org-stored-links)
9308 org-insert-link-history))
9309 (setq all-prefixes (append (mapcar 'car abbrevs)
9310 (mapcar 'car org-link-abbrev-alist)
9311 org-link-types))
9312 (unwind-protect
9313 (progn
9314 (setq link
9315 (let ((org-completion-use-ido nil)
9316 (org-completion-use-iswitchb nil))
9317 (org-completing-read
9318 "Link: "
9319 (append
9320 (mapcar (lambda (x) (list (concat x ":")))
9321 all-prefixes)
9322 (mapcar 'car org-stored-links)
9323 (mapcar 'cadr org-stored-links))
9324 nil nil nil
9325 'tmphist
9326 (caar org-stored-links))))
9327 (if (not (string-match "\\S-" link))
9328 (error "No link selected"))
9329 (mapc (lambda(l)
9330 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9331 org-stored-links)
9332 (if (or (member link all-prefixes)
9333 (and (equal ":" (substring link -1))
9334 (member (substring link 0 -1) all-prefixes)
9335 (setq link (substring link 0 -1))))
9336 (setq link (org-link-try-special-completion link))))
9337 (set-window-configuration wcf)
9338 (kill-buffer "*Org Links*"))
9339 (setq entry (assoc link org-stored-links))
9340 (or entry (push link org-insert-link-history))
9341 (setq desc (or desc (nth 1 entry)))))
9343 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9344 (not org-keep-stored-link-after-insertion))
9345 (setq org-stored-links (delq (assoc link org-stored-links)
9346 org-stored-links)))
9348 (if (string-match org-plain-link-re link)
9349 ;; URL-like link, normalize the use of angular brackets.
9350 (setq link (org-remove-angle-brackets link)))
9352 ;; Check if we are linking to the current file with a search
9353 ;; option If yes, simplify the link by using only the search
9354 ;; option.
9355 (when (and buffer-file-name
9356 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9357 (let* ((path (match-string 1 link))
9358 (case-fold-search nil)
9359 (search (match-string 2 link)))
9360 (save-match-data
9361 (if (equal (file-truename buffer-file-name) (file-truename path))
9362 ;; We are linking to this same file, with a search option
9363 (setq link search)))))
9365 ;; Check if we can/should use a relative path. If yes, simplify the link
9366 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9367 (let* ((type (match-string 1 link))
9368 (path (match-string 2 link))
9369 (origpath path)
9370 (case-fold-search nil))
9371 (cond
9372 ((or (eq org-link-file-path-type 'absolute)
9373 (equal complete-file '(16)))
9374 (setq path (abbreviate-file-name (expand-file-name path))))
9375 ((eq org-link-file-path-type 'noabbrev)
9376 (setq path (expand-file-name path)))
9377 ((eq org-link-file-path-type 'relative)
9378 (setq path (file-relative-name path)))
9380 (save-match-data
9381 (if (string-match (concat "^" (regexp-quote
9382 (expand-file-name
9383 (file-name-as-directory
9384 default-directory))))
9385 (expand-file-name path))
9386 ;; We are linking a file with relative path name.
9387 (setq path (substring (expand-file-name path)
9388 (match-end 0)))
9389 (setq path (abbreviate-file-name (expand-file-name path)))))))
9390 (setq link (concat type path))
9391 (if (equal desc origpath)
9392 (setq desc path))))
9394 (if org-make-link-description-function
9395 (setq desc
9396 (or (condition-case nil
9397 (funcall org-make-link-description-function link desc)
9398 (error (progn (message "Can't get link description from `%s'"
9399 (symbol-name org-make-link-description-function))
9400 (sit-for 2) nil)))
9401 (read-string "Description: " default-description)))
9402 (if default-description (setq desc default-description)
9403 (setq desc (or (and auto-desc desc)
9404 (read-string "Description: " desc)))))
9406 (unless (string-match "\\S-" desc) (setq desc nil))
9407 (if remove (apply 'delete-region remove))
9408 (insert (org-make-link-string link desc))))
9410 (defun org-link-try-special-completion (type)
9411 "If there is completion support for link type TYPE, offer it."
9412 (let ((fun (intern (concat "org-" type "-complete-link"))))
9413 (if (functionp fun)
9414 (funcall fun)
9415 (read-string "Link (no completion support): " (concat type ":")))))
9417 (defun org-file-complete-link (&optional arg)
9418 "Create a file link using completion."
9419 (let (file link)
9420 (setq file (read-file-name "File: "))
9421 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9422 (pwd1 (file-name-as-directory (abbreviate-file-name
9423 (expand-file-name ".")))))
9424 (cond
9425 ((equal arg '(16))
9426 (setq link (concat
9427 "file:"
9428 (abbreviate-file-name (expand-file-name file)))))
9429 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9430 (setq link (concat "file:" (match-string 1 file))))
9431 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9432 (expand-file-name file))
9433 (setq link (concat
9434 "file:" (match-string 1 (expand-file-name file)))))
9435 (t (setq link (concat "file:" file)))))
9436 link))
9438 (defun org-completing-read (&rest args)
9439 "Completing-read with SPACE being a normal character."
9440 (let ((enable-recursive-minibuffers t)
9441 (minibuffer-local-completion-map
9442 (copy-keymap minibuffer-local-completion-map)))
9443 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9444 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9445 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9446 (apply 'org-icompleting-read args)))
9448 (defun org-completing-read-no-i (&rest args)
9449 (let (org-completion-use-ido org-completion-use-iswitchb)
9450 (apply 'org-completing-read args)))
9452 (defun org-iswitchb-completing-read (prompt choices &rest args)
9453 "Use iswitch as a completing-read replacement to choose from choices.
9454 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9455 from."
9456 (let* ((iswitchb-use-virtual-buffers nil)
9457 (iswitchb-make-buflist-hook
9458 (lambda ()
9459 (setq iswitchb-temp-buflist choices))))
9460 (iswitchb-read-buffer prompt)))
9462 (defun org-icompleting-read (&rest args)
9463 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9464 (org-without-partial-completion
9465 (if (and org-completion-use-ido
9466 (fboundp 'ido-completing-read)
9467 (boundp 'ido-mode) ido-mode
9468 (listp (second args)))
9469 (let ((ido-enter-matching-directory nil))
9470 (apply 'ido-completing-read (concat (car args))
9471 (if (consp (car (nth 1 args)))
9472 (mapcar 'car (nth 1 args))
9473 (nth 1 args))
9474 (cddr args)))
9475 (if (and org-completion-use-iswitchb
9476 (boundp 'iswitchb-mode) iswitchb-mode
9477 (listp (second args)))
9478 (apply 'org-iswitchb-completing-read (concat (car args))
9479 (if (consp (car (nth 1 args)))
9480 (mapcar 'car (nth 1 args))
9481 (nth 1 args))
9482 (cddr args))
9483 (apply 'completing-read args)))))
9485 (defun org-extract-attributes (s)
9486 "Extract the attributes cookie from a string and set as text property."
9487 (let (a attr (start 0) key value)
9488 (save-match-data
9489 (when (string-match "{{\\([^}]+\\)}}$" s)
9490 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9491 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9492 (setq key (match-string 1 a) value (match-string 2 a)
9493 start (match-end 0)
9494 attr (plist-put attr (intern key) value))))
9495 (org-add-props s nil 'org-attr attr))
9498 (defun org-extract-attributes-from-string (tag)
9499 (let (key value attr)
9500 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9501 (setq key (match-string 1 tag) value (match-string 2 tag)
9502 tag (replace-match "" t t tag)
9503 attr (plist-put attr (intern key) value)))
9504 (cons tag attr)))
9506 (defun org-attributes-to-string (plist)
9507 "Format a property list into an HTML attribute list."
9508 (let ((s "") key value)
9509 (while plist
9510 (setq key (pop plist) value (pop plist))
9511 (and value
9512 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9515 ;;; Opening/following a link
9517 (defvar org-link-search-failed nil)
9519 (defvar org-open-link-functions nil
9520 "Hook for functions finding a plain text link.
9521 These functions must take a single argument, the link content.
9522 They will be called for links that look like [[link text][description]]
9523 when LINK TEXT does not have a protocol like \"http:\" and does not look
9524 like a filename (e.g. \"./blue.png\").
9526 These functions will be called *before* Org attempts to resolve the
9527 link by doing text searches in the current buffer - so if you want a
9528 link \"[[target]]\" to still find \"<<target>>\", your function should
9529 handle this as a special case.
9531 When the function does handle the link, it must return a non-nil value.
9532 If it decides that it is not responsible for this link, it must return
9533 nil to indicate that that Org-mode can continue with other options
9534 like exact and fuzzy text search.")
9536 (defun org-next-link ()
9537 "Move forward to the next link.
9538 If the link is in hidden text, expose it."
9539 (interactive)
9540 (when (and org-link-search-failed (eq this-command last-command))
9541 (goto-char (point-min))
9542 (message "Link search wrapped back to beginning of buffer"))
9543 (setq org-link-search-failed nil)
9544 (let* ((pos (point))
9545 (ct (org-context))
9546 (a (assoc :link ct)))
9547 (if a (goto-char (nth 2 a)))
9548 (if (re-search-forward org-any-link-re nil t)
9549 (progn
9550 (goto-char (match-beginning 0))
9551 (if (outline-invisible-p) (org-show-context)))
9552 (goto-char pos)
9553 (setq org-link-search-failed t)
9554 (error "No further link found"))))
9556 (defun org-previous-link ()
9557 "Move backward to the previous link.
9558 If the link is in hidden text, expose it."
9559 (interactive)
9560 (when (and org-link-search-failed (eq this-command last-command))
9561 (goto-char (point-max))
9562 (message "Link search wrapped back to end of buffer"))
9563 (setq org-link-search-failed nil)
9564 (let* ((pos (point))
9565 (ct (org-context))
9566 (a (assoc :link ct)))
9567 (if a (goto-char (nth 1 a)))
9568 (if (re-search-backward org-any-link-re nil t)
9569 (progn
9570 (goto-char (match-beginning 0))
9571 (if (outline-invisible-p) (org-show-context)))
9572 (goto-char pos)
9573 (setq org-link-search-failed t)
9574 (error "No further link found"))))
9576 (defun org-translate-link (s)
9577 "Translate a link string if a translation function has been defined."
9578 (if (and org-link-translation-function
9579 (fboundp org-link-translation-function)
9580 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9581 (progn
9582 (setq s (funcall org-link-translation-function
9583 (match-string 1 s) (match-string 2 s)))
9584 (concat (car s) ":" (cdr s)))
9587 (defun org-translate-link-from-planner (type path)
9588 "Translate a link from Emacs Planner syntax so that Org can follow it.
9589 This is still an experimental function, your mileage may vary."
9590 (cond
9591 ((member type '("http" "https" "news" "ftp"))
9592 ;; standard Internet links are the same.
9593 nil)
9594 ((and (equal type "irc") (string-match "^//" path))
9595 ;; Planner has two / at the beginning of an irc link, we have 1.
9596 ;; We should have zero, actually....
9597 (setq path (substring path 1)))
9598 ((and (equal type "lisp") (string-match "^/" path))
9599 ;; Planner has a slash, we do not.
9600 (setq type "elisp" path (substring path 1)))
9601 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9602 ;; A typical message link. Planner has the id after the final slash,
9603 ;; we separate it with a hash mark
9604 (setq path (concat (match-string 1 path) "#"
9605 (org-remove-angle-brackets (match-string 2 path)))))
9607 (cons type path))
9609 (defun org-find-file-at-mouse (ev)
9610 "Open file link or URL at mouse."
9611 (interactive "e")
9612 (mouse-set-point ev)
9613 (org-open-at-point 'in-emacs))
9615 (defun org-open-at-mouse (ev)
9616 "Open file link or URL at mouse.
9617 See the docstring of `org-open-file' for details."
9618 (interactive "e")
9619 (mouse-set-point ev)
9620 (if (eq major-mode 'org-agenda-mode)
9621 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9622 (org-open-at-point))
9624 (defvar org-window-config-before-follow-link nil
9625 "The window configuration before following a link.
9626 This is saved in case the need arises to restore it.")
9628 (defvar org-open-link-marker (make-marker)
9629 "Marker pointing to the location where `org-open-at-point; was called.")
9631 ;;;###autoload
9632 (defun org-open-at-point-global ()
9633 "Follow a link like Org-mode does.
9634 This command can be called in any mode to follow a link that has
9635 Org-mode syntax."
9636 (interactive)
9637 (org-run-like-in-org-mode 'org-open-at-point))
9639 ;;;###autoload
9640 (defun org-open-link-from-string (s &optional arg reference-buffer)
9641 "Open a link in the string S, as if it was in Org-mode."
9642 (interactive "sLink: \nP")
9643 (let ((reference-buffer (or reference-buffer (current-buffer))))
9644 (with-temp-buffer
9645 (let ((org-inhibit-startup (not reference-buffer)))
9646 (org-mode)
9647 (insert s)
9648 (goto-char (point-min))
9649 (when reference-buffer
9650 (setq org-link-abbrev-alist-local
9651 (with-current-buffer reference-buffer
9652 org-link-abbrev-alist-local)))
9653 (org-open-at-point arg reference-buffer)))))
9655 (defvar org-open-at-point-functions nil
9656 "Hook that is run when following a link at point.
9658 Functions in this hook must return t if they identify and follow
9659 a link at point. If they don't find anything interesting at point,
9660 they must return nil.")
9662 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9663 (defun org-open-at-point (&optional arg reference-buffer)
9664 "Open link at or after point.
9665 If there is no link at point, this function will search forward up to
9666 the end of the current line.
9667 Normally, files will be opened by an appropriate application. If the
9668 optional prefix argument ARG is non-nil, Emacs will visit the file.
9669 With a double prefix argument, try to open outside of Emacs, in the
9670 application the system uses for this file type."
9671 (interactive "P")
9672 ;; if in a code block, then open the block's results
9673 (unless (call-interactively #'org-babel-open-src-block-result)
9674 (org-load-modules-maybe)
9675 (move-marker org-open-link-marker (point))
9676 (setq org-window-config-before-follow-link (current-window-configuration))
9677 (org-remove-occur-highlights nil nil t)
9678 (cond
9679 ((and (org-at-heading-p)
9680 (not (org-at-timestamp-p t))
9681 (not (org-in-regexp
9682 (concat org-plain-link-re "\\|"
9683 org-bracket-link-regexp "\\|"
9684 org-angle-link-re "\\|"
9685 "[ \t]:[^ \t\n]+:[ \t]*$")))
9686 (not (get-text-property (point) 'org-linked-text)))
9687 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9688 (lk0 (car lkall))
9689 (lk (if (stringp lk0) (list lk0) lk0))
9690 (lkend (cdr lkall)))
9691 (mapcar (lambda(l)
9692 (search-forward l nil lkend)
9693 (goto-char (match-beginning 0))
9694 (org-open-at-point))
9695 lk))
9696 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9697 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9698 ((and (org-at-timestamp-p t)
9699 (not (org-in-regexp org-bracket-link-regexp)))
9700 (org-follow-timestamp-link))
9701 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9702 (not (org-in-regexp org-any-link-re)))
9703 (org-footnote-action))
9705 (let (type path link line search (pos (point)))
9706 (catch 'match
9707 (save-excursion
9708 (skip-chars-forward "^]\n\r")
9709 (when (org-in-regexp org-bracket-link-regexp 1)
9710 (setq link (org-extract-attributes
9711 (org-link-unescape (org-match-string-no-properties 1))))
9712 (while (string-match " *\n *" link)
9713 (setq link (replace-match " " t t link)))
9714 (setq link (org-link-expand-abbrev link))
9715 (cond
9716 ((or (file-name-absolute-p link)
9717 (string-match "^\\.\\.?/" link))
9718 (setq type "file" path link))
9719 ((string-match org-link-re-with-space3 link)
9720 (setq type (match-string 1 link) path (match-string 2 link)))
9721 ((string-match "^help:+\\(.+\\)" link)
9722 (setq type "help" path (match-string 1 link)))
9723 (t (setq type "thisfile" path link)))
9724 (throw 'match t)))
9726 (when (get-text-property (point) 'org-linked-text)
9727 (setq type "thisfile"
9728 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9729 (1+ (point)) (point))
9730 path (buffer-substring
9731 (or (previous-single-property-change pos 'org-linked-text)
9732 (point-min))
9733 (or (next-single-property-change pos 'org-linked-text)
9734 (point-max))))
9735 (throw 'match t))
9737 (save-excursion
9738 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9739 (when (or (org-in-regexp org-angle-link-re)
9740 (and plinkpos (goto-char (car plinkpos))
9741 (save-match-data (not (looking-back "\\[\\[")))))
9742 (setq type (match-string 1)
9743 path (org-link-unescape (match-string 2)))
9744 (throw 'match t))))
9745 (save-excursion
9746 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9747 (setq type "tags"
9748 path (match-string 1))
9749 (while (string-match ":" path)
9750 (setq path (replace-match "+" t t path)))
9751 (throw 'match t)))
9752 (when (org-in-regexp "<\\([^><\n]+\\)>")
9753 (setq type "tree-match"
9754 path (match-string 1))
9755 (throw 'match t)))
9756 (unless path
9757 (user-error "No link found"))
9759 ;; switch back to reference buffer
9760 ;; needed when if called in a temporary buffer through
9761 ;; org-open-link-from-string
9762 (with-current-buffer (or reference-buffer (current-buffer))
9764 ;; Remove any trailing spaces in path
9765 (if (string-match " +\\'" path)
9766 (setq path (replace-match "" t t path)))
9767 (if (and org-link-translation-function
9768 (fboundp org-link-translation-function))
9769 ;; Check if we need to translate the link
9770 (let ((tmp (funcall org-link-translation-function type path)))
9771 (setq type (car tmp) path (cdr tmp))))
9773 (cond
9775 ((assoc type org-link-protocols)
9776 (funcall (nth 1 (assoc type org-link-protocols)) path))
9778 ((equal type "help")
9779 (let ((f-or-v (intern path)))
9780 (cond ((fboundp f-or-v)
9781 (describe-function f-or-v))
9782 ((boundp f-or-v)
9783 (describe-variable f-or-v))
9784 (t (error "Not a known function or variable")))))
9786 ((equal type "mailto")
9787 (let ((cmd (car org-link-mailto-program))
9788 (args (cdr org-link-mailto-program)) args1
9789 (address path) (subject "") a)
9790 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9791 (setq address (match-string 1 path)
9792 subject (org-link-escape (match-string 2 path))))
9793 (while args
9794 (cond
9795 ((not (stringp (car args))) (push (pop args) args1))
9796 (t (setq a (pop args))
9797 (if (string-match "%a" a)
9798 (setq a (replace-match address t t a)))
9799 (if (string-match "%s" a)
9800 (setq a (replace-match subject t t a)))
9801 (push a args1))))
9802 (apply cmd (nreverse args1))))
9804 ((member type '("http" "https" "ftp" "news"))
9805 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9806 (org-link-escape
9807 path org-link-escape-chars-browser)
9808 path))))
9810 ((string= type "doi")
9811 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9812 (org-link-escape
9813 path org-link-escape-chars-browser)
9814 path))))
9816 ((member type '("message"))
9817 (browse-url (concat type ":" path)))
9819 ((string= type "tags")
9820 (org-tags-view arg path))
9822 ((string= type "tree-match")
9823 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9825 ((string= type "file")
9826 (if (string-match "::\\([0-9]+\\)\\'" path)
9827 (setq line (string-to-number (match-string 1 path))
9828 path (substring path 0 (match-beginning 0)))
9829 (if (string-match "::\\(.+\\)\\'" path)
9830 (setq search (match-string 1 path)
9831 path (substring path 0 (match-beginning 0)))))
9832 (if (string-match "[*?{]" (file-name-nondirectory path))
9833 (dired path)
9834 (org-open-file path arg line search)))
9836 ((string= type "shell")
9837 (let ((buf (generate-new-buffer "*Org Shell Output"))
9838 (cmd path))
9839 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9840 (string-match org-confirm-shell-link-not-regexp cmd))
9841 (not org-confirm-shell-link-function)
9842 (funcall org-confirm-shell-link-function
9843 (format "Execute \"%s\" in shell? "
9844 (org-add-props cmd nil
9845 'face 'org-warning))))
9846 (progn
9847 (message "Executing %s" cmd)
9848 (shell-command cmd buf)
9849 (if (featurep 'midnight)
9850 (setq clean-buffer-list-kill-buffer-names
9851 (cons buf clean-buffer-list-kill-buffer-names))))
9852 (error "Abort"))))
9854 ((string= type "elisp")
9855 (let ((cmd path))
9856 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9857 (string-match org-confirm-elisp-link-not-regexp cmd))
9858 (not org-confirm-elisp-link-function)
9859 (funcall org-confirm-elisp-link-function
9860 (format "Execute \"%s\" as elisp? "
9861 (org-add-props cmd nil
9862 'face 'org-warning))))
9863 (message "%s => %s" cmd
9864 (if (equal (string-to-char cmd) ?\()
9865 (eval (read cmd))
9866 (call-interactively (read cmd))))
9867 (error "Abort"))))
9869 ((and (string= type "thisfile")
9870 (run-hook-with-args-until-success
9871 'org-open-link-functions path)))
9873 ((string= type "thisfile")
9874 (if arg
9875 (switch-to-buffer-other-window
9876 (org-get-buffer-for-internal-link (current-buffer)))
9877 (org-mark-ring-push))
9878 (let ((cmd `(org-link-search
9879 ,path
9880 ,(cond ((equal arg '(4)) ''occur)
9881 ((equal arg '(16)) ''org-occur))
9882 ,pos)))
9883 (condition-case nil (let ((org-link-search-inhibit-query t))
9884 (eval cmd))
9885 (error (progn (widen) (eval cmd))))))
9887 (t (browse-url-at-point)))))))
9888 (move-marker org-open-link-marker nil)
9889 (run-hook-with-args 'org-follow-link-hook)))
9891 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9892 "Offer links in the current entry and return the selected link.
9893 If there is only one link, return it.
9894 If NTH is an integer, return the NTH link found.
9895 If ZERO is a string, check also this string for a link, and if
9896 there is one, return it."
9897 (with-current-buffer buffer
9898 (save-excursion
9899 (save-restriction
9900 (widen)
9901 (goto-char marker)
9902 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9903 "\\(" org-angle-link-re "\\)\\|"
9904 "\\(" org-plain-link-re "\\)"))
9905 (cnt ?0)
9906 (in-emacs (if (integerp nth) nil nth))
9907 have-zero end links link c)
9908 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9909 (push (match-string 0 zero) links)
9910 (setq cnt (1- cnt) have-zero t))
9911 (save-excursion
9912 (org-back-to-heading t)
9913 (setq end (save-excursion (outline-next-heading) (point)))
9914 (while (re-search-forward re end t)
9915 (push (match-string 0) links))
9916 (setq links (org-uniquify (reverse links))))
9917 (cond
9918 ((null links)
9919 (message "No links"))
9920 ((equal (length links) 1)
9921 (setq link (car links)))
9922 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9923 (setq link (nth (if have-zero nth (1- nth)) links)))
9924 (t ; we have to select a link
9925 (save-excursion
9926 (save-window-excursion
9927 (delete-other-windows)
9928 (with-output-to-temp-buffer "*Select Link*"
9929 (mapc (lambda (l)
9930 (if (not (string-match org-bracket-link-regexp l))
9931 (princ (format "[%c] %s\n" (incf cnt)
9932 (org-remove-angle-brackets l)))
9933 (if (match-end 3)
9934 (princ (format "[%c] %s (%s)\n" (incf cnt)
9935 (match-string 3 l) (match-string 1 l)))
9936 (princ (format "[%c] %s\n" (incf cnt)
9937 (match-string 1 l))))))
9938 links))
9939 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9940 (message "Select link to open, RET to open all:")
9941 (setq c (read-char-exclusive))
9942 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9943 (when (equal c ?q) (error "Abort"))
9944 (if (equal c ?\C-m)
9945 (setq link links)
9946 (setq nth (- c ?0))
9947 (if have-zero (setq nth (1+ nth)))
9948 (unless (and (integerp nth) (>= (length links) nth))
9949 (error "Invalid link selection"))
9950 (setq link (nth (1- nth) links)))))
9951 (cons link end))))))
9953 ;; Add special file links that specify the way of opening
9955 (org-add-link-type "file+sys" 'org-open-file-with-system)
9956 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9957 (defun org-open-file-with-system (path)
9958 "Open file at PATH using the system way of opening it."
9959 (org-open-file path 'system))
9960 (defun org-open-file-with-emacs (path)
9961 "Open file at PATH in Emacs."
9962 (org-open-file path 'emacs))
9963 (defun org-remove-file-link-modifiers ()
9964 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9965 (goto-char (point-min))
9966 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9967 (org-if-unprotected
9968 (replace-match "file:" t t))))
9969 (eval-after-load "org-exp"
9970 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9971 'org-remove-file-link-modifiers))
9973 ;;; File search
9975 (defvar org-create-file-search-functions nil
9976 "List of functions to construct the right search string for a file link.
9977 These functions are called in turn with point at the location to
9978 which the link should point.
9980 A function in the hook should first test if it would like to
9981 handle this file type, for example by checking the `major-mode'
9982 or the file extension. If it decides not to handle this file, it
9983 should just return nil to give other functions a chance. If it
9984 does handle the file, it must return the search string to be used
9985 when following the link. The search string will be part of the
9986 file link, given after a double colon, and `org-open-at-point'
9987 will automatically search for it. If special measures must be
9988 taken to make the search successful, another function should be
9989 added to the companion hook `org-execute-file-search-functions',
9990 which see.
9992 A function in this hook may also use `setq' to set the variable
9993 `description' to provide a suggestion for the descriptive text to
9994 be used for this link when it gets inserted into an Org-mode
9995 buffer with \\[org-insert-link].")
9997 (defvar org-execute-file-search-functions nil
9998 "List of functions to execute a file search triggered by a link.
10000 Functions added to this hook must accept a single argument, the
10001 search string that was part of the file link, the part after the
10002 double colon. The function must first check if it would like to
10003 handle this search, for example by checking the `major-mode' or
10004 the file extension. If it decides not to handle this search, it
10005 should just return nil to give other functions a chance. If it
10006 does handle the search, it must return a non-nil value to keep
10007 other functions from trying.
10009 Each function can access the current prefix argument through the
10010 variable `current-prefix-argument'. Note that a single prefix is
10011 used to force opening a link in Emacs, so it may be good to only
10012 use a numeric or double prefix to guide the search function.
10014 In case this is needed, a function in this hook can also restore
10015 the window configuration before `org-open-at-point' was called using:
10017 (set-window-configuration org-window-config-before-follow-link)")
10019 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10020 (defun org-link-search (s &optional type avoid-pos stealth)
10021 "Search for a link search option.
10022 If S is surrounded by forward slashes, it is interpreted as a
10023 regular expression. In org-mode files, this will create an `org-occur'
10024 sparse tree. In ordinary files, `occur' will be used to list matches.
10025 If the current buffer is in `dired-mode', grep will be used to search
10026 in all files. If AVOID-POS is given, ignore matches near that position.
10028 When optional argument STEALTH is non-nil, do not modify
10029 visibility around point, thus ignoring
10030 `org-show-hierarchy-above', `org-show-following-heading' and
10031 `org-show-siblings' variables."
10032 (let ((case-fold-search t)
10033 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10034 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10035 (append '(("") (" ") ("\t") ("\n"))
10036 org-emphasis-alist)
10037 "\\|") "\\)"))
10038 (pos (point))
10039 (pre nil) (post nil)
10040 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10041 (cond
10042 ;; First check if there are any special search functions
10043 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10044 ;; Now try the builtin stuff
10045 ((and (equal (string-to-char s0) ?#)
10046 (> (length s0) 1)
10047 (save-excursion
10048 (goto-char (point-min))
10049 (and
10050 (re-search-forward
10051 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10052 (setq type 'dedicated
10053 pos (match-beginning 0))))
10054 ;; There is an exact target for this
10055 (goto-char pos)
10056 (org-back-to-heading t)))
10057 ((save-excursion
10058 (goto-char (point-min))
10059 (and
10060 (re-search-forward
10061 (concat "<<" (regexp-quote s0) ">>") nil t)
10062 (setq type 'dedicated
10063 pos (match-beginning 0))))
10064 ;; There is an exact target for this
10065 (goto-char pos))
10066 ((save-excursion
10067 (goto-char (point-min))
10068 (and
10069 (re-search-forward
10070 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10071 (setq type 'dedicated pos (match-beginning 0))))
10072 ;; Found an invisible target.
10073 (goto-char pos))
10074 ((save-excursion
10075 (goto-char (point-min))
10076 (and
10077 (re-search-forward
10078 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10079 (setq type 'dedicated pos (match-beginning 0))))
10080 ;; Found an element with a matching #+name affiliated keyword.
10081 (goto-char pos))
10082 ((and (string-match "^(\\(.*\\))$" s0)
10083 (save-excursion
10084 (goto-char (point-min))
10085 (and
10086 (re-search-forward
10087 (concat "[^[]" (regexp-quote
10088 (format org-coderef-label-format
10089 (match-string 1 s0))))
10090 nil t)
10091 (setq type 'dedicated
10092 pos (1+ (match-beginning 0))))))
10093 ;; There is a coderef target for this
10094 (goto-char pos))
10095 ((string-match "^/\\(.*\\)/$" s)
10096 ;; A regular expression
10097 (cond
10098 ((derived-mode-p 'org-mode)
10099 (org-occur (match-string 1 s)))
10100 ;;((eq major-mode 'dired-mode)
10101 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10102 (t (org-do-occur (match-string 1 s)))))
10103 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10104 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10105 (goto-char (point-min))
10106 (cond
10107 ((let (case-fold-search)
10108 (re-search-forward (format org-complex-heading-regexp-format
10109 (regexp-quote s))
10110 nil t))
10111 ;; OK, found a match
10112 (setq type 'dedicated)
10113 (goto-char (match-beginning 0)))
10114 ((and (not org-link-search-inhibit-query)
10115 (eq org-link-search-must-match-exact-headline 'query-to-create)
10116 (y-or-n-p "No match - create this as a new heading? "))
10117 (goto-char (point-max))
10118 (or (bolp) (newline))
10119 (insert "* " s "\n")
10120 (beginning-of-line 0))
10122 (goto-char pos)
10123 (error "No match"))))
10125 ;; A normal search string
10126 (when (equal (string-to-char s) ?*)
10127 ;; Anchor on headlines, post may include tags.
10128 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10129 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10130 s (substring s 1)))
10131 (remove-text-properties
10132 0 (length s)
10133 '(face nil mouse-face nil keymap nil fontified nil) s)
10134 ;; Make a series of regular expressions to find a match
10135 (setq words (org-split-string s "[ \n\r\t]+")
10137 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10138 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10139 "\\)" markers)
10140 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10141 re2a (concat "[ \t\r\n]" re2a_)
10142 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10143 re4 (concat "[^a-zA-Z_]" re4_)
10145 re1 (concat pre re2 post)
10146 re3 (concat pre (if pre re4_ re4) post)
10147 re5 (concat pre ".*" re4)
10148 re2 (concat pre re2)
10149 re2a (concat pre (if pre re2a_ re2a))
10150 re4 (concat pre (if pre re4_ re4))
10151 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10152 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10153 re5 "\\)"
10155 (cond
10156 ((eq type 'org-occur) (org-occur reall))
10157 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10158 (t (goto-char (point-min))
10159 (setq type 'fuzzy)
10160 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10161 (org-search-not-self 1 re1 nil t)
10162 (org-search-not-self 1 re2 nil t)
10163 (org-search-not-self 1 re2a nil t)
10164 (org-search-not-self 1 re3 nil t)
10165 (org-search-not-self 1 re4 nil t)
10166 (org-search-not-self 1 re5 nil t)
10168 (goto-char (match-beginning 1))
10169 (goto-char pos)
10170 (error "No match"))))))
10171 (and (derived-mode-p 'org-mode)
10172 (not stealth)
10173 (org-show-context 'link-search))
10174 type))
10176 (defun org-search-not-self (group &rest args)
10177 "Execute `re-search-forward', but only accept matches that do not
10178 enclose the position of `org-open-link-marker'."
10179 (let ((m org-open-link-marker))
10180 (catch 'exit
10181 (while (apply 're-search-forward args)
10182 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10183 (goto-char (match-end group))
10184 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10185 (> (match-beginning 0) (marker-position m))
10186 (< (match-end 0) (marker-position m)))
10187 (save-match-data
10188 (or (not (org-in-regexp
10189 org-bracket-link-analytic-regexp 1))
10190 (not (match-end 4)) ; no description
10191 (and (<= (match-beginning 4) (point))
10192 (>= (match-end 4) (point))))))
10193 (throw 'exit (point))))))))
10195 (defun org-get-buffer-for-internal-link (buffer)
10196 "Return a buffer to be used for displaying the link target of internal links."
10197 (cond
10198 ((not org-display-internal-link-with-indirect-buffer)
10199 buffer)
10200 ((string-match "(Clone)$" (buffer-name buffer))
10201 (message "Buffer is already a clone, not making another one")
10202 ;; we also do not modify visibility in this case
10203 buffer)
10204 (t ; make a new indirect buffer for displaying the link
10205 (let* ((bn (buffer-name buffer))
10206 (ibn (concat bn "(Clone)"))
10207 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10208 (with-current-buffer ib (org-overview))
10209 ib))))
10211 (defun org-do-occur (regexp &optional cleanup)
10212 "Call the Emacs command `occur'.
10213 If CLEANUP is non-nil, remove the printout of the regular expression
10214 in the *Occur* buffer. This is useful if the regex is long and not useful
10215 to read."
10216 (occur regexp)
10217 (when cleanup
10218 (let ((cwin (selected-window)) win beg end)
10219 (when (setq win (get-buffer-window "*Occur*"))
10220 (select-window win))
10221 (goto-char (point-min))
10222 (when (re-search-forward "match[a-z]+" nil t)
10223 (setq beg (match-end 0))
10224 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10225 (setq end (1- (match-beginning 0)))))
10226 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10227 (goto-char (point-min))
10228 (select-window cwin))))
10230 ;;; The mark ring for links jumps
10232 (defvar org-mark-ring nil
10233 "Mark ring for positions before jumps in Org-mode.")
10234 (defvar org-mark-ring-last-goto nil
10235 "Last position in the mark ring used to go back.")
10236 ;; Fill and close the ring
10237 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10238 (loop for i from 1 to org-mark-ring-length do
10239 (push (make-marker) org-mark-ring))
10240 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10241 org-mark-ring)
10243 (defun org-mark-ring-push (&optional pos buffer)
10244 "Put the current position or POS into the mark ring and rotate it."
10245 (interactive)
10246 (setq pos (or pos (point)))
10247 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10248 (move-marker (car org-mark-ring)
10249 (or pos (point))
10250 (or buffer (current-buffer)))
10251 (message "%s"
10252 (substitute-command-keys
10253 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10255 (defun org-mark-ring-goto (&optional n)
10256 "Jump to the previous position in the mark ring.
10257 With prefix arg N, jump back that many stored positions. When
10258 called several times in succession, walk through the entire ring.
10259 Org-mode commands jumping to a different position in the current file,
10260 or to another Org-mode file, automatically push the old position
10261 onto the ring."
10262 (interactive "p")
10263 (let (p m)
10264 (if (eq last-command this-command)
10265 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10266 (setq p org-mark-ring))
10267 (setq org-mark-ring-last-goto p)
10268 (setq m (car p))
10269 (org-pop-to-buffer-same-window (marker-buffer m))
10270 (goto-char m)
10271 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10273 (defun org-remove-angle-brackets (s)
10274 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10275 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10277 (defun org-add-angle-brackets (s)
10278 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10279 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10281 (defun org-remove-double-quotes (s)
10282 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10283 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10286 ;;; Following specific links
10288 (defun org-follow-timestamp-link ()
10289 "Open an agenda view for the time-stamp date/range at point."
10290 (cond
10291 ((org-at-date-range-p t)
10292 (let ((org-agenda-start-on-weekday)
10293 (t1 (match-string 1))
10294 (t2 (match-string 2)) tt1 tt2)
10295 (setq tt1 (time-to-days (org-time-string-to-time t1))
10296 tt2 (time-to-days (org-time-string-to-time t2)))
10297 (let ((org-agenda-buffer-tmp-name
10298 (format "*Org Agenda(a:%s)"
10299 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10300 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10301 ((org-at-timestamp-p t)
10302 (let ((org-agenda-buffer-tmp-name
10303 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10304 (org-agenda-list nil (time-to-days (org-time-string-to-time
10305 (substring (match-string 1) 0 10)))
10306 1)))
10307 (t (error "This should not happen"))))
10310 ;;; Following file links
10311 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10312 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10313 (declare-function mailcap-mime-info
10314 "mailcap" (string &optional request no-decode))
10315 (defvar org-wait nil)
10316 (defun org-open-file (path &optional in-emacs line search)
10317 "Open the file at PATH.
10318 First, this expands any special file name abbreviations. Then the
10319 configuration variable `org-file-apps' is checked if it contains an
10320 entry for this file type, and if yes, the corresponding command is launched.
10322 If no application is found, Emacs simply visits the file.
10324 With optional prefix argument IN-EMACS, Emacs will visit the file.
10325 With a double \\[universal-argument] \\[universal-argument] \
10326 prefix arg, Org tries to avoid opening in Emacs
10327 and to use an external application to visit the file.
10329 Optional LINE specifies a line to go to, optional SEARCH a string
10330 to search for. If LINE or SEARCH is given, the file will be
10331 opened in Emacs, unless an entry from org-file-apps that makes
10332 use of groups in a regexp matches.
10334 If you want to change the way frames are used when following a
10335 link, please customize `org-link-frame-setup'.
10337 If the file does not exist, an error is thrown."
10338 (let* ((file (if (equal path "")
10339 buffer-file-name
10340 (substitute-in-file-name (expand-file-name path))))
10341 (file-apps (append org-file-apps (org-default-apps)))
10342 (apps (org-remove-if
10343 'org-file-apps-entry-match-against-dlink-p file-apps))
10344 (apps-dlink (org-remove-if-not
10345 'org-file-apps-entry-match-against-dlink-p file-apps))
10346 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10347 (dirp (if remp nil (file-directory-p file)))
10348 (file (if (and dirp org-open-directory-means-index-dot-org)
10349 (concat (file-name-as-directory file) "index.org")
10350 file))
10351 (a-m-a-p (assq 'auto-mode apps))
10352 (dfile (downcase file))
10353 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10354 (link (cond ((and (eq line nil)
10355 (eq search nil))
10356 file)
10357 (line
10358 (concat file "::" (number-to-string line)))
10359 (search
10360 (concat file "::" search))))
10361 (dlink (downcase link))
10362 (old-buffer (current-buffer))
10363 (old-pos (point))
10364 (old-mode major-mode)
10365 ext cmd link-match-data)
10366 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10367 (setq ext (match-string 1 dfile))
10368 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10369 (setq ext (match-string 1 dfile))))
10370 (cond
10371 ((member in-emacs '((16) system))
10372 (setq cmd (cdr (assoc 'system apps))))
10373 (in-emacs (setq cmd 'emacs))
10375 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10376 (and dirp (cdr (assoc 'directory apps)))
10377 ; first, try matching against apps-dlink
10378 ; if we get a match here, store the match data for later
10379 (let ((match (assoc-default dlink apps-dlink
10380 'string-match)))
10381 (if match
10382 (progn (setq link-match-data (match-data))
10383 match)
10384 (progn (setq in-emacs (or in-emacs line search))
10385 nil))) ; if we have no match in apps-dlink,
10386 ; always open the file in emacs if line or search
10387 ; is given (for backwards compatibility)
10388 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10389 'string-match)
10390 (cdr (assoc ext apps))
10391 (cdr (assoc t apps))))))
10392 (when (eq cmd 'system)
10393 (setq cmd (cdr (assoc 'system apps))))
10394 (when (eq cmd 'default)
10395 (setq cmd (cdr (assoc t apps))))
10396 (when (eq cmd 'mailcap)
10397 (require 'mailcap)
10398 (mailcap-parse-mailcaps)
10399 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10400 (command (mailcap-mime-info mime-type)))
10401 (if (stringp command)
10402 (setq cmd command)
10403 (setq cmd 'emacs))))
10404 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10405 (not (file-exists-p file))
10406 (not org-open-non-existing-files))
10407 (error "No such file: %s" file))
10408 (cond
10409 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10410 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10411 (while (string-match "['\"]%s['\"]" cmd)
10412 (setq cmd (replace-match "%s" t t cmd)))
10413 (while (string-match "%s" cmd)
10414 (setq cmd (replace-match
10415 (save-match-data
10416 (shell-quote-argument
10417 (convert-standard-filename file)))
10418 t t cmd)))
10420 ;; Replace "%1", "%2" etc. in command with group matches from regex
10421 (save-match-data
10422 (let ((match-index 1)
10423 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10424 (set-match-data link-match-data)
10425 (while (<= match-index number-of-groups)
10426 (let ((regex (concat "%" (number-to-string match-index)))
10427 (replace-with (match-string match-index dlink)))
10428 (while (string-match regex cmd)
10429 (setq cmd (replace-match replace-with t t cmd))))
10430 (setq match-index (+ match-index 1)))))
10432 (save-window-excursion
10433 (start-process-shell-command cmd nil cmd)
10434 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10436 ((or (stringp cmd)
10437 (eq cmd 'emacs))
10438 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10439 (widen)
10440 (if line (org-goto-line line)
10441 (if search (org-link-search search))))
10442 ((consp cmd)
10443 (let ((file (convert-standard-filename file)))
10444 (save-match-data
10445 (set-match-data link-match-data)
10446 (eval cmd))))
10447 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10448 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10449 (or (not (equal old-buffer (current-buffer)))
10450 (not (equal old-pos (point))))
10451 (org-mark-ring-push old-pos old-buffer))))
10453 (defun org-file-apps-entry-match-against-dlink-p (entry)
10454 "This function returns non-nil if `entry' uses a regular
10455 expression which should be matched against the whole link by
10456 org-open-file.
10458 It assumes that is the case when the entry uses a regular
10459 expression which has at least one grouping construct and the
10460 action is either a lisp form or a command string containing
10461 '%1', i.e. using at least one subexpression match as a
10462 parameter."
10463 (let ((selector (car entry))
10464 (action (cdr entry)))
10465 (if (stringp selector)
10466 (and (> (regexp-opt-depth selector) 0)
10467 (or (and (stringp action)
10468 (string-match "%[0-9]" action))
10469 (consp action)))
10470 nil)))
10472 (defun org-default-apps ()
10473 "Return the default applications for this operating system."
10474 (cond
10475 ((eq system-type 'darwin)
10476 org-file-apps-defaults-macosx)
10477 ((eq system-type 'windows-nt)
10478 org-file-apps-defaults-windowsnt)
10479 (t org-file-apps-defaults-gnu)))
10481 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10482 "Convert extensions to regular expressions in the cars of LIST.
10483 Also, weed out any non-string entries, because the return value is used
10484 only for regexp matching.
10485 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10486 point to the symbol `emacs', indicating that the file should
10487 be opened in Emacs."
10488 (append
10489 (delq nil
10490 (mapcar (lambda (x)
10491 (if (not (stringp (car x)))
10493 (if (string-match "\\W" (car x))
10495 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10496 list))
10497 (if add-auto-mode
10498 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10500 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10501 (defun org-file-remote-p (file)
10502 "Test whether FILE specifies a location on a remote system.
10503 Return non-nil if the location is indeed remote.
10505 For example, the filename \"/user@host:/foo\" specifies a location
10506 on the system \"/user@host:\"."
10507 (cond ((fboundp 'file-remote-p)
10508 (file-remote-p file))
10509 ((fboundp 'tramp-handle-file-remote-p)
10510 (tramp-handle-file-remote-p file))
10511 ((and (boundp 'ange-ftp-name-format)
10512 (string-match (car ange-ftp-name-format) file))
10513 t)))
10516 ;;;; Refiling
10518 (defun org-get-org-file ()
10519 "Read a filename, with default directory `org-directory'."
10520 (let ((default (or org-default-notes-file remember-data-file)))
10521 (read-file-name (format "File name [%s]: " default)
10522 (file-name-as-directory org-directory)
10523 default)))
10525 (defun org-notes-order-reversed-p ()
10526 "Check if the current file should receive notes in reversed order."
10527 (cond
10528 ((not org-reverse-note-order) nil)
10529 ((eq t org-reverse-note-order) t)
10530 ((not (listp org-reverse-note-order)) nil)
10531 (t (catch 'exit
10532 (let ((all org-reverse-note-order)
10533 entry)
10534 (while (setq entry (pop all))
10535 (if (string-match (car entry) buffer-file-name)
10536 (throw 'exit (cdr entry))))
10537 nil)))))
10539 (defvar org-refile-target-table nil
10540 "The list of refile targets, created by `org-refile'.")
10542 (defvar org-agenda-new-buffers nil
10543 "Buffers created to visit agenda files.")
10545 (defvar org-refile-cache nil
10546 "Cache for refile targets.")
10548 (defvar org-refile-markers nil
10549 "All the markers used for caching refile locations.")
10551 (defun org-refile-marker (pos)
10552 "Get a new refile marker, but only if caching is in use."
10553 (if (not org-refile-use-cache)
10555 (let ((m (make-marker)))
10556 (move-marker m pos)
10557 (push m org-refile-markers)
10558 m)))
10560 (defun org-refile-cache-clear ()
10561 "Clear the refile cache and disable all the markers."
10562 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10563 (setq org-refile-markers nil)
10564 (setq org-refile-cache nil)
10565 (message "Refile cache has been cleared"))
10567 (defun org-refile-cache-check-set (set)
10568 "Check if all the markers in the cache still have live buffers."
10569 (let (marker)
10570 (catch 'exit
10571 (while (and set (setq marker (nth 3 (pop set))))
10572 ;; if org-refile-use-outline-path is 'file, marker may be nil
10573 (when (and marker (null (marker-buffer marker)))
10574 (message "not found") (sit-for 3)
10575 (throw 'exit nil)))
10576 t)))
10578 (defun org-refile-cache-put (set &rest identifiers)
10579 "Push the refile targets SET into the cache, under IDENTIFIERS."
10580 (let* ((key (sha1 (prin1-to-string identifiers)))
10581 (entry (assoc key org-refile-cache)))
10582 (if entry
10583 (setcdr entry set)
10584 (push (cons key set) org-refile-cache))))
10586 (defun org-refile-cache-get (&rest identifiers)
10587 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10588 (cond
10589 ((not org-refile-cache) nil)
10590 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10592 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10593 org-refile-cache))))
10594 (and set (org-refile-cache-check-set set) set)))))
10596 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10597 "Produce a table with refile targets."
10598 (let ((case-fold-search nil)
10599 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10600 (entries (or org-refile-targets '((nil . (:level . 1)))))
10601 targets tgs txt re files f desc descre fast-path-p level pos0)
10602 (message "Getting targets...")
10603 (with-current-buffer (or default-buffer (current-buffer))
10604 (while (setq entry (pop entries))
10605 (setq files (car entry) desc (cdr entry))
10606 (setq fast-path-p nil)
10607 (cond
10608 ((null files) (setq files (list (current-buffer))))
10609 ((eq files 'org-agenda-files)
10610 (setq files (org-agenda-files 'unrestricted)))
10611 ((and (symbolp files) (fboundp files))
10612 (setq files (funcall files)))
10613 ((and (symbolp files) (boundp files))
10614 (setq files (symbol-value files))))
10615 (if (stringp files) (setq files (list files)))
10616 (cond
10617 ((eq (car desc) :tag)
10618 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10619 ((eq (car desc) :todo)
10620 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10621 ((eq (car desc) :regexp)
10622 (setq descre (cdr desc)))
10623 ((eq (car desc) :level)
10624 (setq descre (concat "^\\*\\{" (number-to-string
10625 (if org-odd-levels-only
10626 (1- (* 2 (cdr desc)))
10627 (cdr desc)))
10628 "\\}[ \t]")))
10629 ((eq (car desc) :maxlevel)
10630 (setq fast-path-p t)
10631 (setq descre (concat "^\\*\\{1," (number-to-string
10632 (if org-odd-levels-only
10633 (1- (* 2 (cdr desc)))
10634 (cdr desc)))
10635 "\\}[ \t]")))
10636 (t (error "Bad refiling target description %s" desc)))
10637 (while (setq f (pop files))
10638 (with-current-buffer
10639 (if (bufferp f) f (org-get-agenda-file-buffer f))
10641 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10642 (progn
10643 (if (bufferp f) (setq f (buffer-file-name
10644 (buffer-base-buffer f))))
10645 (setq f (and f (expand-file-name f)))
10646 (if (eq org-refile-use-outline-path 'file)
10647 (push (list (file-name-nondirectory f) f nil nil) tgs))
10648 (save-excursion
10649 (save-restriction
10650 (widen)
10651 (goto-char (point-min))
10652 (while (re-search-forward descre nil t)
10653 (goto-char (setq pos0 (point-at-bol)))
10654 (catch 'next
10655 (when org-refile-target-verify-function
10656 (save-match-data
10657 (or (funcall org-refile-target-verify-function)
10658 (throw 'next t))))
10659 (when (and (looking-at org-complex-heading-regexp)
10660 (not (member (match-string 4) excluded-entries))
10661 (match-string 4))
10662 (setq level (org-reduced-level
10663 (- (match-end 1) (match-beginning 1)))
10664 txt (org-link-display-format (match-string 4))
10665 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10666 re (format org-complex-heading-regexp-format
10667 (regexp-quote (match-string 4))))
10668 (when org-refile-use-outline-path
10669 (setq txt (mapconcat
10670 'org-protect-slash
10671 (append
10672 (if (eq org-refile-use-outline-path
10673 'file)
10674 (list (file-name-nondirectory
10675 (buffer-file-name
10676 (buffer-base-buffer))))
10677 (if (eq org-refile-use-outline-path
10678 'full-file-path)
10679 (list (buffer-file-name
10680 (buffer-base-buffer)))))
10681 (org-get-outline-path fast-path-p
10682 level txt)
10683 (list txt))
10684 "/")))
10685 (push (list txt f re (org-refile-marker (point)))
10686 tgs)))
10687 (when (= (point) pos0)
10688 ;; verification function has not moved point
10689 (goto-char (point-at-eol))))))))
10690 (when org-refile-use-cache
10691 (org-refile-cache-put tgs (buffer-file-name) descre))
10692 (setq targets (append tgs targets))
10693 ))))
10694 (message "Getting targets...done")
10695 (nreverse targets)))
10697 (defun org-protect-slash (s)
10698 (while (string-match "/" s)
10699 (setq s (replace-match "\\" t t s)))
10702 (defvar org-olpa (make-vector 20 nil))
10704 (defun org-get-outline-path (&optional fastp level heading)
10705 "Return the outline path to the current entry, as a list.
10707 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10708 routine which makes outline path derivations for an entire file,
10709 avoiding backtracing. Refile target collection makes use of that."
10710 (if fastp
10711 (progn
10712 (if (> level 19)
10713 (error "Outline path failure, more than 19 levels"))
10714 (loop for i from level upto 19 do
10715 (aset org-olpa i nil))
10716 (prog1
10717 (delq nil (append org-olpa nil))
10718 (aset org-olpa level heading)))
10719 (let (rtn case-fold-search)
10720 (save-excursion
10721 (save-restriction
10722 (widen)
10723 (while (org-up-heading-safe)
10724 (when (looking-at org-complex-heading-regexp)
10725 (push (org-match-string-no-properties 4) rtn)))
10726 rtn)))))
10728 (defun org-format-outline-path (path &optional width prefix)
10729 "Format the outline path PATH for display.
10730 Width is the maximum number of characters that is available.
10731 Prefix is a prefix to be included in the returned string,
10732 such as the file name."
10733 (setq width (or width 79))
10734 (if prefix (setq width (- width (length prefix))))
10735 (if (not path)
10736 (or prefix "")
10737 (let* ((nsteps (length path))
10738 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10739 (maxwidth (if (<= total-width width)
10740 10000 ;; everything fits
10741 ;; we need to shorten the level headings
10742 (/ (- width nsteps) nsteps)))
10743 (org-odd-levels-only nil)
10744 (n 0)
10745 (total (1+ (length prefix))))
10746 (setq maxwidth (max maxwidth 10))
10747 (concat prefix
10748 (mapconcat
10749 (lambda (h)
10750 (setq n (1+ n))
10751 (if (and (= n nsteps) (< maxwidth 10000))
10752 (setq maxwidth (- total-width total)))
10753 (if (< (length h) maxwidth)
10754 (progn (setq total (+ total (length h) 1)) h)
10755 (setq h (substring h 0 (- maxwidth 2))
10756 total (+ total maxwidth 1))
10757 (if (string-match "[ \t]+\\'" h)
10758 (setq h (substring h 0 (match-beginning 0))))
10759 (setq h (concat h "..")))
10760 (org-add-props h nil 'face
10761 (nth (% (1- n) org-n-level-faces)
10762 org-level-faces))
10764 path "/")))))
10766 (defun org-display-outline-path (&optional file current)
10767 "Display the current outline path in the echo area."
10768 (interactive "P")
10769 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10770 (case-fold-search nil)
10771 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10772 (if current (setq path (append path
10773 (save-excursion
10774 (org-back-to-heading t)
10775 (if (looking-at org-complex-heading-regexp)
10776 (list (match-string 4)))))))
10777 (message "%s"
10778 (org-format-outline-path
10779 path
10780 (1- (frame-width))
10781 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10783 (defvar org-refile-history nil
10784 "History for refiling operations.")
10786 (defvar org-after-refile-insert-hook nil
10787 "Hook run after `org-refile' has inserted its stuff at the new location.
10788 Note that this is still *before* the stuff will be removed from
10789 the *old* location.")
10791 (defvar org-capture-last-stored-marker)
10792 (defun org-refile (&optional goto default-buffer rfloc)
10793 "Move the entry or entries at point to another heading.
10794 The list of target headings is compiled using the information in
10795 `org-refile-targets', which see.
10797 At the target location, the entry is filed as a subitem of the target
10798 heading. Depending on `org-reverse-note-order', the new subitem will
10799 either be the first or the last subitem.
10801 If there is an active region, all entries in that region will be moved.
10802 However, the region must fulfill the requirement that the first heading
10803 is the first one sets the top-level of the moved text - at most siblings
10804 below it are allowed.
10806 With prefix arg GOTO, the command will only visit the target location
10807 and not actually move anything.
10809 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10810 go to the location where the last refiling operation has put the subtree.
10811 With a prefix argument of `2', refile to the running clock.
10813 RFLOC can be a refile location obtained in a different way.
10815 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10817 If you are using target caching (see `org-refile-use-cache'),
10818 you have to clear the target cache in order to find new targets.
10819 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10820 prefix argument (`C-u C-u C-u C-c C-w')."
10822 (interactive "P")
10823 (if (member goto '(0 (64)))
10824 (org-refile-cache-clear)
10825 (let* ((cbuf (current-buffer))
10826 (regionp (org-region-active-p))
10827 (region-start (and regionp (region-beginning)))
10828 (region-end (and regionp (region-end)))
10829 (region-length (and regionp (- region-end region-start)))
10830 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10831 pos it nbuf file re level reversed)
10832 (setq last-command nil)
10833 (when regionp
10834 (goto-char region-start)
10835 (or (bolp) (goto-char (point-at-bol)))
10836 (setq region-start (point))
10837 (unless (or (org-kill-is-subtree-p
10838 (buffer-substring region-start region-end))
10839 (prog1 org-refile-active-region-within-subtree
10840 (org-toggle-heading)))
10841 (error "The region is not a (sequence of) subtree(s)")))
10842 (if (equal goto '(16))
10843 (org-refile-goto-last-stored)
10844 (when (or
10845 (and (equal goto 2)
10846 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10847 (prog1
10848 (setq it (list (or org-clock-heading "running clock")
10849 (buffer-file-name
10850 (marker-buffer org-clock-hd-marker))
10852 (marker-position org-clock-hd-marker)))
10853 (setq goto nil)))
10854 (setq it (or rfloc
10855 (let (heading-text)
10856 (save-excursion
10857 (unless goto
10858 (org-back-to-heading t)
10859 (setq heading-text
10860 (nth 4 (org-heading-components))))
10861 (org-refile-get-location
10862 (cond (goto "Goto")
10863 (regionp "Refile region to")
10864 (t (concat "Refile subtree \""
10865 heading-text "\" to")))
10866 default-buffer
10867 (and (not (equal '(4) goto))
10868 org-refile-allow-creating-parent-nodes)
10869 goto))))))
10870 (setq file (nth 1 it)
10871 re (nth 2 it)
10872 pos (nth 3 it))
10873 (if (and (not goto)
10875 (equal (buffer-file-name) file)
10876 (if regionp
10877 (and (>= pos region-start)
10878 (<= pos region-end))
10879 (and (>= pos (point))
10880 (< pos (save-excursion
10881 (org-end-of-subtree t t))))))
10882 (error "Cannot refile to position inside the tree or region"))
10884 (setq nbuf (or (find-buffer-visiting file)
10885 (find-file-noselect file)))
10886 (if goto
10887 (progn
10888 (org-pop-to-buffer-same-window nbuf)
10889 (goto-char pos)
10890 (org-show-context 'org-goto))
10891 (if regionp
10892 (progn
10893 (org-kill-new (buffer-substring region-start region-end))
10894 (org-save-markers-in-region region-start region-end))
10895 (org-copy-subtree 1 nil t))
10896 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10897 (find-file-noselect file)))
10898 (setq reversed (org-notes-order-reversed-p))
10899 (save-excursion
10900 (save-restriction
10901 (widen)
10902 (if pos
10903 (progn
10904 (goto-char pos)
10905 (looking-at org-outline-regexp)
10906 (setq level (org-get-valid-level (funcall outline-level) 1))
10907 (goto-char
10908 (if reversed
10909 (or (outline-next-heading) (point-max))
10910 (or (save-excursion (org-get-next-sibling))
10911 (org-end-of-subtree t t)
10912 (point-max)))))
10913 (setq level 1)
10914 (if (not reversed)
10915 (goto-char (point-max))
10916 (goto-char (point-min))
10917 (or (outline-next-heading) (goto-char (point-max)))))
10918 (if (not (bolp)) (newline))
10919 (org-paste-subtree level)
10920 (when org-log-refile
10921 (org-add-log-setup 'refile nil nil 'findpos
10922 org-log-refile)
10923 (unless (eq org-log-refile 'note)
10924 (save-excursion (org-add-log-note))))
10925 (and org-auto-align-tags
10926 (let ((org-loop-over-headlines-in-active-region nil))
10927 (org-set-tags nil t)))
10928 (with-demoted-errors
10929 (bookmark-set "org-refile-last-stored"))
10930 ;; If we are refiling for capture, make sure that the
10931 ;; last-capture pointers point here
10932 (when (org-bound-and-true-p org-refile-for-capture)
10933 (with-demoted-errors
10934 (bookmark-set "org-capture-last-stored-marker"))
10935 (move-marker org-capture-last-stored-marker (point)))
10936 (if (fboundp 'deactivate-mark) (deactivate-mark))
10937 (run-hooks 'org-after-refile-insert-hook))))
10938 (if regionp
10939 (delete-region (point) (+ (point) region-length))
10940 (org-cut-subtree))
10941 (when (featurep 'org-inlinetask)
10942 (org-inlinetask-remove-END-maybe))
10943 (setq org-markers-to-move nil)
10944 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10946 (defun org-refile-goto-last-stored ()
10947 "Go to the location where the last refile was stored."
10948 (interactive)
10949 (bookmark-jump "org-refile-last-stored")
10950 (message "This is the location of the last refile"))
10952 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10953 no-exclude)
10954 "Prompt the user for a refile location, using PROMPT.
10955 PROMPT should not be suffixed with a colon and a space, because
10956 this function appends the default value from
10957 `org-refile-history' automatically, if that is not empty.
10958 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10959 this is used for the GOTO interface."
10960 (let ((org-refile-targets org-refile-targets)
10961 (org-refile-use-outline-path org-refile-use-outline-path)
10962 excluded-entries)
10963 (when (and (derived-mode-p 'org-mode)
10964 (not org-refile-use-cache)
10965 (not no-exclude))
10966 (org-map-tree
10967 (lambda()
10968 (setq excluded-entries
10969 (append excluded-entries (list (org-get-heading t t)))))))
10970 (setq org-refile-target-table
10971 (org-refile-get-targets default-buffer excluded-entries)))
10972 (unless org-refile-target-table
10973 (error "No refile targets"))
10974 (let* ((prompt (concat prompt
10975 (and (car org-refile-history)
10976 (concat " (default " (car org-refile-history) ")"))
10977 ": "))
10978 (cbuf (current-buffer))
10979 (partial-completion-mode nil)
10980 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10981 (cfunc (if (and org-refile-use-outline-path
10982 org-outline-path-complete-in-steps)
10983 'org-olpath-completing-read
10984 'org-icompleting-read))
10985 (extra (if org-refile-use-outline-path "/" ""))
10986 (filename (and cfn (expand-file-name cfn)))
10987 (tbl (mapcar
10988 (lambda (x)
10989 (if (and (not (member org-refile-use-outline-path
10990 '(file full-file-path)))
10991 (not (equal filename (nth 1 x))))
10992 (cons (concat (car x) extra " ("
10993 (file-name-nondirectory (nth 1 x)) ")")
10994 (cdr x))
10995 (cons (concat (car x) extra) (cdr x))))
10996 org-refile-target-table))
10997 (completion-ignore-case t)
10998 pa answ parent-target child parent old-hist)
10999 (setq old-hist org-refile-history)
11000 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11001 nil 'org-refile-history (car org-refile-history)))
11002 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11003 (org-refile-check-position pa)
11004 (if pa
11005 (progn
11006 (when (or (not org-refile-history)
11007 (not (eq old-hist org-refile-history))
11008 (not (equal (car pa) (car org-refile-history))))
11009 (setq org-refile-history
11010 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11011 org-refile-history
11012 (cdr org-refile-history))))
11013 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11014 (pop org-refile-history)))
11016 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11017 (progn
11018 (setq parent (match-string 1 answ)
11019 child (match-string 2 answ))
11020 (setq parent-target (or (assoc parent tbl)
11021 (assoc (concat parent "/") tbl)))
11022 (when (and parent-target
11023 (or (eq new-nodes t)
11024 (and (eq new-nodes 'confirm)
11025 (y-or-n-p (format "Create new node \"%s\"? "
11026 child)))))
11027 (org-refile-new-child parent-target child)))
11028 (error "Invalid target location")))))
11030 (declare-function org-string-nw-p "org-macs" (s))
11031 (defun org-refile-check-position (refile-pointer)
11032 "Check if the refile pointer matches the headline to which it points."
11033 (let* ((file (nth 1 refile-pointer))
11034 (re (nth 2 refile-pointer))
11035 (pos (nth 3 refile-pointer))
11036 buffer)
11037 (if (and (not (markerp pos)) (not file))
11038 (error "Please save the buffer to a file before refiling")
11039 (when (org-string-nw-p re)
11040 (setq buffer (if (markerp pos)
11041 (marker-buffer pos)
11042 (or (find-buffer-visiting file)
11043 (find-file-noselect file))))
11044 (with-current-buffer buffer
11045 (save-excursion
11046 (save-restriction
11047 (widen)
11048 (goto-char pos)
11049 (beginning-of-line 1)
11050 (unless (org-looking-at-p re)
11051 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11053 (defun org-refile-new-child (parent-target child)
11054 "Use refile target PARENT-TARGET to add new CHILD below it."
11055 (unless parent-target
11056 (error "Cannot find parent for new node"))
11057 (let ((file (nth 1 parent-target))
11058 (pos (nth 3 parent-target))
11059 level)
11060 (with-current-buffer (or (find-buffer-visiting file)
11061 (find-file-noselect file))
11062 (save-excursion
11063 (save-restriction
11064 (widen)
11065 (if pos
11066 (goto-char pos)
11067 (goto-char (point-max))
11068 (if (not (bolp)) (newline)))
11069 (when (looking-at org-outline-regexp)
11070 (setq level (funcall outline-level))
11071 (org-end-of-subtree t t))
11072 (org-back-over-empty-lines)
11073 (insert "\n" (make-string
11074 (if pos (org-get-valid-level level 1) 1) ?*)
11075 " " child "\n")
11076 (beginning-of-line 0)
11077 (list (concat (car parent-target) "/" child) file "" (point)))))))
11079 (defun org-olpath-completing-read (prompt collection &rest args)
11080 "Read an outline path like a file name."
11081 (let ((thetable collection)
11082 (org-completion-use-ido nil) ; does not work with ido.
11083 (org-completion-use-iswitchb nil)) ; or iswitchb
11084 (apply
11085 'org-icompleting-read prompt
11086 (lambda (string predicate &optional flag)
11087 (let (rtn r f (l (length string)))
11088 (cond
11089 ((eq flag nil)
11090 ;; try completion
11091 (try-completion string thetable))
11092 ((eq flag t)
11093 ;; all-completions
11094 (setq rtn (all-completions string thetable predicate))
11095 (mapcar
11096 (lambda (x)
11097 (setq r (substring x l))
11098 (if (string-match " ([^)]*)$" x)
11099 (setq f (match-string 0 x))
11100 (setq f ""))
11101 (if (string-match "/" r)
11102 (concat string (substring r 0 (match-end 0)) f)
11104 rtn))
11105 ((eq flag 'lambda)
11106 ;; exact match?
11107 (assoc string thetable)))))
11108 args)))
11110 ;;;; Dynamic blocks
11112 (defun org-find-dblock (name)
11113 "Find the first dynamic block with name NAME in the buffer.
11114 If not found, stay at current position and return nil."
11115 (let ((case-fold-search t) pos)
11116 (save-excursion
11117 (goto-char (point-min))
11118 (setq pos (and (re-search-forward
11119 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11120 (match-beginning 0))))
11121 (if pos (goto-char pos))
11122 pos))
11124 (defconst org-dblock-start-re
11125 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11126 "Matches the start line of a dynamic block, with parameters.")
11128 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11129 "Matches the end of a dynamic block.")
11131 (defun org-create-dblock (plist)
11132 "Create a dynamic block section, with parameters taken from PLIST.
11133 PLIST must contain a :name entry which is used as name of the block."
11134 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11135 (end-of-line 1)
11136 (newline))
11137 (let ((col (current-column))
11138 (name (plist-get plist :name)))
11139 (insert "#+BEGIN: " name)
11140 (while plist
11141 (if (eq (car plist) :name)
11142 (setq plist (cddr plist))
11143 (insert " " (prin1-to-string (pop plist)))))
11144 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11145 (beginning-of-line -2)))
11147 (defun org-prepare-dblock ()
11148 "Prepare dynamic block for refresh.
11149 This empties the block, puts the cursor at the insert position and returns
11150 the property list including an extra property :name with the block name."
11151 (unless (looking-at org-dblock-start-re)
11152 (error "Not at a dynamic block"))
11153 (let* ((begdel (1+ (match-end 0)))
11154 (name (org-no-properties (match-string 1)))
11155 (params (append (list :name name)
11156 (read (concat "(" (match-string 3) ")")))))
11157 (save-excursion
11158 (beginning-of-line 1)
11159 (skip-chars-forward " \t")
11160 (setq params (plist-put params :indentation-column (current-column))))
11161 (unless (re-search-forward org-dblock-end-re nil t)
11162 (error "Dynamic block not terminated"))
11163 (setq params
11164 (append params
11165 (list :content (buffer-substring
11166 begdel (match-beginning 0)))))
11167 (delete-region begdel (match-beginning 0))
11168 (goto-char begdel)
11169 (open-line 1)
11170 params))
11172 (defun org-map-dblocks (&optional command)
11173 "Apply COMMAND to all dynamic blocks in the current buffer.
11174 If COMMAND is not given, use `org-update-dblock'."
11175 (let ((cmd (or command 'org-update-dblock)))
11176 (save-excursion
11177 (goto-char (point-min))
11178 (while (re-search-forward org-dblock-start-re nil t)
11179 (goto-char (match-beginning 0))
11180 (save-excursion
11181 (condition-case nil
11182 (funcall cmd)
11183 (error (message "Error during update of dynamic block"))))
11184 (unless (re-search-forward org-dblock-end-re nil t)
11185 (error "Dynamic block not terminated"))))))
11187 (defun org-dblock-update (&optional arg)
11188 "User command for updating dynamic blocks.
11189 Update the dynamic block at point. With prefix ARG, update all dynamic
11190 blocks in the buffer."
11191 (interactive "P")
11192 (if arg
11193 (org-update-all-dblocks)
11194 (or (looking-at org-dblock-start-re)
11195 (org-beginning-of-dblock))
11196 (org-update-dblock)))
11198 (defun org-update-dblock ()
11199 "Update the dynamic block at point.
11200 This means to empty the block, parse for parameters and then call
11201 the correct writing function."
11202 (interactive)
11203 (save-window-excursion
11204 (let* ((pos (point))
11205 (line (org-current-line))
11206 (params (org-prepare-dblock))
11207 (name (plist-get params :name))
11208 (indent (plist-get params :indentation-column))
11209 (cmd (intern (concat "org-dblock-write:" name))))
11210 (message "Updating dynamic block `%s' at line %d..." name line)
11211 (funcall cmd params)
11212 (message "Updating dynamic block `%s' at line %d...done" name line)
11213 (goto-char pos)
11214 (when (and indent (> indent 0))
11215 (setq indent (make-string indent ?\ ))
11216 (save-excursion
11217 (org-beginning-of-dblock)
11218 (forward-line 1)
11219 (while (not (looking-at org-dblock-end-re))
11220 (insert indent)
11221 (beginning-of-line 2))
11222 (when (looking-at org-dblock-end-re)
11223 (and (looking-at "[ \t]+")
11224 (replace-match ""))
11225 (insert indent)))))))
11227 (defun org-beginning-of-dblock ()
11228 "Find the beginning of the dynamic block at point.
11229 Error if there is no such block at point."
11230 (let ((pos (point))
11231 beg)
11232 (end-of-line 1)
11233 (if (and (re-search-backward org-dblock-start-re nil t)
11234 (setq beg (match-beginning 0))
11235 (re-search-forward org-dblock-end-re nil t)
11236 (> (match-end 0) pos))
11237 (goto-char beg)
11238 (goto-char pos)
11239 (error "Not in a dynamic block"))))
11241 (defun org-update-all-dblocks ()
11242 "Update all dynamic blocks in the buffer.
11243 This function can be used in a hook."
11244 (interactive)
11245 (when (derived-mode-p 'org-mode)
11246 (org-map-dblocks 'org-update-dblock)))
11249 ;;;; Completion
11251 (defconst org-additional-option-like-keywords
11252 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11253 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11254 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11255 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11256 "BEGIN:" "END:"
11257 "ORGTBL" "TBLFM:" "TBLNAME:"
11258 "BEGIN_EXAMPLE" "END_EXAMPLE"
11259 "BEGIN_VERBATIM" "END_VERBATIM"
11260 "BEGIN_QUOTE" "END_QUOTE"
11261 "BEGIN_VERSE" "END_VERSE"
11262 "BEGIN_CENTER" "END_CENTER"
11263 "BEGIN_SRC" "END_SRC"
11264 "BEGIN_RESULT" "END_RESULT"
11265 "BEGIN_lstlisting" "END_lstlisting"
11266 "NAME:" "RESULTS:"
11267 "HEADER:" "HEADERS:"
11268 "COLUMNS:" "PROPERTY:"
11269 "CAPTION:" "LABEL:"
11270 "SETUPFILE:"
11271 "INCLUDE:" "INDEX:"
11272 "BIND:"
11273 "MACRO:"))
11275 (defconst org-options-keywords
11276 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11277 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11278 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11279 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11280 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11281 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11282 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11284 (defconst org-additional-option-like-keywords-for-flyspell
11285 (delete-dups
11286 (split-string
11287 (mapconcat (lambda(k)
11288 (replace-regexp-in-string
11289 "_\\|:" " "
11290 (concat k " " (downcase k) " " (upcase k))))
11291 (append org-options-keywords org-additional-option-like-keywords)
11292 " ")
11293 " +" t)))
11295 (defcustom org-structure-template-alist
11296 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11297 "<src lang=\"?\">\n\n</src>")
11298 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11299 "<example>\n?\n</example>")
11300 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11301 "<quote>\n?\n</quote>")
11302 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11303 "<verse>\n?\n</verse>")
11304 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11305 "<verbatim>\n?\n</verbatim>")
11306 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11307 "<center>\n?\n</center>")
11308 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11309 "<literal style=\"latex\">\n?\n</literal>")
11310 ("L" "#+LaTeX: "
11311 "<literal style=\"latex\">?</literal>")
11312 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11313 "<literal style=\"html\">\n?\n</literal>")
11314 ("H" "#+HTML: "
11315 "<literal style=\"html\">?</literal>")
11316 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11317 ("A" "#+ASCII: ")
11318 ("i" "#+INDEX: ?"
11319 "#+INDEX: ?")
11320 ("I" "#+INCLUDE: %file ?"
11321 "<include file=%file markup=\"?\">"))
11322 "Structure completion elements.
11323 This is a list of abbreviation keys and values. The value gets inserted
11324 if you type `<' followed by the key and then press the completion key,
11325 usually `M-TAB'. %file will be replaced by a file name after prompting
11326 for the file using completion. The cursor will be placed at the position
11327 of the `?` in the template.
11328 There are two templates for each key, the first uses the original Org syntax,
11329 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11330 the default when the /org-mtags.el/ module has been loaded. See also the
11331 variable `org-mtags-prefer-muse-templates'."
11332 :group 'org-completion
11333 :type '(repeat
11334 (string :tag "Key")
11335 (string :tag "Template")
11336 (string :tag "Muse Template")))
11338 (defun org-try-structure-completion ()
11339 "Try to complete a structure template before point.
11340 This looks for strings like \"<e\" on an otherwise empty line and
11341 expands them."
11342 (let ((l (buffer-substring (point-at-bol) (point)))
11344 (when (and (looking-at "[ \t]*$")
11345 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11346 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11347 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11348 (match-beginning 1)) a)
11349 t)))
11351 (defun org-complete-expand-structure-template (start cell)
11352 "Expand a structure template."
11353 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11354 (rpl (nth (if musep 2 1) cell))
11355 (ind ""))
11356 (delete-region start (point))
11357 (when (string-match "\\`#\\+" rpl)
11358 (cond
11359 ((bolp))
11360 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11361 (setq ind (buffer-substring (point-at-bol) (point))))
11362 (t (newline))))
11363 (setq start (point))
11364 (if (string-match "%file" rpl)
11365 (setq rpl (replace-match
11366 (concat
11367 "\""
11368 (save-match-data
11369 (abbreviate-file-name (read-file-name "Include file: ")))
11370 "\"")
11371 t t rpl)))
11372 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11373 (concat "\n" ind)))
11374 (insert rpl)
11375 (if (re-search-backward "\\?" start t) (delete-char 1))))
11377 ;;;; TODO, DEADLINE, Comments
11379 (defun org-toggle-comment ()
11380 "Change the COMMENT state of an entry."
11381 (interactive)
11382 (save-excursion
11383 (org-back-to-heading)
11384 (let (case-fold-search)
11385 (cond
11386 ((looking-at (format org-heading-keyword-regexp-format
11387 org-comment-string))
11388 (goto-char (match-end 1))
11389 (looking-at (concat " +" org-comment-string))
11390 (replace-match "" t t)
11391 (when (eolp) (insert " ")))
11392 ((looking-at org-outline-regexp)
11393 (goto-char (match-end 0))
11394 (insert org-comment-string " "))))))
11396 (defvar org-last-todo-state-is-todo nil
11397 "This is non-nil when the last TODO state change led to a TODO state.
11398 If the last change removed the TODO tag or switched to DONE, then
11399 this is nil.")
11401 (defvar org-setting-tags nil) ; dynamically skipped
11403 (defvar org-todo-setup-filter-hook nil
11404 "Hook for functions that pre-filter todo specs.
11405 Each function takes a todo spec and returns either nil or the spec
11406 transformed into canonical form." )
11408 (defvar org-todo-get-default-hook nil
11409 "Hook for functions that get a default item for todo.
11410 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11411 nil or a string to be used for the todo mark." )
11413 (defvar org-agenda-headline-snapshot-before-repeat)
11415 (defun org-current-effective-time ()
11416 "Return current time adjusted for `org-extend-today-until' variable."
11417 (let* ((ct (org-current-time))
11418 (dct (decode-time ct))
11419 (ct1
11420 (if (and org-use-effective-time
11421 (< (nth 2 dct) org-extend-today-until))
11422 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11423 ct)))
11424 ct1))
11426 (defun org-todo-yesterday (&optional arg)
11427 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11428 (interactive "P")
11429 (if (eq major-mode 'org-agenda-mode)
11430 (apply 'org-agenda-todo-yesterday arg)
11431 (let* ((hour (third (decode-time
11432 (org-current-time))))
11433 (org-extend-today-until (1+ hour)))
11434 (org-todo arg))))
11436 (defun org-todo (&optional arg)
11437 "Change the TODO state of an item.
11438 The state of an item is given by a keyword at the start of the heading,
11439 like
11440 *** TODO Write paper
11441 *** DONE Call mom
11443 The different keywords are specified in the variable `org-todo-keywords'.
11444 By default the available states are \"TODO\" and \"DONE\".
11445 So for this example: when the item starts with TODO, it is changed to DONE.
11446 When it starts with DONE, the DONE is removed. And when neither TODO nor
11447 DONE are present, add TODO at the beginning of the heading.
11449 With \\[universal-argument] prefix arg, use completion to determine the new \
11450 state.
11451 With numeric prefix arg, switch to that state.
11452 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11453 keywords (nextset).
11454 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11455 With a numeric prefix arg of 0, inhibit note taking for the change.
11457 For calling through lisp, arg is also interpreted in the following way:
11458 'none -> empty state
11459 \"\"(empty string) -> switch to empty state
11460 'done -> switch to DONE
11461 'nextset -> switch to the next set of keywords
11462 'previousset -> switch to the previous set of keywords
11463 \"WAITING\" -> switch to the specified keyword, but only if it
11464 really is a member of `org-todo-keywords'."
11465 (interactive "P")
11466 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11467 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11468 'region-start-level 'region))
11469 org-loop-over-headlines-in-active-region)
11470 (org-map-entries
11471 `(org-todo ,arg)
11472 org-loop-over-headlines-in-active-region
11473 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11474 (if (equal arg '(16)) (setq arg 'nextset))
11475 (let ((org-blocker-hook org-blocker-hook)
11476 commentp
11477 case-fold-search)
11478 (when (equal arg '(64))
11479 (setq arg nil org-blocker-hook nil))
11480 (when (and org-blocker-hook
11481 (or org-inhibit-blocking
11482 (org-entry-get nil "NOBLOCKING")))
11483 (setq org-blocker-hook nil))
11484 (save-excursion
11485 (catch 'exit
11486 (org-back-to-heading t)
11487 (when (looking-at (concat "^\\*+ " org-comment-string))
11488 (org-toggle-comment)
11489 (setq commentp t))
11490 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11491 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11492 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11493 (let* ((match-data (match-data))
11494 (startpos (point-at-bol))
11495 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11496 (org-log-done org-log-done)
11497 (org-log-repeat org-log-repeat)
11498 (org-todo-log-states org-todo-log-states)
11499 (org-inhibit-logging
11500 (if (equal arg 0)
11501 (progn (setq arg nil) 'note) org-inhibit-logging))
11502 (this (match-string 1))
11503 (hl-pos (match-beginning 0))
11504 (head (org-get-todo-sequence-head this))
11505 (ass (assoc head org-todo-kwd-alist))
11506 (interpret (nth 1 ass))
11507 (done-word (nth 3 ass))
11508 (final-done-word (nth 4 ass))
11509 (org-last-state (or this ""))
11510 (completion-ignore-case t)
11511 (member (member this org-todo-keywords-1))
11512 (tail (cdr member))
11513 (org-state (cond
11514 ((and org-todo-key-trigger
11515 (or (and (equal arg '(4))
11516 (eq org-use-fast-todo-selection 'prefix))
11517 (and (not arg) org-use-fast-todo-selection
11518 (not (eq org-use-fast-todo-selection
11519 'prefix)))))
11520 ;; Use fast selection
11521 (org-fast-todo-selection))
11522 ((and (equal arg '(4))
11523 (or (not org-use-fast-todo-selection)
11524 (not org-todo-key-trigger)))
11525 ;; Read a state with completion
11526 (org-icompleting-read
11527 "State: " (mapcar (lambda(x) (list x))
11528 org-todo-keywords-1)
11529 nil t))
11530 ((eq arg 'right)
11531 (if this
11532 (if tail (car tail) nil)
11533 (car org-todo-keywords-1)))
11534 ((eq arg 'left)
11535 (if (equal member org-todo-keywords-1)
11537 (if this
11538 (nth (- (length org-todo-keywords-1)
11539 (length tail) 2)
11540 org-todo-keywords-1)
11541 (org-last org-todo-keywords-1))))
11542 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11543 (setq arg nil))) ; hack to fall back to cycling
11544 (arg
11545 ;; user or caller requests a specific state
11546 (cond
11547 ((equal arg "") nil)
11548 ((eq arg 'none) nil)
11549 ((eq arg 'done) (or done-word (car org-done-keywords)))
11550 ((eq arg 'nextset)
11551 (or (car (cdr (member head org-todo-heads)))
11552 (car org-todo-heads)))
11553 ((eq arg 'previousset)
11554 (let ((org-todo-heads (reverse org-todo-heads)))
11555 (or (car (cdr (member head org-todo-heads)))
11556 (car org-todo-heads))))
11557 ((car (member arg org-todo-keywords-1)))
11558 ((stringp arg)
11559 (error "State `%s' not valid in this file" arg))
11560 ((nth (1- (prefix-numeric-value arg))
11561 org-todo-keywords-1))))
11562 ((null member) (or head (car org-todo-keywords-1)))
11563 ((equal this final-done-word) nil) ;; -> make empty
11564 ((null tail) nil) ;; -> first entry
11565 ((memq interpret '(type priority))
11566 (if (eq this-command last-command)
11567 (car tail)
11568 (if (> (length tail) 0)
11569 (or done-word (car org-done-keywords))
11570 nil)))
11572 (car tail))))
11573 (org-state (or
11574 (run-hook-with-args-until-success
11575 'org-todo-get-default-hook org-state org-last-state)
11576 org-state))
11577 (next (if org-state (concat " " org-state " ") " "))
11578 (change-plist (list :type 'todo-state-change :from this :to org-state
11579 :position startpos))
11580 dolog now-done-p)
11581 (when org-blocker-hook
11582 (setq org-last-todo-state-is-todo
11583 (not (member this org-done-keywords)))
11584 (unless (save-excursion
11585 (save-match-data
11586 (org-with-wide-buffer
11587 (run-hook-with-args-until-failure
11588 'org-blocker-hook change-plist))))
11589 (if (org-called-interactively-p 'interactive)
11590 (error "TODO state change from %s to %s blocked" this org-state)
11591 ;; fail silently
11592 (message "TODO state change from %s to %s blocked" this org-state)
11593 (throw 'exit nil))))
11594 (store-match-data match-data)
11595 (replace-match next t t)
11596 (unless (pos-visible-in-window-p hl-pos)
11597 (message "TODO state changed to %s" (org-trim next)))
11598 (unless head
11599 (setq head (org-get-todo-sequence-head org-state)
11600 ass (assoc head org-todo-kwd-alist)
11601 interpret (nth 1 ass)
11602 done-word (nth 3 ass)
11603 final-done-word (nth 4 ass)))
11604 (when (memq arg '(nextset previousset))
11605 (message "Keyword-Set %d/%d: %s"
11606 (- (length org-todo-sets) -1
11607 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11608 (length org-todo-sets)
11609 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11610 (setq org-last-todo-state-is-todo
11611 (not (member org-state org-done-keywords)))
11612 (setq now-done-p (and (member org-state org-done-keywords)
11613 (not (member this org-done-keywords))))
11614 (and logging (org-local-logging logging))
11615 (when (and (or org-todo-log-states org-log-done)
11616 (not (eq org-inhibit-logging t))
11617 (not (memq arg '(nextset previousset))))
11618 ;; we need to look at recording a time and note
11619 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11620 (nth 2 (assoc this org-todo-log-states))))
11621 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11622 (setq dolog 'time))
11623 (when (and org-state
11624 (member org-state org-not-done-keywords)
11625 (not (member this org-not-done-keywords)))
11626 ;; This is now a todo state and was not one before
11627 ;; If there was a CLOSED time stamp, get rid of it.
11628 (org-add-planning-info nil nil 'closed))
11629 (when (and now-done-p org-log-done)
11630 ;; It is now done, and it was not done before
11631 (org-add-planning-info 'closed (org-current-effective-time))
11632 (if (and (not dolog) (eq 'note org-log-done))
11633 (org-add-log-setup 'done org-state this 'findpos 'note)))
11634 (when (and org-state dolog)
11635 ;; This is a non-nil state, and we need to log it
11636 (org-add-log-setup 'state org-state this 'findpos dolog)))
11637 ;; Fixup tag positioning
11638 (org-todo-trigger-tag-changes org-state)
11639 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11640 (when org-provide-todo-statistics
11641 (org-update-parent-todo-statistics))
11642 (run-hooks 'org-after-todo-state-change-hook)
11643 (if (and arg (not (member org-state org-done-keywords)))
11644 (setq head (org-get-todo-sequence-head org-state)))
11645 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11646 ;; Do we need to trigger a repeat?
11647 (when now-done-p
11648 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11649 ;; This is for the agenda, take a snapshot of the headline.
11650 (save-match-data
11651 (setq org-agenda-headline-snapshot-before-repeat
11652 (org-get-heading))))
11653 (org-auto-repeat-maybe org-state))
11654 ;; Fixup cursor location if close to the keyword
11655 (if (and (outline-on-heading-p)
11656 (not (bolp))
11657 (save-excursion (beginning-of-line 1)
11658 (looking-at org-todo-line-regexp))
11659 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11660 (progn
11661 (goto-char (or (match-end 2) (match-end 1)))
11662 (and (looking-at " ") (just-one-space))))
11663 (when org-trigger-hook
11664 (save-excursion
11665 (run-hook-with-args 'org-trigger-hook change-plist)))
11666 (when commentp (org-toggle-comment))))))))
11668 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11669 "Block turning an entry into a TODO, using the hierarchy.
11670 This checks whether the current task should be blocked from state
11671 changes. Such blocking occurs when:
11673 1. The task has children which are not all in a completed state.
11675 2. A task has a parent with the property :ORDERED:, and there
11676 are siblings prior to the current task with incomplete
11677 status.
11679 3. The parent of the task is blocked because it has siblings that should
11680 be done first, or is child of a block grandparent TODO entry."
11682 (if (not org-enforce-todo-dependencies)
11683 t ; if locally turned off don't block
11684 (catch 'dont-block
11685 ;; If this is not a todo state change, or if this entry is already DONE,
11686 ;; do not block
11687 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11688 (member (plist-get change-plist :from)
11689 (cons 'done org-done-keywords))
11690 (member (plist-get change-plist :to)
11691 (cons 'todo org-not-done-keywords))
11692 (not (plist-get change-plist :to)))
11693 (throw 'dont-block t))
11694 ;; If this task has children, and any are undone, it's blocked
11695 (save-excursion
11696 (org-back-to-heading t)
11697 (let ((this-level (funcall outline-level)))
11698 (outline-next-heading)
11699 (let ((child-level (funcall outline-level)))
11700 (while (and (not (eobp))
11701 (> child-level this-level))
11702 ;; this todo has children, check whether they are all
11703 ;; completed
11704 (if (and (not (org-entry-is-done-p))
11705 (org-entry-is-todo-p))
11706 (throw 'dont-block nil))
11707 (outline-next-heading)
11708 (setq child-level (funcall outline-level))))))
11709 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11710 ;; any previous siblings are undone, it's blocked
11711 (save-excursion
11712 (org-back-to-heading t)
11713 (let* ((pos (point))
11714 (parent-pos (and (org-up-heading-safe) (point))))
11715 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11716 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11717 (forward-line 1)
11718 (re-search-forward org-not-done-heading-regexp pos t))
11719 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11720 ;; Search further up the hierarchy, to see if an ancestor is blocked
11721 (while t
11722 (goto-char parent-pos)
11723 (if (not (looking-at org-not-done-heading-regexp))
11724 (throw 'dont-block t)) ; do not block, parent is not a TODO
11725 (setq pos (point))
11726 (setq parent-pos (and (org-up-heading-safe) (point)))
11727 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11728 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11729 (forward-line 1)
11730 (re-search-forward org-not-done-heading-regexp pos t))
11731 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11733 (defcustom org-track-ordered-property-with-tag nil
11734 "Should the ORDERED property also be shown as a tag?
11735 The ORDERED property decides if an entry should require subtasks to be
11736 completed in sequence. Since a property is not very visible, setting
11737 this option means that toggling the ORDERED property with the command
11738 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11739 not relevant for the behavior, but it makes things more visible.
11741 Note that toggling the tag with tags commands will not change the property
11742 and therefore not influence behavior!
11744 This can be t, meaning the tag ORDERED should be used, It can also be a
11745 string to select a different tag for this task."
11746 :group 'org-todo
11747 :type '(choice
11748 (const :tag "No tracking" nil)
11749 (const :tag "Track with ORDERED tag" t)
11750 (string :tag "Use other tag")))
11752 (defun org-toggle-ordered-property ()
11753 "Toggle the ORDERED property of the current entry.
11754 For better visibility, you can track the value of this property with a tag.
11755 See variable `org-track-ordered-property-with-tag'."
11756 (interactive)
11757 (let* ((t1 org-track-ordered-property-with-tag)
11758 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11759 (save-excursion
11760 (org-back-to-heading)
11761 (if (org-entry-get nil "ORDERED")
11762 (progn
11763 (org-delete-property "ORDERED")
11764 (and tag (org-toggle-tag tag 'off))
11765 (message "Subtasks can be completed in arbitrary order"))
11766 (org-entry-put nil "ORDERED" "t")
11767 (and tag (org-toggle-tag tag 'on))
11768 (message "Subtasks must be completed in sequence")))))
11770 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11771 (defun org-block-todo-from-checkboxes (change-plist)
11772 "Block turning an entry into a TODO, using checkboxes.
11773 This checks whether the current task should be blocked from state
11774 changes because there are unchecked boxes in this entry."
11775 (if (not org-enforce-todo-checkbox-dependencies)
11776 t ; if locally turned off don't block
11777 (catch 'dont-block
11778 ;; If this is not a todo state change, or if this entry is already DONE,
11779 ;; do not block
11780 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11781 (member (plist-get change-plist :from)
11782 (cons 'done org-done-keywords))
11783 (member (plist-get change-plist :to)
11784 (cons 'todo org-not-done-keywords))
11785 (not (plist-get change-plist :to)))
11786 (throw 'dont-block t))
11787 ;; If this task has checkboxes that are not checked, it's blocked
11788 (save-excursion
11789 (org-back-to-heading t)
11790 (let ((beg (point)) end)
11791 (outline-next-heading)
11792 (setq end (point))
11793 (goto-char beg)
11794 (if (org-list-search-forward
11795 (concat (org-item-beginning-re)
11796 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11797 "\\[[- ]\\]")
11798 end t)
11799 (progn
11800 (if (boundp 'org-blocked-by-checkboxes)
11801 (setq org-blocked-by-checkboxes t))
11802 (throw 'dont-block nil)))))
11803 t))) ; do not block
11805 (defun org-entry-blocked-p ()
11806 "Is the current entry blocked?"
11807 (org-with-buffer-modified-unmodified
11808 (if (org-entry-get nil "NOBLOCKING")
11809 nil ;; Never block this entry
11810 (not
11811 (run-hook-with-args-until-failure
11812 'org-blocker-hook
11813 (list :type 'todo-state-change
11814 :position (point)
11815 :from 'todo
11816 :to 'done))))))
11818 (defun org-update-statistics-cookies (all)
11819 "Update the statistics cookie, either from TODO or from checkboxes.
11820 This should be called with the cursor in a line with a statistics cookie."
11821 (interactive "P")
11822 (if all
11823 (progn
11824 (org-update-checkbox-count 'all)
11825 (org-map-entries 'org-update-parent-todo-statistics))
11826 (if (not (org-at-heading-p))
11827 (org-update-checkbox-count)
11828 (let ((pos (point-marker))
11829 end l1 l2)
11830 (ignore-errors (org-back-to-heading t))
11831 (if (not (org-at-heading-p))
11832 (org-update-checkbox-count)
11833 (setq l1 (org-outline-level))
11834 (setq end (save-excursion
11835 (outline-next-heading)
11836 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11837 (point)))
11838 (if (and (save-excursion
11839 (re-search-forward
11840 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11841 (not (save-excursion (re-search-forward
11842 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11843 (org-update-checkbox-count)
11844 (if (and l2 (> l2 l1))
11845 (progn
11846 (goto-char end)
11847 (org-update-parent-todo-statistics))
11848 (goto-char pos)
11849 (beginning-of-line 1)
11850 (while (re-search-forward
11851 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11852 (point-at-eol) t)
11853 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11854 (goto-char pos)
11855 (move-marker pos nil)))))
11857 (defvar org-entry-property-inherited-from) ;; defined below
11858 (defun org-update-parent-todo-statistics ()
11859 "Update any statistics cookie in the parent of the current headline.
11860 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11861 the entire subtree and this will travel up the hierarchy and update
11862 statistics everywhere."
11863 (let* ((prop (save-excursion (org-up-heading-safe)
11864 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11865 (recursive (or (not org-hierarchical-todo-statistics)
11866 (and prop (string-match "\\<recursive\\>" prop))))
11867 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11869 (first t)
11870 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11871 level ltoggle l1 new ndel
11872 (cnt-all 0) (cnt-done 0) is-percent kwd
11873 checkbox-beg ov ovs ove cookie-present)
11874 (catch 'exit
11875 (save-excursion
11876 (beginning-of-line 1)
11877 (setq ltoggle (funcall outline-level))
11878 ;; Three situations are to consider:
11880 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11881 ;; to the top-level ancestor on the headline;
11883 ;; 2. If parent has "recursive" property, repeat up to the
11884 ;; headline setting that property, taking inheritance into
11885 ;; account;
11887 ;; 3. Else, move up to direct parent and proceed only once.
11888 (while (and (setq level (org-up-heading-safe))
11889 (or recursive first)
11890 (>= (point) lim))
11891 (setq first nil cookie-present nil)
11892 (unless (and level
11893 (not (string-match
11894 "\\<checkbox\\>"
11895 (downcase (or (org-entry-get nil "COOKIE_DATA")
11896 "")))))
11897 (throw 'exit nil))
11898 (while (re-search-forward box-re (point-at-eol) t)
11899 (setq cnt-all 0 cnt-done 0 cookie-present t)
11900 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11901 (save-match-data
11902 (unless (outline-next-heading) (throw 'exit nil))
11903 (while (and (looking-at org-complex-heading-regexp)
11904 (> (setq l1 (length (match-string 1))) level))
11905 (setq kwd (and (or recursive (= l1 ltoggle))
11906 (match-string 2)))
11907 (if (or (eq org-provide-todo-statistics 'all-headlines)
11908 (and (listp org-provide-todo-statistics)
11909 (or (member kwd org-provide-todo-statistics)
11910 (member kwd org-done-keywords))))
11911 (setq cnt-all (1+ cnt-all))
11912 (if (eq org-provide-todo-statistics t)
11913 (and kwd (setq cnt-all (1+ cnt-all)))))
11914 (and (member kwd org-done-keywords)
11915 (setq cnt-done (1+ cnt-done)))
11916 (outline-next-heading)))
11917 (setq new
11918 (if is-percent
11919 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11920 (format "[%d/%d]" cnt-done cnt-all))
11921 ndel (- (match-end 0) checkbox-beg))
11922 ;; handle overlays when updating cookie from column view
11923 (when (setq ov (car (overlays-at checkbox-beg)))
11924 (setq ovs (overlay-start ov) ove (overlay-end ov))
11925 (delete-overlay ov))
11926 (goto-char checkbox-beg)
11927 (insert new)
11928 (delete-region (point) (+ (point) ndel))
11929 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11930 (when ov (move-overlay ov ovs ove)))
11931 (when cookie-present
11932 (run-hook-with-args 'org-after-todo-statistics-hook
11933 cnt-done (- cnt-all cnt-done))))))
11934 (run-hooks 'org-todo-statistics-hook)))
11936 (defvar org-after-todo-statistics-hook nil
11937 "Hook that is called after a TODO statistics cookie has been updated.
11938 Each function is called with two arguments: the number of not-done entries
11939 and the number of done entries.
11941 For example, the following function, when added to this hook, will switch
11942 an entry to DONE when all children are done, and back to TODO when new
11943 entries are set to a TODO status. Note that this hook is only called
11944 when there is a statistics cookie in the headline!
11946 (defun org-summary-todo (n-done n-not-done)
11947 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11948 (let (org-log-done org-log-states) ; turn off logging
11949 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11952 (defvar org-todo-statistics-hook nil
11953 "Hook that is run whenever Org thinks TODO statistics should be updated.
11954 This hook runs even if there is no statistics cookie present, in which case
11955 `org-after-todo-statistics-hook' would not run.")
11957 (defun org-todo-trigger-tag-changes (state)
11958 "Apply the changes defined in `org-todo-state-tags-triggers'."
11959 (let ((l org-todo-state-tags-triggers)
11960 changes)
11961 (when (or (not state) (equal state ""))
11962 (setq changes (append changes (cdr (assoc "" l)))))
11963 (when (and (stringp state) (> (length state) 0))
11964 (setq changes (append changes (cdr (assoc state l)))))
11965 (when (member state org-not-done-keywords)
11966 (setq changes (append changes (cdr (assoc 'todo l)))))
11967 (when (member state org-done-keywords)
11968 (setq changes (append changes (cdr (assoc 'done l)))))
11969 (dolist (c changes)
11970 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11972 (defun org-local-logging (value)
11973 "Get logging settings from a property VALUE."
11974 (let* (words w a)
11975 ;; directly set the variables, they are already local.
11976 (setq org-log-done nil
11977 org-log-repeat nil
11978 org-todo-log-states nil)
11979 (setq words (org-split-string value))
11980 (while (setq w (pop words))
11981 (cond
11982 ((setq a (assoc w org-startup-options))
11983 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11984 (set (nth 1 a) (nth 2 a))))
11985 ((setq a (org-extract-log-state-settings w))
11986 (and (member (car a) org-todo-keywords-1)
11987 (push a org-todo-log-states)))))))
11989 (defun org-get-todo-sequence-head (kwd)
11990 "Return the head of the TODO sequence to which KWD belongs.
11991 If KWD is not set, check if there is a text property remembering the
11992 right sequence."
11993 (let (p)
11994 (cond
11995 ((not kwd)
11996 (or (get-text-property (point-at-bol) 'org-todo-head)
11997 (progn
11998 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11999 nil (point-at-eol)))
12000 (get-text-property p 'org-todo-head))))
12001 ((not (member kwd org-todo-keywords-1))
12002 (car org-todo-keywords-1))
12003 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12005 (defun org-fast-todo-selection ()
12006 "Fast TODO keyword selection with single keys.
12007 Returns the new TODO keyword, or nil if no state change should occur."
12008 (let* ((fulltable org-todo-key-alist)
12009 (done-keywords org-done-keywords) ;; needed for the faces.
12010 (maxlen (apply 'max (mapcar
12011 (lambda (x)
12012 (if (stringp (car x)) (string-width (car x)) 0))
12013 fulltable)))
12014 (expert nil)
12015 (fwidth (+ maxlen 3 1 3))
12016 (ncol (/ (- (window-width) 4) fwidth))
12017 tg cnt e c tbl
12018 groups ingroup)
12019 (save-excursion
12020 (save-window-excursion
12021 (if expert
12022 (set-buffer (get-buffer-create " *Org todo*"))
12023 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12024 (erase-buffer)
12025 (org-set-local 'org-done-keywords done-keywords)
12026 (setq tbl fulltable cnt 0)
12027 (while (setq e (pop tbl))
12028 (cond
12029 ((equal e '(:startgroup))
12030 (push '() groups) (setq ingroup t)
12031 (when (not (= cnt 0))
12032 (setq cnt 0)
12033 (insert "\n"))
12034 (insert "{ "))
12035 ((equal e '(:endgroup))
12036 (setq ingroup nil cnt 0)
12037 (insert "}\n"))
12038 ((equal e '(:newline))
12039 (when (not (= cnt 0))
12040 (setq cnt 0)
12041 (insert "\n")
12042 (setq e (car tbl))
12043 (while (equal (car tbl) '(:newline))
12044 (insert "\n")
12045 (setq tbl (cdr tbl)))))
12047 (setq tg (car e) c (cdr e))
12048 (if ingroup (push tg (car groups)))
12049 (setq tg (org-add-props tg nil 'face
12050 (org-get-todo-face tg)))
12051 (if (and (= cnt 0) (not ingroup)) (insert " "))
12052 (insert "[" c "] " tg (make-string
12053 (- fwidth 4 (length tg)) ?\ ))
12054 (when (= (setq cnt (1+ cnt)) ncol)
12055 (insert "\n")
12056 (if ingroup (insert " "))
12057 (setq cnt 0)))))
12058 (insert "\n")
12059 (goto-char (point-min))
12060 (if (not expert) (org-fit-window-to-buffer))
12061 (message "[a-z..]:Set [SPC]:clear")
12062 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12063 (cond
12064 ((or (= c ?\C-g)
12065 (and (= c ?q) (not (rassoc c fulltable))))
12066 (setq quit-flag t))
12067 ((= c ?\ ) nil)
12068 ((setq e (rassoc c fulltable) tg (car e))
12070 (t (setq quit-flag t)))))))
12072 (defun org-entry-is-todo-p ()
12073 (member (org-get-todo-state) org-not-done-keywords))
12075 (defun org-entry-is-done-p ()
12076 (member (org-get-todo-state) org-done-keywords))
12078 (defun org-get-todo-state ()
12079 (save-excursion
12080 (org-back-to-heading t)
12081 (and (looking-at org-todo-line-regexp)
12082 (match-end 2)
12083 (match-string 2))))
12085 (defun org-at-date-range-p (&optional inactive-ok)
12086 "Is the cursor inside a date range?"
12087 (interactive)
12088 (save-excursion
12089 (catch 'exit
12090 (let ((pos (point)))
12091 (skip-chars-backward "^[<\r\n")
12092 (skip-chars-backward "<[")
12093 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12094 (>= (match-end 0) pos)
12095 (throw 'exit t))
12096 (skip-chars-backward "^<[\r\n")
12097 (skip-chars-backward "<[")
12098 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12099 (>= (match-end 0) pos)
12100 (throw 'exit t)))
12101 nil)))
12103 (defun org-get-repeat (&optional tagline)
12104 "Check if there is a deadline/schedule with repeater in this entry."
12105 (save-match-data
12106 (save-excursion
12107 (org-back-to-heading t)
12108 (and (re-search-forward (if tagline
12109 (concat tagline "\\s-*" org-repeat-re)
12110 org-repeat-re)
12111 (org-entry-end-position) t)
12112 (match-string-no-properties 1)))))
12114 (defvar org-last-changed-timestamp)
12115 (defvar org-last-inserted-timestamp)
12116 (defvar org-log-post-message)
12117 (defvar org-log-note-purpose)
12118 (defvar org-log-note-how)
12119 (defvar org-log-note-extra)
12120 (defun org-auto-repeat-maybe (done-word)
12121 "Check if the current headline contains a repeated deadline/schedule.
12122 If yes, set TODO state back to what it was and change the base date
12123 of repeating deadline/scheduled time stamps to new date.
12124 This function is run automatically after each state change to a DONE state."
12125 ;; last-state is dynamically scoped into this function
12126 (let* ((repeat (org-get-repeat))
12127 (aa (assoc org-last-state org-todo-kwd-alist))
12128 (interpret (nth 1 aa))
12129 (head (nth 2 aa))
12130 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12131 (msg "Entry repeats: ")
12132 (org-log-done nil)
12133 (org-todo-log-states nil)
12134 re type n what ts time to-state)
12135 (when repeat
12136 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12137 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12138 org-todo-repeat-to-state))
12139 (unless (and to-state (member to-state org-todo-keywords-1))
12140 (setq to-state (if (eq interpret 'type) org-last-state head)))
12141 (org-todo to-state)
12142 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12143 (org-entry-put nil "LAST_REPEAT" (format-time-string
12144 (org-time-stamp-format t t))))
12145 (when org-log-repeat
12146 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12147 (memq 'org-add-log-note post-command-hook))
12148 ;; OK, we are already setup for some record
12149 (if (eq org-log-repeat 'note)
12150 ;; make sure we take a note, not only a time stamp
12151 (setq org-log-note-how 'note))
12152 ;; Set up for taking a record
12153 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12154 org-last-state
12155 'findpos org-log-repeat)))
12156 (org-back-to-heading t)
12157 (org-add-planning-info nil nil 'closed)
12158 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12159 org-deadline-time-regexp "\\)\\|\\("
12160 org-ts-regexp "\\)"))
12161 (while (re-search-forward
12162 re (save-excursion (outline-next-heading) (point)) t)
12163 (setq type (if (match-end 1) org-scheduled-string
12164 (if (match-end 3) org-deadline-string "Plain:"))
12165 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12166 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12167 (setq n (string-to-number (match-string 2 ts))
12168 what (match-string 3 ts))
12169 (if (equal what "w") (setq n (* n 7) what "d"))
12170 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12171 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12172 ;; Preparation, see if we need to modify the start date for the change
12173 (when (match-end 1)
12174 (setq time (save-match-data (org-time-string-to-time ts)))
12175 (cond
12176 ((equal (match-string 1 ts) ".")
12177 ;; Shift starting date to today
12178 (org-timestamp-change
12179 (- (org-today) (time-to-days time))
12180 'day))
12181 ((equal (match-string 1 ts) "+")
12182 (let ((nshiftmax 10) (nshift 0))
12183 (while (or (= nshift 0)
12184 (<= (time-to-days time)
12185 (time-to-days (current-time))))
12186 (when (= (incf nshift) nshiftmax)
12187 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12188 (error "Abort")))
12189 (org-timestamp-change n (cdr (assoc what whata)))
12190 (org-at-timestamp-p t)
12191 (setq ts (match-string 1))
12192 (setq time (save-match-data (org-time-string-to-time ts)))))
12193 (org-timestamp-change (- n) (cdr (assoc what whata)))
12194 ;; rematch, so that we have everything in place for the real shift
12195 (org-at-timestamp-p t)
12196 (setq ts (match-string 1))
12197 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12198 (org-timestamp-change n (cdr (assoc what whata)))
12199 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12200 (setq org-log-post-message msg)
12201 (message "%s" msg))))
12203 (defun org-show-todo-tree (arg)
12204 "Make a compact tree which shows all headlines marked with TODO.
12205 The tree will show the lines where the regexp matches, and all higher
12206 headlines above the match.
12207 With a \\[universal-argument] prefix, prompt for a regexp to match.
12208 With a numeric prefix N, construct a sparse tree for the Nth element
12209 of `org-todo-keywords-1'."
12210 (interactive "P")
12211 (let ((case-fold-search nil)
12212 (kwd-re
12213 (cond ((null arg) org-not-done-regexp)
12214 ((equal arg '(4))
12215 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12216 (mapcar 'list org-todo-keywords-1))))
12217 (concat "\\("
12218 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12219 "\\)\\>")))
12220 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12221 (regexp-quote (nth (1- (prefix-numeric-value arg))
12222 org-todo-keywords-1)))
12223 (t (error "Invalid prefix argument: %s" arg)))))
12224 (message "%d TODO entries found"
12225 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12227 (defun org-deadline (&optional remove time)
12228 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12229 With argument REMOVE, remove any deadline from the item.
12230 With argument TIME, set the deadline at the corresponding date. TIME
12231 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12232 (interactive "P")
12233 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12234 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12235 'region-start-level 'region))
12236 org-loop-over-headlines-in-active-region)
12237 (org-map-entries
12238 `(org-deadline ',remove ,time)
12239 org-loop-over-headlines-in-active-region
12240 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12241 (let* ((old-date (org-entry-get nil "DEADLINE"))
12242 (repeater (and old-date
12243 (string-match
12244 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12245 old-date)
12246 (match-string 1 old-date))))
12247 (if remove
12248 (progn
12249 (when (and old-date org-log-redeadline)
12250 (org-add-log-setup 'deldeadline nil old-date 'findpos
12251 org-log-redeadline))
12252 (org-remove-timestamp-with-keyword org-deadline-string)
12253 (message "Item no longer has a deadline."))
12254 (org-add-planning-info 'deadline time 'closed)
12255 (when (and old-date org-log-redeadline
12256 (not (equal old-date
12257 (substring org-last-inserted-timestamp 1 -1))))
12258 (org-add-log-setup 'redeadline nil old-date 'findpos
12259 org-log-redeadline))
12260 (when repeater
12261 (save-excursion
12262 (org-back-to-heading t)
12263 (when (re-search-forward (concat org-deadline-string " "
12264 org-last-inserted-timestamp)
12265 (save-excursion
12266 (outline-next-heading) (point)) t)
12267 (goto-char (1- (match-end 0)))
12268 (insert " " repeater)
12269 (setq org-last-inserted-timestamp
12270 (concat (substring org-last-inserted-timestamp 0 -1)
12271 " " repeater
12272 (substring org-last-inserted-timestamp -1))))))
12273 (message "Deadline on %s" org-last-inserted-timestamp)))))
12275 (defun org-schedule (&optional remove time)
12276 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12277 With argument REMOVE, remove any scheduling date from the item.
12278 With argument TIME, scheduled at the corresponding date. TIME can
12279 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12280 (interactive "P")
12281 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12282 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12283 'region-start-level 'region))
12284 org-loop-over-headlines-in-active-region)
12285 (org-map-entries
12286 `(org-schedule ',remove ,time)
12287 org-loop-over-headlines-in-active-region
12288 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12289 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12290 (repeater (and old-date
12291 (string-match
12292 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12293 old-date)
12294 (match-string 1 old-date))))
12295 (if remove
12296 (progn
12297 (when (and old-date org-log-reschedule)
12298 (org-add-log-setup 'delschedule nil old-date 'findpos
12299 org-log-reschedule))
12300 (org-remove-timestamp-with-keyword org-scheduled-string)
12301 (message "Item is no longer scheduled."))
12302 (org-add-planning-info 'scheduled time 'closed)
12303 (when (and old-date org-log-reschedule
12304 (not (equal old-date
12305 (substring org-last-inserted-timestamp 1 -1))))
12306 (org-add-log-setup 'reschedule nil old-date 'findpos
12307 org-log-reschedule))
12308 (when repeater
12309 (save-excursion
12310 (org-back-to-heading t)
12311 (when (re-search-forward (concat org-scheduled-string " "
12312 org-last-inserted-timestamp)
12313 (save-excursion
12314 (outline-next-heading) (point)) t)
12315 (goto-char (1- (match-end 0)))
12316 (insert " " repeater)
12317 (setq org-last-inserted-timestamp
12318 (concat (substring org-last-inserted-timestamp 0 -1)
12319 " " repeater
12320 (substring org-last-inserted-timestamp -1))))))
12321 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12323 (defun org-get-scheduled-time (pom &optional inherit)
12324 "Get the scheduled time as a time tuple, of a format suitable
12325 for calling org-schedule with, or if there is no scheduling,
12326 returns nil."
12327 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12328 (when time
12329 (apply 'encode-time (org-parse-time-string time)))))
12331 (defun org-get-deadline-time (pom &optional inherit)
12332 "Get the deadline as a time tuple, of a format suitable for
12333 calling org-deadline with, or if there is no scheduling, returns
12334 nil."
12335 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12336 (when time
12337 (apply 'encode-time (org-parse-time-string time)))))
12339 (defun org-remove-timestamp-with-keyword (keyword)
12340 "Remove all time stamps with KEYWORD in the current entry."
12341 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12342 beg)
12343 (save-excursion
12344 (org-back-to-heading t)
12345 (setq beg (point))
12346 (outline-next-heading)
12347 (while (re-search-backward re beg t)
12348 (replace-match "")
12349 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12350 (equal (char-before) ?\ ))
12351 (backward-delete-char 1)
12352 (if (string-match "^[ \t]*$" (buffer-substring
12353 (point-at-bol) (point-at-eol)))
12354 (delete-region (point-at-bol)
12355 (min (point-max) (1+ (point-at-eol))))))))))
12357 (defun org-add-planning-info (what &optional time &rest remove)
12358 "Insert new timestamp with keyword in the line directly after the headline.
12359 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12360 If non is given, the user is prompted for a date.
12361 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12362 be removed."
12363 (interactive)
12364 (let (org-time-was-given org-end-time-was-given ts
12365 end default-time default-input)
12367 (catch 'exit
12368 (when (and (memq what '(scheduled deadline))
12369 (or (not time)
12370 (and (stringp time)
12371 (string-match "^[-+]+[0-9]" time))))
12372 ;; Try to get a default date/time from existing timestamp
12373 (save-excursion
12374 (org-back-to-heading t)
12375 (setq end (save-excursion (outline-next-heading) (point)))
12376 (when (re-search-forward (if (eq what 'scheduled)
12377 org-scheduled-time-regexp
12378 org-deadline-time-regexp)
12379 end t)
12380 (setq ts (match-string 1)
12381 default-time
12382 (apply 'encode-time (org-parse-time-string ts))
12383 default-input (and ts (org-get-compact-tod ts))))))
12384 (when what
12385 (setq time
12386 (if (stringp time)
12387 ;; This is a string (relative or absolute), set proper date
12388 (apply 'encode-time
12389 (org-read-date-analyze
12390 time default-time (decode-time default-time)))
12391 ;; If necessary, get the time from the user
12392 (or time (org-read-date nil 'to-time nil nil
12393 default-time default-input)))))
12395 (when (and org-insert-labeled-timestamps-at-point
12396 (member what '(scheduled deadline)))
12397 (insert
12398 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12399 (org-insert-time-stamp time org-time-was-given
12400 nil nil nil (list org-end-time-was-given))
12401 (setq what nil))
12402 (save-excursion
12403 (save-restriction
12404 (let (col list elt ts buffer-invisibility-spec)
12405 (org-back-to-heading t)
12406 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12407 (goto-char (match-end 1))
12408 (setq col (current-column))
12409 (goto-char (match-end 0))
12410 (if (eobp) (insert "\n") (forward-char 1))
12411 (when (and (not what)
12412 (not (looking-at
12413 (concat "[ \t]*"
12414 org-keyword-time-not-clock-regexp))))
12415 ;; Nothing to add, nothing to remove...... :-)
12416 (throw 'exit nil))
12417 (if (and (not (looking-at org-outline-regexp))
12418 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12419 "[^\r\n]*"))
12420 (not (equal (match-string 1) org-clock-string)))
12421 (narrow-to-region (match-beginning 0) (match-end 0))
12422 (insert-before-markers "\n")
12423 (backward-char 1)
12424 (narrow-to-region (point) (point))
12425 (and org-adapt-indentation (org-indent-to-column col)))
12426 ;; Check if we have to remove something.
12427 (setq list (cons what remove))
12428 (while list
12429 (setq elt (pop list))
12430 (when (or (and (eq elt 'scheduled)
12431 (re-search-forward org-scheduled-time-regexp nil t))
12432 (and (eq elt 'deadline)
12433 (re-search-forward org-deadline-time-regexp nil t))
12434 (and (eq elt 'closed)
12435 (re-search-forward org-closed-time-regexp nil t)))
12436 (replace-match "")
12437 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12438 (and (looking-at "[ \t]+") (replace-match ""))
12439 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12440 (when what
12441 (insert
12442 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12443 (cond ((eq what 'scheduled) org-scheduled-string)
12444 ((eq what 'deadline) org-deadline-string)
12445 ((eq what 'closed) org-closed-string))
12446 " ")
12447 (setq ts (org-insert-time-stamp
12448 time
12449 (or org-time-was-given
12450 (and (eq what 'closed) org-log-done-with-time))
12451 (eq what 'closed)
12452 nil nil (list org-end-time-was-given)))
12453 (insert
12454 (if (not (or (bolp) (eq (char-before) ?\ )
12455 (memq (char-after) '(32 10))
12456 (eobp))) " " ""))
12457 (end-of-line 1))
12458 (goto-char (point-min))
12459 (widen)
12460 (if (and (looking-at "[ \t]*\n")
12461 (equal (char-before) ?\n))
12462 (delete-region (1- (point)) (point-at-eol)))
12463 ts))))))
12465 (defvar org-log-note-marker (make-marker))
12466 (defvar org-log-note-purpose nil)
12467 (defvar org-log-note-state nil)
12468 (defvar org-log-note-previous-state nil)
12469 (defvar org-log-note-how nil)
12470 (defvar org-log-note-extra nil)
12471 (defvar org-log-note-window-configuration nil)
12472 (defvar org-log-note-return-to (make-marker))
12473 (defvar org-log-note-effective-time nil
12474 "Remembered current time so that dynamically scoped
12475 `org-extend-today-until' affects tha timestamps in state change
12476 log")
12478 (defvar org-log-post-message nil
12479 "Message to be displayed after a log note has been stored.
12480 The auto-repeater uses this.")
12482 (defun org-add-note ()
12483 "Add a note to the current entry.
12484 This is done in the same way as adding a state change note."
12485 (interactive)
12486 (org-add-log-setup 'note nil nil 'findpos nil))
12488 (defvar org-property-end-re)
12489 (defun org-add-log-setup (&optional purpose state prev-state
12490 findpos how extra)
12491 "Set up the post command hook to take a note.
12492 If this is about to TODO state change, the new state is expected in STATE.
12493 When FINDPOS is non-nil, find the correct position for the note in
12494 the current entry. If not, assume that it can be inserted at point.
12495 HOW is an indicator what kind of note should be created.
12496 EXTRA is additional text that will be inserted into the notes buffer."
12497 (let* ((org-log-into-drawer (org-log-into-drawer))
12498 (drawer (cond ((stringp org-log-into-drawer)
12499 org-log-into-drawer)
12500 (org-log-into-drawer "LOGBOOK"))))
12501 (save-restriction
12502 (save-excursion
12503 (when findpos
12504 (org-back-to-heading t)
12505 (narrow-to-region (point) (save-excursion
12506 (outline-next-heading) (point)))
12507 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12508 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12509 "[^\r\n]*\\)?"))
12510 (goto-char (match-end 0))
12511 (cond
12512 (drawer
12513 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12514 nil t)
12515 (progn
12516 (goto-char (match-end 0))
12517 (or org-log-states-order-reversed
12518 (and (re-search-forward org-property-end-re nil t)
12519 (goto-char (1- (match-beginning 0))))))
12520 (insert "\n:" drawer ":\n:END:")
12521 (beginning-of-line 0)
12522 (org-indent-line)
12523 (beginning-of-line 2)
12524 (org-indent-line)
12525 (end-of-line 0)))
12526 ((and org-log-state-notes-insert-after-drawers
12527 (save-excursion
12528 (forward-line) (looking-at org-drawer-regexp)))
12529 (forward-line)
12530 (while (looking-at org-drawer-regexp)
12531 (goto-char (match-end 0))
12532 (re-search-forward org-property-end-re (point-max) t)
12533 (forward-line))
12534 (forward-line -1)))
12535 (unless org-log-states-order-reversed
12536 (and (= (char-after) ?\n) (forward-char 1))
12537 (org-skip-over-state-notes)
12538 (skip-chars-backward " \t\n\r")))
12539 (move-marker org-log-note-marker (point))
12540 (setq org-log-note-purpose purpose
12541 org-log-note-state state
12542 org-log-note-previous-state prev-state
12543 org-log-note-how how
12544 org-log-note-extra extra
12545 org-log-note-effective-time (org-current-effective-time))
12546 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12548 (defun org-skip-over-state-notes ()
12549 "Skip past the list of State notes in an entry."
12550 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12551 (when (ignore-errors (goto-char (org-in-item-p)))
12552 (let* ((struct (org-list-struct))
12553 (prevs (org-list-prevs-alist struct)))
12554 (while (looking-at "[ \t]*- State")
12555 (goto-char (or (org-list-get-next-item (point) struct prevs)
12556 (org-list-get-item-end (point) struct)))))))
12558 (defun org-add-log-note (&optional purpose)
12559 "Pop up a window for taking a note, and add this note later at point."
12560 (remove-hook 'post-command-hook 'org-add-log-note)
12561 (setq org-log-note-window-configuration (current-window-configuration))
12562 (delete-other-windows)
12563 (move-marker org-log-note-return-to (point))
12564 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12565 (goto-char org-log-note-marker)
12566 (org-switch-to-buffer-other-window "*Org Note*")
12567 (erase-buffer)
12568 (if (memq org-log-note-how '(time state))
12569 (let (current-prefix-arg) (org-store-log-note))
12570 (let ((org-inhibit-startup t)) (org-mode))
12571 (insert (format "# Insert note for %s.
12572 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12573 (cond
12574 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12575 ((eq org-log-note-purpose 'done) "closed todo item")
12576 ((eq org-log-note-purpose 'state)
12577 (format "state change from \"%s\" to \"%s\""
12578 (or org-log-note-previous-state "")
12579 (or org-log-note-state "")))
12580 ((eq org-log-note-purpose 'reschedule)
12581 "rescheduling")
12582 ((eq org-log-note-purpose 'delschedule)
12583 "no longer scheduled")
12584 ((eq org-log-note-purpose 'redeadline)
12585 "changing deadline")
12586 ((eq org-log-note-purpose 'deldeadline)
12587 "removing deadline")
12588 ((eq org-log-note-purpose 'refile)
12589 "refiling")
12590 ((eq org-log-note-purpose 'note)
12591 "this entry")
12592 (t (error "This should not happen")))))
12593 (if org-log-note-extra (insert org-log-note-extra))
12594 (org-set-local 'org-finish-function 'org-store-log-note)
12595 (run-hooks 'org-log-buffer-setup-hook)))
12597 (defvar org-note-abort nil) ; dynamically scoped
12598 (defun org-store-log-note ()
12599 "Finish taking a log note, and insert it to where it belongs."
12600 (let ((txt (buffer-string))
12601 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12602 lines ind bul)
12603 (kill-buffer (current-buffer))
12604 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12605 (setq txt (replace-match "" t t txt)))
12606 (if (string-match "\\s-+\\'" txt)
12607 (setq txt (replace-match "" t t txt)))
12608 (setq lines (org-split-string txt "\n"))
12609 (when (and note (string-match "\\S-" note))
12610 (setq note
12611 (org-replace-escapes
12612 note
12613 (list (cons "%u" (user-login-name))
12614 (cons "%U" user-full-name)
12615 (cons "%t" (format-time-string
12616 (org-time-stamp-format 'long 'inactive)
12617 org-log-note-effective-time))
12618 (cons "%T" (format-time-string
12619 (org-time-stamp-format 'long nil)
12620 org-log-note-effective-time))
12621 (cons "%d" (format-time-string
12622 (org-time-stamp-format nil 'inactive)
12623 org-log-note-effective-time))
12624 (cons "%D" (format-time-string
12625 (org-time-stamp-format nil nil)
12626 org-log-note-effective-time))
12627 (cons "%s" (if org-log-note-state
12628 (concat "\"" org-log-note-state "\"")
12629 ""))
12630 (cons "%S" (if org-log-note-previous-state
12631 (concat "\"" org-log-note-previous-state "\"")
12632 "\"\"")))))
12633 (if lines (setq note (concat note " \\\\")))
12634 (push note lines))
12635 (when (or current-prefix-arg org-note-abort)
12636 (when org-log-into-drawer
12637 (org-remove-empty-drawer-at
12638 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12639 org-log-note-marker))
12640 (setq lines nil))
12641 (when lines
12642 (with-current-buffer (marker-buffer org-log-note-marker)
12643 (save-excursion
12644 (goto-char org-log-note-marker)
12645 (move-marker org-log-note-marker nil)
12646 (end-of-line 1)
12647 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12648 (setq ind (save-excursion
12649 (if (ignore-errors (goto-char (org-in-item-p)))
12650 (let ((struct (org-list-struct)))
12651 (org-list-get-ind
12652 (org-list-get-top-point struct) struct))
12653 (skip-chars-backward " \r\t\n")
12654 (cond
12655 ((and (org-at-heading-p)
12656 org-adapt-indentation)
12657 (1+ (org-current-level)))
12658 ((org-at-heading-p) 0)
12659 (t (org-get-indentation))))))
12660 (setq bul (org-list-bullet-string "-"))
12661 (org-indent-line-to ind)
12662 (insert bul (pop lines))
12663 (let ((ind-body (+ (length bul) ind)))
12664 (while lines
12665 (insert "\n")
12666 (org-indent-line-to ind-body)
12667 (insert (pop lines))))
12668 (message "Note stored")
12669 (org-back-to-heading t)
12670 (org-cycle-hide-drawers 'children)))))
12671 (set-window-configuration org-log-note-window-configuration)
12672 (with-current-buffer (marker-buffer org-log-note-return-to)
12673 (goto-char org-log-note-return-to))
12674 (move-marker org-log-note-return-to nil)
12675 (and org-log-post-message (message "%s" org-log-post-message)))
12677 (defun org-remove-empty-drawer-at (drawer pos)
12678 "Remove an empty drawer DRAWER at position POS.
12679 POS may also be a marker."
12680 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12681 (save-excursion
12682 (save-restriction
12683 (widen)
12684 (goto-char pos)
12685 (if (org-in-regexp
12686 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12687 (replace-match ""))))))
12689 (defvar org-ts-type nil)
12690 (defun org-sparse-tree (&optional arg type)
12691 "Create a sparse tree, prompt for the details.
12692 This command can create sparse trees. You first need to select the type
12693 of match used to create the tree:
12695 t Show all TODO entries.
12696 T Show entries with a specific TODO keyword.
12697 m Show entries selected by a tags/property match.
12698 p Enter a property name and its value (both with completion on existing
12699 names/values) and show entries with that property.
12700 r Show entries matching a regular expression (`/' can be used as well).
12701 b Show deadlines and scheduled items before a date.
12702 a Show deadlines and scheduled items after a date.
12703 d Show deadlines due within `org-deadline-warning-days'.
12704 D Show deadlines and scheduled items between a date range."
12705 (interactive "P")
12706 (let (ans kwd value ts-type)
12707 (setq type (or type org-sparse-tree-default-date-type))
12708 (setq org-ts-type type)
12709 (message "Sparse tree: [/]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"
12710 (cond ((eq type 'all) "all timestamps")
12711 ((eq type 'scheduled) "only scheduled")
12712 ((eq type 'deadline) "only deadline")
12713 ((eq type 'active) "only active timestamps")
12714 ((eq type 'inactive) "only inactive timestamps")
12715 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12716 (t "scheduled/deadline")))
12717 (setq ans (read-char-exclusive))
12718 (cond
12719 ((equal ans ?c)
12720 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12721 ((equal ans ?d)
12722 (call-interactively 'org-check-deadlines))
12723 ((equal ans ?b)
12724 (call-interactively 'org-check-before-date))
12725 ((equal ans ?a)
12726 (call-interactively 'org-check-after-date))
12727 ((equal ans ?D)
12728 (call-interactively 'org-check-dates-range))
12729 ((equal ans ?t)
12730 (call-interactively 'org-show-todo-tree))
12731 ((equal ans ?T)
12732 (org-show-todo-tree '(4)))
12733 ((member ans '(?T ?m))
12734 (call-interactively 'org-match-sparse-tree))
12735 ((member ans '(?p ?P))
12736 (setq kwd (org-icompleting-read "Property: "
12737 (mapcar 'list (org-buffer-property-keys))))
12738 (setq value (org-icompleting-read "Value: "
12739 (mapcar 'list (org-property-values kwd))))
12740 (unless (string-match "\\`{.*}\\'" value)
12741 (setq value (concat "\"" value "\"")))
12742 (org-match-sparse-tree arg (concat kwd "=" value)))
12743 ((member ans '(?r ?R ?/))
12744 (call-interactively 'org-occur))
12745 (t (error "No such sparse tree command \"%c\"" ans)))))
12747 (defvar org-occur-highlights nil
12748 "List of overlays used for occur matches.")
12749 (make-variable-buffer-local 'org-occur-highlights)
12750 (defvar org-occur-parameters nil
12751 "Parameters of the active org-occur calls.
12752 This is a list, each call to org-occur pushes as cons cell,
12753 containing the regular expression and the callback, onto the list.
12754 The list can contain several entries if `org-occur' has been called
12755 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12756 will only contain one set of parameters. When the highlights are
12757 removed (for example with `C-c C-c', or with the next edit (depending
12758 on `org-remove-highlights-with-change'), this variable is emptied
12759 as well.")
12760 (make-variable-buffer-local 'org-occur-parameters)
12762 (defun org-occur (regexp &optional keep-previous callback)
12763 "Make a compact tree which shows all matches of REGEXP.
12764 The tree will show the lines where the regexp matches, and all higher
12765 headlines above the match. It will also show the heading after the match,
12766 to make sure editing the matching entry is easy.
12767 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12768 call to `org-occur' will be kept, to allow stacking of calls to this
12769 command.
12770 If CALLBACK is non-nil, it is a function which is called to confirm
12771 that the match should indeed be shown."
12772 (interactive "sRegexp: \nP")
12773 (when (equal regexp "")
12774 (error "Regexp cannot be empty"))
12775 (unless keep-previous
12776 (org-remove-occur-highlights nil nil t))
12777 (push (cons regexp callback) org-occur-parameters)
12778 (let ((cnt 0))
12779 (save-excursion
12780 (goto-char (point-min))
12781 (if (or (not keep-previous) ; do not want to keep
12782 (not org-occur-highlights)) ; no previous matches
12783 ;; hide everything
12784 (org-overview))
12785 (while (re-search-forward regexp nil t)
12786 (when (or (not callback)
12787 (save-match-data (funcall callback)))
12788 (setq cnt (1+ cnt))
12789 (when org-highlight-sparse-tree-matches
12790 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12791 (org-show-context 'occur-tree))))
12792 (when org-remove-highlights-with-change
12793 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12794 nil 'local))
12795 (unless org-sparse-tree-open-archived-trees
12796 (org-hide-archived-subtrees (point-min) (point-max)))
12797 (run-hooks 'org-occur-hook)
12798 (if (org-called-interactively-p 'interactive)
12799 (message "%d match(es) for regexp %s" cnt regexp))
12800 cnt))
12802 (defun org-occur-next-match (&optional n reset)
12803 "Function for `next-error-function' to find sparse tree matches.
12804 N is the number of matches to move, when negative move backwards.
12805 RESET is entirely ignored - this function always goes back to the
12806 starting point when no match is found."
12807 (let* ((limit (if (< n 0) (point-min) (point-max)))
12808 (search-func (if (< n 0)
12809 'previous-single-char-property-change
12810 'next-single-char-property-change))
12811 (n (abs n))
12812 (pos (point))
12814 (catch 'exit
12815 (while (setq p1 (funcall search-func (point) 'org-type))
12816 (when (equal p1 limit)
12817 (goto-char pos)
12818 (error "No more matches"))
12819 (when (equal (get-char-property p1 'org-type) 'org-occur)
12820 (setq n (1- n))
12821 (when (= n 0)
12822 (goto-char p1)
12823 (throw 'exit (point))))
12824 (goto-char p1))
12825 (goto-char p1)
12826 (error "No more matches"))))
12828 (defun org-show-context (&optional key)
12829 "Make sure point and context are visible.
12830 How much context is shown depends upon the variables
12831 `org-show-hierarchy-above', `org-show-following-heading',
12832 `org-show-entry-below' and `org-show-siblings'."
12833 (let ((heading-p (org-at-heading-p t))
12834 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12835 (following-p (org-get-alist-option org-show-following-heading key))
12836 (entry-p (org-get-alist-option org-show-entry-below key))
12837 (siblings-p (org-get-alist-option org-show-siblings key)))
12838 (catch 'exit
12839 ;; Show heading or entry text
12840 (if (and heading-p (not entry-p))
12841 (org-flag-heading nil) ; only show the heading
12842 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12843 (org-show-hidden-entry))) ; show entire entry
12844 (when following-p
12845 ;; Show next sibling, or heading below text
12846 (save-excursion
12847 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12848 (org-flag-heading nil))))
12849 (when siblings-p (org-show-siblings))
12850 (when hierarchy-p
12851 ;; show all higher headings, possibly with siblings
12852 (save-excursion
12853 (while (and (condition-case nil
12854 (progn (org-up-heading-all 1) t)
12855 (error nil))
12856 (not (bobp)))
12857 (org-flag-heading nil)
12858 (when siblings-p (org-show-siblings))))))))
12860 (defvar org-reveal-start-hook nil
12861 "Hook run before revealing a location.")
12863 (defun org-reveal (&optional siblings)
12864 "Show current entry, hierarchy above it, and the following headline.
12865 This can be used to show a consistent set of context around locations
12866 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12867 not t for the search context.
12869 With optional argument SIBLINGS, on each level of the hierarchy all
12870 siblings are shown. This repairs the tree structure to what it would
12871 look like when opened with hierarchical calls to `org-cycle'.
12872 With double optional argument \\[universal-argument] \\[universal-argument], \
12873 go to the parent and show the
12874 entire tree."
12875 (interactive "P")
12876 (run-hooks 'org-reveal-start-hook)
12877 (let ((org-show-hierarchy-above t)
12878 (org-show-following-heading t)
12879 (org-show-siblings (if siblings t org-show-siblings)))
12880 (org-show-context nil))
12881 (when (equal siblings '(16))
12882 (save-excursion
12883 (when (org-up-heading-safe)
12884 (org-show-subtree)
12885 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12887 (defun org-highlight-new-match (beg end)
12888 "Highlight from BEG to END and mark the highlight is an occur headline."
12889 (let ((ov (make-overlay beg end)))
12890 (overlay-put ov 'face 'secondary-selection)
12891 (overlay-put ov 'org-type 'org-occur)
12892 (push ov org-occur-highlights)))
12894 (defun org-remove-occur-highlights (&optional beg end noremove)
12895 "Remove the occur highlights from the buffer.
12896 BEG and END are ignored. If NOREMOVE is nil, remove this function
12897 from the `before-change-functions' in the current buffer."
12898 (interactive)
12899 (unless org-inhibit-highlight-removal
12900 (mapc 'delete-overlay org-occur-highlights)
12901 (setq org-occur-highlights nil)
12902 (setq org-occur-parameters nil)
12903 (unless noremove
12904 (remove-hook 'before-change-functions
12905 'org-remove-occur-highlights 'local))))
12907 ;;;; Priorities
12909 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12910 "Regular expression matching the priority indicator.")
12912 (defvar org-remove-priority-next-time nil)
12914 (defun org-priority-up ()
12915 "Increase the priority of the current item."
12916 (interactive)
12917 (org-priority 'up))
12919 (defun org-priority-down ()
12920 "Decrease the priority of the current item."
12921 (interactive)
12922 (org-priority 'down))
12924 (defun org-priority (&optional action show)
12925 "Change the priority of an item.
12926 ACTION can be `set', `up', `down', or a character."
12927 (interactive "P")
12928 (if (equal action '(4))
12929 (org-show-priority)
12930 (unless org-enable-priority-commands
12931 (error "Priority commands are disabled"))
12932 (setq action (or action 'set))
12933 (let (current new news have remove)
12934 (save-excursion
12935 (org-back-to-heading t)
12936 (if (looking-at org-priority-regexp)
12937 (setq current (string-to-char (match-string 2))
12938 have t))
12939 (cond
12940 ((eq action 'remove)
12941 (setq remove t new ?\ ))
12942 ((or (eq action 'set)
12943 (if (featurep 'xemacs) (characterp action) (integerp action)))
12944 (if (not (eq action 'set))
12945 (setq new action)
12946 (message "Priority %c-%c, SPC to remove: "
12947 org-highest-priority org-lowest-priority)
12948 (save-match-data
12949 (setq new (read-char-exclusive))))
12950 (if (and (= (upcase org-highest-priority) org-highest-priority)
12951 (= (upcase org-lowest-priority) org-lowest-priority))
12952 (setq new (upcase new)))
12953 (cond ((equal new ?\ ) (setq remove t))
12954 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12955 (error "Priority must be between `%c' and `%c'"
12956 org-highest-priority org-lowest-priority))))
12957 ((eq action 'up)
12958 (setq new (if have
12959 (1- current) ; normal cycling
12960 ;; last priority was empty
12961 (if (eq last-command this-command)
12962 org-lowest-priority ; wrap around empty to lowest
12963 ;; default
12964 (if org-priority-start-cycle-with-default
12965 org-default-priority
12966 (1- org-default-priority))))))
12967 ((eq action 'down)
12968 (setq new (if have
12969 (1+ current) ; normal cycling
12970 ;; last priority was empty
12971 (if (eq last-command this-command)
12972 org-highest-priority ; wrap around empty to highest
12973 ;; default
12974 (if org-priority-start-cycle-with-default
12975 org-default-priority
12976 (1+ org-default-priority))))))
12977 (t (error "Invalid action")))
12978 (if (or (< (upcase new) org-highest-priority)
12979 (> (upcase new) org-lowest-priority))
12980 (if (and (memq action '(up down))
12981 (not have) (not (eq last-command this-command)))
12982 ;; `new' is from default priority
12983 (error
12984 "The default can not be set, see `org-default-priority' why")
12985 ;; normal cycling: `new' is beyond highest/lowest priority
12986 ;; and is wrapped around to the empty priority
12987 (setq remove t)))
12988 (setq news (format "%c" new))
12989 (if have
12990 (if remove
12991 (replace-match "" t t nil 1)
12992 (replace-match news t t nil 2))
12993 (if remove
12994 (error "No priority cookie found in line")
12995 (let ((case-fold-search nil))
12996 (looking-at org-todo-line-regexp))
12997 (if (match-end 2)
12998 (progn
12999 (goto-char (match-end 2))
13000 (insert " [#" news "]"))
13001 (goto-char (match-beginning 3))
13002 (insert "[#" news "] "))))
13003 (org-preserve-lc (org-set-tags nil 'align)))
13004 (if remove
13005 (message "Priority removed")
13006 (message "Priority of current item set to %s" news)))))
13008 (defun org-show-priority ()
13009 "Show the priority of the current item.
13010 This priority is composed of the main priority given with the [#A] cookies,
13011 and by additional input from the age of a schedules or deadline entry."
13012 (interactive)
13013 (let ((pri (if (eq major-mode 'org-agenda-mode)
13014 (org-get-at-bol 'priority)
13015 (save-excursion
13016 (save-match-data
13017 (beginning-of-line)
13018 (and (looking-at org-heading-regexp)
13019 (org-get-priority (match-string 0))))))))
13020 (message "Priority is %d" (if pri pri -1000))))
13022 (defun org-get-priority (s)
13023 "Find priority cookie and return priority."
13024 (save-match-data
13025 (if (functionp org-get-priority-function)
13026 (funcall org-get-priority-function)
13027 (if (not (string-match org-priority-regexp s))
13028 (* 1000 (- org-lowest-priority org-default-priority))
13029 (* 1000 (- org-lowest-priority
13030 (string-to-char (match-string 2 s))))))))
13032 ;;;; Tags
13034 (defvar org-agenda-archives-mode)
13035 (defvar org-map-continue-from nil
13036 "Position from where mapping should continue.
13037 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13039 (defvar org-scanner-tags nil
13040 "The current tag list while the tags scanner is running.")
13041 (defvar org-trust-scanner-tags nil
13042 "Should `org-get-tags-at' use the tags for the scanner.
13043 This is for internal dynamical scoping only.
13044 When this is non-nil, the function `org-get-tags-at' will return the value
13045 of `org-scanner-tags' instead of building the list by itself. This
13046 can lead to large speed-ups when the tags scanner is used in a file with
13047 many entries, and when the list of tags is retrieved, for example to
13048 obtain a list of properties. Building the tags list for each entry in such
13049 a file becomes an N^2 operation - but with this variable set, it scales
13050 as N.")
13052 (defun org-scan-tags (action matcher todo-only &optional start-level)
13053 "Scan headline tags with inheritance and produce output ACTION.
13055 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13056 or `agenda' to produce an entry list for an agenda view. It can also be
13057 a Lisp form or a function that should be called at each matched headline, in
13058 this case the return value is a list of all return values from these calls.
13060 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13061 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13062 only lines with a not-done TODO keyword are included in the output.
13063 This should be the same variable that was scoped into
13064 and set by `org-make-tags-matcher' when it constructed MATCHER.
13066 START-LEVEL can be a string with asterisks, reducing the scope to
13067 headlines matching this string."
13068 (require 'org-agenda)
13069 (let* ((re (concat "^"
13070 (if start-level
13071 ;; Get the correct level to match
13072 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13073 org-outline-regexp)
13074 " *\\(\\<\\("
13075 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13076 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13077 (props (list 'face 'default
13078 'done-face 'org-agenda-done
13079 'undone-face 'default
13080 'mouse-face 'highlight
13081 'org-not-done-regexp org-not-done-regexp
13082 'org-todo-regexp org-todo-regexp
13083 'org-complex-heading-regexp org-complex-heading-regexp
13084 'help-echo
13085 (format "mouse-2 or RET jump to org file %s"
13086 (abbreviate-file-name
13087 (or (buffer-file-name (buffer-base-buffer))
13088 (buffer-name (buffer-base-buffer)))))))
13089 (case-fold-search nil)
13090 (org-map-continue-from nil)
13091 lspos tags tags-list
13092 (tags-alist (list (cons 0 org-file-tags)))
13093 (llast 0) rtn rtn1 level category i txt
13094 todo marker entry priority)
13095 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13096 (setq action (list 'lambda nil action)))
13097 (save-excursion
13098 (goto-char (point-min))
13099 (when (eq action 'sparse-tree)
13100 (org-overview)
13101 (org-remove-occur-highlights))
13102 (while (re-search-forward re nil t)
13103 (setq org-map-continue-from nil)
13104 (catch :skip
13105 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13106 tags (if (match-end 4) (org-match-string-no-properties 4)))
13107 (goto-char (setq lspos (match-beginning 0)))
13108 (setq level (org-reduced-level (funcall outline-level))
13109 category (org-get-category))
13110 (setq i llast llast level)
13111 ;; remove tag lists from same and sublevels
13112 (while (>= i level)
13113 (when (setq entry (assoc i tags-alist))
13114 (setq tags-alist (delete entry tags-alist)))
13115 (setq i (1- i)))
13116 ;; add the next tags
13117 (when tags
13118 (setq tags (org-split-string tags ":")
13119 tags-alist
13120 (cons (cons level tags) tags-alist)))
13121 ;; compile tags for current headline
13122 (setq tags-list
13123 (if org-use-tag-inheritance
13124 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13125 tags)
13126 org-scanner-tags tags-list)
13127 (when org-use-tag-inheritance
13128 (setcdr (car tags-alist)
13129 (mapcar (lambda (x)
13130 (setq x (copy-sequence x))
13131 (org-add-prop-inherited x))
13132 (cdar tags-alist))))
13133 (when (and tags org-use-tag-inheritance
13134 (or (not (eq t org-use-tag-inheritance))
13135 org-tags-exclude-from-inheritance))
13136 ;; selective inheritance, remove uninherited ones
13137 (setcdr (car tags-alist)
13138 (org-remove-uninherited-tags (cdar tags-alist))))
13139 (when (and
13141 ;; eval matcher only when the todo condition is OK
13142 (and (or (not todo-only) (member todo org-not-done-keywords))
13143 (let ((case-fold-search t) (org-trust-scanner-tags t))
13144 (eval matcher)))
13146 ;; Call the skipper, but return t if it does not skip,
13147 ;; so that the `and' form continues evaluating
13148 (progn
13149 (unless (eq action 'sparse-tree) (org-agenda-skip))
13152 ;; Check if timestamps are deselecting this entry
13153 (or (not todo-only)
13154 (and (member todo org-not-done-keywords)
13155 (or (not org-agenda-tags-todo-honor-ignore-options)
13156 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13158 ;; select this headline
13159 (cond
13160 ((eq action 'sparse-tree)
13161 (and org-highlight-sparse-tree-matches
13162 (org-get-heading) (match-end 0)
13163 (org-highlight-new-match
13164 (match-beginning 1) (match-end 1)))
13165 (org-show-context 'tags-tree))
13166 ((eq action 'agenda)
13167 (setq txt (org-agenda-format-item
13169 (concat
13170 (if (eq org-tags-match-list-sublevels 'indented)
13171 (make-string (1- level) ?.) "")
13172 (org-get-heading))
13173 category
13174 tags-list)
13175 priority (org-get-priority txt))
13176 (goto-char lspos)
13177 (setq marker (org-agenda-new-marker))
13178 (org-add-props txt props
13179 'org-marker marker 'org-hd-marker marker 'org-category category
13180 'todo-state todo
13181 'priority priority 'type "tagsmatch")
13182 (push txt rtn))
13183 ((functionp action)
13184 (setq org-map-continue-from nil)
13185 (save-excursion
13186 (setq rtn1 (funcall action))
13187 (push rtn1 rtn)))
13188 (t (error "Invalid action")))
13190 ;; if we are to skip sublevels, jump to end of subtree
13191 (unless org-tags-match-list-sublevels
13192 (org-end-of-subtree t)
13193 (backward-char 1))))
13194 ;; Get the correct position from where to continue
13195 (if org-map-continue-from
13196 (goto-char org-map-continue-from)
13197 (and (= (point) lspos) (end-of-line 1)))))
13198 (when (and (eq action 'sparse-tree)
13199 (not org-sparse-tree-open-archived-trees))
13200 (org-hide-archived-subtrees (point-min) (point-max)))
13201 (nreverse rtn)))
13203 (defun org-remove-uninherited-tags (tags)
13204 "Remove all tags that are not inherited from the list TAGS."
13205 (cond
13206 ((eq org-use-tag-inheritance t)
13207 (if org-tags-exclude-from-inheritance
13208 (org-delete-all org-tags-exclude-from-inheritance tags)
13209 tags))
13210 ((not org-use-tag-inheritance) nil)
13211 ((stringp org-use-tag-inheritance)
13212 (delq nil (mapcar
13213 (lambda (x)
13214 (if (and (string-match org-use-tag-inheritance x)
13215 (not (member x org-tags-exclude-from-inheritance)))
13216 x nil))
13217 tags)))
13218 ((listp org-use-tag-inheritance)
13219 (delq nil (mapcar
13220 (lambda (x)
13221 (if (member x org-use-tag-inheritance) x nil))
13222 tags)))))
13224 (defun org-match-sparse-tree (&optional todo-only match)
13225 "Create a sparse tree according to tags string MATCH.
13226 MATCH can contain positive and negative selection of tags, like
13227 \"+WORK+URGENT-WITHBOSS\".
13228 If optional argument TODO-ONLY is non-nil, only select lines that are
13229 also TODO lines."
13230 (interactive "P")
13231 (org-agenda-prepare-buffers (list (current-buffer)))
13232 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13234 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13236 (defvar org-cached-props nil)
13237 (defun org-cached-entry-get (pom property)
13238 (if (or (eq t org-use-property-inheritance)
13239 (and (stringp org-use-property-inheritance)
13240 (string-match org-use-property-inheritance property))
13241 (and (listp org-use-property-inheritance)
13242 (member property org-use-property-inheritance)))
13243 ;; Caching is not possible, check it directly
13244 (org-entry-get pom property 'inherit)
13245 ;; Get all properties, so that we can do complicated checks easily
13246 (cdr (assoc property (or org-cached-props
13247 (setq org-cached-props
13248 (org-entry-properties pom)))))))
13250 (defun org-global-tags-completion-table (&optional files)
13251 "Return the list of all tags in all agenda buffer/files.
13252 Optional FILES argument is a list of files which can be used
13253 instead of the agenda files."
13254 (save-excursion
13255 (org-uniquify
13256 (delq nil
13257 (apply 'append
13258 (mapcar
13259 (lambda (file)
13260 (set-buffer (find-file-noselect file))
13261 (append (org-get-buffer-tags)
13262 (mapcar (lambda (x) (if (stringp (car-safe x))
13263 (list (car-safe x)) nil))
13264 org-tag-alist)))
13265 (if (and files (car files))
13266 files
13267 (org-agenda-files))))))))
13269 (defun org-make-tags-matcher (match)
13270 "Create the TAGS/TODO matcher form for the selection string MATCH.
13272 The variable `todo-only' is scoped dynamically into this function.
13273 It will be set to t if the matcher restricts matching to TODO entries,
13274 otherwise will not be touched.
13276 Returns a cons of the selection string MATCH and the constructed
13277 lisp form implementing the matcher. The matcher is to be evaluated
13278 at an Org entry, with point on the headline, and returns t if the
13279 entry matches the selection string MATCH. The returned lisp form
13280 references two variables with information about the entry, which
13281 must be bound around the form's evaluation: todo, the TODO keyword
13282 at the entry (or nil of none); and tags-list, the list of all tags
13283 at the entry including inherited ones. Additionally, the category
13284 of the entry (if any) must be specified as the text property
13285 'org-category on the headline.
13287 See also `org-scan-tags'.
13289 (declare (special todo-only))
13290 (unless (boundp 'todo-only)
13291 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13292 (unless match
13293 ;; Get a new match request, with completion
13294 (let ((org-last-tags-completion-table
13295 (org-global-tags-completion-table)))
13296 (setq match (org-completing-read-no-i
13297 "Match: " 'org-tags-completion-function nil nil nil
13298 'org-tags-history))))
13300 ;; Parse the string and create a lisp form
13301 (let ((match0 match)
13302 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13303 minus tag mm
13304 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13305 orterms term orlist re-p str-p level-p level-op time-p
13306 prop-p pn pv po gv rest)
13307 (if (string-match "/+" match)
13308 ;; match contains also a todo-matching request
13309 (progn
13310 (setq tagsmatch (substring match 0 (match-beginning 0))
13311 todomatch (substring match (match-end 0)))
13312 (if (string-match "^!" todomatch)
13313 (setq todo-only t todomatch (substring todomatch 1)))
13314 (if (string-match "^\\s-*$" todomatch)
13315 (setq todomatch nil)))
13316 ;; only matching tags
13317 (setq tagsmatch match todomatch nil))
13319 ;; Make the tags matcher
13320 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13321 (setq tagsmatcher t)
13322 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13323 (while (setq term (pop orterms))
13324 (while (and (equal (substring term -1) "\\") orterms)
13325 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13326 (while (string-match re term)
13327 (setq rest (substring term (match-end 0))
13328 minus (and (match-end 1)
13329 (equal (match-string 1 term) "-"))
13330 tag (save-match-data (replace-regexp-in-string
13331 "\\\\-" "-"
13332 (match-string 2 term)))
13333 re-p (equal (string-to-char tag) ?{)
13334 level-p (match-end 4)
13335 prop-p (match-end 5)
13336 mm (cond
13337 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13338 (level-p
13339 (setq level-op (org-op-to-function (match-string 3 term)))
13340 `(,level-op level ,(string-to-number
13341 (match-string 4 term))))
13342 (prop-p
13343 (setq pn (match-string 5 term)
13344 po (match-string 6 term)
13345 pv (match-string 7 term)
13346 re-p (equal (string-to-char pv) ?{)
13347 str-p (equal (string-to-char pv) ?\")
13348 time-p (save-match-data
13349 (string-match "^\"[[<].*[]>]\"$" pv))
13350 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13351 (if time-p (setq pv (org-matcher-time pv)))
13352 (setq po (org-op-to-function po (if time-p 'time str-p)))
13353 (cond
13354 ((equal pn "CATEGORY")
13355 (setq gv '(get-text-property (point) 'org-category)))
13356 ((equal pn "TODO")
13357 (setq gv 'todo))
13359 (setq gv `(org-cached-entry-get nil ,pn))))
13360 (if re-p
13361 (if (eq po 'org<>)
13362 `(not (string-match ,pv (or ,gv "")))
13363 `(string-match ,pv (or ,gv "")))
13364 (if str-p
13365 `(,po (or ,gv "") ,pv)
13366 `(,po (string-to-number (or ,gv ""))
13367 ,(string-to-number pv) ))))
13368 (t `(member ,tag tags-list)))
13369 mm (if minus (list 'not mm) mm)
13370 term rest)
13371 (push mm tagsmatcher))
13372 (push (if (> (length tagsmatcher) 1)
13373 (cons 'and tagsmatcher)
13374 (car tagsmatcher))
13375 orlist)
13376 (setq tagsmatcher nil))
13377 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13378 (setq tagsmatcher
13379 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13380 ;; Make the todo matcher
13381 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13382 (setq todomatcher t)
13383 (setq orterms (org-split-string todomatch "|") orlist nil)
13384 (while (setq term (pop orterms))
13385 (while (string-match re term)
13386 (setq minus (and (match-end 1)
13387 (equal (match-string 1 term) "-"))
13388 kwd (match-string 2 term)
13389 re-p (equal (string-to-char kwd) ?{)
13390 term (substring term (match-end 0))
13391 mm (if re-p
13392 `(string-match ,(substring kwd 1 -1) todo)
13393 (list 'equal 'todo kwd))
13394 mm (if minus (list 'not mm) mm))
13395 (push mm todomatcher))
13396 (push (if (> (length todomatcher) 1)
13397 (cons 'and todomatcher)
13398 (car todomatcher))
13399 orlist)
13400 (setq todomatcher nil))
13401 (setq todomatcher (if (> (length orlist) 1)
13402 (cons 'or orlist) (car orlist))))
13404 ;; Return the string and lisp forms of the matcher
13405 (setq matcher (if todomatcher
13406 (list 'and tagsmatcher todomatcher)
13407 tagsmatcher))
13408 (when todo-only
13409 (setq matcher (list 'and '(member todo org-not-done-keywords)
13410 matcher)))
13411 (cons match0 matcher)))
13413 (defun org-op-to-function (op &optional stringp)
13414 "Turn an operator into the appropriate function."
13415 (setq op
13416 (cond
13417 ((equal op "<" ) '(< string< org-time<))
13418 ((equal op ">" ) '(> org-string> org-time>))
13419 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13420 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13421 ((member op '("=" "==")) '(= string= org-time=))
13422 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13423 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13425 (defun org<> (a b) (not (= a b)))
13426 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13427 (defun org-string>= (a b) (not (string< a b)))
13428 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13429 (defun org-string<> (a b) (not (string= a b)))
13430 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13431 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13432 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13433 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13434 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13435 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13436 (defun org-2ft (s)
13437 "Convert S to a floating point time.
13438 If S is already a number, just return it. If it is a string, parse
13439 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13440 (cond
13441 ((numberp s) s)
13442 ((stringp s)
13443 (condition-case nil
13444 (float-time (apply 'encode-time (org-parse-time-string s)))
13445 (error 0.)))
13446 (t 0.)))
13448 (defun org-time-today ()
13449 "Time in seconds today at 0:00.
13450 Returns the float number of seconds since the beginning of the
13451 epoch to the beginning of today (00:00)."
13452 (float-time (apply 'encode-time
13453 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13455 (defun org-matcher-time (s)
13456 "Interpret a time comparison value."
13457 (save-match-data
13458 (cond
13459 ((string= s "<now>") (float-time))
13460 ((string= s "<today>") (org-time-today))
13461 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13462 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13463 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13464 (+ (org-time-today)
13465 (* (string-to-number (match-string 1 s))
13466 (cdr (assoc (match-string 2 s)
13467 '(("d" . 86400.0) ("w" . 604800.0)
13468 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13469 (t (org-2ft s)))))
13471 (defun org-match-any-p (re list)
13472 "Does re match any element of list?"
13473 (setq list (mapcar (lambda (x) (string-match re x)) list))
13474 (delq nil list))
13476 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13477 (defvar org-tags-overlay (make-overlay 1 1))
13478 (org-detach-overlay org-tags-overlay)
13480 (defun org-get-local-tags-at (&optional pos)
13481 "Get a list of tags defined in the current headline."
13482 (org-get-tags-at pos 'local))
13484 (defun org-get-local-tags ()
13485 "Get a list of tags defined in the current headline."
13486 (org-get-tags-at nil 'local))
13488 (defun org-get-tags-at (&optional pos local)
13489 "Get a list of all headline tags applicable at POS.
13490 POS defaults to point. If tags are inherited, the list contains
13491 the targets in the same sequence as the headlines appear, i.e.
13492 the tags of the current headline come last.
13493 When LOCAL is non-nil, only return tags from the current headline,
13494 ignore inherited ones."
13495 (interactive)
13496 (if (and org-trust-scanner-tags
13497 (or (not pos) (equal pos (point)))
13498 (not local))
13499 org-scanner-tags
13500 (let (tags ltags lastpos parent)
13501 (save-excursion
13502 (save-restriction
13503 (widen)
13504 (goto-char (or pos (point)))
13505 (save-match-data
13506 (catch 'done
13507 (condition-case nil
13508 (progn
13509 (org-back-to-heading t)
13510 (while (not (equal lastpos (point)))
13511 (setq lastpos (point))
13512 (when (looking-at
13513 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13514 (setq ltags (org-split-string
13515 (org-match-string-no-properties 1) ":"))
13516 (when parent
13517 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13518 (setq tags (append
13519 (if parent
13520 (org-remove-uninherited-tags ltags)
13521 ltags)
13522 tags)))
13523 (or org-use-tag-inheritance (throw 'done t))
13524 (if local (throw 'done t))
13525 (or (org-up-heading-safe) (error nil))
13526 (setq parent t)))
13527 (error nil)))))
13528 (if local
13529 tags
13530 (reverse (delete-dups
13531 (reverse (append
13532 (org-remove-uninherited-tags
13533 org-file-tags) tags)))))))))
13535 (defun org-add-prop-inherited (s)
13536 (add-text-properties 0 (length s) '(inherited t) s)
13539 (defun org-toggle-tag (tag &optional onoff)
13540 "Toggle the tag TAG for the current line.
13541 If ONOFF is `on' or `off', don't toggle but set to this state."
13542 (let (res current)
13543 (save-excursion
13544 (org-back-to-heading t)
13545 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13546 (point-at-eol) t)
13547 (progn
13548 (setq current (match-string 1))
13549 (replace-match ""))
13550 (setq current ""))
13551 (setq current (nreverse (org-split-string current ":")))
13552 (cond
13553 ((eq onoff 'on)
13554 (setq res t)
13555 (or (member tag current) (push tag current)))
13556 ((eq onoff 'off)
13557 (or (not (member tag current)) (setq current (delete tag current))))
13558 (t (if (member tag current)
13559 (setq current (delete tag current))
13560 (setq res t)
13561 (push tag current))))
13562 (end-of-line 1)
13563 (if current
13564 (progn
13565 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13566 (org-set-tags nil t))
13567 (delete-horizontal-space))
13568 (run-hooks 'org-after-tags-change-hook))
13569 res))
13571 (defun org-align-tags-here (to-col)
13572 ;; Assumes that this is a headline
13573 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13574 (beginning-of-line 1)
13575 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13576 (< pos (match-beginning 2)))
13577 (progn
13578 (setq tags-l (- (match-end 2) (match-beginning 2)))
13579 (goto-char (match-beginning 1))
13580 (insert " ")
13581 (delete-region (point) (1+ (match-beginning 2)))
13582 (setq ncol (max (current-column)
13583 (1+ col)
13584 (if (> to-col 0)
13585 to-col
13586 (- (abs to-col) tags-l))))
13587 (setq p (point))
13588 (insert (make-string (- ncol (current-column)) ?\ ))
13589 (setq ncol (current-column))
13590 (when indent-tabs-mode (tabify p (point-at-eol)))
13591 (org-move-to-column (min ncol col) t))
13592 (goto-char pos))))
13594 (defun org-set-tags-command (&optional arg just-align)
13595 "Call the set-tags command for the current entry."
13596 (interactive "P")
13597 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13598 (org-set-tags arg just-align)
13599 (save-excursion
13600 (org-back-to-heading t)
13601 (org-set-tags arg just-align))))
13603 (defun org-set-tags-to (data)
13604 "Set the tags of the current entry to DATA, replacing the current tags.
13605 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13606 If DATA is nil or the empty string, any tags will be removed."
13607 (interactive "sTags: ")
13608 (setq data
13609 (cond
13610 ((eq data nil) "")
13611 ((equal data "") "")
13612 ((stringp data)
13613 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13614 ":"))
13615 ((listp data)
13616 (concat ":" (mapconcat 'identity data ":") ":"))))
13617 (when data
13618 (save-excursion
13619 (org-back-to-heading t)
13620 (when (looking-at org-complex-heading-regexp)
13621 (if (match-end 5)
13622 (progn
13623 (goto-char (match-beginning 5))
13624 (insert data)
13625 (delete-region (point) (point-at-eol))
13626 (org-set-tags nil 'align))
13627 (goto-char (point-at-eol))
13628 (insert " " data)
13629 (org-set-tags nil 'align)))
13630 (beginning-of-line 1)
13631 (if (looking-at ".*?\\([ \t]+\\)$")
13632 (delete-region (match-beginning 1) (match-end 1))))))
13634 (defun org-align-all-tags ()
13635 "Align the tags i all headings."
13636 (interactive)
13637 (save-excursion
13638 (or (ignore-errors (org-back-to-heading t))
13639 (outline-next-heading))
13640 (if (org-at-heading-p)
13641 (org-set-tags t)
13642 (message "No headings"))))
13644 (defvar org-indent-indentation-per-level)
13645 (defun org-set-tags (&optional arg just-align)
13646 "Set the tags for the current headline.
13647 With prefix ARG, realign all tags in headings in the current buffer."
13648 (interactive "P")
13649 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13650 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13651 'region-start-level 'region))
13652 org-loop-over-headlines-in-active-region)
13653 (org-map-entries
13654 ;; We don't use ARG and JUST-ALIGN here these args are not
13655 ;; useful when looping over headlines
13656 `(org-set-tags)
13657 org-loop-over-headlines-in-active-region
13658 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13659 (let* ((re org-outline-regexp-bol)
13660 (current (unless arg (org-get-tags-string)))
13661 (col (current-column))
13662 (org-setting-tags t)
13663 table current-tags inherited-tags ; computed below when needed
13664 tags p0 c0 c1 rpl di tc level)
13665 (if arg
13666 (save-excursion
13667 (goto-char (point-min))
13668 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13669 (while (re-search-forward re nil t)
13670 (org-set-tags nil t)
13671 (end-of-line 1)))
13672 (message "All tags realigned to column %d" org-tags-column))
13673 (if just-align
13674 (setq tags current)
13675 ;; Get a new set of tags from the user
13676 (save-excursion
13677 (setq table (append org-tag-persistent-alist
13678 (or org-tag-alist (org-get-buffer-tags))
13679 (and
13680 org-complete-tags-always-offer-all-agenda-tags
13681 (org-global-tags-completion-table
13682 (org-agenda-files))))
13683 org-last-tags-completion-table table
13684 current-tags (org-split-string current ":")
13685 inherited-tags (nreverse
13686 (nthcdr (length current-tags)
13687 (nreverse (org-get-tags-at))))
13688 tags
13689 (if (or (eq t org-use-fast-tag-selection)
13690 (and org-use-fast-tag-selection
13691 (delq nil (mapcar 'cdr table))))
13692 (org-fast-tag-selection
13693 current-tags inherited-tags table
13694 (if org-fast-tag-selection-include-todo
13695 org-todo-key-alist))
13696 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13697 (org-trim
13698 (org-icompleting-read "Tags: "
13699 'org-tags-completion-function
13700 nil nil current 'org-tags-history))))))
13701 (while (string-match "[-+&]+" tags)
13702 ;; No boolean logic, just a list
13703 (setq tags (replace-match ":" t t tags))))
13705 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13707 (if org-tags-sort-function
13708 (setq tags (mapconcat 'identity
13709 (sort (org-split-string
13710 tags (org-re "[^[:alnum:]_@#%]+"))
13711 org-tags-sort-function) ":")))
13713 (if (string-match "\\`[\t ]*\\'" tags)
13714 (setq tags "")
13715 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13716 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13718 ;; Insert new tags at the correct column
13719 (beginning-of-line 1)
13720 (setq level (or (and (looking-at org-outline-regexp)
13721 (- (match-end 0) (point) 1))
13723 (cond
13724 ((and (equal current "") (equal tags "")))
13725 ((re-search-forward
13726 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13727 (point-at-eol) t)
13728 (if (equal tags "")
13729 (setq rpl "")
13730 (goto-char (match-beginning 0))
13731 (setq c0 (current-column)
13732 ;; compute offset for the case of org-indent-mode active
13733 di (if org-indent-mode
13734 (* (1- org-indent-indentation-per-level) (1- level))
13736 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13737 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13738 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13739 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13740 (replace-match rpl t t)
13741 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13742 tags)
13743 (t (error "Tags alignment failed")))
13744 (org-move-to-column col)
13745 (unless just-align
13746 (run-hooks 'org-after-tags-change-hook))))))
13748 (defun org-change-tag-in-region (beg end tag off)
13749 "Add or remove TAG for each entry in the region.
13750 This works in the agenda, and also in an org-mode buffer."
13751 (interactive
13752 (list (region-beginning) (region-end)
13753 (let ((org-last-tags-completion-table
13754 (if (derived-mode-p 'org-mode)
13755 (org-get-buffer-tags)
13756 (org-global-tags-completion-table))))
13757 (org-icompleting-read
13758 "Tag: " 'org-tags-completion-function nil nil nil
13759 'org-tags-history))
13760 (progn
13761 (message "[s]et or [r]emove? ")
13762 (equal (read-char-exclusive) ?r))))
13763 (if (fboundp 'deactivate-mark) (deactivate-mark))
13764 (let ((agendap (equal major-mode 'org-agenda-mode))
13765 l1 l2 m buf pos newhead (cnt 0))
13766 (goto-char end)
13767 (setq l2 (1- (org-current-line)))
13768 (goto-char beg)
13769 (setq l1 (org-current-line))
13770 (loop for l from l1 to l2 do
13771 (org-goto-line l)
13772 (setq m (get-text-property (point) 'org-hd-marker))
13773 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13774 (and agendap m))
13775 (setq buf (if agendap (marker-buffer m) (current-buffer))
13776 pos (if agendap m (point)))
13777 (with-current-buffer buf
13778 (save-excursion
13779 (save-restriction
13780 (goto-char pos)
13781 (setq cnt (1+ cnt))
13782 (org-toggle-tag tag (if off 'off 'on))
13783 (setq newhead (org-get-heading)))))
13784 (and agendap (org-agenda-change-all-lines newhead m))))
13785 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13787 (defun org-tags-completion-function (string predicate &optional flag)
13788 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13789 (confirm (lambda (x) (stringp (car x)))))
13790 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13791 (setq s1 (match-string 1 string)
13792 s2 (match-string 2 string))
13793 (setq s1 "" s2 string))
13794 (cond
13795 ((eq flag nil)
13796 ;; try completion
13797 (setq rtn (try-completion s2 ctable confirm))
13798 (if (stringp rtn)
13799 (setq rtn
13800 (concat s1 s2 (substring rtn (length s2))
13801 (if (and org-add-colon-after-tag-completion
13802 (assoc rtn ctable))
13803 ":" ""))))
13804 rtn)
13805 ((eq flag t)
13806 ;; all-completions
13807 (all-completions s2 ctable confirm)
13809 ((eq flag 'lambda)
13810 ;; exact match?
13811 (assoc s2 ctable)))
13814 (defun org-fast-tag-insert (kwd tags face &optional end)
13815 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13816 (insert (format "%-12s" (concat kwd ":"))
13817 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13818 (or end "")))
13820 (defun org-fast-tag-show-exit (flag)
13821 (save-excursion
13822 (org-goto-line 3)
13823 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13824 (replace-match ""))
13825 (when flag
13826 (end-of-line 1)
13827 (org-move-to-column (- (window-width) 19) t)
13828 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13830 (defun org-set-current-tags-overlay (current prefix)
13831 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13832 (if (featurep 'xemacs)
13833 (org-overlay-display org-tags-overlay (concat prefix s)
13834 'secondary-selection)
13835 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13836 (org-overlay-display org-tags-overlay (concat prefix s)))))
13838 (defvar org-last-tag-selection-key nil)
13839 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13840 "Fast tag selection with single keys.
13841 CURRENT is the current list of tags in the headline, INHERITED is the
13842 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13843 possibly with grouping information. TODO-TABLE is a similar table with
13844 TODO keywords, should these have keys assigned to them.
13845 If the keys are nil, a-z are automatically assigned.
13846 Returns the new tags string, or nil to not change the current settings."
13847 (let* ((fulltable (append table todo-table))
13848 (maxlen (apply 'max (mapcar
13849 (lambda (x)
13850 (if (stringp (car x)) (string-width (car x)) 0))
13851 fulltable)))
13852 (buf (current-buffer))
13853 (expert (eq org-fast-tag-selection-single-key 'expert))
13854 (buffer-tags nil)
13855 (fwidth (+ maxlen 3 1 3))
13856 (ncol (/ (- (window-width) 4) fwidth))
13857 (i-face 'org-done)
13858 (c-face 'org-todo)
13859 tg cnt e c char c1 c2 ntable tbl rtn
13860 ov-start ov-end ov-prefix
13861 (exit-after-next org-fast-tag-selection-single-key)
13862 (done-keywords org-done-keywords)
13863 groups ingroup)
13864 (save-excursion
13865 (beginning-of-line 1)
13866 (if (looking-at
13867 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13868 (setq ov-start (match-beginning 1)
13869 ov-end (match-end 1)
13870 ov-prefix "")
13871 (setq ov-start (1- (point-at-eol))
13872 ov-end (1+ ov-start))
13873 (skip-chars-forward "^\n\r")
13874 (setq ov-prefix
13875 (concat
13876 (buffer-substring (1- (point)) (point))
13877 (if (> (current-column) org-tags-column)
13879 (make-string (- org-tags-column (current-column)) ?\ ))))))
13880 (move-overlay org-tags-overlay ov-start ov-end)
13881 (save-window-excursion
13882 (if expert
13883 (set-buffer (get-buffer-create " *Org tags*"))
13884 (delete-other-windows)
13885 (split-window-vertically)
13886 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13887 (erase-buffer)
13888 (org-set-local 'org-done-keywords done-keywords)
13889 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13890 (org-fast-tag-insert "Current" current c-face "\n\n")
13891 (org-fast-tag-show-exit exit-after-next)
13892 (org-set-current-tags-overlay current ov-prefix)
13893 (setq tbl fulltable char ?a cnt 0)
13894 (while (setq e (pop tbl))
13895 (cond
13896 ((equal (car e) :startgroup)
13897 (push '() groups) (setq ingroup t)
13898 (when (not (= cnt 0))
13899 (setq cnt 0)
13900 (insert "\n"))
13901 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13902 ((equal (car e) :endgroup)
13903 (setq ingroup nil cnt 0)
13904 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13905 ((equal e '(:newline))
13906 (when (not (= cnt 0))
13907 (setq cnt 0)
13908 (insert "\n")
13909 (setq e (car tbl))
13910 (while (equal (car tbl) '(:newline))
13911 (insert "\n")
13912 (setq tbl (cdr tbl)))))
13914 (setq tg (copy-sequence (car e)) c2 nil)
13915 (if (cdr e)
13916 (setq c (cdr e))
13917 ;; automatically assign a character.
13918 (setq c1 (string-to-char
13919 (downcase (substring
13920 tg (if (= (string-to-char tg) ?@) 1 0)))))
13921 (if (or (rassoc c1 ntable) (rassoc c1 table))
13922 (while (or (rassoc char ntable) (rassoc char table))
13923 (setq char (1+ char)))
13924 (setq c2 c1))
13925 (setq c (or c2 char)))
13926 (if ingroup (push tg (car groups)))
13927 (setq tg (org-add-props tg nil 'face
13928 (cond
13929 ((not (assoc tg table))
13930 (org-get-todo-face tg))
13931 ((member tg current) c-face)
13932 ((member tg inherited) i-face))))
13933 (if (and (= cnt 0) (not ingroup)) (insert " "))
13934 (insert "[" c "] " tg (make-string
13935 (- fwidth 4 (length tg)) ?\ ))
13936 (push (cons tg c) ntable)
13937 (when (= (setq cnt (1+ cnt)) ncol)
13938 (insert "\n")
13939 (if ingroup (insert " "))
13940 (setq cnt 0)))))
13941 (setq ntable (nreverse ntable))
13942 (insert "\n")
13943 (goto-char (point-min))
13944 (if (not expert) (org-fit-window-to-buffer))
13945 (setq rtn
13946 (catch 'exit
13947 (while t
13948 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13949 (if (not groups) "no " "")
13950 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13951 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13952 (setq org-last-tag-selection-key c)
13953 (cond
13954 ((= c ?\r) (throw 'exit t))
13955 ((= c ?!)
13956 (setq groups (not groups))
13957 (goto-char (point-min))
13958 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13959 ((= c ?\C-c)
13960 (if (not expert)
13961 (org-fast-tag-show-exit
13962 (setq exit-after-next (not exit-after-next)))
13963 (setq expert nil)
13964 (delete-other-windows)
13965 (set-window-buffer (split-window-vertically) " *Org tags*")
13966 (org-switch-to-buffer-other-window " *Org tags*")
13967 (org-fit-window-to-buffer)))
13968 ((or (= c ?\C-g)
13969 (and (= c ?q) (not (rassoc c ntable))))
13970 (org-detach-overlay org-tags-overlay)
13971 (setq quit-flag t))
13972 ((= c ?\ )
13973 (setq current nil)
13974 (if exit-after-next (setq exit-after-next 'now)))
13975 ((= c ?\t)
13976 (condition-case nil
13977 (setq tg (org-icompleting-read
13978 "Tag: "
13979 (or buffer-tags
13980 (with-current-buffer buf
13981 (org-get-buffer-tags)))))
13982 (quit (setq tg "")))
13983 (when (string-match "\\S-" tg)
13984 (add-to-list 'buffer-tags (list tg))
13985 (if (member tg current)
13986 (setq current (delete tg current))
13987 (push tg current)))
13988 (if exit-after-next (setq exit-after-next 'now)))
13989 ((setq e (rassoc c todo-table) tg (car e))
13990 (with-current-buffer buf
13991 (save-excursion (org-todo tg)))
13992 (if exit-after-next (setq exit-after-next 'now)))
13993 ((setq e (rassoc c ntable) tg (car e))
13994 (if (member tg current)
13995 (setq current (delete tg current))
13996 (loop for g in groups do
13997 (if (member tg g)
13998 (mapc (lambda (x)
13999 (setq current (delete x current)))
14000 g)))
14001 (push tg current))
14002 (if exit-after-next (setq exit-after-next 'now))))
14004 ;; Create a sorted list
14005 (setq current
14006 (sort current
14007 (lambda (a b)
14008 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14009 (if (eq exit-after-next 'now) (throw 'exit t))
14010 (goto-char (point-min))
14011 (beginning-of-line 2)
14012 (delete-region (point) (point-at-eol))
14013 (org-fast-tag-insert "Current" current c-face)
14014 (org-set-current-tags-overlay current ov-prefix)
14015 (while (re-search-forward
14016 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14017 (setq tg (match-string 1))
14018 (add-text-properties
14019 (match-beginning 1) (match-end 1)
14020 (list 'face
14021 (cond
14022 ((member tg current) c-face)
14023 ((member tg inherited) i-face)
14024 (t (get-text-property (match-beginning 1) 'face))))))
14025 (goto-char (point-min)))))
14026 (org-detach-overlay org-tags-overlay)
14027 (if rtn
14028 (mapconcat 'identity current ":")
14029 nil))))
14031 (defun org-get-tags-string ()
14032 "Get the TAGS string in the current headline."
14033 (unless (org-at-heading-p t)
14034 (error "Not on a heading"))
14035 (save-excursion
14036 (beginning-of-line 1)
14037 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14038 (org-match-string-no-properties 1)
14039 "")))
14041 (defun org-get-tags ()
14042 "Get the list of tags specified in the current headline."
14043 (org-split-string (org-get-tags-string) ":"))
14045 (defun org-get-buffer-tags ()
14046 "Get a table of all tags used in the buffer, for completion."
14047 (let (tags)
14048 (save-excursion
14049 (goto-char (point-min))
14050 (while (re-search-forward
14051 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14052 (when (equal (char-after (point-at-bol 0)) ?*)
14053 (mapc (lambda (x) (add-to-list 'tags x))
14054 (org-split-string (org-match-string-no-properties 1) ":")))))
14055 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14056 (mapcar 'list tags)))
14058 ;;;; The mapping API
14060 (defun org-map-entries (func &optional match scope &rest skip)
14061 "Call FUNC at each headline selected by MATCH in SCOPE.
14063 FUNC is a function or a lisp form. The function will be called without
14064 arguments, with the cursor positioned at the beginning of the headline.
14065 The return values of all calls to the function will be collected and
14066 returned as a list.
14068 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14069 does not need to preserve point. After evaluation, the cursor will be
14070 moved to the end of the line (presumably of the headline of the
14071 processed entry) and search continues from there. Under some
14072 circumstances, this may not produce the wanted results. For example,
14073 if you have removed (e.g. archived) the current (sub)tree it could
14074 mean that the next entry will be skipped entirely. In such cases, you
14075 can specify the position from where search should continue by making
14076 FUNC set the variable `org-map-continue-from' to the desired buffer
14077 position.
14079 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14080 Only headlines that are matched by this query will be considered during
14081 the iteration. When MATCH is nil or t, all headlines will be
14082 visited by the iteration.
14084 SCOPE determines the scope of this command. It can be any of:
14086 nil The current buffer, respecting the restriction if any
14087 tree The subtree started with the entry at point
14088 region The entries within the active region, if any
14089 region-start-level
14090 The entries within the active region, but only those at
14091 the same level than the first one.
14092 file The current buffer, without restriction
14093 file-with-archives
14094 The current buffer, and any archives associated with it
14095 agenda All agenda files
14096 agenda-with-archives
14097 All agenda files with any archive files associated with them
14098 \(file1 file2 ...)
14099 If this is a list, all files in the list will be scanned
14101 The remaining args are treated as settings for the skipping facilities of
14102 the scanner. The following items can be given here:
14104 archive skip trees with the archive tag.
14105 comment skip trees with the COMMENT keyword
14106 function or Emacs Lisp form:
14107 will be used as value for `org-agenda-skip-function', so whenever
14108 the function returns t, FUNC will not be called for that
14109 entry and search will continue from the point where the
14110 function leaves it.
14112 If your function needs to retrieve the tags including inherited tags
14113 at the *current* entry, you can use the value of the variable
14114 `org-scanner-tags' which will be much faster than getting the value
14115 with `org-get-tags-at'. If your function gets properties with
14116 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14117 to t around the call to `org-entry-properties' to get the same speedup.
14118 Note that if your function moves around to retrieve tags and properties at
14119 a *different* entry, you cannot use these techniques."
14120 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14121 (not (org-region-active-p)))
14122 (let* ((org-agenda-archives-mode nil) ; just to make sure
14123 (org-agenda-skip-archived-trees (memq 'archive skip))
14124 (org-agenda-skip-comment-trees (memq 'comment skip))
14125 (org-agenda-skip-function
14126 (car (org-delete-all '(comment archive) skip)))
14127 (org-tags-match-list-sublevels t)
14128 (start-level (eq scope 'region-start-level))
14129 matcher file res
14130 org-todo-keywords-for-agenda
14131 org-done-keywords-for-agenda
14132 org-todo-keyword-alist-for-agenda
14133 org-drawers-for-agenda
14134 org-tag-alist-for-agenda
14135 todo-only)
14137 (cond
14138 ((eq match t) (setq matcher t))
14139 ((eq match nil) (setq matcher t))
14140 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14142 (save-excursion
14143 (save-restriction
14144 (cond ((eq scope 'tree)
14145 (org-back-to-heading t)
14146 (org-narrow-to-subtree)
14147 (setq scope nil))
14148 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14149 (org-region-active-p))
14150 ;; If needed, set start-level to a string like "2"
14151 (when start-level
14152 (save-excursion
14153 (goto-char (region-beginning))
14154 (unless (org-at-heading-p) (outline-next-heading))
14155 (setq start-level (org-current-level))))
14156 (narrow-to-region (region-beginning)
14157 (save-excursion
14158 (goto-char (region-end))
14159 (unless (and (bolp) (org-at-heading-p))
14160 (outline-next-heading))
14161 (point)))
14162 (setq scope nil)))
14164 (if (not scope)
14165 (progn
14166 (org-agenda-prepare-buffers
14167 (list (buffer-file-name (current-buffer))))
14168 (setq res (org-scan-tags func matcher todo-only start-level)))
14169 ;; Get the right scope
14170 (cond
14171 ((and scope (listp scope) (symbolp (car scope)))
14172 (setq scope (eval scope)))
14173 ((eq scope 'agenda)
14174 (setq scope (org-agenda-files t)))
14175 ((eq scope 'agenda-with-archives)
14176 (setq scope (org-agenda-files t))
14177 (setq scope (org-add-archive-files scope)))
14178 ((eq scope 'file)
14179 (setq scope (list (buffer-file-name))))
14180 ((eq scope 'file-with-archives)
14181 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14182 (org-agenda-prepare-buffers scope)
14183 (while (setq file (pop scope))
14184 (with-current-buffer (org-find-base-buffer-visiting file)
14185 (save-excursion
14186 (save-restriction
14187 (widen)
14188 (goto-char (point-min))
14189 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14190 res)))
14192 ;;;; Properties
14194 ;;; Setting and retrieving properties
14196 (defconst org-special-properties
14197 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14198 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14199 "The special properties valid in Org-mode.
14201 These are properties that are not defined in the property drawer,
14202 but in some other way.")
14204 (defconst org-default-properties
14205 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14206 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14207 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14208 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14209 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14210 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14211 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14212 "Some properties that are used by Org-mode for various purposes.
14213 Being in this list makes sure that they are offered for completion.")
14215 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14216 "Regular expression matching the first line of a property drawer.")
14218 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14219 "Regular expression matching the last line of a property drawer.")
14221 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14222 "Regular expression matching the first line of a property drawer.")
14224 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14225 "Regular expression matching the first line of a property drawer.")
14227 (defconst org-property-drawer-re
14228 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14229 org-property-end-re "\\)\n?")
14230 "Matches an entire property drawer.")
14232 (defconst org-clock-drawer-re
14233 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14234 org-property-end-re "\\)\n?")
14235 "Matches an entire clock drawer.")
14237 (defsubst org-re-property (property)
14238 "Return a regexp matching a PROPERTY line.
14239 Match group 1 will be set to the value."
14240 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14242 (defsubst org-re-property-keyword (property)
14243 "Return a regexp matching a PROPERTY line, possibly with no
14244 value for the property."
14245 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14247 (defun org-property-action ()
14248 "Do an action on properties."
14249 (interactive)
14250 (let (c)
14251 (org-at-property-p)
14252 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14253 (setq c (read-char-exclusive))
14254 (cond
14255 ((equal c ?s)
14256 (call-interactively 'org-set-property))
14257 ((equal c ?d)
14258 (call-interactively 'org-delete-property))
14259 ((equal c ?D)
14260 (call-interactively 'org-delete-property-globally))
14261 ((equal c ?c)
14262 (call-interactively 'org-compute-property-at-point))
14263 (t (error "No such property action %c" c)))))
14265 (defun org-inc-effort ()
14266 "Increment the value of the effort property in the current entry."
14267 (interactive)
14268 (org-set-effort nil t))
14270 (defun org-set-effort (&optional value increment)
14271 "Set the effort property of the current entry.
14272 With numerical prefix arg, use the nth allowed value, 0 stands for the
14273 10th allowed value.
14275 When INCREMENT is non-nil, set the property to the next allowed value."
14276 (interactive "P")
14277 (if (equal value 0) (setq value 10))
14278 (let* ((completion-ignore-case t)
14279 (prop org-effort-property)
14280 (cur (org-entry-get nil prop))
14281 (allowed (org-property-get-allowed-values nil prop 'table))
14282 (existing (mapcar 'list (org-property-values prop)))
14284 (val (cond
14285 ((stringp value) value)
14286 ((and allowed (integerp value))
14287 (or (car (nth (1- value) allowed))
14288 (car (org-last allowed))))
14289 ((and allowed increment)
14290 (or (caadr (member (list cur) allowed))
14291 (error "Allowed effort values are not set")))
14292 (allowed
14293 (message "Select 1-9,0, [RET%s]: %s"
14294 (if cur (concat "=" cur) "")
14295 (mapconcat 'car allowed " "))
14296 (setq rpl (read-char-exclusive))
14297 (if (equal rpl ?\r)
14299 (setq rpl (- rpl ?0))
14300 (if (equal rpl 0) (setq rpl 10))
14301 (if (and (> rpl 0) (<= rpl (length allowed)))
14302 (car (nth (1- rpl) allowed))
14303 (org-completing-read "Effort: " allowed nil))))
14305 (let (org-completion-use-ido org-completion-use-iswitchb)
14306 (org-completing-read
14307 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14308 (concat "[" cur "]") "")
14309 ": ")
14310 existing nil nil "" nil cur))))))
14311 (unless (equal (org-entry-get nil prop) val)
14312 (org-entry-put nil prop val))
14313 (save-excursion
14314 (org-back-to-heading t)
14315 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14316 (message "%s is now %s" prop val)))
14318 (defun org-at-property-p ()
14319 "Is cursor inside a property drawer?"
14320 (save-excursion
14321 (beginning-of-line 1)
14322 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14323 (save-match-data ;; Used by calling procedures
14324 (let ((p (point))
14325 (range (unless (org-before-first-heading-p)
14326 (org-get-property-block))))
14327 (and range (<= (car range) p) (< p (cdr range))))))))
14329 (defun org-get-property-block (&optional beg end force)
14330 "Return the (beg . end) range of the body of the property drawer.
14331 BEG and END are the beginning and end of the current subtree, or of
14332 the part before the first headline. If they are not given, they will
14333 be found. If the drawer does not exist and FORCE is non-nil, create
14334 the drawer."
14335 (catch 'exit
14336 (save-excursion
14337 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14338 (progn (org-back-to-heading t) (point))))
14339 (end (or end (and (not (outline-next-heading)) (point-max))
14340 (point))))
14341 (goto-char beg)
14342 (if (re-search-forward org-property-start-re end t)
14343 (setq beg (1+ (match-end 0)))
14344 (if force
14345 (save-excursion
14346 (org-insert-property-drawer)
14347 (setq end (progn (outline-next-heading) (point))))
14348 (throw 'exit nil))
14349 (goto-char beg)
14350 (if (re-search-forward org-property-start-re end t)
14351 (setq beg (1+ (match-end 0)))))
14352 (if (re-search-forward org-property-end-re end t)
14353 (setq end (match-beginning 0))
14354 (or force (throw 'exit nil))
14355 (goto-char beg)
14356 (setq end beg)
14357 (org-indent-line)
14358 (insert ":END:\n"))
14359 (cons beg end)))))
14361 (defun org-entry-properties (&optional pom which specific)
14362 "Get all properties of the entry at point-or-marker POM.
14363 This includes the TODO keyword, the tags, time strings for deadline,
14364 scheduled, and clocking, and any additional properties defined in the
14365 entry. The return value is an alist, keys may occur multiple times
14366 if the property key was used several times.
14367 POM may also be nil, in which case the current entry is used.
14368 If WHICH is nil or `all', get all properties. If WHICH is
14369 `special' or `standard', only get that subclass. If WHICH
14370 is a string only get exactly this property. SPECIFIC can be a string, the
14371 specific property we are interested in. Specifying it can speed
14372 things up because then unnecessary parsing is avoided."
14373 (setq which (or which 'all))
14374 (org-with-point-at pom
14375 (let ((clockstr (substring org-clock-string 0 -1))
14376 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14377 (case-fold-search nil)
14378 beg end range props sum-props key key1 value string clocksum clocksumt)
14379 (save-excursion
14380 (when (condition-case nil
14381 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14382 (error nil))
14383 (setq beg (point))
14384 (setq sum-props (get-text-property (point) 'org-summaries))
14385 (setq clocksum (get-text-property (point) :org-clock-minutes)
14386 clocksumt (get-text-property (point) :org-clock-minutes-today))
14387 (outline-next-heading)
14388 (setq end (point))
14389 (when (memq which '(all special))
14390 ;; Get the special properties, like TODO and tags
14391 (goto-char beg)
14392 (when (and (or (not specific) (string= specific "TODO"))
14393 (looking-at org-todo-line-regexp) (match-end 2))
14394 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14395 (when (and (or (not specific) (string= specific "PRIORITY"))
14396 (looking-at org-priority-regexp))
14397 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14398 (when (or (not specific) (string= specific "FILE"))
14399 (push (cons "FILE" buffer-file-name) props))
14400 (when (and (or (not specific) (string= specific "TAGS"))
14401 (setq value (org-get-tags-string))
14402 (string-match "\\S-" value))
14403 (push (cons "TAGS" value) props))
14404 (when (and (or (not specific) (string= specific "ALLTAGS"))
14405 (setq value (org-get-tags-at)))
14406 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14407 ":"))
14408 props))
14409 (when (or (not specific) (string= specific "BLOCKED"))
14410 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14411 (when (or (not specific)
14412 (member specific
14413 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14414 "TIMESTAMP" "TIMESTAMP_IA")))
14415 (catch 'match
14416 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14417 (setq key (if (match-end 1)
14418 (substring (org-match-string-no-properties 1)
14419 0 -1))
14420 string (if (equal key clockstr)
14421 (org-trim
14422 (buffer-substring-no-properties
14423 (match-beginning 3) (goto-char
14424 (point-at-eol))))
14425 (substring (org-match-string-no-properties 3)
14426 1 -1)))
14427 ;; Get the correct property name from the key. This is
14428 ;; necessary if the user has configured time keywords.
14429 (setq key1 (concat key ":"))
14430 (cond
14431 ((not key)
14432 (setq key
14433 (if (= (char-after (match-beginning 3)) ?\[)
14434 "TIMESTAMP_IA" "TIMESTAMP")))
14435 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14436 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14437 ((equal key1 org-closed-string) (setq key "CLOSED"))
14438 ((equal key1 org-clock-string) (setq key "CLOCK")))
14439 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14440 (progn
14441 (push (cons key string) props)
14442 ;; no need to search further if match is found
14443 (throw 'match t))
14444 (when (or (equal key "CLOCK") (not (assoc key props)))
14445 (push (cons key string) props)))))))
14447 (when (memq which '(all standard))
14448 ;; Get the standard properties, like :PROP: ...
14449 (setq range (org-get-property-block beg end))
14450 (when range
14451 (goto-char (car range))
14452 (while (re-search-forward
14453 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14454 (cdr range) t)
14455 (setq key (org-match-string-no-properties 1)
14456 value (org-trim (or (org-match-string-no-properties 2) "")))
14457 (unless (member key excluded)
14458 (push (cons key (or value "")) props)))))
14459 (if clocksum
14460 (push (cons "CLOCKSUM"
14461 (org-columns-number-to-string (/ (float clocksum) 60.)
14462 'add_times))
14463 props))
14464 (if clocksumt
14465 (push (cons "CLOCKSUM_T"
14466 (org-columns-number-to-string (/ (float clocksumt) 60.)
14467 'add_times))
14468 props))
14469 (unless (assoc "CATEGORY" props)
14470 (push (cons "CATEGORY" (org-get-category)) props))
14471 (append sum-props (nreverse props)))))))
14473 (defun org-entry-get (pom property &optional inherit literal-nil)
14474 "Get value of PROPERTY for entry or content at point-or-marker POM.
14475 If INHERIT is non-nil and the entry does not have the property,
14476 then also check higher levels of the hierarchy.
14477 If INHERIT is the symbol `selective', use inheritance only if the setting
14478 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14479 If the property is present but empty, the return value is the empty string.
14480 If the property is not present at all, nil is returned.
14482 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14483 do not interpret it as the list atom nil. This is used for inheritance
14484 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14485 (org-with-point-at pom
14486 (if (and inherit (if (eq inherit 'selective)
14487 (org-property-inherit-p property)
14489 (org-entry-get-with-inheritance property literal-nil)
14490 (if (member property org-special-properties)
14491 ;; We need a special property. Use `org-entry-properties' to
14492 ;; retrieve it, but specify the wanted property
14493 (cdr (assoc property (org-entry-properties nil 'special property)))
14494 (let ((range (org-get-property-block)))
14495 (when (and range (not (eq (car range) (cdr range))))
14496 (let* ((props (list (or (assoc property org-file-properties)
14497 (assoc property org-global-properties)
14498 (assoc property org-global-properties-fixed))))
14499 (ap (lambda (key)
14500 (when (re-search-forward
14501 (org-re-property key) (cdr range) t)
14502 (setq props
14503 (org-update-property-plist
14505 (if (match-end 1)
14506 (org-match-string-no-properties 1) "")
14507 props)))))
14508 val)
14509 (goto-char (car range))
14510 (funcall ap property)
14511 (goto-char (car range))
14512 (while (funcall ap (concat property "+")))
14513 (setq val (cdr (assoc property props)))
14514 (when val (if literal-nil val (org-not-nil val))))))))))
14516 (defun org-property-or-variable-value (var &optional inherit)
14517 "Check if there is a property fixing the value of VAR.
14518 If yes, return this value. If not, return the current value of the variable."
14519 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14520 (if (and prop (stringp prop) (string-match "\\S-" prop))
14521 (read prop)
14522 (symbol-value var))))
14524 (defun org-entry-delete (pom property)
14525 "Delete the property PROPERTY from entry at point-or-marker POM."
14526 (org-with-point-at pom
14527 (if (member property org-special-properties)
14528 nil ; cannot delete these properties.
14529 (let ((range (org-get-property-block)))
14530 (if (and range
14531 (goto-char (car range))
14532 (re-search-forward
14533 (org-re-property property)
14534 (cdr range) t))
14535 (progn
14536 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14538 nil)))))
14540 ;; Multi-values properties are properties that contain multiple values
14541 ;; These values are assumed to be single words, separated by whitespace.
14542 (defun org-entry-add-to-multivalued-property (pom property value)
14543 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14544 (let* ((old (org-entry-get pom property))
14545 (values (and old (org-split-string old "[ \t]"))))
14546 (setq value (org-entry-protect-space value))
14547 (unless (member value values)
14548 (setq values (cons value values))
14549 (org-entry-put pom property
14550 (mapconcat 'identity values " ")))))
14552 (defun org-entry-remove-from-multivalued-property (pom property value)
14553 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14554 (let* ((old (org-entry-get pom property))
14555 (values (and old (org-split-string old "[ \t]"))))
14556 (setq value (org-entry-protect-space value))
14557 (when (member value values)
14558 (setq values (delete value values))
14559 (org-entry-put pom property
14560 (mapconcat 'identity values " ")))))
14562 (defun org-entry-member-in-multivalued-property (pom property value)
14563 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14564 (let* ((old (org-entry-get pom property))
14565 (values (and old (org-split-string old "[ \t]"))))
14566 (setq value (org-entry-protect-space value))
14567 (member value values)))
14569 (defun org-entry-get-multivalued-property (pom property)
14570 "Return a list of values in a multivalued property."
14571 (let* ((value (org-entry-get pom property))
14572 (values (and value (org-split-string value "[ \t]"))))
14573 (mapcar 'org-entry-restore-space values)))
14575 (defun org-entry-put-multivalued-property (pom property &rest values)
14576 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14577 VALUES should be a list of strings. Spaces will be protected."
14578 (org-entry-put pom property
14579 (mapconcat 'org-entry-protect-space values " "))
14580 (let* ((value (org-entry-get pom property))
14581 (values (and value (org-split-string value "[ \t]"))))
14582 (mapcar 'org-entry-restore-space values)))
14584 (defun org-entry-protect-space (s)
14585 "Protect spaces and newline in string S."
14586 (while (string-match " " s)
14587 (setq s (replace-match "%20" t t s)))
14588 (while (string-match "\n" s)
14589 (setq s (replace-match "%0A" t t s)))
14592 (defun org-entry-restore-space (s)
14593 "Restore spaces and newline in string S."
14594 (while (string-match "%20" s)
14595 (setq s (replace-match " " t t s)))
14596 (while (string-match "%0A" s)
14597 (setq s (replace-match "\n" t t s)))
14600 (defvar org-entry-property-inherited-from (make-marker)
14601 "Marker pointing to the entry from where a property was inherited.
14602 Each call to `org-entry-get-with-inheritance' will set this marker to the
14603 location of the entry where the inheritance search matched. If there was
14604 no match, the marker will point nowhere.
14605 Note that also `org-entry-get' calls this function, if the INHERIT flag
14606 is set.")
14608 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14609 "Get PROPERTY of entry or content at point, search higher levels if needed.
14610 The search will stop at the first ancestor which has the property defined.
14611 If the value found is \"nil\", return nil to show that the property
14612 should be considered as undefined (this is the meaning of nil here).
14613 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14614 (move-marker org-entry-property-inherited-from nil)
14615 (let (tmp)
14616 (save-excursion
14617 (save-restriction
14618 (widen)
14619 (catch 'ex
14620 (while t
14621 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14622 (or (ignore-errors (org-back-to-heading t))
14623 (goto-char (point-min)))
14624 (move-marker org-entry-property-inherited-from (point))
14625 (throw 'ex tmp))
14626 (or (ignore-errors (org-up-heading-safe))
14627 (throw 'ex nil))))))
14628 (setq tmp (or tmp
14629 (cdr (assoc property org-file-properties))
14630 (cdr (assoc property org-global-properties))
14631 (cdr (assoc property org-global-properties-fixed))))
14632 (if literal-nil tmp (org-not-nil tmp))))
14634 (defvar org-property-changed-functions nil
14635 "Hook called when the value of a property has changed.
14636 Each hook function should accept two arguments, the name of the property
14637 and the new value.")
14639 (defun org-entry-put (pom property value)
14640 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14641 (org-with-point-at pom
14642 (org-back-to-heading t)
14643 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14644 range)
14645 (cond
14646 ((equal property "TODO")
14647 (when (and (stringp value) (string-match "\\S-" value)
14648 (not (member value org-todo-keywords-1)))
14649 (error "\"%s\" is not a valid TODO state" value))
14650 (if (or (not value)
14651 (not (string-match "\\S-" value)))
14652 (setq value 'none))
14653 (org-todo value)
14654 (org-set-tags nil 'align))
14655 ((equal property "PRIORITY")
14656 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14657 (string-to-char value) ?\ ))
14658 (org-set-tags nil 'align))
14659 ((equal property "SCHEDULED")
14660 (if (re-search-forward org-scheduled-time-regexp end t)
14661 (cond
14662 ((eq value 'earlier) (org-timestamp-change -1 'day))
14663 ((eq value 'later) (org-timestamp-change 1 'day))
14664 (t (call-interactively 'org-schedule)))
14665 (call-interactively 'org-schedule)))
14666 ((equal property "DEADLINE")
14667 (if (re-search-forward org-deadline-time-regexp end t)
14668 (cond
14669 ((eq value 'earlier) (org-timestamp-change -1 'day))
14670 ((eq value 'later) (org-timestamp-change 1 'day))
14671 (t (call-interactively 'org-deadline)))
14672 (call-interactively 'org-deadline)))
14673 ((member property org-special-properties)
14674 (error "The %s property can not yet be set with `org-entry-put'"
14675 property))
14676 (t ; a non-special property
14677 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14678 (setq range (org-get-property-block beg end 'force))
14679 (goto-char (car range))
14680 (if (re-search-forward
14681 (org-re-property-keyword property) (cdr range) t)
14682 (progn
14683 (delete-region (match-beginning 0) (match-end 0))
14684 (goto-char (match-beginning 0)))
14685 (goto-char (cdr range))
14686 (insert "\n")
14687 (backward-char 1)
14688 (org-indent-line))
14689 (insert ":" property ":")
14690 (and value (insert " " value))
14691 (org-indent-line)))))
14692 (run-hook-with-args 'org-property-changed-functions property value)))
14694 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14695 "Get all property keys in the current buffer.
14696 With INCLUDE-SPECIALS, also list the special properties that reflect things
14697 like tags and TODO state.
14698 With INCLUDE-DEFAULTS, also include properties that has special meaning
14699 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14700 and others.
14701 With INCLUDE-COLUMNS, also include property names given in COLUMN
14702 formats in the current buffer."
14703 (let (rtn range cfmt s p)
14704 (save-excursion
14705 (save-restriction
14706 (widen)
14707 (goto-char (point-min))
14708 (while (re-search-forward org-property-start-re nil t)
14709 (setq range (org-get-property-block))
14710 (goto-char (car range))
14711 (while (re-search-forward
14712 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14713 (cdr range) t)
14714 (add-to-list 'rtn (org-match-string-no-properties 1)))
14715 (outline-next-heading))))
14717 (when include-specials
14718 (setq rtn (append org-special-properties rtn)))
14720 (when include-defaults
14721 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14722 (add-to-list 'rtn org-effort-property))
14724 (when include-columns
14725 (save-excursion
14726 (save-restriction
14727 (widen)
14728 (goto-char (point-min))
14729 (while (re-search-forward
14730 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14731 nil t)
14732 (setq cfmt (match-string 2) s 0)
14733 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14734 cfmt s)
14735 (setq s (match-end 0)
14736 p (match-string 1 cfmt))
14737 (unless (or (equal p "ITEM")
14738 (member p org-special-properties))
14739 (add-to-list 'rtn (match-string 1 cfmt))))))))
14741 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14743 (defun org-property-values (key)
14744 "Return a list of all values of property KEY in the current buffer."
14745 (save-excursion
14746 (save-restriction
14747 (widen)
14748 (goto-char (point-min))
14749 (let ((re (org-re-property key))
14750 values)
14751 (while (re-search-forward re nil t)
14752 (add-to-list 'values (org-trim (match-string 1))))
14753 (delete "" values)))))
14755 (defun org-insert-property-drawer ()
14756 "Insert a property drawer into the current entry."
14757 (org-back-to-heading t)
14758 (looking-at org-outline-regexp)
14759 (let ((indent (if org-adapt-indentation
14760 (- (match-end 0) (match-beginning 0))
14762 (beg (point))
14763 (re (concat "^[ \t]*" org-keyword-time-regexp))
14764 end hiddenp)
14765 (outline-next-heading)
14766 (setq end (point))
14767 (goto-char beg)
14768 (while (re-search-forward re end t))
14769 (setq hiddenp (outline-invisible-p))
14770 (end-of-line 1)
14771 (and (equal (char-after) ?\n) (forward-char 1))
14772 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14773 (if (member (match-string 1) '("CLOCK:" ":END:"))
14774 ;; just skip this line
14775 (beginning-of-line 2)
14776 ;; Drawer start, find the end
14777 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14778 (beginning-of-line 1)))
14779 (org-skip-over-state-notes)
14780 (skip-chars-backward " \t\n\r")
14781 (if (eq (char-before) ?*) (forward-char 1))
14782 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14783 (beginning-of-line 0)
14784 (org-indent-to-column indent)
14785 (beginning-of-line 2)
14786 (org-indent-to-column indent)
14787 (beginning-of-line 0)
14788 (if hiddenp
14789 (save-excursion
14790 (org-back-to-heading t)
14791 (hide-entry))
14792 (org-flag-drawer t))))
14794 (defun org-insert-drawer (&optional arg drawer)
14795 "Insert a drawer at point.
14797 Optional argument DRAWER, when non-nil, is a string representing
14798 drawer's name. Otherwise, the user is prompted for a name.
14800 If a region is active, insert the drawer around that region
14801 instead.
14803 Point is left between drawer's boundaries."
14804 (interactive "P")
14805 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14806 "LOGBOOK"))
14807 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14808 ;; internally by Org. They are meant to be inserted
14809 ;; automatically.
14810 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14811 ;; Remove system drawers from list. Note: For some reason,
14812 ;; `org-completing-read' ignores the predicate while
14813 ;; `completing-read' handles it fine.
14814 (drawer (if arg "PROPERTIES"
14815 (or drawer
14816 (completing-read
14817 "Drawer: " org-drawers
14818 (lambda (d) (not (member d system-drawers))))))))
14819 (cond
14820 ;; With C-u, fall back on `org-insert-property-drawer'
14821 (arg (org-insert-property-drawer))
14822 ;; With an active region, insert a drawer at point.
14823 ((not (org-region-active-p))
14824 (progn
14825 (unless (bolp) (insert "\n"))
14826 (insert (format ":%s:\n\n:END:\n" drawer))
14827 (forward-line -2)))
14828 ;; Otherwise, insert the drawer at point
14830 (let ((rbeg (region-beginning))
14831 (rend (copy-marker (region-end))))
14832 (unwind-protect
14833 (progn
14834 (goto-char rbeg)
14835 (beginning-of-line)
14836 (when (save-excursion
14837 (re-search-forward org-outline-regexp-bol rend t))
14838 (error "Drawers cannot contain headlines"))
14839 ;; Position point at the beginning of the first
14840 ;; non-blank line in region. Insert drawer's opening
14841 ;; there, then indent it.
14842 (org-skip-whitespace)
14843 (beginning-of-line)
14844 (insert ":" drawer ":\n")
14845 (forward-line -1)
14846 (indent-for-tab-command)
14847 ;; Move point to the beginning of the first blank line
14848 ;; after the last non-blank line in region. Insert
14849 ;; drawer's closing, then indent it.
14850 (goto-char rend)
14851 (skip-chars-backward " \r\t\n")
14852 (insert "\n:END:")
14853 (deactivate-mark t)
14854 (indent-for-tab-command)
14855 (unless (eolp) (insert "\n")))
14856 ;; Clear marker, whatever the outcome of insertion is.
14857 (set-marker rend nil)))))))
14859 (defvar org-property-set-functions-alist nil
14860 "Property set function alist.
14861 Each entry should have the following format:
14863 (PROPERTY . READ-FUNCTION)
14865 The read function will be called with the same argument as
14866 `org-completing-read'.")
14868 (defun org-set-property-function (property)
14869 "Get the function that should be used to set PROPERTY.
14870 This is computed according to `org-property-set-functions-alist'."
14871 (or (cdr (assoc property org-property-set-functions-alist))
14872 'org-completing-read))
14874 (defun org-read-property-value (property)
14875 "Read PROPERTY value from user."
14876 (let* ((completion-ignore-case t)
14877 (allowed (org-property-get-allowed-values nil property 'table))
14878 (cur (org-entry-get nil property))
14879 (prompt (concat property " value"
14880 (if (and cur (string-match "\\S-" cur))
14881 (concat " [" cur "]") "") ": "))
14882 (set-function (org-set-property-function property))
14883 (val (if allowed
14884 (funcall set-function prompt allowed nil
14885 (not (get-text-property 0 'org-unrestricted
14886 (caar allowed))))
14887 (let (org-completion-use-ido org-completion-use-iswitchb)
14888 (funcall set-function prompt
14889 (mapcar 'list (org-property-values property))
14890 nil nil "" nil cur)))))
14891 (if (equal val "")
14893 val)))
14895 (defvar org-last-set-property nil)
14896 (defun org-read-property-name ()
14897 "Read a property name."
14898 (let* ((completion-ignore-case t)
14899 (keys (org-buffer-property-keys nil t t))
14900 (default-prop (or (save-excursion
14901 (save-match-data
14902 (beginning-of-line)
14903 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14904 (null (string= (match-string 1) "END"))
14905 (match-string 1))))
14906 org-last-set-property))
14907 (property (org-icompleting-read
14908 (concat "Property"
14909 (if default-prop (concat " [" default-prop "]") "")
14910 ": ")
14911 (mapcar 'list keys)
14912 nil nil nil nil
14913 default-prop
14915 (if (member property keys)
14916 property
14917 (or (cdr (assoc (downcase property)
14918 (mapcar (lambda (x) (cons (downcase x) x))
14919 keys)))
14920 property))))
14922 (defun org-set-property (property value)
14923 "In the current entry, set PROPERTY to VALUE.
14924 When called interactively, this will prompt for a property name, offering
14925 completion on existing and default properties. And then it will prompt
14926 for a value, offering completion either on allowed values (via an inherited
14927 xxx_ALL property) or on existing values in other instances of this property
14928 in the current file."
14929 (interactive (list nil nil))
14930 (let* ((property (or property (org-read-property-name)))
14931 (value (or value (org-read-property-value property)))
14932 (fn (cdr (assoc property org-properties-postprocess-alist))))
14933 (setq org-last-set-property property)
14934 ;; Possibly postprocess the inserted value:
14935 (when fn (setq value (funcall fn value)))
14936 (unless (equal (org-entry-get nil property) value)
14937 (org-entry-put nil property value))))
14939 (defun org-delete-property (property)
14940 "In the current entry, delete PROPERTY."
14941 (interactive
14942 (let* ((completion-ignore-case t)
14943 (prop (org-icompleting-read "Property: "
14944 (org-entry-properties nil 'standard))))
14945 (list prop)))
14946 (message "Property %s %s" property
14947 (if (org-entry-delete nil property)
14948 "deleted"
14949 "was not present in the entry")))
14951 (defun org-delete-property-globally (property)
14952 "Remove PROPERTY globally, from all entries."
14953 (interactive
14954 (let* ((completion-ignore-case t)
14955 (prop (org-icompleting-read
14956 "Globally remove property: "
14957 (mapcar 'list (org-buffer-property-keys)))))
14958 (list prop)))
14959 (save-excursion
14960 (save-restriction
14961 (widen)
14962 (goto-char (point-min))
14963 (let ((cnt 0))
14964 (while (re-search-forward
14965 (org-re-property property)
14966 nil t)
14967 (setq cnt (1+ cnt))
14968 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14969 (message "Property \"%s\" removed from %d entries" property cnt)))))
14971 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14973 (defun org-compute-property-at-point ()
14974 "Compute the property at point.
14975 This looks for an enclosing column format, extracts the operator and
14976 then applies it to the property in the column format's scope."
14977 (interactive)
14978 (unless (org-at-property-p)
14979 (error "Not at a property"))
14980 (let ((prop (org-match-string-no-properties 2)))
14981 (org-columns-get-format-and-top-level)
14982 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14983 (error "No operator defined for property %s" prop))
14984 (org-columns-compute prop)))
14986 (defvar org-property-allowed-value-functions nil
14987 "Hook for functions supplying allowed values for a specific property.
14988 The functions must take a single argument, the name of the property, and
14989 return a flat list of allowed values. If \":ETC\" is one of
14990 the values, this means that these values are intended as defaults for
14991 completion, but that other values should be allowed too.
14992 The functions must return nil if they are not responsible for this
14993 property.")
14995 (defun org-property-get-allowed-values (pom property &optional table)
14996 "Get allowed values for the property PROPERTY.
14997 When TABLE is non-nil, return an alist that can directly be used for
14998 completion."
14999 (let (vals)
15000 (cond
15001 ((equal property "TODO")
15002 (setq vals (org-with-point-at pom
15003 (append org-todo-keywords-1 '("")))))
15004 ((equal property "PRIORITY")
15005 (let ((n org-lowest-priority))
15006 (while (>= n org-highest-priority)
15007 (push (char-to-string n) vals)
15008 (setq n (1- n)))))
15009 ((member property org-special-properties))
15010 ((setq vals (run-hook-with-args-until-success
15011 'org-property-allowed-value-functions property)))
15013 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15014 (when (and vals (string-match "\\S-" vals))
15015 (setq vals (car (read-from-string (concat "(" vals ")"))))
15016 (setq vals (mapcar (lambda (x)
15017 (cond ((stringp x) x)
15018 ((numberp x) (number-to-string x))
15019 ((symbolp x) (symbol-name x))
15020 (t "???")))
15021 vals)))))
15022 (when (member ":ETC" vals)
15023 (setq vals (remove ":ETC" vals))
15024 (org-add-props (car vals) '(org-unrestricted t)))
15025 (if table (mapcar 'list vals) vals)))
15027 (defun org-property-previous-allowed-value (&optional previous)
15028 "Switch to the next allowed value for this property."
15029 (interactive)
15030 (org-property-next-allowed-value t))
15032 (defun org-property-next-allowed-value (&optional previous)
15033 "Switch to the next allowed value for this property."
15034 (interactive)
15035 (unless (org-at-property-p)
15036 (error "Not at a property"))
15037 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15038 (key (match-string 2))
15039 (value (match-string 3))
15040 (allowed (or (org-property-get-allowed-values (point) key)
15041 (and (member value '("[ ]" "[-]" "[X]"))
15042 '("[ ]" "[X]"))))
15043 nval)
15044 (unless allowed
15045 (error "Allowed values for this property have not been defined"))
15046 (if previous (setq allowed (reverse allowed)))
15047 (if (member value allowed)
15048 (setq nval (car (cdr (member value allowed)))))
15049 (setq nval (or nval (car allowed)))
15050 (if (equal nval value)
15051 (error "Only one allowed value for this property"))
15052 (org-at-property-p)
15053 (replace-match (concat " :" key ": " nval) t t)
15054 (org-indent-line)
15055 (beginning-of-line 1)
15056 (skip-chars-forward " \t")
15057 (when (equal prop org-effort-property)
15058 (save-excursion
15059 (org-back-to-heading t)
15060 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15061 (run-hook-with-args 'org-property-changed-functions key nval)))
15063 (defun org-find-olp (path &optional this-buffer)
15064 "Return a marker pointing to the entry at outline path OLP.
15065 If anything goes wrong, throw an error.
15066 You can wrap this call to catch the error like this:
15068 (condition-case msg
15069 (org-mobile-locate-entry (match-string 4))
15070 (error (nth 1 msg)))
15072 The return value will then be either a string with the error message,
15073 or a marker if everything is OK.
15075 If THIS-BUFFER is set, the outline path does not contain a file,
15076 only headings."
15077 (let* ((file (if this-buffer buffer-file-name (pop path)))
15078 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15079 (level 1)
15080 (lmin 1)
15081 (lmax 1)
15082 limit re end found pos heading cnt flevel)
15083 (unless buffer (error "File not found :%s" file))
15084 (with-current-buffer buffer
15085 (save-excursion
15086 (save-restriction
15087 (widen)
15088 (setq limit (point-max))
15089 (goto-char (point-min))
15090 (while (setq heading (pop path))
15091 (setq re (format org-complex-heading-regexp-format
15092 (regexp-quote heading)))
15093 (setq cnt 0 pos (point))
15094 (while (re-search-forward re end t)
15095 (setq level (- (match-end 1) (match-beginning 1)))
15096 (if (and (>= level lmin) (<= level lmax))
15097 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15098 (when (= cnt 0) (error "Heading not found on level %d: %s"
15099 lmax heading))
15100 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15101 lmax heading))
15102 (goto-char found)
15103 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15104 (setq end (save-excursion (org-end-of-subtree t t))))
15105 (when (org-at-heading-p)
15106 (point-marker)))))))
15108 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15109 "Find node HEADING in BUFFER.
15110 Return a marker to the heading if it was found, or nil if not.
15111 If POS-ONLY is set, return just the position instead of a marker.
15113 The heading text must match exact, but it may have a TODO keyword,
15114 a priority cookie and tags in the standard locations."
15115 (with-current-buffer (or buffer (current-buffer))
15116 (save-excursion
15117 (save-restriction
15118 (widen)
15119 (goto-char (point-min))
15120 (let (case-fold-search)
15121 (if (re-search-forward
15122 (format org-complex-heading-regexp-format
15123 (regexp-quote heading)) nil t)
15124 (if pos-only
15125 (match-beginning 0)
15126 (move-marker (make-marker) (match-beginning 0)))))))))
15128 (defun org-find-exact-heading-in-directory (heading &optional dir)
15129 "Find Org node headline HEADING in all .org files in directory DIR.
15130 When the target headline is found, return a marker to this location."
15131 (let ((files (directory-files (or dir default-directory)
15132 nil "\\`[^.#].*\\.org\\'"))
15133 file visiting m buffer)
15134 (catch 'found
15135 (while (setq file (pop files))
15136 (message "trying %s" file)
15137 (setq visiting (org-find-base-buffer-visiting file))
15138 (setq buffer (or visiting (find-file-noselect file)))
15139 (setq m (org-find-exact-headline-in-buffer
15140 heading buffer))
15141 (when (and (not m) (not visiting)) (kill-buffer buffer))
15142 (and m (throw 'found m))))))
15144 (defun org-find-entry-with-id (ident)
15145 "Locate the entry that contains the ID property with exact value IDENT.
15146 IDENT can be a string, a symbol or a number, this function will search for
15147 the string representation of it.
15148 Return the position where this entry starts, or nil if there is no such entry."
15149 (interactive "sID: ")
15150 (let ((id (cond
15151 ((stringp ident) ident)
15152 ((symbol-name ident) (symbol-name ident))
15153 ((numberp ident) (number-to-string ident))
15154 (t (error "IDENT %s must be a string, symbol or number" ident))))
15155 (case-fold-search nil))
15156 (save-excursion
15157 (save-restriction
15158 (widen)
15159 (goto-char (point-min))
15160 (when (re-search-forward
15161 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15162 nil t)
15163 (org-back-to-heading t)
15164 (point))))))
15166 ;;;; Timestamps
15168 (defvar org-last-changed-timestamp nil)
15169 (defvar org-last-inserted-timestamp nil
15170 "The last time stamp inserted with `org-insert-time-stamp'.")
15171 (defvar org-time-was-given) ; dynamically scoped parameter
15172 (defvar org-end-time-was-given) ; dynamically scoped parameter
15173 (defvar org-ts-what) ; dynamically scoped parameter
15175 (defun org-time-stamp (arg &optional inactive)
15176 "Prompt for a date/time and insert a time stamp.
15177 If the user specifies a time like HH:MM or if this command is
15178 called with at least one prefix argument, the time stamp contains
15179 the date and the time. Otherwise, only the date is be included.
15181 All parts of a date not specified by the user is filled in from
15182 the current date/time. So if you just press return without
15183 typing anything, the time stamp will represent the current
15184 date/time.
15186 If there is already a timestamp at the cursor, it will be
15187 modified.
15189 With two universal prefix arguments, insert an active timestamp
15190 with the current time without prompting the user."
15191 (interactive "P")
15192 (let* ((ts nil)
15193 (default-time
15194 ;; Default time is either today, or, when entering a range,
15195 ;; the range start.
15196 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15197 (save-excursion
15198 (re-search-backward
15199 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15200 (- (point) 20) t)))
15201 (apply 'encode-time (org-parse-time-string (match-string 1)))
15202 (current-time)))
15203 (default-input (and ts (org-get-compact-tod ts)))
15204 (repeater (save-excursion
15205 (save-match-data
15206 (beginning-of-line)
15207 (when (re-search-forward
15208 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15209 (save-excursion (progn (end-of-line) (point))) t)
15210 (match-string 0)))))
15211 org-time-was-given org-end-time-was-given time)
15212 (cond
15213 ((and (org-at-timestamp-p t)
15214 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15215 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15216 (insert "--")
15217 (setq time (let ((this-command this-command))
15218 (org-read-date arg 'totime nil nil
15219 default-time default-input inactive)))
15220 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15221 ((org-at-timestamp-p t)
15222 (setq time (let ((this-command this-command))
15223 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15224 (when (org-at-timestamp-p t) ; just to get the match data
15225 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15226 (replace-match "")
15227 (setq org-last-changed-timestamp
15228 (org-insert-time-stamp
15229 time (or org-time-was-given arg)
15230 inactive nil nil (list org-end-time-was-given)))
15231 (when repeater (goto-char (1- (point))) (insert " " repeater)
15232 (setq org-last-changed-timestamp
15233 (concat (substring org-last-inserted-timestamp 0 -1)
15234 " " repeater ">"))))
15235 (message "Timestamp updated"))
15236 ((equal arg '(16))
15237 (org-insert-time-stamp (current-time) t))
15239 (setq time (let ((this-command this-command))
15240 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15241 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15242 nil nil (list org-end-time-was-given))))))
15244 ;; FIXME: can we use this for something else, like computing time differences?
15245 (defun org-get-compact-tod (s)
15246 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15247 (let* ((t1 (match-string 1 s))
15248 (h1 (string-to-number (match-string 2 s)))
15249 (m1 (string-to-number (match-string 3 s)))
15250 (t2 (and (match-end 4) (match-string 5 s)))
15251 (h2 (and t2 (string-to-number (match-string 6 s))))
15252 (m2 (and t2 (string-to-number (match-string 7 s))))
15253 dh dm)
15254 (if (not t2)
15256 (setq dh (- h2 h1) dm (- m2 m1))
15257 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15258 (concat t1 "+" (number-to-string dh)
15259 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15261 (defun org-time-stamp-inactive (&optional arg)
15262 "Insert an inactive time stamp.
15263 An inactive time stamp is enclosed in square brackets instead of angle
15264 brackets. It is inactive in the sense that it does not trigger agenda entries,
15265 does not link to the calendar and cannot be changed with the S-cursor keys.
15266 So these are more for recording a certain time/date."
15267 (interactive "P")
15268 (org-time-stamp arg 'inactive))
15270 (defvar org-date-ovl (make-overlay 1 1))
15271 (overlay-put org-date-ovl 'face 'org-date-selected)
15272 (org-detach-overlay org-date-ovl)
15274 (defvar org-ans1) ; dynamically scoped parameter
15275 (defvar org-ans2) ; dynamically scoped parameter
15277 (defvar org-plain-time-of-day-regexp) ; defined below
15279 (defvar org-overriding-default-time nil) ; dynamically scoped
15280 (defvar org-read-date-overlay nil)
15281 (defvar org-dcst nil) ; dynamically scoped
15282 (defvar org-read-date-history nil)
15283 (defvar org-read-date-final-answer nil)
15284 (defvar org-read-date-analyze-futurep nil)
15285 (defvar org-read-date-analyze-forced-year nil)
15286 (defvar org-read-date-inactive)
15288 (defun org-read-date (&optional org-with-time to-time from-string prompt
15289 default-time default-input inactive)
15290 "Read a date, possibly a time, and make things smooth for the user.
15291 The prompt will suggest to enter an ISO date, but you can also enter anything
15292 which will at least partially be understood by `parse-time-string'.
15293 Unrecognized parts of the date will default to the current day, month, year,
15294 hour and minute. If this command is called to replace a timestamp at point,
15295 or to enter the second timestamp of a range, the default time is taken
15296 from the existing stamp. Furthermore, the command prefers the future,
15297 so if you are giving a date where the year is not given, and the day-month
15298 combination is already past in the current year, it will assume you
15299 mean next year. For details, see the manual. A few examples:
15301 3-2-5 --> 2003-02-05
15302 feb 15 --> currentyear-02-15
15303 2/15 --> currentyear-02-15
15304 sep 12 9 --> 2009-09-12
15305 12:45 --> today 12:45
15306 22 sept 0:34 --> currentyear-09-22 0:34
15307 12 --> currentyear-currentmonth-12
15308 Fri --> nearest Friday (today or later)
15309 etc.
15311 Furthermore you can specify a relative date by giving, as the *first* thing
15312 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15313 change in days weeks, months, years.
15314 With a single plus or minus, the date is relative to today. With a double
15315 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15316 +4d --> four days from today
15317 +4 --> same as above
15318 +2w --> two weeks from today
15319 ++5 --> five days from default date
15321 The function understands only English month and weekday abbreviations.
15323 While prompting, a calendar is popped up - you can also select the
15324 date with the mouse (button 1). The calendar shows a period of three
15325 months. To scroll it to other months, use the keys `>' and `<'.
15326 If you don't like the calendar, turn it off with
15327 \(setq org-read-date-popup-calendar nil)
15329 With optional argument TO-TIME, the date will immediately be converted
15330 to an internal time.
15331 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15332 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15333 still enter a time, and this function will inform the calling routine
15334 about this change. The calling routine may then choose to change the
15335 format used to insert the time stamp into the buffer to include the time.
15336 With optional argument FROM-STRING, read from this string instead from
15337 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15338 the time/date that is used for everything that is not specified by the
15339 user."
15340 (require 'parse-time)
15341 (let* ((org-time-stamp-rounding-minutes
15342 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15343 (org-dcst org-display-custom-times)
15344 (ct (org-current-time))
15345 (org-def (or org-overriding-default-time default-time ct))
15346 (org-defdecode (decode-time org-def))
15347 (dummy (progn
15348 (when (< (nth 2 org-defdecode) org-extend-today-until)
15349 (setcar (nthcdr 2 org-defdecode) -1)
15350 (setcar (nthcdr 1 org-defdecode) 59)
15351 (setq org-def (apply 'encode-time org-defdecode)
15352 org-defdecode (decode-time org-def)))))
15353 (mouse-autoselect-window nil) ; Don't let the mouse jump
15354 (calendar-frame-setup nil)
15355 (calendar-setup nil)
15356 (calendar-move-hook nil)
15357 (calendar-view-diary-initially-flag nil)
15358 (calendar-view-holidays-initially-flag nil)
15359 (timestr (format-time-string
15360 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15361 (prompt (concat (if prompt (concat prompt " ") "")
15362 (format "Date+time [%s]: " timestr)))
15363 ans (org-ans0 "") org-ans1 org-ans2 final)
15365 (cond
15366 (from-string (setq ans from-string))
15367 (org-read-date-popup-calendar
15368 (save-excursion
15369 (save-window-excursion
15370 (calendar)
15371 (org-eval-in-calendar '(setq cursor-type nil) t)
15372 (unwind-protect
15373 (progn
15374 (calendar-forward-day (- (time-to-days org-def)
15375 (calendar-absolute-from-gregorian
15376 (calendar-current-date))))
15377 (org-eval-in-calendar nil t)
15378 (let* ((old-map (current-local-map))
15379 (map (copy-keymap calendar-mode-map))
15380 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15381 (org-defkey map (kbd "RET") 'org-calendar-select)
15382 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15383 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15384 (org-defkey minibuffer-local-map [(meta shift left)]
15385 (lambda () (interactive)
15386 (org-eval-in-calendar '(calendar-backward-month 1))))
15387 (org-defkey minibuffer-local-map [(meta shift right)]
15388 (lambda () (interactive)
15389 (org-eval-in-calendar '(calendar-forward-month 1))))
15390 (org-defkey minibuffer-local-map [(meta shift up)]
15391 (lambda () (interactive)
15392 (org-eval-in-calendar '(calendar-backward-year 1))))
15393 (org-defkey minibuffer-local-map [(meta shift down)]
15394 (lambda () (interactive)
15395 (org-eval-in-calendar '(calendar-forward-year 1))))
15396 (org-defkey minibuffer-local-map [?\e (shift left)]
15397 (lambda () (interactive)
15398 (org-eval-in-calendar '(calendar-backward-month 1))))
15399 (org-defkey minibuffer-local-map [?\e (shift right)]
15400 (lambda () (interactive)
15401 (org-eval-in-calendar '(calendar-forward-month 1))))
15402 (org-defkey minibuffer-local-map [?\e (shift up)]
15403 (lambda () (interactive)
15404 (org-eval-in-calendar '(calendar-backward-year 1))))
15405 (org-defkey minibuffer-local-map [?\e (shift down)]
15406 (lambda () (interactive)
15407 (org-eval-in-calendar '(calendar-forward-year 1))))
15408 (org-defkey minibuffer-local-map [(shift up)]
15409 (lambda () (interactive)
15410 (org-eval-in-calendar '(calendar-backward-week 1))))
15411 (org-defkey minibuffer-local-map [(shift down)]
15412 (lambda () (interactive)
15413 (org-eval-in-calendar '(calendar-forward-week 1))))
15414 (org-defkey minibuffer-local-map [(shift left)]
15415 (lambda () (interactive)
15416 (org-eval-in-calendar '(calendar-backward-day 1))))
15417 (org-defkey minibuffer-local-map [(shift right)]
15418 (lambda () (interactive)
15419 (org-eval-in-calendar '(calendar-forward-day 1))))
15420 (org-defkey minibuffer-local-map ">"
15421 (lambda () (interactive)
15422 (org-eval-in-calendar '(scroll-calendar-left 1))))
15423 (org-defkey minibuffer-local-map "<"
15424 (lambda () (interactive)
15425 (org-eval-in-calendar '(scroll-calendar-right 1))))
15426 (org-defkey minibuffer-local-map "\C-v"
15427 (lambda () (interactive)
15428 (org-eval-in-calendar
15429 '(calendar-scroll-left-three-months 1))))
15430 (org-defkey minibuffer-local-map "\M-v"
15431 (lambda () (interactive)
15432 (org-eval-in-calendar
15433 '(calendar-scroll-right-three-months 1))))
15434 (run-hooks 'org-read-date-minibuffer-setup-hook)
15435 (unwind-protect
15436 (progn
15437 (use-local-map map)
15438 (setq org-read-date-inactive inactive)
15439 (add-hook 'post-command-hook 'org-read-date-display)
15440 (setq org-ans0 (read-string prompt default-input
15441 'org-read-date-history nil))
15442 ;; org-ans0: from prompt
15443 ;; org-ans1: from mouse click
15444 ;; org-ans2: from calendar motion
15445 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15446 (remove-hook 'post-command-hook 'org-read-date-display)
15447 (use-local-map old-map)
15448 (when org-read-date-overlay
15449 (delete-overlay org-read-date-overlay)
15450 (setq org-read-date-overlay nil)))))
15451 (bury-buffer "*Calendar*")))))
15453 (t ; Naked prompt only
15454 (unwind-protect
15455 (setq ans (read-string prompt default-input
15456 'org-read-date-history timestr))
15457 (when org-read-date-overlay
15458 (delete-overlay org-read-date-overlay)
15459 (setq org-read-date-overlay nil)))))
15461 (setq final (org-read-date-analyze ans org-def org-defdecode))
15463 (when org-read-date-analyze-forced-year
15464 (message "Year was forced into %s"
15465 (if org-read-date-force-compatible-dates
15466 "compatible range (1970-2037)"
15467 "range representable on this machine"))
15468 (ding))
15470 ;; One round trip to get rid of 34th of August and stuff like that....
15471 (setq final (decode-time (apply 'encode-time final)))
15473 (setq org-read-date-final-answer ans)
15475 (if to-time
15476 (apply 'encode-time final)
15477 (if (and (boundp 'org-time-was-given) org-time-was-given)
15478 (format "%04d-%02d-%02d %02d:%02d"
15479 (nth 5 final) (nth 4 final) (nth 3 final)
15480 (nth 2 final) (nth 1 final))
15481 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15483 (defvar org-def)
15484 (defvar org-defdecode)
15485 (defvar org-with-time)
15486 (defun org-read-date-display ()
15487 "Display the current date prompt interpretation in the minibuffer."
15488 (when org-read-date-display-live
15489 (when org-read-date-overlay
15490 (delete-overlay org-read-date-overlay))
15491 (when (minibufferp (current-buffer))
15492 (save-excursion
15493 (end-of-line 1)
15494 (while (not (equal (buffer-substring
15495 (max (point-min) (- (point) 4)) (point))
15496 " "))
15497 (insert " ")))
15498 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15499 " " (or org-ans1 org-ans2)))
15500 (org-end-time-was-given nil)
15501 (f (org-read-date-analyze ans org-def org-defdecode))
15502 (fmts (if org-dcst
15503 org-time-stamp-custom-formats
15504 org-time-stamp-formats))
15505 (fmt (if (or org-with-time
15506 (and (boundp 'org-time-was-given) org-time-was-given))
15507 (cdr fmts)
15508 (car fmts)))
15509 (txt (format-time-string fmt (apply 'encode-time f)))
15510 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15511 (txt (concat "=> " txt)))
15512 (when (and org-end-time-was-given
15513 (string-match org-plain-time-of-day-regexp txt))
15514 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15515 org-end-time-was-given
15516 (substring txt (match-end 0)))))
15517 (when org-read-date-analyze-futurep
15518 (setq txt (concat txt " (=>F)")))
15519 (setq org-read-date-overlay
15520 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15521 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15523 (defun org-read-date-analyze (ans org-def org-defdecode)
15524 "Analyze the combined answer of the date prompt."
15525 ;; FIXME: cleanup and comment
15526 (let ((nowdecode (decode-time (current-time)))
15527 delta deltan deltaw deltadef year month day
15528 hour minute second wday pm h2 m2 tl wday1
15529 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15530 (setq org-read-date-analyze-futurep nil
15531 org-read-date-analyze-forced-year nil)
15532 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15533 (setq ans "+0"))
15535 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15536 (setq ans (replace-match "" t t ans)
15537 deltan (car delta)
15538 deltaw (nth 1 delta)
15539 deltadef (nth 2 delta)))
15541 ;; Check if there is an iso week date in there. If yes, store the
15542 ;; info and postpone interpreting it until the rest of the parsing
15543 ;; is done.
15544 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15545 (setq iso-year (if (match-end 1)
15546 (org-small-year-to-year
15547 (string-to-number (match-string 1 ans))))
15548 iso-weekday (if (match-end 3)
15549 (string-to-number (match-string 3 ans)))
15550 iso-week (string-to-number (match-string 2 ans)))
15551 (setq ans (replace-match "" t t ans)))
15553 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15554 (when (string-match
15555 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15556 (setq year (if (match-end 2)
15557 (string-to-number (match-string 2 ans))
15558 (progn (setq kill-year t)
15559 (string-to-number (format-time-string "%Y"))))
15560 month (string-to-number (match-string 3 ans))
15561 day (string-to-number (match-string 4 ans)))
15562 (if (< year 100) (setq year (+ 2000 year)))
15563 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15564 t nil ans)))
15566 ;; Help matching dotted european dates
15567 (when (string-match
15568 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15569 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15570 (setq kill-year t)
15571 (string-to-number (format-time-string "%Y")))
15572 day (string-to-number (match-string 1 ans))
15573 month (string-to-number (match-string 2 ans))
15574 ans (replace-match (format "%04d-%02d-%02d" year month day)
15575 t nil ans)))
15577 ;; Help matching american dates, like 5/30 or 5/30/7
15578 (when (string-match
15579 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15580 (setq year (if (match-end 4)
15581 (string-to-number (match-string 4 ans))
15582 (progn (setq kill-year t)
15583 (string-to-number (format-time-string "%Y"))))
15584 month (string-to-number (match-string 1 ans))
15585 day (string-to-number (match-string 2 ans)))
15586 (if (< year 100) (setq year (+ 2000 year)))
15587 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15588 t nil ans)))
15589 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15590 ;; If there is a time with am/pm, and *no* time without it, we convert
15591 ;; so that matching will be successful.
15592 (loop for i from 1 to 2 do ; twice, for end time as well
15593 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15594 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15595 (setq hour (string-to-number (match-string 1 ans))
15596 minute (if (match-end 3)
15597 (string-to-number (match-string 3 ans))
15599 pm (equal ?p
15600 (string-to-char (downcase (match-string 4 ans)))))
15601 (if (and (= hour 12) (not pm))
15602 (setq hour 0)
15603 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15604 (setq ans (replace-match (format "%02d:%02d" hour minute)
15605 t t ans))))
15607 ;; Check if a time range is given as a duration
15608 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15609 (setq hour (string-to-number (match-string 1 ans))
15610 h2 (+ hour (string-to-number (match-string 3 ans)))
15611 minute (string-to-number (match-string 2 ans))
15612 m2 (+ minute (if (match-end 5) (string-to-number
15613 (match-string 5 ans))0)))
15614 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15615 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15616 t t ans)))
15618 ;; Check if there is a time range
15619 (when (boundp 'org-end-time-was-given)
15620 (setq org-time-was-given nil)
15621 (when (and (string-match org-plain-time-of-day-regexp ans)
15622 (match-end 8))
15623 (setq org-end-time-was-given (match-string 8 ans))
15624 (setq ans (concat (substring ans 0 (match-beginning 7))
15625 (substring ans (match-end 7))))))
15627 (setq tl (parse-time-string ans)
15628 day (or (nth 3 tl) (nth 3 org-defdecode))
15629 month (or (nth 4 tl)
15630 (if (and org-read-date-prefer-future
15631 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15632 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15633 (nth 4 org-defdecode)))
15634 year (or (and (not kill-year) (nth 5 tl))
15635 (if (and org-read-date-prefer-future
15636 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15637 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15638 (nth 5 org-defdecode)))
15639 hour (or (nth 2 tl) (nth 2 org-defdecode))
15640 minute (or (nth 1 tl) (nth 1 org-defdecode))
15641 second (or (nth 0 tl) 0)
15642 wday (nth 6 tl))
15644 (when (and (eq org-read-date-prefer-future 'time)
15645 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15646 (equal day (nth 3 nowdecode))
15647 (equal month (nth 4 nowdecode))
15648 (equal year (nth 5 nowdecode))
15649 (nth 2 tl)
15650 (or (< (nth 2 tl) (nth 2 nowdecode))
15651 (and (= (nth 2 tl) (nth 2 nowdecode))
15652 (nth 1 tl)
15653 (< (nth 1 tl) (nth 1 nowdecode)))))
15654 (setq day (1+ day)
15655 futurep t))
15657 ;; Special date definitions below
15658 (cond
15659 (iso-week
15660 ;; There was an iso week
15661 (require 'cal-iso)
15662 (setq futurep nil)
15663 (setq year (or iso-year year)
15664 day (or iso-weekday wday 1)
15665 wday nil ; to make sure that the trigger below does not match
15666 iso-date (calendar-gregorian-from-absolute
15667 (calendar-absolute-from-iso
15668 (list iso-week day year))))
15669 ; FIXME: Should we also push ISO weeks into the future?
15670 ; (when (and org-read-date-prefer-future
15671 ; (not iso-year)
15672 ; (< (calendar-absolute-from-gregorian iso-date)
15673 ; (time-to-days (current-time))))
15674 ; (setq year (1+ year)
15675 ; iso-date (calendar-gregorian-from-absolute
15676 ; (calendar-absolute-from-iso
15677 ; (list iso-week day year)))))
15678 (setq month (car iso-date)
15679 year (nth 2 iso-date)
15680 day (nth 1 iso-date)))
15681 (deltan
15682 (setq futurep nil)
15683 (unless deltadef
15684 (let ((now (decode-time (current-time))))
15685 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15686 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15687 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15688 ((equal deltaw "m") (setq month (+ month deltan)))
15689 ((equal deltaw "y") (setq year (+ year deltan)))))
15690 ((and wday (not (nth 3 tl)))
15691 ;; Weekday was given, but no day, so pick that day in the week
15692 ;; on or after the derived date.
15693 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15694 (unless (equal wday wday1)
15695 (setq day (+ day (% (- wday wday1 -7) 7))))))
15696 (if (and (boundp 'org-time-was-given)
15697 (nth 2 tl))
15698 (setq org-time-was-given t))
15699 (if (< year 100) (setq year (+ 2000 year)))
15700 ;; Check of the date is representable
15701 (if org-read-date-force-compatible-dates
15702 (progn
15703 (if (< year 1970)
15704 (setq year 1970 org-read-date-analyze-forced-year t))
15705 (if (> year 2037)
15706 (setq year 2037 org-read-date-analyze-forced-year t)))
15707 (condition-case nil
15708 (ignore (encode-time second minute hour day month year))
15709 (error
15710 (setq year (nth 5 org-defdecode))
15711 (setq org-read-date-analyze-forced-year t))))
15712 (setq org-read-date-analyze-futurep futurep)
15713 (list second minute hour day month year)))
15715 (defvar parse-time-weekdays)
15716 (defun org-read-date-get-relative (s today default)
15717 "Check string S for special relative date string.
15718 TODAY and DEFAULT are internal times, for today and for a default.
15719 Return shift list (N what def-flag)
15720 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15721 N is the number of WHATs to shift.
15722 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15723 the DEFAULT date rather than TODAY."
15724 (require 'parse-time)
15725 (when (and
15726 (string-match
15727 (concat
15728 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15729 "\\([0-9]+\\)?"
15730 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15731 "\\([ \t]\\|$\\)") s)
15732 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15733 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15734 (string-to-char (substring (match-string 1 s) -1))
15735 ?+))
15736 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15737 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15738 (what (if (match-end 3) (match-string 3 s) "d"))
15739 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15740 (date (if rel default today))
15741 (wday (nth 6 (decode-time date)))
15742 delta)
15743 (if wday1
15744 (progn
15745 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15746 (if (= dir ?-) (setq delta (- delta 7)))
15747 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15748 (list delta "d" rel))
15749 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15751 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15752 "Turn a user-specified date into the internal representation.
15753 The internal representation needed by the calendar is (month day year).
15754 This is a wrapper to handle the brain-dead convention in calendar that
15755 user function argument order change dependent on argument order."
15756 (if (boundp 'calendar-date-style)
15757 (cond
15758 ((eq calendar-date-style 'american)
15759 (list arg1 arg2 arg3))
15760 ((eq calendar-date-style 'european)
15761 (list arg2 arg1 arg3))
15762 ((eq calendar-date-style 'iso)
15763 (list arg2 arg3 arg1)))
15764 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15765 (if (org-bound-and-true-p european-calendar-style)
15766 (list arg2 arg1 arg3)
15767 (list arg1 arg2 arg3)))))
15769 (defun org-eval-in-calendar (form &optional keepdate)
15770 "Eval FORM in the calendar window and return to current window.
15771 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15772 otherwise stick to the current value of `org-ans2'."
15773 (let ((sf (selected-frame))
15774 (sw (selected-window)))
15775 (select-window (get-buffer-window "*Calendar*" t))
15776 (eval form)
15777 (when (and (not keepdate) (calendar-cursor-to-date))
15778 (let* ((date (calendar-cursor-to-date))
15779 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15780 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15781 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15782 (select-window sw)
15783 (org-select-frame-set-input-focus sf)))
15785 (defun org-calendar-select ()
15786 "Return to `org-read-date' with the date currently selected.
15787 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15788 (interactive)
15789 (when (calendar-cursor-to-date)
15790 (let* ((date (calendar-cursor-to-date))
15791 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15792 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15793 (if (active-minibuffer-window) (exit-minibuffer))))
15795 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15796 "Insert a date stamp for the date given by the internal TIME.
15797 WITH-HM means use the stamp format that includes the time of the day.
15798 INACTIVE means use square brackets instead of angular ones, so that the
15799 stamp will not contribute to the agenda.
15800 PRE and POST are optional strings to be inserted before and after the
15801 stamp.
15802 The command returns the inserted time stamp."
15803 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15804 stamp)
15805 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15806 (insert-before-markers (or pre ""))
15807 (when (listp extra)
15808 (setq extra (car extra))
15809 (if (and (stringp extra)
15810 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15811 (setq extra (format "-%02d:%02d"
15812 (string-to-number (match-string 1 extra))
15813 (string-to-number (match-string 2 extra))))
15814 (setq extra nil)))
15815 (when extra
15816 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15817 (insert-before-markers (setq stamp (format-time-string fmt time)))
15818 (insert-before-markers (or post ""))
15819 (setq org-last-inserted-timestamp stamp)))
15821 (defun org-toggle-time-stamp-overlays ()
15822 "Toggle the use of custom time stamp formats."
15823 (interactive)
15824 (setq org-display-custom-times (not org-display-custom-times))
15825 (unless org-display-custom-times
15826 (let ((p (point-min)) (bmp (buffer-modified-p)))
15827 (while (setq p (next-single-property-change p 'display))
15828 (if (and (get-text-property p 'display)
15829 (eq (get-text-property p 'face) 'org-date))
15830 (remove-text-properties
15831 p (setq p (next-single-property-change p 'display))
15832 '(display t))))
15833 (set-buffer-modified-p bmp)))
15834 (if (featurep 'xemacs)
15835 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15836 (org-restart-font-lock)
15837 (setq org-table-may-need-update t)
15838 (if org-display-custom-times
15839 (message "Time stamps are overlaid with custom format")
15840 (message "Time stamp overlays removed")))
15842 (defun org-display-custom-time (beg end)
15843 "Overlay modified time stamp format over timestamp between BEG and END."
15844 (let* ((ts (buffer-substring beg end))
15845 t1 w1 with-hm tf time str w2 (off 0))
15846 (save-match-data
15847 (setq t1 (org-parse-time-string ts t))
15848 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15849 (setq off (- (match-end 0) (match-beginning 0)))))
15850 (setq end (- end off))
15851 (setq w1 (- end beg)
15852 with-hm (and (nth 1 t1) (nth 2 t1))
15853 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15854 time (org-fix-decoded-time t1)
15855 str (org-add-props
15856 (format-time-string
15857 (substring tf 1 -1) (apply 'encode-time time))
15858 nil 'mouse-face 'highlight)
15859 w2 (length str))
15860 (if (not (= w2 w1))
15861 (add-text-properties (1+ beg) (+ 2 beg)
15862 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15863 (if (featurep 'xemacs)
15864 (progn
15865 (put-text-property beg end 'invisible t)
15866 (put-text-property beg end 'end-glyph (make-glyph str)))
15867 (put-text-property beg end 'display str))))
15869 (defun org-translate-time (string)
15870 "Translate all timestamps in STRING to custom format.
15871 But do this only if the variable `org-display-custom-times' is set."
15872 (when org-display-custom-times
15873 (save-match-data
15874 (let* ((start 0)
15875 (re org-ts-regexp-both)
15876 t1 with-hm inactive tf time str beg end)
15877 (while (setq start (string-match re string start))
15878 (setq beg (match-beginning 0)
15879 end (match-end 0)
15880 t1 (save-match-data
15881 (org-parse-time-string (substring string beg end) t))
15882 with-hm (and (nth 1 t1) (nth 2 t1))
15883 inactive (equal (substring string beg (1+ beg)) "[")
15884 tf (funcall (if with-hm 'cdr 'car)
15885 org-time-stamp-custom-formats)
15886 time (org-fix-decoded-time t1)
15887 str (format-time-string
15888 (concat
15889 (if inactive "[" "<") (substring tf 1 -1)
15890 (if inactive "]" ">"))
15891 (apply 'encode-time time))
15892 string (replace-match str t t string)
15893 start (+ start (length str)))))))
15894 string)
15896 (defun org-fix-decoded-time (time)
15897 "Set 0 instead of nil for the first 6 elements of time.
15898 Don't touch the rest."
15899 (let ((n 0))
15900 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15902 (defun org-days-to-time (timestamp-string)
15903 "Difference between TIMESTAMP-STRING and now in days."
15904 (- (time-to-days (org-time-string-to-time timestamp-string))
15905 (time-to-days (current-time))))
15907 (defun org-deadline-close (timestamp-string &optional ndays)
15908 "Is the time in TIMESTAMP-STRING close to the current date?"
15909 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15910 (and (< (org-days-to-time timestamp-string) ndays)
15911 (not (org-entry-is-done-p))))
15913 (defun org-get-wdays (ts)
15914 "Get the deadline lead time appropriate for timestring TS."
15915 (cond
15916 ((<= org-deadline-warning-days 0)
15917 ;; 0 or negative, enforce this value no matter what
15918 (- org-deadline-warning-days))
15919 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15920 ;; lead time is specified.
15921 (floor (* (string-to-number (match-string 1 ts))
15922 (cdr (assoc (match-string 2 ts)
15923 '(("d" . 1) ("w" . 7)
15924 ("m" . 30.4) ("y" . 365.25)))))))
15925 ;; go for the default.
15926 (t org-deadline-warning-days)))
15928 (defun org-calendar-select-mouse (ev)
15929 "Return to `org-read-date' with the date currently selected.
15930 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15931 (interactive "e")
15932 (mouse-set-point ev)
15933 (when (calendar-cursor-to-date)
15934 (let* ((date (calendar-cursor-to-date))
15935 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15936 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15937 (if (active-minibuffer-window) (exit-minibuffer))))
15939 (defun org-check-deadlines (ndays)
15940 "Check if there are any deadlines due or past due.
15941 A deadline is considered due if it happens within `org-deadline-warning-days'
15942 days from today's date. If the deadline appears in an entry marked DONE,
15943 it is not shown. The prefix arg NDAYS can be used to test that many
15944 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15945 (interactive "P")
15946 (let* ((org-warn-days
15947 (cond
15948 ((equal ndays '(4)) 100000)
15949 (ndays (prefix-numeric-value ndays))
15950 (t (abs org-deadline-warning-days))))
15951 (case-fold-search nil)
15952 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15953 (callback
15954 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15956 (message "%d deadlines past-due or due within %d days"
15957 (org-occur regexp nil callback)
15958 org-warn-days)))
15960 (defsubst org-re-timestamp (type)
15961 "Return a regexp for timestamp TYPE.
15962 Allowed values for TYPE are:
15964 all: all timestamps
15965 active: only active timestamps (<...>)
15966 inactive: only inactive timestamps ([...])
15967 scheduled: only scheduled timestamps
15968 deadline: only deadline timestamps
15970 When TYPE is nil, fall back on returning a regexp that matches
15971 both scheduled and deadline timestamps."
15972 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15973 ((eq type 'active) org-ts-regexp)
15974 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15975 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15976 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15977 ((eq type 'scheduled-or-deadline)
15978 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15980 (defun org-check-before-date (date)
15981 "Check if there are deadlines or scheduled entries before DATE."
15982 (interactive (list (org-read-date)))
15983 (let ((case-fold-search nil)
15984 (regexp (org-re-timestamp org-ts-type))
15985 (callback
15986 (lambda () (time-less-p
15987 (org-time-string-to-time (match-string 1))
15988 (org-time-string-to-time date)))))
15989 (message "%d entries before %s"
15990 (org-occur regexp nil callback) date)))
15992 (defun org-check-after-date (date)
15993 "Check if there are deadlines or scheduled entries after DATE."
15994 (interactive (list (org-read-date)))
15995 (let ((case-fold-search nil)
15996 (regexp (org-re-timestamp org-ts-type))
15997 (callback
15998 (lambda () (not
15999 (time-less-p
16000 (org-time-string-to-time (match-string 1))
16001 (org-time-string-to-time date))))))
16002 (message "%d entries after %s"
16003 (org-occur regexp nil callback) date)))
16005 (defun org-check-dates-range (start-date end-date)
16006 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16007 (interactive (list (org-read-date nil nil nil "Range starts")
16008 (org-read-date nil nil nil "Range end")))
16009 (let ((case-fold-search nil)
16010 (regexp (org-re-timestamp org-ts-type))
16011 (callback
16012 (lambda ()
16013 (let ((match (match-string 1)))
16014 (and
16015 (not (time-less-p
16016 (org-time-string-to-time match)
16017 (org-time-string-to-time start-date)))
16018 (time-less-p
16019 (org-time-string-to-time match)
16020 (org-time-string-to-time end-date)))))))
16021 (message "%d entries between %s and %s"
16022 (org-occur regexp nil callback) start-date end-date)))
16024 (defun org-evaluate-time-range (&optional to-buffer)
16025 "Evaluate a time range by computing the difference between start and end.
16026 Normally the result is just printed in the echo area, but with prefix arg
16027 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16028 If the time range is actually in a table, the result is inserted into the
16029 next column.
16030 For time difference computation, a year is assumed to be exactly 365
16031 days in order to avoid rounding problems."
16032 (interactive "P")
16034 (org-clock-update-time-maybe)
16035 (save-excursion
16036 (unless (org-at-date-range-p t)
16037 (goto-char (point-at-bol))
16038 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16039 (if (not (org-at-date-range-p t))
16040 (error "Not at a time-stamp range, and none found in current line")))
16041 (let* ((ts1 (match-string 1))
16042 (ts2 (match-string 2))
16043 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16044 (match-end (match-end 0))
16045 (time1 (org-time-string-to-time ts1))
16046 (time2 (org-time-string-to-time ts2))
16047 (t1 (org-float-time time1))
16048 (t2 (org-float-time time2))
16049 (diff (abs (- t2 t1)))
16050 (negative (< (- t2 t1) 0))
16051 ;; (ys (floor (* 365 24 60 60)))
16052 (ds (* 24 60 60))
16053 (hs (* 60 60))
16054 (fy "%dy %dd %02d:%02d")
16055 (fy1 "%dy %dd")
16056 (fd "%dd %02d:%02d")
16057 (fd1 "%dd")
16058 (fh "%02d:%02d")
16059 y d h m align)
16060 (if havetime
16061 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16063 d (floor (/ diff ds)) diff (mod diff ds)
16064 h (floor (/ diff hs)) diff (mod diff hs)
16065 m (floor (/ diff 60)))
16066 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16068 d (floor (+ (/ diff ds) 0.5))
16069 h 0 m 0))
16070 (if (not to-buffer)
16071 (message "%s" (org-make-tdiff-string y d h m))
16072 (if (org-at-table-p)
16073 (progn
16074 (goto-char match-end)
16075 (setq align t)
16076 (and (looking-at " *|") (goto-char (match-end 0))))
16077 (goto-char match-end))
16078 (if (looking-at
16079 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16080 (replace-match ""))
16081 (if negative (insert " -"))
16082 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16083 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16084 (insert " " (format fh h m))))
16085 (if align (org-table-align))
16086 (message "Time difference inserted")))))
16088 (defun org-make-tdiff-string (y d h m)
16089 (let ((fmt "")
16090 (l nil))
16091 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16092 l (push y l)))
16093 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16094 l (push d l)))
16095 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16096 l (push h l)))
16097 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16098 l (push m l)))
16099 (apply 'format fmt (nreverse l))))
16101 (defun org-time-string-to-time (s &optional buffer pos)
16102 "Convert a timestamp string into internal time."
16103 (condition-case errdata
16104 (apply 'encode-time (org-parse-time-string s))
16105 (error (error "Bad timestamp `%s'%s\nError was: %s"
16106 s (if (not (and buffer pos))
16108 (format " at %d in buffer `%s'" pos buffer))
16109 (cdr errdata)))))
16111 (defun org-time-string-to-seconds (s)
16112 "Convert a timestamp string to a number of seconds."
16113 (org-float-time (org-time-string-to-time s)))
16115 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16116 "Convert a time stamp to an absolute day number.
16117 If there is a specifier for a cyclic time stamp, get the closest date to
16118 DAYNR.
16119 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16120 The variable date is bound by the calendar when this is called."
16121 (cond
16122 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16123 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16124 daynr
16125 (+ daynr 1000)))
16126 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16127 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16128 (time-to-days (current-time))) (match-string 0 s)
16129 prefer show-all))
16130 (t (time-to-days
16131 (condition-case errdata
16132 (apply 'encode-time (org-parse-time-string s))
16133 (error (error "Bad timestamp `%s'%s\nError was: %s"
16134 s (if (not (and buffer pos))
16136 (format " at %d in buffer `%s'" pos buffer))
16137 (cdr errdata))))))))
16139 (defun org-days-to-iso-week (days)
16140 "Return the iso week number."
16141 (require 'cal-iso)
16142 (car (calendar-iso-from-absolute days)))
16144 (defun org-small-year-to-year (year)
16145 "Convert 2-digit years into 4-digit years.
16146 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16147 The year 2000 cannot be abbreviated. Any year larger than 99
16148 is returned unchanged."
16149 (if (< year 38)
16150 (setq year (+ 2000 year))
16151 (if (< year 100)
16152 (setq year (+ 1900 year))))
16153 year)
16155 (defun org-time-from-absolute (d)
16156 "Return the time corresponding to date D.
16157 D may be an absolute day number, or a calendar-type list (month day year)."
16158 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16159 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16161 (defun org-calendar-holiday ()
16162 "List of holidays, for Diary display in Org-mode."
16163 (require 'holidays)
16164 (let ((hl (funcall
16165 (if (fboundp 'calendar-check-holidays)
16166 'calendar-check-holidays 'check-calendar-holidays) date)))
16167 (if hl (mapconcat 'identity hl "; "))))
16169 (defun org-diary-sexp-entry (sexp entry date)
16170 "Process a SEXP diary ENTRY for DATE."
16171 (require 'diary-lib)
16172 (let ((result (if calendar-debug-sexp
16173 (let ((stack-trace-on-error t))
16174 (eval (car (read-from-string sexp))))
16175 (condition-case nil
16176 (eval (car (read-from-string sexp)))
16177 (error
16178 (beep)
16179 (message "Bad sexp at line %d in %s: %s"
16180 (org-current-line)
16181 (buffer-file-name) sexp)
16182 (sleep-for 2))))))
16183 (cond ((stringp result) (split-string result "; "))
16184 ((and (consp result)
16185 (not (consp (cdr result)))
16186 (stringp (cdr result))) (cdr result))
16187 ((and (consp result)
16188 (stringp (car result))) result)
16189 (result entry))))
16191 (defun org-diary-to-ical-string (frombuf)
16192 "Get iCalendar entries from diary entries in buffer FROMBUF.
16193 This uses the icalendar.el library."
16194 (let* ((tmpdir (if (featurep 'xemacs)
16195 (temp-directory)
16196 temporary-file-directory))
16197 (tmpfile (make-temp-name
16198 (expand-file-name "orgics" tmpdir)))
16199 buf rtn b e)
16200 (with-current-buffer frombuf
16201 (icalendar-export-region (point-min) (point-max) tmpfile)
16202 (setq buf (find-buffer-visiting tmpfile))
16203 (set-buffer buf)
16204 (goto-char (point-min))
16205 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16206 (setq b (match-beginning 0)))
16207 (goto-char (point-max))
16208 (if (re-search-backward "^END:VEVENT" nil t)
16209 (setq e (match-end 0)))
16210 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16211 (kill-buffer buf)
16212 (delete-file tmpfile)
16213 rtn))
16215 (defun org-closest-date (start current change prefer show-all)
16216 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16217 When PREFER is `past', return a date that is either CURRENT or past.
16218 When PREFER is `future', return a date that is either CURRENT or future.
16219 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16220 ;; Make the proper lists from the dates
16221 (catch 'exit
16222 (let ((a1 '(("h" . hour)
16223 ("d" . day)
16224 ("w" . week)
16225 ("m" . month)
16226 ("y" . year)))
16227 (shour (nth 2 (org-parse-time-string start)))
16228 dn dw sday cday n1 n2 n0
16229 d m y y1 y2 date1 date2 nmonths nm ny m2)
16231 (setq start (org-date-to-gregorian start)
16232 current (org-date-to-gregorian
16233 (if show-all
16234 current
16235 (time-to-days (current-time))))
16236 sday (calendar-absolute-from-gregorian start)
16237 cday (calendar-absolute-from-gregorian current))
16239 (if (<= cday sday) (throw 'exit sday))
16241 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16242 (setq dn (string-to-number (match-string 1 change))
16243 dw (cdr (assoc (match-string 2 change) a1)))
16244 (error "Invalid change specifier: %s" change))
16245 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16246 (cond
16247 ((eq dw 'hour)
16248 (let ((missing-hours
16249 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16250 dn)))
16251 (setq n1 (if (zerop missing-hours) cday
16252 (- cday (1+ (floor (/ missing-hours 24)))))
16253 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16254 ((eq dw 'day)
16255 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16256 n2 (+ n1 dn)))
16257 ((eq dw 'year)
16258 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16259 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16260 (setq date1 (list m d y1)
16261 n1 (calendar-absolute-from-gregorian date1)
16262 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16263 n2 (calendar-absolute-from-gregorian date2)))
16264 ((eq dw 'month)
16265 ;; approx number of month between the two dates
16266 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16267 ;; How often does dn fit in there?
16268 (setq d (nth 1 start) m (car start) y (nth 2 start)
16269 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16270 m (+ m nm)
16271 ny (floor (/ m 12))
16272 y (+ y ny)
16273 m (- m (* ny 12)))
16274 (while (> m 12) (setq m (- m 12) y (1+ y)))
16275 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16276 (setq m2 (+ m dn) y2 y)
16277 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16278 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16279 (while (<= n2 cday)
16280 (setq n1 n2 m m2 y y2)
16281 (setq m2 (+ m dn) y2 y)
16282 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16283 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16284 ;; Make sure n1 is the earlier date
16285 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16286 (if show-all
16287 (cond
16288 ((eq prefer 'past) (if (= cday n2) n2 n1))
16289 ((eq prefer 'future) (if (= cday n1) n1 n2))
16290 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16291 (cond
16292 ((eq prefer 'past) (if (= cday n2) n2 n1))
16293 ((eq prefer 'future) (if (= cday n1) n1 n2))
16294 (t (if (= cday n1) n1 n2)))))))
16296 (defun org-date-to-gregorian (date)
16297 "Turn any specification of DATE into a Gregorian date for the calendar."
16298 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16299 ((and (listp date) (= (length date) 3)) date)
16300 ((stringp date)
16301 (setq date (org-parse-time-string date))
16302 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16303 ((listp date)
16304 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16306 (defun org-parse-time-string (s &optional nodefault)
16307 "Parse the standard Org-mode time string.
16308 This should be a lot faster than the normal `parse-time-string'.
16309 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16310 hour and minute fields will be nil if not given."
16311 (if (string-match org-ts-regexp0 s)
16312 (list 0
16313 (if (or (match-beginning 8) (not nodefault))
16314 (string-to-number (or (match-string 8 s) "0")))
16315 (if (or (match-beginning 7) (not nodefault))
16316 (string-to-number (or (match-string 7 s) "0")))
16317 (string-to-number (match-string 4 s))
16318 (string-to-number (match-string 3 s))
16319 (string-to-number (match-string 2 s))
16320 nil nil nil)
16321 (error "Not a standard Org-mode time string: %s" s)))
16323 (defun org-timestamp-up (&optional arg)
16324 "Increase the date item at the cursor by one.
16325 If the cursor is on the year, change the year. If it is on the month,
16326 the day or the time, change that.
16327 With prefix ARG, change by that many units."
16328 (interactive "p")
16329 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16331 (defun org-timestamp-down (&optional arg)
16332 "Decrease the date item at the cursor by one.
16333 If the cursor is on the year, change the year. If it is on the month,
16334 the day or the time, change that.
16335 With prefix ARG, change by that many units."
16336 (interactive "p")
16337 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16339 (defun org-timestamp-up-day (&optional arg)
16340 "Increase the date in the time stamp by one day.
16341 With prefix ARG, change that many days."
16342 (interactive "p")
16343 (if (and (not (org-at-timestamp-p t))
16344 (org-at-heading-p))
16345 (org-todo 'up)
16346 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16348 (defun org-timestamp-down-day (&optional arg)
16349 "Decrease the date in the time stamp by one day.
16350 With prefix ARG, change that many days."
16351 (interactive "p")
16352 (if (and (not (org-at-timestamp-p t))
16353 (org-at-heading-p))
16354 (org-todo 'down)
16355 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16357 (defun org-at-timestamp-p (&optional inactive-ok)
16358 "Determine if the cursor is in or at a timestamp."
16359 (interactive)
16360 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16361 (pos (point))
16362 (ans (or (looking-at tsr)
16363 (save-excursion
16364 (skip-chars-backward "^[<\n\r\t")
16365 (if (> (point) (point-min)) (backward-char 1))
16366 (and (looking-at tsr)
16367 (> (- (match-end 0) pos) -1))))))
16368 (and ans
16369 (boundp 'org-ts-what)
16370 (setq org-ts-what
16371 (cond
16372 ((= pos (match-beginning 0)) 'bracket)
16373 ;; Point is considered to be "on the bracket" whether
16374 ;; it's really on it or right after it.
16375 ((= pos (1- (match-end 0))) 'bracket)
16376 ((= pos (match-end 0)) 'after)
16377 ((org-pos-in-match-range pos 2) 'year)
16378 ((org-pos-in-match-range pos 3) 'month)
16379 ((org-pos-in-match-range pos 7) 'hour)
16380 ((org-pos-in-match-range pos 8) 'minute)
16381 ((or (org-pos-in-match-range pos 4)
16382 (org-pos-in-match-range pos 5)) 'day)
16383 ((and (> pos (or (match-end 8) (match-end 5)))
16384 (< pos (match-end 0)))
16385 (- pos (or (match-end 8) (match-end 5))))
16386 (t 'day))))
16387 ans))
16389 (defun org-toggle-timestamp-type ()
16390 "Toggle the type (<active> or [inactive]) of a time stamp."
16391 (interactive)
16392 (when (org-at-timestamp-p t)
16393 (let ((beg (match-beginning 0)) (end (match-end 0))
16394 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16395 (save-excursion
16396 (goto-char beg)
16397 (while (re-search-forward "[][<>]" end t)
16398 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16399 t t)))
16400 (message "Timestamp is now %sactive"
16401 (if (equal (char-after beg) ?<) "" "in")))))
16403 (defvar org-clock-history) ; defined in org-clock.el
16404 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16405 (defun org-timestamp-change (n &optional what updown)
16406 "Change the date in the time stamp at point.
16407 The date will be changed by N times WHAT. WHAT can be `day', `month',
16408 `year', `minute', `second'. If WHAT is not given, the cursor position
16409 in the timestamp determines what will be changed."
16410 (let ((origin (point)) origin-cat
16411 with-hm inactive
16412 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16413 org-ts-what
16414 extra rem
16415 ts time time0 fixnext clrgx)
16416 (if (not (org-at-timestamp-p t))
16417 (error "Not at a timestamp"))
16418 (if (and (not what) (eq org-ts-what 'bracket))
16419 (org-toggle-timestamp-type)
16420 ;; Point isn't on brackets. Remember the part of the time-stamp
16421 ;; the point was in. Indeed, size of time-stamps may change,
16422 ;; but point must be kept in the same category nonetheless.
16423 (setq origin-cat org-ts-what)
16424 (if (and (not what) (not (eq org-ts-what 'day))
16425 org-display-custom-times
16426 (get-text-property (point) 'display)
16427 (not (get-text-property (1- (point)) 'display)))
16428 (setq org-ts-what 'day))
16429 (setq org-ts-what (or what org-ts-what)
16430 inactive (= (char-after (match-beginning 0)) ?\[)
16431 ts (match-string 0))
16432 (replace-match "")
16433 (if (string-match
16434 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16436 (setq extra (match-string 1 ts)))
16437 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16438 (setq with-hm t))
16439 (setq time0 (org-parse-time-string ts))
16440 (when (and updown
16441 (eq org-ts-what 'minute)
16442 (not current-prefix-arg))
16443 ;; This looks like s-up and s-down. Change by one rounding step.
16444 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16445 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16446 (setcar (cdr time0) (+ (nth 1 time0)
16447 (if (> n 0) (- rem) (- dm rem))))))
16448 (setq time
16449 (encode-time (or (car time0) 0)
16450 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16451 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16452 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16453 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16454 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16455 (nthcdr 6 time0)))
16456 (when (and (member org-ts-what '(hour minute))
16457 extra
16458 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16459 (setq extra (org-modify-ts-extra
16460 extra
16461 (if (eq org-ts-what 'hour) 2 5)
16462 n dm)))
16463 (when (integerp org-ts-what)
16464 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16465 (if (eq what 'calendar)
16466 (let ((cal-date (org-get-date-from-calendar)))
16467 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16468 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16469 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16470 (setcar time0 (or (car time0) 0))
16471 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16472 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16473 (setq time (apply 'encode-time time0))))
16474 ;; Insert the new time-stamp, and ensure point stays in the same
16475 ;; category as before (i.e. not after the last position in that
16476 ;; category).
16477 (let ((pos (point)))
16478 ;; Stay before inserted string. `save-excursion' is of no use.
16479 (setq org-last-changed-timestamp
16480 (org-insert-time-stamp time with-hm inactive nil nil extra))
16481 (goto-char pos))
16482 (save-match-data
16483 (looking-at org-ts-regexp3)
16484 (goto-char (cond
16485 ;; `day' category ends before `hour' if any, or at
16486 ;; the end of the day name.
16487 ((eq origin-cat 'day)
16488 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16489 ((eq origin-cat 'hour) (min (match-end 7) origin))
16490 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16491 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16492 ;; `year' and `month' have both fixed size: point
16493 ;; couldn't have moved into another part.
16494 (t origin))))
16495 ;; Update clock if on a CLOCK line.
16496 (org-clock-update-time-maybe)
16497 ;; Maybe adjust the closest clock in `org-clock-history'
16498 (when org-clock-adjust-closest
16499 (if (not (and (org-at-clock-log-p)
16500 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16501 org-clock-history))))))
16502 (message "No clock to adjust")
16503 (cond ((save-excursion ; fix previous clock?
16504 (re-search-backward org-ts-regexp0 nil t)
16505 (org-looking-back (concat org-clock-string " \\[")))
16506 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16507 ((save-excursion ; fix next clock?
16508 (re-search-backward org-ts-regexp0 nil t)
16509 (looking-at (concat org-ts-regexp0 "\\] =>")))
16510 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16511 (save-window-excursion
16512 ;; Find closest clock to point, adjust the previous/next one in history
16513 (let* ((p (save-excursion (org-back-to-heading t)))
16514 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16515 (clfixnth
16516 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16517 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16518 (if (not clfixpos)
16519 (message "No clock to adjust")
16520 (save-excursion
16521 (org-goto-marker-or-bmk clfixpos)
16522 (org-show-subtree)
16523 (when (re-search-forward clrgx nil t)
16524 (goto-char (match-beginning 1))
16525 (let (org-clock-adjust-closest)
16526 (org-timestamp-change n org-ts-what updown))
16527 (message "Clock adjusted in %s for heading: %s"
16528 (file-name-nondirectory (buffer-file-name))
16529 (org-get-heading t t)))))))))
16530 ;; Try to recenter the calendar window, if any.
16531 (if (and org-calendar-follow-timestamp-change
16532 (get-buffer-window "*Calendar*" t)
16533 (memq org-ts-what '(day month year)))
16534 (org-recenter-calendar (time-to-days time))))))
16536 (defun org-modify-ts-extra (s pos n dm)
16537 "Change the different parts of the lead-time and repeat fields in timestamp."
16538 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16539 ng h m new rem)
16540 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16541 (cond
16542 ((or (org-pos-in-match-range pos 2)
16543 (org-pos-in-match-range pos 3))
16544 (setq m (string-to-number (match-string 3 s))
16545 h (string-to-number (match-string 2 s)))
16546 (if (org-pos-in-match-range pos 2)
16547 (setq h (+ h n))
16548 (setq n (* dm (org-no-warnings (signum n))))
16549 (when (not (= 0 (setq rem (% m dm))))
16550 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16551 (setq m (+ m n)))
16552 (if (< m 0) (setq m (+ m 60) h (1- h)))
16553 (if (> m 59) (setq m (- m 60) h (1+ h)))
16554 (setq h (min 24 (max 0 h)))
16555 (setq ng 1 new (format "-%02d:%02d" h m)))
16556 ((org-pos-in-match-range pos 6)
16557 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16558 ((org-pos-in-match-range pos 5)
16559 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16561 ((org-pos-in-match-range pos 9)
16562 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16563 ((org-pos-in-match-range pos 8)
16564 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16566 (when ng
16567 (setq s (concat
16568 (substring s 0 (match-beginning ng))
16570 (substring s (match-end ng))))))
16573 (defun org-recenter-calendar (date)
16574 "If the calendar is visible, recenter it to DATE."
16575 (let ((cwin (get-buffer-window "*Calendar*" t)))
16576 (when cwin
16577 (let ((calendar-move-hook nil))
16578 (with-selected-window cwin
16579 (calendar-goto-date (if (listp date) date
16580 (calendar-gregorian-from-absolute date))))))))
16582 (defun org-goto-calendar (&optional arg)
16583 "Go to the Emacs calendar at the current date.
16584 If there is a time stamp in the current line, go to that date.
16585 A prefix ARG can be used to force the current date."
16586 (interactive "P")
16587 (let ((tsr org-ts-regexp) diff
16588 (calendar-move-hook nil)
16589 (calendar-view-holidays-initially-flag nil)
16590 (calendar-view-diary-initially-flag nil))
16591 (if (or (org-at-timestamp-p)
16592 (save-excursion
16593 (beginning-of-line 1)
16594 (looking-at (concat ".*" tsr))))
16595 (let ((d1 (time-to-days (current-time)))
16596 (d2 (time-to-days
16597 (org-time-string-to-time (match-string 1)))))
16598 (setq diff (- d2 d1))))
16599 (calendar)
16600 (calendar-goto-today)
16601 (if (and diff (not arg)) (calendar-forward-day diff))))
16603 (defun org-get-date-from-calendar ()
16604 "Return a list (month day year) of date at point in calendar."
16605 (with-current-buffer "*Calendar*"
16606 (save-match-data
16607 (calendar-cursor-to-date))))
16609 (defun org-date-from-calendar ()
16610 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16611 If there is already a time stamp at the cursor position, update it."
16612 (interactive)
16613 (if (org-at-timestamp-p t)
16614 (org-timestamp-change 0 'calendar)
16615 (let ((cal-date (org-get-date-from-calendar)))
16616 (org-insert-time-stamp
16617 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16619 (defun org-minutes-to-hh:mm-string (m)
16620 "Compute H:MM from a number of minutes."
16621 (let ((h (/ m 60)))
16622 (setq m (- m (* 60 h)))
16623 (format org-time-clocksum-format h m)))
16625 (defun org-hh:mm-string-to-minutes (s)
16626 "Convert a string H:MM to a number of minutes.
16627 If the string is just a number, interpret it as minutes.
16628 In fact, the first hh:mm or number in the string will be taken,
16629 there can be extra stuff in the string.
16630 If no number is found, the return value is 0."
16631 (cond
16632 ((integerp s) s)
16633 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16634 (+ (* (string-to-number (match-string 1 s)) 60)
16635 (string-to-number (match-string 2 s))))
16636 ((string-match "\\([0-9]+\\)" s)
16637 (string-to-number (match-string 1 s)))
16638 (t 0)))
16640 (defcustom org-effort-durations
16641 `(("h" . 60)
16642 ("d" . ,(* 60 8))
16643 ("w" . ,(* 60 8 5))
16644 ("m" . ,(* 60 8 5 4))
16645 ("y" . ,(* 60 8 5 40)))
16646 "Conversion factor to minutes for an effort modifier.
16648 Each entry has the form (MODIFIER . MINUTES).
16650 In an effort string, a number followed by MODIFIER is multiplied
16651 by the specified number of MINUTES to obtain an effort in
16652 minutes.
16654 For example, if the value of this variable is ((\"hours\" . 60)), then an
16655 effort string \"2hours\" is equivalent to 120 minutes."
16656 :group 'org-agenda
16657 :version "24.1"
16658 :type '(alist :key-type (string :tag "Modifier")
16659 :value-type (number :tag "Minutes")))
16661 (defcustom org-agenda-inhibit-startup t
16662 "Inhibit startup when preparing agenda buffers.
16663 When this variable is `t' (the default), the initialization of
16664 the Org agenda buffers is inhibited: e.g. the visibility state
16665 is not set, the tables are not re-aligned, etc."
16666 :type 'boolean
16667 :version "24.3"
16668 :group 'org-agenda)
16670 (defun org-duration-string-to-minutes (s &optional output-to-string)
16671 "Convert a duration string S to minutes.
16673 A bare number is interpreted as minutes, modifiers can be set by
16674 customizing `org-effort-durations' (which see).
16676 Entries containing a colon are interpreted as H:MM by
16677 `org-hh:mm-string-to-minutes'."
16678 (let ((result 0)
16679 (re (concat "\\([0-9.]+\\) *\\("
16680 (regexp-opt (mapcar 'car org-effort-durations))
16681 "\\)")))
16682 (while (string-match re s)
16683 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16684 (string-to-number (match-string 1 s))))
16685 (setq s (replace-match "" nil t s)))
16686 (setq result (floor result))
16687 (incf result (org-hh:mm-string-to-minutes s))
16688 (if output-to-string (number-to-string result) result)))
16690 ;;;; Files
16692 (defun org-save-all-org-buffers ()
16693 "Save all Org-mode buffers without user confirmation."
16694 (interactive)
16695 (message "Saving all Org-mode buffers...")
16696 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16697 (when (featurep 'org-id) (org-id-locations-save))
16698 (message "Saving all Org-mode buffers... done"))
16700 (defun org-revert-all-org-buffers ()
16701 "Revert all Org-mode buffers.
16702 Prompt for confirmation when there are unsaved changes.
16703 Be sure you know what you are doing before letting this function
16704 overwrite your changes.
16706 This function is useful in a setup where one tracks org files
16707 with a version control system, to revert on one machine after pulling
16708 changes from another. I believe the procedure must be like this:
16710 1. M-x org-save-all-org-buffers
16711 2. Pull changes from the other machine, resolve conflicts
16712 3. M-x org-revert-all-org-buffers"
16713 (interactive)
16714 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16715 (error "Abort"))
16716 (save-excursion
16717 (save-window-excursion
16718 (mapc
16719 (lambda (b)
16720 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16721 (with-current-buffer b buffer-file-name))
16722 (org-pop-to-buffer-same-window b)
16723 (revert-buffer t 'no-confirm)))
16724 (buffer-list))
16725 (when (and (featurep 'org-id) org-id-track-globally)
16726 (org-id-locations-load)))))
16728 ;;;; Agenda files
16730 ;;;###autoload
16731 (defun org-switchb (&optional arg)
16732 "Switch between Org buffers.
16733 With one prefix argument, restrict available buffers to files.
16734 With two prefix arguments, restrict available buffers to agenda files.
16736 Defaults to `iswitchb' for buffer name completion.
16737 Set `org-completion-use-ido' to make it use ido instead."
16738 (interactive "P")
16739 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16740 ((equal arg '(16)) (org-buffer-list 'agenda))
16741 (t (org-buffer-list))))
16742 (org-completion-use-iswitchb org-completion-use-iswitchb)
16743 (org-completion-use-ido org-completion-use-ido))
16744 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16745 (setq org-completion-use-iswitchb t))
16746 (org-pop-to-buffer-same-window
16747 (org-icompleting-read "Org buffer: "
16748 (mapcar 'list (mapcar 'buffer-name blist))
16749 nil t))))
16751 ;;; Define some older names previously used for this functionality
16752 ;;;###autoload
16753 (defalias 'org-ido-switchb 'org-switchb)
16754 ;;;###autoload
16755 (defalias 'org-iswitchb 'org-switchb)
16757 (defun org-buffer-list (&optional predicate exclude-tmp)
16758 "Return a list of Org buffers.
16759 PREDICATE can be `export', `files' or `agenda'.
16761 export restrict the list to Export buffers.
16762 files restrict the list to buffers visiting Org files.
16763 agenda restrict the list to buffers visiting agenda files.
16765 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16766 (let* ((bfn nil)
16767 (agenda-files (and (eq predicate 'agenda)
16768 (mapcar 'file-truename (org-agenda-files t))))
16769 (filter
16770 (cond
16771 ((eq predicate 'files)
16772 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16773 ((eq predicate 'export)
16774 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16775 ((eq predicate 'agenda)
16776 (lambda (b)
16777 (with-current-buffer b
16778 (and (derived-mode-p 'org-mode)
16779 (setq bfn (buffer-file-name b))
16780 (member (file-truename bfn) agenda-files)))))
16781 (t (lambda (b) (with-current-buffer b
16782 (or (derived-mode-p 'org-mode)
16783 (string-match "\*Org .*Export"
16784 (buffer-name b)))))))))
16785 (delq nil
16786 (mapcar
16787 (lambda(b)
16788 (if (and (funcall filter b)
16789 (or (not exclude-tmp)
16790 (not (string-match "tmp" (buffer-name b)))))
16792 nil))
16793 (buffer-list)))))
16795 (defun org-agenda-files (&optional unrestricted archives)
16796 "Get the list of agenda files.
16797 Optional UNRESTRICTED means return the full list even if a restriction
16798 is currently in place.
16799 When ARCHIVES is t, include all archive files that are really being
16800 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16801 `org-agenda-archives-mode' is t."
16802 (let ((files
16803 (cond
16804 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16805 ((stringp org-agenda-files) (org-read-agenda-file-list))
16806 ((listp org-agenda-files) org-agenda-files)
16807 (t (error "Invalid value of `org-agenda-files'")))))
16808 (setq files (apply 'append
16809 (mapcar (lambda (f)
16810 (if (file-directory-p f)
16811 (directory-files
16812 f t org-agenda-file-regexp)
16813 (list f)))
16814 files)))
16815 (when org-agenda-skip-unavailable-files
16816 (setq files (delq nil
16817 (mapcar (function
16818 (lambda (file)
16819 (and (file-readable-p file) file)))
16820 files))))
16821 (when (or (eq archives t)
16822 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16823 (setq files (org-add-archive-files files)))
16824 files))
16826 (defun org-agenda-file-p (&optional file)
16827 "Return non-nil, if FILE is an agenda file.
16828 If FILE is omitted, use the file associated with the current
16829 buffer."
16830 (member (or file (buffer-file-name))
16831 (org-agenda-files t)))
16833 (defun org-edit-agenda-file-list ()
16834 "Edit the list of agenda files.
16835 Depending on setup, this either uses customize to edit the variable
16836 `org-agenda-files', or it visits the file that is holding the list. In the
16837 latter case, the buffer is set up in a way that saving it automatically kills
16838 the buffer and restores the previous window configuration."
16839 (interactive)
16840 (if (stringp org-agenda-files)
16841 (let ((cw (current-window-configuration)))
16842 (find-file org-agenda-files)
16843 (org-set-local 'org-window-configuration cw)
16844 (org-add-hook 'after-save-hook
16845 (lambda ()
16846 (set-window-configuration
16847 (prog1 org-window-configuration
16848 (kill-buffer (current-buffer))))
16849 (org-install-agenda-files-menu)
16850 (message "New agenda file list installed"))
16851 nil 'local)
16852 (message "%s" (substitute-command-keys
16853 "Edit list and finish with \\[save-buffer]")))
16854 (customize-variable 'org-agenda-files)))
16856 (defun org-store-new-agenda-file-list (list)
16857 "Set new value for the agenda file list and save it correctly."
16858 (if (stringp org-agenda-files)
16859 (let ((fe (org-read-agenda-file-list t)) b u)
16860 (while (setq b (find-buffer-visiting org-agenda-files))
16861 (kill-buffer b))
16862 (with-temp-file org-agenda-files
16863 (insert
16864 (mapconcat
16865 (lambda (f) ;; Keep un-expanded entries.
16866 (if (setq u (assoc f fe))
16867 (cdr u)
16869 list "\n")
16870 "\n")))
16871 (let ((org-mode-hook nil) (org-inhibit-startup t)
16872 (org-insert-mode-line-in-empty-file nil))
16873 (setq org-agenda-files list)
16874 (customize-save-variable 'org-agenda-files org-agenda-files))))
16876 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16877 "Read the list of agenda files from a file.
16878 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16879 filenames, used by `org-store-new-agenda-file-list' to write back
16880 un-expanded file names."
16881 (when (file-directory-p org-agenda-files)
16882 (error "`org-agenda-files' cannot be a single directory"))
16883 (when (stringp org-agenda-files)
16884 (with-temp-buffer
16885 (insert-file-contents org-agenda-files)
16886 (mapcar
16887 (lambda (f)
16888 (let ((e (expand-file-name (substitute-in-file-name f)
16889 org-directory)))
16890 (if pair-with-expansion
16891 (cons e f)
16892 e)))
16893 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16895 ;;;###autoload
16896 (defun org-cycle-agenda-files ()
16897 "Cycle through the files in `org-agenda-files'.
16898 If the current buffer visits an agenda file, find the next one in the list.
16899 If the current buffer does not, find the first agenda file."
16900 (interactive)
16901 (let* ((fs (org-agenda-files t))
16902 (files (append fs (list (car fs))))
16903 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16904 file)
16905 (unless files (error "No agenda files"))
16906 (catch 'exit
16907 (while (setq file (pop files))
16908 (if (equal (file-truename file) tcf)
16909 (when (car files)
16910 (find-file (car files))
16911 (throw 'exit t))))
16912 (find-file (car fs)))
16913 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16915 (defun org-agenda-file-to-front (&optional to-end)
16916 "Move/add the current file to the top of the agenda file list.
16917 If the file is not present in the list, it is added to the front. If it is
16918 present, it is moved there. With optional argument TO-END, add/move to the
16919 end of the list."
16920 (interactive "P")
16921 (let ((org-agenda-skip-unavailable-files nil)
16922 (file-alist (mapcar (lambda (x)
16923 (cons (file-truename x) x))
16924 (org-agenda-files t)))
16925 (ctf (file-truename
16926 (or buffer-file-name
16927 (error "Please save the current buffer to a file"))))
16928 x had)
16929 (setq x (assoc ctf file-alist) had x)
16931 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16932 (if to-end
16933 (setq file-alist (append (delq x file-alist) (list x)))
16934 (setq file-alist (cons x (delq x file-alist))))
16935 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16936 (org-install-agenda-files-menu)
16937 (message "File %s to %s of agenda file list"
16938 (if had "moved" "added") (if to-end "end" "front"))))
16940 (defun org-remove-file (&optional file)
16941 "Remove current file from the list of files in variable `org-agenda-files'.
16942 These are the files which are being checked for agenda entries.
16943 Optional argument FILE means use this file instead of the current."
16944 (interactive)
16945 (let* ((org-agenda-skip-unavailable-files nil)
16946 (file (or file buffer-file-name
16947 (error "Current buffer does not visit a file")))
16948 (true-file (file-truename file))
16949 (afile (abbreviate-file-name file))
16950 (files (delq nil (mapcar
16951 (lambda (x)
16952 (if (equal true-file
16953 (file-truename x))
16954 nil x))
16955 (org-agenda-files t)))))
16956 (if (not (= (length files) (length (org-agenda-files t))))
16957 (progn
16958 (org-store-new-agenda-file-list files)
16959 (org-install-agenda-files-menu)
16960 (message "Removed file: %s" afile))
16961 (message "File was not in list: %s (not removed)" afile))))
16963 (defun org-file-menu-entry (file)
16964 (vector file (list 'find-file file) t))
16966 (defun org-check-agenda-file (file)
16967 "Make sure FILE exists. If not, ask user what to do."
16968 (when (not (file-exists-p file))
16969 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16970 (abbreviate-file-name file))
16971 (let ((r (downcase (read-char-exclusive))))
16972 (cond
16973 ((equal r ?r)
16974 (org-remove-file file)
16975 (throw 'nextfile t))
16976 (t (error "Abort"))))))
16978 (defun org-get-agenda-file-buffer (file)
16979 "Get a buffer visiting FILE. If the buffer needs to be created, add
16980 it to the list of buffers which might be released later."
16981 (let ((buf (org-find-base-buffer-visiting file)))
16982 (if buf
16983 buf ; just return it
16984 ;; Make a new buffer and remember it
16985 (setq buf (find-file-noselect file))
16986 (if buf (push buf org-agenda-new-buffers))
16987 buf)))
16989 (defun org-release-buffers (blist)
16990 "Release all buffers in list, asking the user for confirmation when needed.
16991 When a buffer is unmodified, it is just killed. When modified, it is saved
16992 \(if the user agrees) and then killed."
16993 (let (buf file)
16994 (while (setq buf (pop blist))
16995 (setq file (buffer-file-name buf))
16996 (when (and (buffer-modified-p buf)
16997 file
16998 (y-or-n-p (format "Save file %s? " file)))
16999 (with-current-buffer buf (save-buffer)))
17000 (kill-buffer buf))))
17002 (defun org-agenda-prepare-buffers (files)
17003 "Create buffers for all agenda files, protect archived trees and comments."
17004 (interactive)
17005 (let ((pa '(:org-archived t))
17006 (pc '(:org-comment t))
17007 (pall '(:org-archived t :org-comment t))
17008 (inhibit-read-only t)
17009 (org-inhibit-startup org-agenda-inhibit-startup)
17010 (rea (concat ":" org-archive-tag ":"))
17011 bmp file re)
17012 (save-excursion
17013 (save-restriction
17014 (while (setq file (pop files))
17015 (catch 'nextfile
17016 (if (bufferp file)
17017 (set-buffer file)
17018 (org-check-agenda-file file)
17019 (set-buffer (org-get-agenda-file-buffer file)))
17020 (widen)
17021 (setq bmp (buffer-modified-p))
17022 (org-refresh-category-properties)
17023 (org-refresh-properties org-effort-property 'org-effort)
17024 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17025 (setq org-todo-keywords-for-agenda
17026 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17027 (setq org-done-keywords-for-agenda
17028 (append org-done-keywords-for-agenda org-done-keywords))
17029 (setq org-todo-keyword-alist-for-agenda
17030 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17031 (setq org-drawers-for-agenda
17032 (append org-drawers-for-agenda org-drawers))
17033 (setq org-tag-alist-for-agenda
17034 (append org-tag-alist-for-agenda org-tag-alist))
17036 (save-excursion
17037 (remove-text-properties (point-min) (point-max) pall)
17038 (when org-agenda-skip-archived-trees
17039 (goto-char (point-min))
17040 (while (re-search-forward rea nil t)
17041 (if (org-at-heading-p t)
17042 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17043 (goto-char (point-min))
17044 (setq re (format org-heading-keyword-regexp-format
17045 org-comment-string))
17046 (while (re-search-forward re nil t)
17047 (add-text-properties
17048 (match-beginning 0) (org-end-of-subtree t) pc)))
17049 (set-buffer-modified-p bmp)))))
17050 (setq org-todo-keywords-for-agenda
17051 (org-uniquify org-todo-keywords-for-agenda))
17052 (setq org-todo-keyword-alist-for-agenda
17053 (org-uniquify org-todo-keyword-alist-for-agenda)
17054 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17056 ;;;; Embedded LaTeX
17058 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17059 "Keymap for the minor `org-cdlatex-mode'.")
17061 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17062 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17063 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17064 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17065 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17067 (defvar org-cdlatex-texmathp-advice-is-done nil
17068 "Flag remembering if we have applied the advice to texmathp already.")
17070 (define-minor-mode org-cdlatex-mode
17071 "Toggle the minor `org-cdlatex-mode'.
17072 This mode supports entering LaTeX environment and math in LaTeX fragments
17073 in Org-mode.
17074 \\{org-cdlatex-mode-map}"
17075 nil " OCDL" nil
17076 (when org-cdlatex-mode
17077 (require 'cdlatex)
17078 (run-hooks 'cdlatex-mode-hook)
17079 (cdlatex-compute-tables))
17080 (unless org-cdlatex-texmathp-advice-is-done
17081 (setq org-cdlatex-texmathp-advice-is-done t)
17082 (defadvice texmathp (around org-math-always-on activate)
17083 "Always return t in org-mode buffers.
17084 This is because we want to insert math symbols without dollars even outside
17085 the LaTeX math segments. If Orgmode thinks that point is actually inside
17086 an embedded LaTeX fragment, let texmathp do its job.
17087 \\[org-cdlatex-mode-map]"
17088 (interactive)
17089 (let (p)
17090 (cond
17091 ((not (derived-mode-p 'org-mode)) ad-do-it)
17092 ((eq this-command 'cdlatex-math-symbol)
17093 (setq ad-return-value t
17094 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17096 (let ((p (org-inside-LaTeX-fragment-p)))
17097 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17098 (setq ad-return-value t
17099 texmathp-why '("Org-mode embedded math" . 0))
17100 (if p ad-do-it)))))))))
17102 (defun turn-on-org-cdlatex ()
17103 "Unconditionally turn on `org-cdlatex-mode'."
17104 (org-cdlatex-mode 1))
17106 (defun org-inside-LaTeX-fragment-p ()
17107 "Test if point is inside a LaTeX fragment.
17108 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17109 sequence appearing also before point.
17110 Even though the matchers for math are configurable, this function assumes
17111 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17112 delimiters are skipped when they have been removed by customization.
17113 The return value is nil, or a cons cell with the delimiter and the
17114 position of this delimiter.
17116 This function does a reasonably good job, but can locally be fooled by
17117 for example currency specifications. For example it will assume being in
17118 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17119 fragments that are properly closed, but during editing, we have to live
17120 with the uncertainty caused by missing closing delimiters. This function
17121 looks only before point, not after."
17122 (catch 'exit
17123 (let ((pos (point))
17124 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17125 (lim (progn
17126 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17127 (point)))
17128 dd-on str (start 0) m re)
17129 (goto-char pos)
17130 (when dodollar
17131 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17132 re (nth 1 (assoc "$" org-latex-regexps)))
17133 (while (string-match re str start)
17134 (cond
17135 ((= (match-end 0) (length str))
17136 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17137 ((= (match-end 0) (- (length str) 5))
17138 (throw 'exit nil))
17139 (t (setq start (match-end 0))))))
17140 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17141 (goto-char pos)
17142 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17143 (and (match-beginning 2) (throw 'exit nil))
17144 ;; count $$
17145 (while (re-search-backward "\\$\\$" lim t)
17146 (setq dd-on (not dd-on)))
17147 (goto-char pos)
17148 (if dd-on (cons "$$" m))))))
17150 (defun org-inside-latex-macro-p ()
17151 "Is point inside a LaTeX macro or its arguments?"
17152 (save-match-data
17153 (org-in-regexp
17154 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17156 (defun org-try-cdlatex-tab ()
17157 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17158 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17159 - inside a LaTeX fragment, or
17160 - after the first word in a line, where an abbreviation expansion could
17161 insert a LaTeX environment."
17162 (when org-cdlatex-mode
17163 (cond
17164 ;; Before any word on the line: No expansion possible.
17165 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17166 ;; Just after first word on the line: Expand it. Make sure it
17167 ;; cannot happen on headlines, though.
17168 ((save-excursion
17169 (skip-chars-backward "a-zA-Z0-9*")
17170 (skip-chars-backward " \t")
17171 (and (bolp) (not (org-at-heading-p))))
17172 (cdlatex-tab) t)
17173 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17175 (defun org-cdlatex-underscore-caret (&optional arg)
17176 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17177 Revert to the normal definition outside of these fragments."
17178 (interactive "P")
17179 (if (org-inside-LaTeX-fragment-p)
17180 (call-interactively 'cdlatex-sub-superscript)
17181 (let (org-cdlatex-mode)
17182 (call-interactively (key-binding (vector last-input-event))))))
17184 (defun org-cdlatex-math-modify (&optional arg)
17185 "Execute `cdlatex-math-modify' in LaTeX fragments.
17186 Revert to the normal definition outside of these fragments."
17187 (interactive "P")
17188 (if (org-inside-LaTeX-fragment-p)
17189 (call-interactively 'cdlatex-math-modify)
17190 (let (org-cdlatex-mode)
17191 (call-interactively (key-binding (vector last-input-event))))))
17193 (defvar org-latex-fragment-image-overlays nil
17194 "List of overlays carrying the images of latex fragments.")
17195 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17197 (defun org-remove-latex-fragment-image-overlays ()
17198 "Remove all overlays with LaTeX fragment images in current buffer."
17199 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17200 (setq org-latex-fragment-image-overlays nil))
17202 (defun org-preview-latex-fragment (&optional subtree)
17203 "Preview the LaTeX fragment at point, or all locally or globally.
17204 If the cursor is in a LaTeX fragment, create the image and overlay
17205 it over the source code. If there is no fragment at point, display
17206 all fragments in the current text, from one headline to the next. With
17207 prefix SUBTREE, display all fragments in the current subtree. With a
17208 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17209 the cursor is before the first headline,
17210 display all fragments in the buffer.
17211 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17212 (interactive "P")
17213 (unless buffer-file-name
17214 (error "Can't preview LaTeX fragment in a non-file buffer"))
17215 (org-remove-latex-fragment-image-overlays)
17216 (save-excursion
17217 (save-restriction
17218 (let (beg end at msg)
17219 (cond
17220 ((or (equal subtree '(16))
17221 (not (save-excursion
17222 (re-search-backward org-outline-regexp-bol nil t))))
17223 (setq beg (point-min) end (point-max)
17224 msg "Creating images for buffer...%s"))
17225 ((equal subtree '(4))
17226 (org-back-to-heading)
17227 (setq beg (point) end (org-end-of-subtree t)
17228 msg "Creating images for subtree...%s"))
17230 (if (setq at (org-inside-LaTeX-fragment-p))
17231 (goto-char (max (point-min) (- (cdr at) 2)))
17232 (org-back-to-heading))
17233 (setq beg (point) end (progn (outline-next-heading) (point))
17234 msg (if at "Creating image...%s"
17235 "Creating images for entry...%s"))))
17236 (message msg "")
17237 (narrow-to-region beg end)
17238 (goto-char beg)
17239 (org-format-latex
17240 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17241 (file-name-nondirectory
17242 buffer-file-name)))
17243 default-directory 'overlays msg at 'forbuffer
17244 org-latex-create-formula-image-program)
17245 (message msg "done. Use `C-c C-c' to remove images.")))))
17247 (defvar org-latex-regexps
17248 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17249 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17250 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17251 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17252 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17253 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17254 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17255 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17256 "Regular expressions for matching embedded LaTeX.")
17258 (defvar org-export-have-math nil) ;; dynamic scoping
17259 (defun org-format-latex (prefix &optional dir overlays msg at
17260 forbuffer processing-type)
17261 "Replace LaTeX fragments with links to an image, and produce images.
17262 Some of the options can be changed using the variable
17263 `org-format-latex-options'."
17264 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17265 (let* ((prefixnodir (file-name-nondirectory prefix))
17266 (absprefix (expand-file-name prefix dir))
17267 (todir (file-name-directory absprefix))
17268 (opt org-format-latex-options)
17269 (matchers (plist-get opt :matchers))
17270 (re-list org-latex-regexps)
17271 (org-format-latex-header-extra
17272 (plist-get (org-infile-export-plist) :latex-header-extra))
17273 (cnt 0) txt hash link beg end re e checkdir
17274 executables-checked string
17275 m n block-type block linkfile movefile ov)
17276 ;; Check the different regular expressions
17277 (while (setq e (pop re-list))
17278 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17279 block (if block-type "\n\n" ""))
17280 (when (member m matchers)
17281 (goto-char (point-min))
17282 (while (re-search-forward re nil t)
17283 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17284 (not (get-text-property (match-beginning n)
17285 'org-protected))
17286 (or (not overlays)
17287 (not (eq (get-char-property (match-beginning n)
17288 'org-overlay-type)
17289 'org-latex-overlay))))
17290 (setq org-export-have-math t)
17291 (cond
17292 ((eq processing-type 'verbatim)
17293 ;; Leave the text verbatim, just protect it
17294 (add-text-properties (match-beginning n) (match-end n)
17295 '(org-protected t)))
17296 ((eq processing-type 'mathjax)
17297 ;; Prepare for MathJax processing
17298 (setq string (match-string n))
17299 (if (member m '("$" "$1"))
17300 (save-excursion
17301 (delete-region (match-beginning n) (match-end n))
17302 (goto-char (match-beginning n))
17303 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17304 "\\)")
17305 '(org-protected t))))
17306 (add-text-properties (match-beginning n) (match-end n)
17307 '(org-protected t))))
17308 ((or (eq processing-type 'dvipng)
17309 (eq processing-type 'imagemagick))
17310 ;; Process to an image
17311 (setq txt (match-string n)
17312 beg (match-beginning n) end (match-end n)
17313 cnt (1+ cnt))
17314 (let (print-length print-level) ; make sure full list is printed
17315 (setq hash (sha1 (prin1-to-string
17316 (list org-format-latex-header
17317 org-format-latex-header-extra
17318 org-export-latex-default-packages-alist
17319 org-export-latex-packages-alist
17320 org-format-latex-options
17321 forbuffer txt)))
17322 linkfile (format "%s_%s.png" prefix hash)
17323 movefile (format "%s_%s.png" absprefix hash)))
17324 (setq link (concat block "[[file:" linkfile "]]" block))
17325 (if msg (message msg cnt))
17326 (goto-char beg)
17327 (unless checkdir ; make sure the directory exists
17328 (setq checkdir t)
17329 (or (file-directory-p todir) (make-directory todir t)))
17330 (cond
17331 ((eq processing-type 'dvipng)
17332 (unless executables-checked
17333 (org-check-external-command
17334 "latex" "needed to convert LaTeX fragments to images")
17335 (org-check-external-command
17336 "dvipng" "needed to convert LaTeX fragments to images")
17337 (setq executables-checked t))
17338 (unless (file-exists-p movefile)
17339 (org-create-formula-image-with-dvipng
17340 txt movefile opt forbuffer)))
17341 ((eq processing-type 'imagemagick)
17342 (unless executables-checked
17343 (org-check-external-command
17344 "convert" "you need to install imagemagick")
17345 (setq executables-checked t))
17346 (unless (file-exists-p movefile)
17347 (org-create-formula-image-with-imagemagick
17348 txt movefile opt forbuffer))))
17349 (if overlays
17350 (progn
17351 (mapc (lambda (o)
17352 (if (eq (overlay-get o 'org-overlay-type)
17353 'org-latex-overlay)
17354 (delete-overlay o)))
17355 (overlays-in beg end))
17356 (setq ov (make-overlay beg end))
17357 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17358 (if (featurep 'xemacs)
17359 (progn
17360 (overlay-put ov 'invisible t)
17361 (overlay-put
17362 ov 'end-glyph
17363 (make-glyph (vector 'png :file movefile))))
17364 (overlay-put
17365 ov 'display
17366 (list 'image :type 'png :file movefile :ascent 'center)))
17367 (push ov org-latex-fragment-image-overlays)
17368 (goto-char end))
17369 (delete-region beg end)
17370 (insert (org-add-props link
17371 (list 'org-latex-src
17372 (replace-regexp-in-string
17373 "\"" "" txt)
17374 'org-latex-src-embed-type
17375 (if block-type 'paragraph 'character))))))
17376 ((eq processing-type 'mathml)
17377 ;; Process to MathML
17378 (unless executables-checked
17379 (unless (save-match-data (org-format-latex-mathml-available-p))
17380 (error "LaTeX to MathML converter not configured"))
17381 (setq executables-checked t))
17382 (setq txt (match-string n)
17383 beg (match-beginning n) end (match-end n)
17384 cnt (1+ cnt))
17385 (if msg (message msg cnt))
17386 (goto-char beg)
17387 (delete-region beg end)
17388 (insert (org-format-latex-as-mathml
17389 txt block-type prefix dir)))
17391 (error "Unknown conversion type %s for latex fragments"
17392 processing-type)))))))))
17394 (defun org-create-math-formula (latex-frag &optional mathml-file)
17395 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17396 Use `org-latex-to-mathml-convert-command'. If the conversion is
17397 sucessful, return the portion between \"<math...> </math>\"
17398 elements otherwise return nil. When MATHML-FILE is specified,
17399 write the results in to that file. When invoked as an
17400 interactive command, prompt for LATEX-FRAG, with initial value
17401 set to the current active region and echo the results for user
17402 inspection."
17403 (interactive (list (let ((frag (when (org-region-active-p)
17404 (buffer-substring-no-properties
17405 (region-beginning) (region-end)))))
17406 (read-string "LaTeX Fragment: " frag nil frag))))
17407 (unless latex-frag (error "Invalid latex-frag"))
17408 (let* ((tmp-in-file (file-relative-name
17409 (make-temp-name (expand-file-name "ltxmathml-in"))))
17410 (ignore (write-region latex-frag nil tmp-in-file))
17411 (tmp-out-file (file-relative-name
17412 (make-temp-name (expand-file-name "ltxmathml-out"))))
17413 (cmd (format-spec
17414 org-latex-to-mathml-convert-command
17415 `((?j . ,(shell-quote-argument
17416 (expand-file-name org-latex-to-mathml-jar-file)))
17417 (?I . ,(shell-quote-argument tmp-in-file))
17418 (?o . ,(shell-quote-argument tmp-out-file)))))
17419 mathml shell-command-output)
17420 (when (org-called-interactively-p 'any)
17421 (unless (org-format-latex-mathml-available-p)
17422 (error "LaTeX to MathML converter not configured")))
17423 (message "Running %s" cmd)
17424 (setq shell-command-output (shell-command-to-string cmd))
17425 (setq mathml
17426 (when (file-readable-p tmp-out-file)
17427 (with-current-buffer (find-file-noselect tmp-out-file t)
17428 (goto-char (point-min))
17429 (when (re-search-forward
17430 (concat
17431 (regexp-quote
17432 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17433 "\\(.\\|\n\\)*"
17434 (regexp-quote "</math>")) nil t)
17435 (prog1 (match-string 0) (kill-buffer))))))
17436 (cond
17437 (mathml
17438 (setq mathml
17439 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17440 (when mathml-file
17441 (write-region mathml nil mathml-file))
17442 (when (org-called-interactively-p 'any)
17443 (message mathml)))
17444 ((message "LaTeX to MathML conversion failed")
17445 (message shell-command-output)))
17446 (delete-file tmp-in-file)
17447 (when (file-exists-p tmp-out-file)
17448 (delete-file tmp-out-file))
17449 mathml))
17451 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17452 prefix &optional dir)
17453 "Use `org-create-math-formula' but check local cache first."
17454 (let* ((absprefix (expand-file-name prefix dir))
17455 (print-length nil) (print-level nil)
17456 (formula-id (concat
17457 "formula-"
17458 (sha1
17459 (prin1-to-string
17460 (list latex-frag
17461 org-latex-to-mathml-convert-command)))))
17462 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17463 (formula-cache-dir (file-name-directory formula-cache)))
17465 (unless (file-directory-p formula-cache-dir)
17466 (make-directory formula-cache-dir t))
17468 (unless (file-exists-p formula-cache)
17469 (org-create-math-formula latex-frag formula-cache))
17471 (if (file-exists-p formula-cache)
17472 ;; Successful conversion. Return the link to MathML file.
17473 (org-add-props
17474 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17475 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17476 'org-latex-src-embed-type (if latex-frag-type
17477 'paragraph 'character)))
17478 ;; Failed conversion. Return the LaTeX fragment verbatim
17479 (add-text-properties
17480 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17481 latex-frag)))
17483 ;; This function borrows from Ganesh Swami's latex2png.el
17484 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17485 "This calls dvipng."
17486 (require 'org-latex)
17487 (let* ((tmpdir (if (featurep 'xemacs)
17488 (temp-directory)
17489 temporary-file-directory))
17490 (texfilebase (make-temp-name
17491 (expand-file-name "orgtex" tmpdir)))
17492 (texfile (concat texfilebase ".tex"))
17493 (dvifile (concat texfilebase ".dvi"))
17494 (pngfile (concat texfilebase ".png"))
17495 (fnh (if (featurep 'xemacs)
17496 (font-height (face-font 'default))
17497 (face-attribute 'default :height nil)))
17498 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17499 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17500 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17501 "Black"))
17502 (bg (or (plist-get options (if buffer :background :html-background))
17503 "Transparent")))
17504 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17505 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17506 (with-temp-file texfile
17507 (insert (org-splice-latex-header
17508 org-format-latex-header
17509 org-export-latex-default-packages-alist
17510 org-export-latex-packages-alist t
17511 org-format-latex-header-extra))
17512 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17513 (require 'org-latex)
17514 (org-export-latex-fix-inputenc))
17515 (let ((dir default-directory))
17516 (condition-case nil
17517 (progn
17518 (cd tmpdir)
17519 (call-process "latex" nil nil nil texfile))
17520 (error nil))
17521 (cd dir))
17522 (if (not (file-exists-p dvifile))
17523 (progn (message "Failed to create dvi file from %s" texfile) nil)
17524 (condition-case nil
17525 (if (featurep 'xemacs)
17526 (call-process "dvipng" nil nil nil
17527 "-fg" fg "-bg" bg
17528 "-T" "tight"
17529 "-o" pngfile
17530 dvifile)
17531 (call-process "dvipng" nil nil nil
17532 "-fg" fg "-bg" bg
17533 "-D" dpi
17534 ;;"-x" scale "-y" scale
17535 "-T" "tight"
17536 "-o" pngfile
17537 dvifile))
17538 (error nil))
17539 (if (not (file-exists-p pngfile))
17540 (if org-format-latex-signal-error
17541 (error "Failed to create png file from %s" texfile)
17542 (message "Failed to create png file from %s" texfile)
17543 nil)
17544 ;; Use the requested file name and clean up
17545 (copy-file pngfile tofile 'replace)
17546 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17547 (if (file-exists-p (concat texfilebase e))
17548 (delete-file (concat texfilebase e))))
17549 pngfile))))
17551 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17552 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17553 "This calls convert, which is included into imagemagick."
17554 (require 'org-latex)
17555 (let* ((tmpdir (if (featurep 'xemacs)
17556 (temp-directory)
17557 temporary-file-directory))
17558 (texfilebase (make-temp-name
17559 (expand-file-name "orgtex" tmpdir)))
17560 (texfile (concat texfilebase ".tex"))
17561 (pdffile (concat texfilebase ".pdf"))
17562 (pngfile (concat texfilebase ".png"))
17563 (fnh (if (featurep 'xemacs)
17564 (font-height (face-font 'default))
17565 (face-attribute 'default :height nil)))
17566 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17567 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17568 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17569 "black"))
17570 (bg (or (plist-get options (if buffer :background :html-background))
17571 "white")))
17572 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17573 (setq fg (org-latex-color-format fg)))
17574 (if (eq bg 'default) (setq bg (org-latex-color :background))
17575 (setq bg (org-latex-color-format
17576 (if (string= bg "Transparent")(setq bg "white")))))
17577 (with-temp-file texfile
17578 (insert (org-splice-latex-header
17579 org-format-latex-header
17580 org-export-latex-default-packages-alist
17581 org-export-latex-packages-alist t
17582 org-format-latex-header-extra))
17583 (insert "\n\\begin{document}\n"
17584 "\\definecolor{fg}{rgb}{" fg "}\n"
17585 "\\definecolor{bg}{rgb}{" bg "}\n"
17586 "\n\\pagecolor{bg}\n"
17587 "\n{\\color{fg}\n"
17588 string
17589 "\n}\n"
17590 "\n\\end{document}\n" )
17591 (require 'org-latex)
17592 (org-export-latex-fix-inputenc))
17593 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17594 (condition-case nil
17595 (progn
17596 (cd tmpdir)
17597 (setq cmds org-latex-to-pdf-process)
17598 (while cmds
17599 (setq latex-frags-cmds (pop cmds))
17600 (if (listp latex-frags-cmds)
17601 (setq cmds nil)
17602 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17603 (while latex-frags-cmds
17604 (setq cmd (pop latex-frags-cmds))
17605 (while (string-match "%b" cmd)
17606 (setq cmd (replace-match
17607 (save-match-data
17608 (shell-quote-argument texfile))
17609 t t cmd)))
17610 (while (string-match "%f" cmd)
17611 (setq cmd (replace-match
17612 (save-match-data
17613 (shell-quote-argument (file-name-nondirectory texfile)))
17614 t t cmd)))
17615 (while (string-match "%o" cmd)
17616 (setq cmd (replace-match
17617 (save-match-data
17618 (shell-quote-argument (file-name-directory texfile)))
17619 t t cmd)))
17620 (setq cmd (split-string cmd))
17621 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17622 (error nil))
17623 (cd dir))
17624 (if (not (file-exists-p pdffile))
17625 (progn (message "Failed to create pdf file from %s" texfile) nil)
17626 (condition-case nil
17627 (if (featurep 'xemacs)
17628 (call-process "convert" nil nil nil
17629 "-density" "96"
17630 "-trim"
17631 "-antialias"
17632 pdffile
17633 "-quality" "100"
17634 ;; "-sharpen" "0x1.0"
17635 pngfile)
17636 (call-process "convert" nil nil nil
17637 "-density" dpi
17638 "-trim"
17639 "-antialias"
17640 pdffile
17641 "-quality" "100"
17642 ; "-sharpen" "0x1.0"
17643 pngfile))
17644 (error nil))
17645 (if (not (file-exists-p pngfile))
17646 (if org-format-latex-signal-error
17647 (error "Failed to create png file from %s" texfile)
17648 (message "Failed to create png file from %s" texfile)
17649 nil)
17650 ;; Use the requested file name and clean up
17651 (copy-file pngfile tofile 'replace)
17652 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17653 (if (file-exists-p (concat texfilebase e))
17654 (delete-file (concat texfilebase e))))
17655 pngfile))))
17657 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17658 "Fill a LaTeX header template TPL.
17659 In the template, the following place holders will be recognized:
17661 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17662 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17663 [PACKAGES] \\usepackage statements for PKG
17664 [NO-PACKAGES] do not include PKG
17665 [EXTRA] the string EXTRA
17666 [NO-EXTRA] do not include EXTRA
17668 For backward compatibility, if both the positive and the negative place
17669 holder is missing, the positive one (without the \"NO-\") will be
17670 assumed to be present at the end of the template.
17671 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17672 EXTRA is a string.
17673 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17674 (let (rpl (end ""))
17675 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17676 (setq rpl (if (or (match-end 1) (not def-pkg))
17677 "" (org-latex-packages-to-string def-pkg snippets-p t))
17678 tpl (replace-match rpl t t tpl))
17679 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17681 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17682 (setq rpl (if (or (match-end 1) (not pkg))
17683 "" (org-latex-packages-to-string pkg snippets-p t))
17684 tpl (replace-match rpl t t tpl))
17685 (if pkg (setq end
17686 (concat end "\n"
17687 (org-latex-packages-to-string pkg snippets-p)))))
17689 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17690 (setq rpl (if (or (match-end 1) (not extra))
17691 "" (concat extra "\n"))
17692 tpl (replace-match rpl t t tpl))
17693 (if (and extra (string-match "\\S-" extra))
17694 (setq end (concat end "\n" extra))))
17696 (if (string-match "\\S-" end)
17697 (concat tpl "\n" end)
17698 tpl)))
17700 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17701 "Turn an alist of packages into a string with the \\usepackage macros."
17702 (setq pkg (mapconcat (lambda(p)
17703 (cond
17704 ((stringp p) p)
17705 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17706 (format "%% Package %s omitted" (cadr p)))
17707 ((equal "" (car p))
17708 (format "\\usepackage{%s}" (cadr p)))
17710 (format "\\usepackage[%s]{%s}"
17711 (car p) (cadr p)))))
17713 "\n"))
17714 (if newline (concat pkg "\n") pkg))
17716 (defun org-dvipng-color (attr)
17717 "Return a RGB color specification for dvipng."
17718 (apply 'format "rgb %s %s %s"
17719 (mapcar 'org-normalize-color
17720 (if (featurep 'xemacs)
17721 (color-rgb-components
17722 (face-property 'default
17723 (cond ((eq attr :foreground) 'foreground)
17724 ((eq attr :background) 'background))))
17725 (color-values (face-attribute 'default attr nil))))))
17727 (defun org-latex-color (attr)
17728 "Return a RGB color for the LaTeX color package."
17729 (apply 'format "%s,%s,%s"
17730 (mapcar 'org-normalize-color
17731 (if (featurep 'xemacs)
17732 (color-rgb-components
17733 (face-property 'default
17734 (cond ((eq attr :foreground) 'foreground)
17735 ((eq attr :background) 'background))))
17736 (color-values (face-attribute 'default attr nil))))))
17738 (defun org-latex-color-format (color-name)
17739 "Convert COLOR-NAME to a RGB color value."
17740 (apply 'format "%s,%s,%s"
17741 (mapcar 'org-normalize-color
17742 (color-values color-name))))
17744 (defun org-normalize-color (value)
17745 "Return string to be used as color value for an RGB component."
17746 (format "%g" (/ value 65535.0)))
17748 ;; Image display
17751 (defvar org-inline-image-overlays nil)
17752 (make-variable-buffer-local 'org-inline-image-overlays)
17754 (defun org-toggle-inline-images (&optional include-linked)
17755 "Toggle the display of inline images.
17756 INCLUDE-LINKED is passed to `org-display-inline-images'."
17757 (interactive "P")
17758 (if org-inline-image-overlays
17759 (progn
17760 (org-remove-inline-images)
17761 (message "Inline image display turned off"))
17762 (org-display-inline-images include-linked)
17763 (if org-inline-image-overlays
17764 (message "%d images displayed inline"
17765 (length org-inline-image-overlays))
17766 (message "No images to display inline"))))
17768 (defun org-redisplay-inline-images ()
17769 "Refresh the display of inline images."
17770 (interactive)
17771 (if (not org-inline-image-overlays)
17772 (org-toggle-inline-images)
17773 (org-toggle-inline-images)
17774 (org-toggle-inline-images)))
17776 (defun org-display-inline-images (&optional include-linked refresh beg end)
17777 "Display inline images.
17778 Normally only links without a description part are inlined, because this
17779 is how it will work for export. When INCLUDE-LINKED is set, also links
17780 with a description part will be inlined. This can be nice for a quick
17781 look at those images, but it does not reflect what exported files will look
17782 like.
17783 When REFRESH is set, refresh existing images between BEG and END.
17784 This will create new image displays only if necessary.
17785 BEG and END default to the buffer boundaries."
17786 (interactive "P")
17787 (unless refresh
17788 (org-remove-inline-images)
17789 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17790 (save-excursion
17791 (save-restriction
17792 (widen)
17793 (setq beg (or beg (point-min)) end (or end (point-max)))
17794 (goto-char beg)
17795 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17796 (substring (org-image-file-name-regexp) 0 -2)
17797 "\\)\\]" (if include-linked "" "\\]")))
17798 old file ov img)
17799 (while (re-search-forward re end t)
17800 (setq old (get-char-property-and-overlay (match-beginning 1)
17801 'org-image-overlay))
17802 (setq file (expand-file-name
17803 (concat (or (match-string 3) "") (match-string 4))))
17804 (when (file-exists-p file)
17805 (if (and (car-safe old) refresh)
17806 (image-refresh (overlay-get (cdr old) 'display))
17807 (setq img (save-match-data (create-image file)))
17808 (when img
17809 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17810 (overlay-put ov 'display img)
17811 (overlay-put ov 'face 'default)
17812 (overlay-put ov 'org-image-overlay t)
17813 (overlay-put ov 'modification-hooks
17814 (list 'org-display-inline-remove-overlay))
17815 (push ov org-inline-image-overlays)))))))))
17817 (define-obsolete-function-alias
17818 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17820 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17821 "Remove inline-display overlay if a corresponding region is modified."
17822 (let ((inhibit-modification-hooks t))
17823 (when (and ov after)
17824 (delete ov org-inline-image-overlays)
17825 (delete-overlay ov))))
17827 (defun org-remove-inline-images ()
17828 "Remove inline display of images."
17829 (interactive)
17830 (mapc 'delete-overlay org-inline-image-overlays)
17831 (setq org-inline-image-overlays nil))
17833 ;;;; Key bindings
17835 ;; Outline functions from `outline-mode-prefix-map'
17836 ;; that can be remapped in Org:
17837 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17838 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17839 (define-key org-mode-map [remap outline-forward-same-level]
17840 'org-forward-heading-same-level)
17841 (define-key org-mode-map [remap outline-backward-same-level]
17842 'org-backward-heading-same-level)
17843 (define-key org-mode-map [remap show-branches]
17844 'org-kill-note-or-show-branches)
17845 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17846 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17847 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17849 ;; Outline functions from `outline-mode-prefix-map' that can not
17850 ;; be remapped in Org:
17852 ;; - the column "key binding" shows whether the Outline function is still
17853 ;; available in Org mode on the same key that it has been bound to in
17854 ;; Outline mode:
17855 ;; - "overridden": key used for a different functionality in Org mode
17856 ;; - else: key still bound to the same Outline function in Org mode
17858 ;; | Outline function | key binding | Org replacement |
17859 ;; |------------------------------------+-------------+-----------------------|
17860 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17861 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17862 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17863 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17864 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17865 ;; | `show-entry' | overridden | no replacement |
17866 ;; | `show-children' | `C-c C-i' | visibility cycling |
17867 ;; | `show-branches' | `C-c C-k' | still same function |
17868 ;; | `show-subtree' | overridden | visibility cycling |
17869 ;; | `show-all' | overridden | no replacement |
17870 ;; | `hide-subtree' | overridden | visibility cycling |
17871 ;; | `hide-body' | overridden | no replacement |
17872 ;; | `hide-entry' | overridden | visibility cycling |
17873 ;; | `hide-leaves' | overridden | no replacement |
17874 ;; | `hide-sublevels' | overridden | no replacement |
17875 ;; | `hide-other' | overridden | no replacement |
17877 ;; Make `C-c C-x' a prefix key
17878 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17880 ;; TAB key with modifiers
17881 (org-defkey org-mode-map "\C-i" 'org-cycle)
17882 (org-defkey org-mode-map [(tab)] 'org-cycle)
17883 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17884 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17885 ;; The following line is necessary under Suse GNU/Linux
17886 (unless (featurep 'xemacs)
17887 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17888 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17889 (define-key org-mode-map [backtab] 'org-shifttab)
17891 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17892 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17893 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17895 ;; Cursor keys with modifiers
17896 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17897 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17898 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17899 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17901 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17902 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17903 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17904 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17906 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17907 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17908 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17909 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17911 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17912 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17913 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17914 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17916 ;; Babel keys
17917 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17918 (mapc (lambda (pair)
17919 (define-key org-babel-map (car pair) (cdr pair)))
17920 org-babel-key-bindings)
17922 ;;; Extra keys for tty access.
17923 ;; We only set them when really needed because otherwise the
17924 ;; menus don't show the simple keys
17926 (when (or org-use-extra-keys
17927 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17928 (not window-system))
17929 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17930 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17931 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17932 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17933 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17934 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17935 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17936 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17937 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17938 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17939 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17940 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17941 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17942 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17943 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17944 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17945 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17946 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17947 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17948 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17949 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17950 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17951 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17952 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17953 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17954 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17955 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17956 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17958 ;; All the other keys
17960 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17961 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17962 (if (boundp 'narrow-map)
17963 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17964 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17965 (if (boundp 'narrow-map)
17966 (org-defkey narrow-map "b" 'org-narrow-to-block)
17967 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17968 (if (boundp 'narrow-map)
17969 (org-defkey narrow-map "e" 'org-narrow-to-element)
17970 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17971 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17972 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17973 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17974 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17975 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17976 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17977 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17978 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17979 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17980 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17981 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17982 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17983 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17984 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17985 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17986 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17987 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17988 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17989 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17990 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17991 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17992 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17993 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17994 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17995 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17996 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17997 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17998 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17999 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18000 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18001 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18002 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18003 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18004 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18005 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18006 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18007 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18008 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18009 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18010 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18011 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18012 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18013 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18014 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18015 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18016 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18017 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18018 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18019 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18020 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18021 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18022 (org-defkey org-mode-map "\C-c^" 'org-sort)
18023 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18024 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18025 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18026 (org-defkey org-mode-map "\C-m" 'org-return)
18027 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18028 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18029 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18030 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18031 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18032 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18033 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18034 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18035 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18036 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18037 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18038 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18039 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18040 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18041 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18042 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18043 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18044 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18045 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18046 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18047 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18048 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18049 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18051 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18052 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18053 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18055 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18056 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18057 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18058 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18059 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18060 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18061 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18062 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18063 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18064 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18065 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18066 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18067 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18068 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18069 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18070 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18071 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18072 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18073 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18074 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18075 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18076 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18078 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18079 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18080 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18081 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18082 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18084 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18086 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18088 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18089 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18091 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18094 (when (featurep 'xemacs)
18095 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18098 (defconst org-speed-commands-default
18100 ("Outline Navigation")
18101 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18102 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18103 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18104 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18105 ("u" . (org-speed-move-safe 'outline-up-heading))
18106 ("j" . org-goto)
18107 ("g" . (org-refile t))
18108 ("Outline Visibility")
18109 ("c" . org-cycle)
18110 ("C" . org-shifttab)
18111 (" " . org-display-outline-path)
18112 ("=" . org-columns)
18113 ("Outline Structure Editing")
18114 ("U" . org-shiftmetaup)
18115 ("D" . org-shiftmetadown)
18116 ("r" . org-metaright)
18117 ("l" . org-metaleft)
18118 ("R" . org-shiftmetaright)
18119 ("L" . org-shiftmetaleft)
18120 ("i" . (progn (forward-char 1) (call-interactively
18121 'org-insert-heading-respect-content)))
18122 ("^" . org-sort)
18123 ("w" . org-refile)
18124 ("a" . org-archive-subtree-default-with-confirmation)
18125 ("." . org-mark-subtree)
18126 ("#" . org-toggle-comment)
18127 ("Clock Commands")
18128 ("I" . org-clock-in)
18129 ("O" . org-clock-out)
18130 ("Meta Data Editing")
18131 ("t" . org-todo)
18132 ("," . (org-priority))
18133 ("0" . (org-priority ?\ ))
18134 ("1" . (org-priority ?A))
18135 ("2" . (org-priority ?B))
18136 ("3" . (org-priority ?C))
18137 (":" . org-set-tags-command)
18138 ("e" . org-set-effort)
18139 ("E" . org-inc-effort)
18140 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18141 (org-entry-put (point) "APPT_WARNTIME" m)))
18142 ("Agenda Views etc")
18143 ("v" . org-agenda)
18144 ("/" . org-sparse-tree)
18145 ("Misc")
18146 ("o" . org-open-at-point)
18147 ("?" . org-speed-command-help)
18148 ("<" . (org-agenda-set-restriction-lock 'subtree))
18149 (">" . (org-agenda-remove-restriction-lock))
18151 "The default speed commands.")
18153 (defun org-print-speed-command (e)
18154 (if (> (length (car e)) 1)
18155 (progn
18156 (princ "\n")
18157 (princ (car e))
18158 (princ "\n")
18159 (princ (make-string (length (car e)) ?-))
18160 (princ "\n"))
18161 (princ (car e))
18162 (princ " ")
18163 (if (symbolp (cdr e))
18164 (princ (symbol-name (cdr e)))
18165 (prin1 (cdr e)))
18166 (princ "\n")))
18168 (defun org-speed-command-help ()
18169 "Show the available speed commands."
18170 (interactive)
18171 (if (not org-use-speed-commands)
18172 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18173 (with-output-to-temp-buffer "*Help*"
18174 (princ "User-defined Speed commands\n===========================\n")
18175 (mapc 'org-print-speed-command org-speed-commands-user)
18176 (princ "\n")
18177 (princ "Built-in Speed commands\n=======================\n")
18178 (mapc 'org-print-speed-command org-speed-commands-default))
18179 (with-current-buffer "*Help*"
18180 (setq truncate-lines t))))
18182 (defun org-speed-move-safe (cmd)
18183 "Execute CMD, but make sure that the cursor always ends up in a headline.
18184 If not, return to the original position and throw an error."
18185 (interactive)
18186 (let ((pos (point)))
18187 (call-interactively cmd)
18188 (unless (and (bolp) (org-at-heading-p))
18189 (goto-char pos)
18190 (error "Boundary reached while executing %s" cmd))))
18192 (defvar org-self-insert-command-undo-counter 0)
18194 (defvar org-table-auto-blank-field) ; defined in org-table.el
18195 (defvar org-speed-command nil)
18197 (define-obsolete-function-alias
18198 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18200 (defun org-speed-command-activate (keys)
18201 "Hook for activating single-letter speed commands.
18202 `org-speed-commands-default' specifies a minimal command set.
18203 Use `org-speed-commands-user' for further customization."
18204 (when (or (and (bolp) (looking-at org-outline-regexp))
18205 (and (functionp org-use-speed-commands)
18206 (funcall org-use-speed-commands)))
18207 (cdr (assoc keys (append org-speed-commands-user
18208 org-speed-commands-default)))))
18210 (define-obsolete-function-alias
18211 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18213 (defun org-babel-speed-command-activate (keys)
18214 "Hook for activating single-letter code block commands."
18215 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18216 (cdr (assoc keys org-babel-key-bindings))))
18218 (defcustom org-speed-command-hook
18219 '(org-speed-command-default-hook org-babel-speed-command-hook)
18220 "Hook for activating speed commands at strategic locations.
18221 Hook functions are called in sequence until a valid handler is
18222 found.
18224 Each hook takes a single argument, a user-pressed command key
18225 which is also a `self-insert-command' from the global map.
18227 Within the hook, examine the cursor position and the command key
18228 and return nil or a valid handler as appropriate. Handler could
18229 be one of an interactive command, a function, or a form.
18231 Set `org-use-speed-commands' to non-nil value to enable this
18232 hook. The default setting is `org-speed-command-activate'."
18233 :group 'org-structure
18234 :version "24.1"
18235 :type 'hook)
18237 (defun org-self-insert-command (N)
18238 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18239 If the cursor is in a table looking at whitespace, the whitespace is
18240 overwritten, and the table is not marked as requiring realignment."
18241 (interactive "p")
18242 (org-check-before-invisible-edit 'insert)
18243 (cond
18244 ((and org-use-speed-commands
18245 (setq org-speed-command
18246 (run-hook-with-args-until-success
18247 'org-speed-command-hook (this-command-keys))))
18248 (cond
18249 ((commandp org-speed-command)
18250 (setq this-command org-speed-command)
18251 (call-interactively org-speed-command))
18252 ((functionp org-speed-command)
18253 (funcall org-speed-command))
18254 ((and org-speed-command (listp org-speed-command))
18255 (eval org-speed-command))
18256 (t (let (org-use-speed-commands)
18257 (call-interactively 'org-self-insert-command)))))
18258 ((and
18259 (org-table-p)
18260 (progn
18261 ;; check if we blank the field, and if that triggers align
18262 (and (featurep 'org-table) org-table-auto-blank-field
18263 (member last-command
18264 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18265 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18266 ;; got extra space, this field does not determine column width
18267 (let (org-table-may-need-update) (org-table-blank-field))
18268 ;; no extra space, this field may determine column width
18269 (org-table-blank-field)))
18271 (eq N 1)
18272 (looking-at "[^|\n]* |"))
18273 (let (org-table-may-need-update)
18274 (goto-char (1- (match-end 0)))
18275 (backward-delete-char 1)
18276 (goto-char (match-beginning 0))
18277 (self-insert-command N)))
18279 (setq org-table-may-need-update t)
18280 (self-insert-command N)
18281 (org-fix-tags-on-the-fly)
18282 (if org-self-insert-cluster-for-undo
18283 (if (not (eq last-command 'org-self-insert-command))
18284 (setq org-self-insert-command-undo-counter 1)
18285 (if (>= org-self-insert-command-undo-counter 20)
18286 (setq org-self-insert-command-undo-counter 1)
18287 (and (> org-self-insert-command-undo-counter 0)
18288 buffer-undo-list (listp buffer-undo-list)
18289 (not (cadr buffer-undo-list)) ; remove nil entry
18290 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18291 (setq org-self-insert-command-undo-counter
18292 (1+ org-self-insert-command-undo-counter))))))))
18294 (defun org-check-before-invisible-edit (kind)
18295 "Check is editing if kind KIND would be dangerous with invisible text around.
18296 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18297 ;; First, try to get out of here as quickly as possible, to reduce overhead
18298 (if (and org-catch-invisible-edits
18299 (or (not (boundp 'visible-mode)) (not visible-mode))
18300 (or (get-char-property (point) 'invisible)
18301 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18302 ;; OK, we need to take a closer look
18303 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18304 (invisible-before-point (if (bobp) nil (get-char-property
18305 (1- (point)) 'invisible)))
18306 (border-and-ok-direction
18308 ;; Check if we are acting predictably before invisible text
18309 (and invisible-at-point (not invisible-before-point)
18310 (memq kind '(insert delete-backward)))
18311 ;; Check if we are acting predictably after invisible text
18312 ;; This works not well, and I have turned it off. It seems
18313 ;; better to always show and stop after invisible text.
18314 ;; (and (not invisible-at-point) invisible-before-point
18315 ;; (memq kind '(insert delete)))
18317 (when (or (memq invisible-at-point '(outline org-hide-block t))
18318 (memq invisible-before-point '(outline org-hide-block t)))
18319 (if (eq org-catch-invisible-edits 'error)
18320 (error "Editing in invisible areas is prohibited - make visible first"))
18321 (if (and org-custom-properties-overlays
18322 (y-or-n-p "Display invisible properties in this buffer? "))
18323 (org-toggle-custom-properties-visibility)
18324 ;; Make the area visible
18325 (save-excursion
18326 (if invisible-before-point
18327 (goto-char (previous-single-char-property-change
18328 (point) 'invisible)))
18329 (org-cycle))
18330 (cond
18331 ((eq org-catch-invisible-edits 'show)
18332 ;; That's it, we do the edit after showing
18333 (message
18334 "Unfolding invisible region around point before editing")
18335 (sit-for 1))
18336 ((and (eq org-catch-invisible-edits 'smart)
18337 border-and-ok-direction)
18338 (message "Unfolding invisible region around point before editing"))
18340 ;; Don't do the edit, make the user repeat it in full visibility
18341 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18343 (defun org-fix-tags-on-the-fly ()
18344 (when (and (equal (char-after (point-at-bol)) ?*)
18345 (org-at-heading-p))
18346 (org-align-tags-here org-tags-column)))
18348 (defun org-delete-backward-char (N)
18349 "Like `delete-backward-char', insert whitespace at field end in tables.
18350 When deleting backwards, in tables this function will insert whitespace in
18351 front of the next \"|\" separator, to keep the table aligned. The table will
18352 still be marked for re-alignment if the field did fill the entire column,
18353 because, in this case the deletion might narrow the column."
18354 (interactive "p")
18355 (save-match-data
18356 (org-check-before-invisible-edit 'delete-backward)
18357 (if (and (org-table-p)
18358 (eq N 1)
18359 (string-match "|" (buffer-substring (point-at-bol) (point)))
18360 (looking-at ".*?|"))
18361 (let ((pos (point))
18362 (noalign (looking-at "[^|\n\r]* |"))
18363 (c org-table-may-need-update))
18364 (backward-delete-char N)
18365 (if (not overwrite-mode)
18366 (progn
18367 (skip-chars-forward "^|")
18368 (insert " ")
18369 (goto-char (1- pos))))
18370 ;; noalign: if there were two spaces at the end, this field
18371 ;; does not determine the width of the column.
18372 (if noalign (setq org-table-may-need-update c)))
18373 (backward-delete-char N)
18374 (org-fix-tags-on-the-fly))))
18376 (defun org-delete-char (N)
18377 "Like `delete-char', but insert whitespace at field end in tables.
18378 When deleting characters, in tables this function will insert whitespace in
18379 front of the next \"|\" separator, to keep the table aligned. The table will
18380 still be marked for re-alignment if the field did fill the entire column,
18381 because, in this case the deletion might narrow the column."
18382 (interactive "p")
18383 (save-match-data
18384 (org-check-before-invisible-edit 'delete)
18385 (if (and (org-table-p)
18386 (not (bolp))
18387 (not (= (char-after) ?|))
18388 (eq N 1))
18389 (if (looking-at ".*?|")
18390 (let ((pos (point))
18391 (noalign (looking-at "[^|\n\r]* |"))
18392 (c org-table-may-need-update))
18393 (replace-match (concat
18394 (substring (match-string 0) 1 -1)
18395 " |"))
18396 (goto-char pos)
18397 ;; noalign: if there were two spaces at the end, this field
18398 ;; does not determine the width of the column.
18399 (if noalign (setq org-table-may-need-update c)))
18400 (delete-char N))
18401 (delete-char N)
18402 (org-fix-tags-on-the-fly))))
18404 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18405 (put 'org-self-insert-command 'delete-selection t)
18406 (put 'orgtbl-self-insert-command 'delete-selection t)
18407 (put 'org-delete-char 'delete-selection 'supersede)
18408 (put 'org-delete-backward-char 'delete-selection 'supersede)
18409 (put 'org-yank 'delete-selection 'yank)
18411 ;; Make `flyspell-mode' delay after some commands
18412 (put 'org-self-insert-command 'flyspell-delayed t)
18413 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18414 (put 'org-delete-char 'flyspell-delayed t)
18415 (put 'org-delete-backward-char 'flyspell-delayed t)
18417 ;; Make pabbrev-mode expand after org-mode commands
18418 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18419 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18421 ;; How to do this: Measure non-white length of current string
18422 ;; If equal to column width, we should realign.
18424 (defun org-remap (map &rest commands)
18425 "In MAP, remap the functions given in COMMANDS.
18426 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18427 (let (new old)
18428 (while commands
18429 (setq old (pop commands) new (pop commands))
18430 (if (fboundp 'command-remapping)
18431 (org-defkey map (vector 'remap old) new)
18432 (substitute-key-definition old new map global-map)))))
18434 (when (eq org-enable-table-editor 'optimized)
18435 ;; If the user wants maximum table support, we need to hijack
18436 ;; some standard editing functions
18437 (org-remap org-mode-map
18438 'self-insert-command 'org-self-insert-command
18439 'delete-char 'org-delete-char
18440 'delete-backward-char 'org-delete-backward-char)
18441 (org-defkey org-mode-map "|" 'org-force-self-insert))
18443 (defvar org-ctrl-c-ctrl-c-hook nil
18444 "Hook for functions attaching themselves to `C-c C-c'.
18446 This can be used to add additional functionality to the C-c C-c
18447 key which executes context-dependent commands. This hook is run
18448 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18449 run after the last test.
18451 Each function will be called with no arguments. The function
18452 must check if the context is appropriate for it to act. If yes,
18453 it should do its thing and then return a non-nil value. If the
18454 context is wrong, just do nothing and return nil.")
18456 (defvar org-ctrl-c-ctrl-c-final-hook nil
18457 "Hook for functions attaching themselves to `C-c C-c'.
18459 This can be used to add additional functionality to the C-c C-c
18460 key which executes context-dependent commands. This hook is run
18461 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18462 before the first test.
18464 Each function will be called with no arguments. The function
18465 must check if the context is appropriate for it to act. If yes,
18466 it should do its thing and then return a non-nil value. If the
18467 context is wrong, just do nothing and return nil.")
18469 (defvar org-tab-first-hook nil
18470 "Hook for functions to attach themselves to TAB.
18471 See `org-ctrl-c-ctrl-c-hook' for more information.
18472 This hook runs as the first action when TAB is pressed, even before
18473 `org-cycle' messes around with the `outline-regexp' to cater for
18474 inline tasks and plain list item folding.
18475 If any function in this hook returns t, any other actions that
18476 would have been caused by TAB (such as table field motion or visibility
18477 cycling) will not occur.")
18479 (defvar org-tab-after-check-for-table-hook nil
18480 "Hook for functions to attach themselves to TAB.
18481 See `org-ctrl-c-ctrl-c-hook' for more information.
18482 This hook runs after it has been established that the cursor is not in a
18483 table, but before checking if the cursor is in a headline or if global cycling
18484 should be done.
18485 If any function in this hook returns t, not other actions like visibility
18486 cycling will be done.")
18488 (defvar org-tab-after-check-for-cycling-hook nil
18489 "Hook for functions to attach themselves to TAB.
18490 See `org-ctrl-c-ctrl-c-hook' for more information.
18491 This hook runs after it has been established that not table field motion and
18492 not visibility should be done because of current context. This is probably
18493 the place where a package like yasnippets can hook in.")
18495 (defvar org-tab-before-tab-emulation-hook nil
18496 "Hook for functions to attach themselves to TAB.
18497 See `org-ctrl-c-ctrl-c-hook' for more information.
18498 This hook runs after every other options for TAB have been exhausted, but
18499 before indentation and \t insertion takes place.")
18501 (defvar org-metaleft-hook nil
18502 "Hook for functions attaching themselves to `M-left'.
18503 See `org-ctrl-c-ctrl-c-hook' for more information.")
18504 (defvar org-metaright-hook nil
18505 "Hook for functions attaching themselves to `M-right'.
18506 See `org-ctrl-c-ctrl-c-hook' for more information.")
18507 (defvar org-metaup-hook nil
18508 "Hook for functions attaching themselves to `M-up'.
18509 See `org-ctrl-c-ctrl-c-hook' for more information.")
18510 (defvar org-metadown-hook nil
18511 "Hook for functions attaching themselves to `M-down'.
18512 See `org-ctrl-c-ctrl-c-hook' for more information.")
18513 (defvar org-shiftmetaleft-hook nil
18514 "Hook for functions attaching themselves to `M-S-left'.
18515 See `org-ctrl-c-ctrl-c-hook' for more information.")
18516 (defvar org-shiftmetaright-hook nil
18517 "Hook for functions attaching themselves to `M-S-right'.
18518 See `org-ctrl-c-ctrl-c-hook' for more information.")
18519 (defvar org-shiftmetaup-hook nil
18520 "Hook for functions attaching themselves to `M-S-up'.
18521 See `org-ctrl-c-ctrl-c-hook' for more information.")
18522 (defvar org-shiftmetadown-hook nil
18523 "Hook for functions attaching themselves to `M-S-down'.
18524 See `org-ctrl-c-ctrl-c-hook' for more information.")
18525 (defvar org-metareturn-hook nil
18526 "Hook for functions attaching themselves to `M-RET'.
18527 See `org-ctrl-c-ctrl-c-hook' for more information.")
18528 (defvar org-shiftup-hook nil
18529 "Hook for functions attaching themselves to `S-up'.
18530 See `org-ctrl-c-ctrl-c-hook' for more information.")
18531 (defvar org-shiftup-final-hook nil
18532 "Hook for functions attaching themselves to `S-up'.
18533 This one runs after all other options except shift-select have been excluded.
18534 See `org-ctrl-c-ctrl-c-hook' for more information.")
18535 (defvar org-shiftdown-hook nil
18536 "Hook for functions attaching themselves to `S-down'.
18537 See `org-ctrl-c-ctrl-c-hook' for more information.")
18538 (defvar org-shiftdown-final-hook nil
18539 "Hook for functions attaching themselves to `S-down'.
18540 This one runs after all other options except shift-select have been excluded.
18541 See `org-ctrl-c-ctrl-c-hook' for more information.")
18542 (defvar org-shiftleft-hook nil
18543 "Hook for functions attaching themselves to `S-left'.
18544 See `org-ctrl-c-ctrl-c-hook' for more information.")
18545 (defvar org-shiftleft-final-hook nil
18546 "Hook for functions attaching themselves to `S-left'.
18547 This one runs after all other options except shift-select have been excluded.
18548 See `org-ctrl-c-ctrl-c-hook' for more information.")
18549 (defvar org-shiftright-hook nil
18550 "Hook for functions attaching themselves to `S-right'.
18551 See `org-ctrl-c-ctrl-c-hook' for more information.")
18552 (defvar org-shiftright-final-hook nil
18553 "Hook for functions attaching themselves to `S-right'.
18554 This one runs after all other options except shift-select have been excluded.
18555 See `org-ctrl-c-ctrl-c-hook' for more information.")
18557 (defun org-modifier-cursor-error ()
18558 "Throw an error, a modified cursor command was applied in wrong context."
18559 (error "This command is active in special context like tables, headlines or items"))
18561 (defun org-shiftselect-error ()
18562 "Throw an error because Shift-Cursor command was applied in wrong context."
18563 (if (and (boundp 'shift-select-mode) shift-select-mode)
18564 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18565 (error "This command works only in special context like headlines or timestamps")))
18567 (defun org-call-for-shift-select (cmd)
18568 (let ((this-command-keys-shift-translated t))
18569 (call-interactively cmd)))
18571 (defun org-shifttab (&optional arg)
18572 "Global visibility cycling or move to previous table field.
18573 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18574 on context.
18575 See the individual commands for more information."
18576 (interactive "P")
18577 (cond
18578 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18579 ((integerp arg)
18580 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18581 (message "Content view to level: %d" arg)
18582 (org-content (prefix-numeric-value arg2))
18583 (setq org-cycle-global-status 'overview)))
18584 (t (call-interactively 'org-global-cycle))))
18586 (defun org-shiftmetaleft ()
18587 "Promote subtree or delete table column.
18588 Calls `org-promote-subtree', `org-outdent-item-tree', or
18589 `org-table-delete-column', depending on context. See the
18590 individual commands for more information."
18591 (interactive)
18592 (cond
18593 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18594 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18595 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18596 ((if (not (org-region-active-p)) (org-at-item-p)
18597 (save-excursion (goto-char (region-beginning))
18598 (org-at-item-p)))
18599 (call-interactively 'org-outdent-item-tree))
18600 (t (org-modifier-cursor-error))))
18602 (defun org-shiftmetaright ()
18603 "Demote subtree or insert table column.
18604 Calls `org-demote-subtree', `org-indent-item-tree', or
18605 `org-table-insert-column', depending on context. See the
18606 individual commands for more information."
18607 (interactive)
18608 (cond
18609 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18610 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18611 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18612 ((if (not (org-region-active-p)) (org-at-item-p)
18613 (save-excursion (goto-char (region-beginning))
18614 (org-at-item-p)))
18615 (call-interactively 'org-indent-item-tree))
18616 (t (org-modifier-cursor-error))))
18618 (defun org-shiftmetaup (&optional arg)
18619 "Move subtree up or kill table row.
18620 Calls `org-move-subtree-up' or `org-table-kill-row' or
18621 `org-move-item-up' or `org-timestamp-up', depending on context.
18622 See the individual commands for more information."
18623 (interactive "P")
18624 (cond
18625 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18626 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18627 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18628 ((org-at-item-p) (call-interactively 'org-move-item-up))
18629 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18630 (call-interactively 'org-timestamp-up)))
18631 (t (org-modifier-cursor-error))))
18633 (defun org-shiftmetadown (&optional arg)
18634 "Move subtree down or insert table row.
18635 Calls `org-move-subtree-down' or `org-table-insert-row' or
18636 `org-move-item-down' or `org-timestamp-up', depending on context.
18637 See the individual commands for more information."
18638 (interactive "P")
18639 (cond
18640 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18641 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18642 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18643 ((org-at-item-p) (call-interactively 'org-move-item-down))
18644 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18645 (call-interactively 'org-timestamp-down)))
18646 (t (org-modifier-cursor-error))))
18648 (defsubst org-hidden-tree-error ()
18649 (error
18650 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18652 (defun org-metaleft (&optional arg)
18653 "Promote heading or move table column to left.
18654 Calls `org-do-promote' or `org-table-move-column', depending on context.
18655 With no specific context, calls the Emacs default `backward-word'.
18656 See the individual commands for more information."
18657 (interactive "P")
18658 (cond
18659 ((run-hook-with-args-until-success 'org-metaleft-hook))
18660 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18661 ((org-with-limited-levels
18662 (or (org-at-heading-p)
18663 (and (org-region-active-p)
18664 (save-excursion
18665 (goto-char (region-beginning))
18666 (org-at-heading-p)))))
18667 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18668 (call-interactively 'org-do-promote))
18669 ;; At an inline task.
18670 ((org-at-heading-p)
18671 (call-interactively 'org-inlinetask-promote))
18672 ((or (org-at-item-p)
18673 (and (org-region-active-p)
18674 (save-excursion
18675 (goto-char (region-beginning))
18676 (org-at-item-p))))
18677 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18678 (call-interactively 'org-outdent-item))
18679 (t (call-interactively 'backward-word))))
18681 (defun org-metaright (&optional arg)
18682 "Demote a subtree, a list item or move table column to right.
18683 In front of a drawer or a block keyword, indent it correctly.
18684 With no specific context, calls the Emacs default `forward-word'.
18685 See the individual commands for more information."
18686 (interactive "P")
18687 (cond
18688 ((run-hook-with-args-until-success 'org-metaright-hook))
18689 ((org-at-table-p) (call-interactively 'org-table-move-column))
18690 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18691 ((org-at-block-p) (call-interactively 'org-indent-block))
18692 ((org-with-limited-levels
18693 (or (org-at-heading-p)
18694 (and (org-region-active-p)
18695 (save-excursion
18696 (goto-char (region-beginning))
18697 (org-at-heading-p)))))
18698 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18699 (call-interactively 'org-do-demote))
18700 ;; At an inline task.
18701 ((org-at-heading-p)
18702 (call-interactively 'org-inlinetask-demote))
18703 ((or (org-at-item-p)
18704 (and (org-region-active-p)
18705 (save-excursion
18706 (goto-char (region-beginning))
18707 (org-at-item-p))))
18708 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18709 (call-interactively 'org-indent-item))
18710 (t (call-interactively 'forward-word))))
18712 (defun org-check-for-hidden (what)
18713 "Check if there are hidden headlines/items in the current visual line.
18714 WHAT can be either `headlines' or `items'. If the current line is
18715 an outline or item heading and it has a folded subtree below it,
18716 this function returns t, nil otherwise."
18717 (let ((re (cond
18718 ((eq what 'headlines) org-outline-regexp-bol)
18719 ((eq what 'items) (org-item-beginning-re))
18720 (t (error "This should not happen"))))
18721 beg end)
18722 (save-excursion
18723 (catch 'exit
18724 (unless (org-region-active-p)
18725 (setq beg (point-at-bol))
18726 (beginning-of-line 2)
18727 (while (and (not (eobp)) ;; this is like `next-line'
18728 (get-char-property (1- (point)) 'invisible))
18729 (beginning-of-line 2))
18730 (setq end (point))
18731 (goto-char beg)
18732 (goto-char (point-at-eol))
18733 (setq end (max end (point)))
18734 (while (re-search-forward re end t)
18735 (if (get-char-property (match-beginning 0) 'invisible)
18736 (throw 'exit t))))
18737 nil))))
18739 (autoload 'org-element-at-point "org-element")
18740 (autoload 'org-element-type "org-element")
18742 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18743 (declare-function org-element-type "org-element" (element))
18744 (declare-function org-element-contents "org-element" (element))
18745 (declare-function org-element-property "org-element" (property element))
18746 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18747 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18748 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18749 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18750 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18752 (defun org-metaup (&optional arg)
18753 "Move subtree up or move table row up.
18754 Calls `org-move-subtree-up' or `org-table-move-row' or
18755 `org-move-item-up', depending on context. See the individual commands
18756 for more information."
18757 (interactive "P")
18758 (cond
18759 ((run-hook-with-args-until-success 'org-metaup-hook))
18760 ((org-region-active-p)
18761 (let* ((a (min (region-beginning) (region-end)))
18762 (b (1- (max (region-beginning) (region-end))))
18763 (c (save-excursion (goto-char a)
18764 (move-beginning-of-line 0)))
18765 (d (save-excursion (goto-char a)
18766 (move-end-of-line 0) (point))))
18767 (transpose-regions a b c d)
18768 (goto-char c)))
18769 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18770 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18771 ((org-at-item-p) (call-interactively 'org-move-item-up))
18772 (t (org-drag-element-backward))))
18774 (defun org-metadown (&optional arg)
18775 "Move subtree down or move table row down.
18776 Calls `org-move-subtree-down' or `org-table-move-row' or
18777 `org-move-item-down', depending on context. See the individual
18778 commands for more information."
18779 (interactive "P")
18780 (cond
18781 ((run-hook-with-args-until-success 'org-metadown-hook))
18782 ((org-region-active-p)
18783 (let* ((a (min (region-beginning) (region-end)))
18784 (b (max (region-beginning) (region-end)))
18785 (c (save-excursion (goto-char b)
18786 (move-beginning-of-line 1)))
18787 (d (save-excursion (goto-char b)
18788 (move-end-of-line 1) (1+ (point)))))
18789 (transpose-regions a b c d)
18790 (goto-char d)))
18791 ((org-at-table-p) (call-interactively 'org-table-move-row))
18792 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18793 ((org-at-item-p) (call-interactively 'org-move-item-down))
18794 (t (org-drag-element-forward))))
18796 (defun org-shiftup (&optional arg)
18797 "Increase item in timestamp or increase priority of current headline.
18798 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18799 depending on context. See the individual commands for more information."
18800 (interactive "P")
18801 (cond
18802 ((run-hook-with-args-until-success 'org-shiftup-hook))
18803 ((and org-support-shift-select (org-region-active-p))
18804 (org-call-for-shift-select 'previous-line))
18805 ((org-at-timestamp-p t)
18806 (call-interactively (if org-edit-timestamp-down-means-later
18807 'org-timestamp-down 'org-timestamp-up)))
18808 ((and (not (eq org-support-shift-select 'always))
18809 org-enable-priority-commands
18810 (org-at-heading-p))
18811 (call-interactively 'org-priority-up))
18812 ((and (not org-support-shift-select) (org-at-item-p))
18813 (call-interactively 'org-previous-item))
18814 ((org-clocktable-try-shift 'up arg))
18815 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18816 (org-support-shift-select
18817 (org-call-for-shift-select 'previous-line))
18818 (t (org-shiftselect-error))))
18820 (defun org-shiftdown (&optional arg)
18821 "Decrease item in timestamp or decrease priority of current headline.
18822 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18823 depending on context. See the individual commands for more information."
18824 (interactive "P")
18825 (cond
18826 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18827 ((and org-support-shift-select (org-region-active-p))
18828 (org-call-for-shift-select 'next-line))
18829 ((org-at-timestamp-p t)
18830 (call-interactively (if org-edit-timestamp-down-means-later
18831 'org-timestamp-up 'org-timestamp-down)))
18832 ((and (not (eq org-support-shift-select 'always))
18833 org-enable-priority-commands
18834 (org-at-heading-p))
18835 (call-interactively 'org-priority-down))
18836 ((and (not org-support-shift-select) (org-at-item-p))
18837 (call-interactively 'org-next-item))
18838 ((org-clocktable-try-shift 'down arg))
18839 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18840 (org-support-shift-select
18841 (org-call-for-shift-select 'next-line))
18842 (t (org-shiftselect-error))))
18844 (defun org-shiftright (&optional arg)
18845 "Cycle the thing at point or in the current line, depending on context.
18846 Depending on context, this does one of the following:
18848 - switch a timestamp at point one day into the future
18849 - on a headline, switch to the next TODO keyword.
18850 - on an item, switch entire list to the next bullet type
18851 - on a property line, switch to the next allowed value
18852 - on a clocktable definition line, move time block into the future"
18853 (interactive "P")
18854 (cond
18855 ((run-hook-with-args-until-success 'org-shiftright-hook))
18856 ((and org-support-shift-select (org-region-active-p))
18857 (org-call-for-shift-select 'forward-char))
18858 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18859 ((and (not (eq org-support-shift-select 'always))
18860 (org-at-heading-p))
18861 (let ((org-inhibit-logging
18862 (not org-treat-S-cursor-todo-selection-as-state-change))
18863 (org-inhibit-blocking
18864 (not org-treat-S-cursor-todo-selection-as-state-change)))
18865 (org-call-with-arg 'org-todo 'right)))
18866 ((or (and org-support-shift-select
18867 (not (eq org-support-shift-select 'always))
18868 (org-at-item-bullet-p))
18869 (and (not org-support-shift-select) (org-at-item-p)))
18870 (org-call-with-arg 'org-cycle-list-bullet nil))
18871 ((and (not (eq org-support-shift-select 'always))
18872 (org-at-property-p))
18873 (call-interactively 'org-property-next-allowed-value))
18874 ((org-clocktable-try-shift 'right arg))
18875 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18876 (org-support-shift-select
18877 (org-call-for-shift-select 'forward-char))
18878 (t (org-shiftselect-error))))
18880 (defun org-shiftleft (&optional arg)
18881 "Cycle the thing at point or in the current line, depending on context.
18882 Depending on context, this does one of the following:
18884 - switch a timestamp at point one day into the past
18885 - on a headline, switch to the previous TODO keyword.
18886 - on an item, switch entire list to the previous bullet type
18887 - on a property line, switch to the previous allowed value
18888 - on a clocktable definition line, move time block into the past"
18889 (interactive "P")
18890 (cond
18891 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18892 ((and org-support-shift-select (org-region-active-p))
18893 (org-call-for-shift-select 'backward-char))
18894 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18895 ((and (not (eq org-support-shift-select 'always))
18896 (org-at-heading-p))
18897 (let ((org-inhibit-logging
18898 (not org-treat-S-cursor-todo-selection-as-state-change))
18899 (org-inhibit-blocking
18900 (not org-treat-S-cursor-todo-selection-as-state-change)))
18901 (org-call-with-arg 'org-todo 'left)))
18902 ((or (and org-support-shift-select
18903 (not (eq org-support-shift-select 'always))
18904 (org-at-item-bullet-p))
18905 (and (not org-support-shift-select) (org-at-item-p)))
18906 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18907 ((and (not (eq org-support-shift-select 'always))
18908 (org-at-property-p))
18909 (call-interactively 'org-property-previous-allowed-value))
18910 ((org-clocktable-try-shift 'left arg))
18911 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18912 (org-support-shift-select
18913 (org-call-for-shift-select 'backward-char))
18914 (t (org-shiftselect-error))))
18916 (defun org-shiftcontrolright ()
18917 "Switch to next TODO set."
18918 (interactive)
18919 (cond
18920 ((and org-support-shift-select (org-region-active-p))
18921 (org-call-for-shift-select 'forward-word))
18922 ((and (not (eq org-support-shift-select 'always))
18923 (org-at-heading-p))
18924 (org-call-with-arg 'org-todo 'nextset))
18925 (org-support-shift-select
18926 (org-call-for-shift-select 'forward-word))
18927 (t (org-shiftselect-error))))
18929 (defun org-shiftcontrolleft ()
18930 "Switch to previous TODO set."
18931 (interactive)
18932 (cond
18933 ((and org-support-shift-select (org-region-active-p))
18934 (org-call-for-shift-select 'backward-word))
18935 ((and (not (eq org-support-shift-select 'always))
18936 (org-at-heading-p))
18937 (org-call-with-arg 'org-todo 'previousset))
18938 (org-support-shift-select
18939 (org-call-for-shift-select 'backward-word))
18940 (t (org-shiftselect-error))))
18942 (defun org-shiftcontrolup ()
18943 "Change timestamps synchronously up in CLOCK log lines."
18944 (interactive)
18945 (cond ((and (not org-support-shift-select)
18946 (org-at-clock-log-p)
18947 (org-at-timestamp-p t))
18948 (org-clock-timestamps-up))
18949 (t (org-shiftselect-error))))
18951 (defun org-shiftcontroldown ()
18952 "Change timestamps synchronously down in CLOCK log lines."
18953 (interactive)
18954 (cond ((and (not org-support-shift-select)
18955 (org-at-clock-log-p)
18956 (org-at-timestamp-p t))
18957 (org-clock-timestamps-down))
18958 (t (org-shiftselect-error))))
18960 (defun org-ctrl-c-ret ()
18961 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18962 (interactive)
18963 (cond
18964 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18965 (t (call-interactively 'org-insert-heading))))
18967 (defun org-find-visible ()
18968 (let ((s (point)))
18969 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18970 (get-char-property s 'invisible)))
18972 (defun org-find-invisible ()
18973 (let ((s (point)))
18974 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18975 (not (get-char-property s 'invisible))))
18978 (defun org-copy-visible (beg end)
18979 "Copy the visible parts of the region."
18980 (interactive "r")
18981 (let (snippets s)
18982 (save-excursion
18983 (save-restriction
18984 (narrow-to-region beg end)
18985 (setq s (goto-char (point-min)))
18986 (while (not (= (point) (point-max)))
18987 (goto-char (org-find-invisible))
18988 (push (buffer-substring s (point)) snippets)
18989 (setq s (goto-char (org-find-visible))))))
18990 (kill-new (apply 'concat (nreverse snippets)))))
18992 (defun org-copy-special ()
18993 "Copy region in table or copy current subtree.
18994 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18995 See the individual commands for more information."
18996 (interactive)
18997 (call-interactively
18998 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19000 (defun org-cut-special ()
19001 "Cut region in table or cut current subtree.
19002 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19003 See the individual commands for more information."
19004 (interactive)
19005 (call-interactively
19006 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19008 (defun org-paste-special (arg)
19009 "Paste rectangular region into table, or past subtree relative to level.
19010 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19011 See the individual commands for more information."
19012 (interactive "P")
19013 (if (org-at-table-p)
19014 (org-table-paste-rectangle)
19015 (org-paste-subtree arg)))
19017 (defsubst org-in-fixed-width-region-p ()
19018 "Is point in a fixed-width region?"
19019 (save-match-data
19020 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19022 (defun org-edit-special (&optional arg)
19023 "Call a special editor for the stuff at point.
19024 When at a table, call the formula editor with `org-table-edit-formulas'.
19025 When in a source code block, call `org-edit-src-code'.
19026 When in a fixed-width region, call `org-edit-fixed-width-region'.
19027 When in an #+include line, visit the included file.
19028 On a link, call `ffap' to visit the link at point.
19029 Otherwise, return a user error."
19030 (interactive)
19031 ;; possibly prep session before editing source
19032 (when (and (org-in-src-block-p) arg)
19033 (let* ((info (org-babel-get-src-block-info))
19034 (lang (nth 0 info))
19035 (params (nth 2 info))
19036 (session (cdr (assoc :session params))))
19037 (when (and info session) ;; we are in a source-code block with a session
19038 (funcall
19039 (intern (concat "org-babel-prep-session:" lang)) session params))))
19040 (cond ;; proceed with `org-edit-special'
19041 ((save-excursion
19042 (beginning-of-line 1)
19043 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19044 (find-file (org-trim (match-string 1))))
19045 ((org-at-table.el-p) (org-edit-src-code))
19046 ((or (org-at-table-p)
19047 (save-excursion
19048 (beginning-of-line 1)
19049 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19050 (call-interactively 'org-table-edit-formulas))
19051 ((org-in-block-p '("src" "example" "latex" "html")) (org-edit-src-code))
19052 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19053 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19054 (t (user-error "No special environment to edit here"))))
19056 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19057 (defun org-ctrl-c-ctrl-c (&optional arg)
19058 "Set tags in headline, or update according to changed information at point.
19060 This command does many different things, depending on context:
19062 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19063 this is what we do.
19065 - If the cursor is on a statistics cookie, update it.
19067 - If the cursor is in a headline, prompt for tags and insert them
19068 into the current line, aligned to `org-tags-column'. When called
19069 with prefix arg, realign all tags in the current buffer.
19071 - If the cursor is in one of the special #+KEYWORD lines, this
19072 triggers scanning the buffer for these lines and updating the
19073 information.
19075 - If the cursor is inside a table, realign the table. This command
19076 works even if the automatic table editor has been turned off.
19078 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19079 the entire table.
19081 - If the cursor is at a footnote reference or definition, jump to
19082 the corresponding definition or references, respectively.
19084 - If the cursor is a the beginning of a dynamic block, update it.
19086 - If the current buffer is a capture buffer, close note and file it.
19088 - If the cursor is on a <<<target>>>, update radio targets and
19089 corresponding links in this buffer.
19091 - If the cursor is on a numbered item in a plain list, renumber the
19092 ordered list.
19094 - If the cursor is on a checkbox, toggle it.
19096 - If the cursor is on a code block, evaluate it. The variable
19097 `org-confirm-babel-evaluate' can be used to control prompting
19098 before code block evaluation, by default every code block
19099 evaluation requires confirmation. Code block evaluation can be
19100 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19101 (interactive "P")
19102 (let ((org-enable-table-editor t))
19103 (cond
19104 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19105 org-occur-highlights
19106 org-latex-fragment-image-overlays)
19107 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19108 (org-remove-occur-highlights)
19109 (org-remove-latex-fragment-image-overlays)
19110 (message "Temporary highlights/overlays removed from current buffer"))
19111 ((and (local-variable-p 'org-finish-function (current-buffer))
19112 (fboundp org-finish-function))
19113 (funcall org-finish-function))
19114 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19115 ((org-in-regexp org-ts-regexp-both)
19116 (org-timestamp-change 0 'day))
19117 ((or (looking-at org-property-start-re)
19118 (org-at-property-p))
19119 (call-interactively 'org-property-action))
19120 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19121 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19122 (or (org-at-heading-p) (org-at-item-p)))
19123 (call-interactively 'org-update-statistics-cookies))
19124 ((org-at-heading-p) (call-interactively 'org-set-tags))
19125 ((org-at-table.el-p)
19126 (message "Use C-c ' to edit table.el tables"))
19127 ((org-at-table-p)
19128 (org-table-maybe-eval-formula)
19129 (if arg
19130 (call-interactively 'org-table-recalculate)
19131 (org-table-maybe-recalculate-line))
19132 (call-interactively 'org-table-align)
19133 (orgtbl-send-table 'maybe))
19134 ((or (org-footnote-at-reference-p)
19135 (org-footnote-at-definition-p))
19136 (call-interactively 'org-footnote-action))
19137 ((org-at-item-checkbox-p)
19138 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19139 ;; list only if at top item.
19140 (let* ((cbox (match-string 1))
19141 (struct (org-list-struct))
19142 (old-struct (copy-tree struct))
19143 (parents (org-list-parents-alist struct))
19144 (orderedp (org-entry-get nil "ORDERED"))
19145 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19146 block-item)
19147 ;; Use a light version of `org-toggle-checkbox' to avoid
19148 ;; computing list structure twice.
19149 (let ((new-box (cond
19150 ((equal arg '(16)) "[-]")
19151 ((equal arg '(4)) nil)
19152 ((equal "[X]" cbox) "[ ]")
19153 (t "[X]"))))
19154 (if (and firstp arg)
19155 ;; If at first item of sub-list, remove check-box from
19156 ;; every item at the same level.
19157 (mapc
19158 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19159 (org-list-get-all-items
19160 (point-at-bol) struct (org-list-prevs-alist struct)))
19161 (org-list-set-checkbox (point-at-bol) struct new-box)))
19162 ;; Replicate `org-list-write-struct', while grabbing a return
19163 ;; value from `org-list-struct-fix-box'.
19164 (org-list-struct-fix-ind struct parents 2)
19165 (org-list-struct-fix-item-end struct)
19166 (let ((prevs (org-list-prevs-alist struct)))
19167 (org-list-struct-fix-bul struct prevs)
19168 (org-list-struct-fix-ind struct parents)
19169 (setq block-item
19170 (org-list-struct-fix-box struct parents prevs orderedp)))
19171 (if (equal struct old-struct)
19172 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19173 (org-list-struct-apply-struct struct old-struct)
19174 (org-update-checkbox-count-maybe))
19175 (when block-item
19176 (message
19177 "Checkboxes were removed due to unchecked box at line %d"
19178 (org-current-line block-item)))
19179 (when firstp (org-list-send-list 'maybe))))
19180 ((org-at-item-p)
19181 ;; Cursor at an item: repair list. Do checkbox related actions
19182 ;; only if function was called with an argument. Send list only
19183 ;; if at top item.
19184 (let* ((struct (org-list-struct))
19185 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19186 old-struct)
19187 (when arg
19188 (setq old-struct (copy-tree struct))
19189 (if firstp
19190 ;; If at first item of sub-list, add check-box to every
19191 ;; item at the same level.
19192 (mapc
19193 (lambda (pos)
19194 (unless (org-list-get-checkbox pos struct)
19195 (org-list-set-checkbox pos struct "[ ]")))
19196 (org-list-get-all-items
19197 (point-at-bol) struct (org-list-prevs-alist struct)))
19198 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19199 (org-list-write-struct
19200 struct (org-list-parents-alist struct) old-struct)
19201 (when arg (org-update-checkbox-count-maybe))
19202 (when firstp (org-list-send-list 'maybe))))
19203 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19204 ;; Dynamic block
19205 (beginning-of-line 1)
19206 (save-excursion (org-update-dblock)))
19207 ((save-excursion
19208 (let ((case-fold-search t))
19209 (beginning-of-line 1)
19210 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19211 (cond
19212 ((or (equal (match-string 1) "TBLFM")
19213 (equal (match-string 1) "tblfm"))
19214 ;; Recalculate the table before this line
19215 (save-excursion
19216 (beginning-of-line 1)
19217 (skip-chars-backward " \r\n\t")
19218 (if (org-at-table-p)
19219 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19221 (let ((org-inhibit-startup-visibility-stuff t)
19222 (org-startup-align-all-tables nil))
19223 (when (boundp 'org-table-coordinate-overlays)
19224 (mapc 'delete-overlay org-table-coordinate-overlays)
19225 (setq org-table-coordinate-overlays nil))
19226 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19227 (message "Local setup has been refreshed"))))
19228 ((org-clock-update-time-maybe))
19230 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19231 (error "C-c C-c can do nothing useful at this location"))))))
19233 (defun org-mode-restart ()
19234 "Restart Org-mode, to scan again for special lines.
19235 Also updates the keyword regular expressions."
19236 (interactive)
19237 (org-mode)
19238 (message "Org-mode restarted"))
19240 (defun org-kill-note-or-show-branches ()
19241 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19242 (interactive)
19243 (if (not org-finish-function)
19244 (progn
19245 (hide-subtree)
19246 (call-interactively 'show-branches))
19247 (let ((org-note-abort t))
19248 (funcall org-finish-function))))
19250 (defun org-return (&optional indent)
19251 "Goto next table row or insert a newline.
19252 Calls `org-table-next-row' or `newline', depending on context.
19253 See the individual commands for more information."
19254 (interactive)
19255 (let (org-ts-what)
19256 (cond
19257 ((or (bobp) (org-in-src-block-p))
19258 (if indent (newline-and-indent) (newline)))
19259 ((org-at-table-p)
19260 (org-table-justify-field-maybe)
19261 (call-interactively 'org-table-next-row))
19262 ;; when `newline-and-indent' is called within a list, make sure
19263 ;; text moved stays inside the item.
19264 ((and (org-in-item-p) indent)
19265 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19266 (progn
19267 (save-match-data (newline))
19268 (org-indent-line-to (length (match-string 0))))
19269 (let ((ind (org-get-indentation)))
19270 (newline)
19271 (if (org-looking-back org-list-end-re)
19272 (org-indent-line)
19273 (org-indent-line-to ind)))))
19274 ((and org-return-follows-link
19275 (org-at-timestamp-p t)
19276 (not (eq org-ts-what 'after)))
19277 (org-follow-timestamp-link))
19278 ((and org-return-follows-link
19279 (let ((tprop (get-text-property (point) 'face)))
19280 (or (eq tprop 'org-link)
19281 (and (listp tprop) (memq 'org-link tprop)))))
19282 (call-interactively 'org-open-at-point))
19283 ((and (org-at-heading-p)
19284 (looking-at
19285 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19286 (org-show-entry)
19287 (end-of-line 1)
19288 (newline))
19289 (t (if indent (newline-and-indent) (newline))))))
19291 (defun org-return-indent ()
19292 "Goto next table row or insert a newline and indent.
19293 Calls `org-table-next-row' or `newline-and-indent', depending on
19294 context. See the individual commands for more information."
19295 (interactive)
19296 (org-return t))
19298 (defun org-ctrl-c-star ()
19299 "Compute table, or change heading status of lines.
19300 Calls `org-table-recalculate' or `org-toggle-heading',
19301 depending on context."
19302 (interactive)
19303 (cond
19304 ((org-at-table-p)
19305 (call-interactively 'org-table-recalculate))
19307 ;; Convert all lines in region to list items
19308 (call-interactively 'org-toggle-heading))))
19310 (defun org-ctrl-c-minus ()
19311 "Insert separator line in table or modify bullet status of line.
19312 Also turns a plain line or a region of lines into list items.
19313 Calls `org-table-insert-hline', `org-toggle-item', or
19314 `org-cycle-list-bullet', depending on context."
19315 (interactive)
19316 (cond
19317 ((org-at-table-p)
19318 (call-interactively 'org-table-insert-hline))
19319 ((org-region-active-p)
19320 (call-interactively 'org-toggle-item))
19321 ((org-in-item-p)
19322 (call-interactively 'org-cycle-list-bullet))
19324 (call-interactively 'org-toggle-item))))
19326 (defun org-toggle-item (arg)
19327 "Convert headings or normal lines to items, items to normal lines.
19328 If there is no active region, only the current line is considered.
19330 If the first non blank line in the region is an headline, convert
19331 all headlines to items, shifting text accordingly.
19333 If it is an item, convert all items to normal lines.
19335 If it is normal text, change region into an item. With a prefix
19336 argument ARG, change each line in region into an item."
19337 (interactive "P")
19338 (let ((shift-text
19339 (function
19340 ;; Shift text in current section to IND, from point to END.
19341 ;; The function leaves point to END line.
19342 (lambda (ind end)
19343 (let ((min-i 1000) (end (copy-marker end)))
19344 ;; First determine the minimum indentation (MIN-I) of
19345 ;; the text.
19346 (save-excursion
19347 (catch 'exit
19348 (while (< (point) end)
19349 (let ((i (org-get-indentation)))
19350 (cond
19351 ;; Skip blank lines and inline tasks.
19352 ((looking-at "^[ \t]*$"))
19353 ((looking-at org-outline-regexp-bol))
19354 ;; We can't find less than 0 indentation.
19355 ((zerop i) (throw 'exit (setq min-i 0)))
19356 ((< i min-i) (setq min-i i))))
19357 (forward-line))))
19358 ;; Then indent each line so that a line indented to
19359 ;; MIN-I becomes indented to IND. Ignore blank lines
19360 ;; and inline tasks in the process.
19361 (let ((delta (- ind min-i)))
19362 (while (< (point) end)
19363 (unless (or (looking-at "^[ \t]*$")
19364 (looking-at org-outline-regexp-bol))
19365 (org-indent-line-to (+ (org-get-indentation) delta)))
19366 (forward-line)))))))
19367 (skip-blanks
19368 (function
19369 ;; Return beginning of first non-blank line, starting from
19370 ;; line at POS.
19371 (lambda (pos)
19372 (save-excursion
19373 (goto-char pos)
19374 (skip-chars-forward " \r\t\n")
19375 (point-at-bol)))))
19376 beg end)
19377 ;; Determine boundaries of changes.
19378 (if (org-region-active-p)
19379 (setq beg (funcall skip-blanks (region-beginning))
19380 end (copy-marker (region-end)))
19381 (setq beg (funcall skip-blanks (point-at-bol))
19382 end (copy-marker (point-at-eol))))
19383 ;; Depending on the starting line, choose an action on the text
19384 ;; between BEG and END.
19385 (org-with-limited-levels
19386 (save-excursion
19387 (goto-char beg)
19388 (cond
19389 ;; Case 1. Start at an item: de-itemize. Note that it only
19390 ;; happens when a region is active: `org-ctrl-c-minus'
19391 ;; would call `org-cycle-list-bullet' otherwise.
19392 ((org-at-item-p)
19393 (while (< (point) end)
19394 (when (org-at-item-p)
19395 (skip-chars-forward " \t")
19396 (delete-region (point) (match-end 0)))
19397 (forward-line)))
19398 ;; Case 2. Start at an heading: convert to items.
19399 ((org-at-heading-p)
19400 (let* ((bul (org-list-bullet-string "-"))
19401 (bul-len (length bul))
19402 ;; Indentation of the first heading. It should be
19403 ;; relative to the indentation of its parent, if any.
19404 (start-ind (save-excursion
19405 (cond
19406 ((not org-adapt-indentation) 0)
19407 ((not (outline-previous-heading)) 0)
19408 (t (length (match-string 0))))))
19409 ;; Level of first heading. Further headings will be
19410 ;; compared to it to determine hierarchy in the list.
19411 (ref-level (org-reduced-level (org-outline-level))))
19412 (while (< (point) end)
19413 (let* ((level (org-reduced-level (org-outline-level)))
19414 (delta (max 0 (- level ref-level))))
19415 ;; If current headline is less indented than the first
19416 ;; one, set it as reference, in order to preserve
19417 ;; subtrees.
19418 (when (< level ref-level) (setq ref-level level))
19419 (replace-match bul t t)
19420 (org-indent-line-to (+ start-ind (* delta bul-len)))
19421 ;; Ensure all text down to END (or SECTION-END) belongs
19422 ;; to the newly created item.
19423 (let ((section-end (save-excursion
19424 (or (outline-next-heading) (point)))))
19425 (forward-line)
19426 (funcall shift-text
19427 (+ start-ind (* (1+ delta) bul-len))
19428 (min end section-end)))))))
19429 ;; Case 3. Normal line with ARG: turn each non-item line into
19430 ;; an item.
19431 (arg
19432 (while (< (point) end)
19433 (unless (or (org-at-heading-p) (org-at-item-p))
19434 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19435 (replace-match
19436 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19437 (forward-line)))
19438 ;; Case 4. Normal line without ARG: make the first line of
19439 ;; region an item, and shift indentation of others
19440 ;; lines to set them as item's body.
19441 (t (let* ((bul (org-list-bullet-string "-"))
19442 (bul-len (length bul))
19443 (ref-ind (org-get-indentation)))
19444 (skip-chars-forward " \t")
19445 (insert bul)
19446 (forward-line)
19447 (while (< (point) end)
19448 ;; Ensure that lines less indented than first one
19449 ;; still get included in item body.
19450 (funcall shift-text
19451 (+ ref-ind bul-len)
19452 (min end (save-excursion (or (outline-next-heading)
19453 (point)))))
19454 (forward-line)))))))))
19456 (defun org-toggle-heading (&optional nstars)
19457 "Convert headings to normal text, or items or text to headings.
19458 If there is no active region, only the current line is considered.
19460 With a \\[universal-argument] prefix, convert the whole list at
19461 point into heading.
19463 In a region:
19465 - If the first non blank line is an headline, remove the stars
19466 from all headlines in the region.
19468 - If it is a normal line turn each and every normal line (i.e. not an
19469 heading or an item) in the region into a heading.
19471 - If it is a plain list item, turn all plain list items into headings.
19473 When converting a line into a heading, the number of stars is chosen
19474 such that the lines become children of the current entry. However,
19475 when a prefix argument is given, its value determines the number of
19476 stars to add."
19477 (interactive "P")
19478 (let ((skip-blanks
19479 (function
19480 ;; Return beginning of first non-blank line, starting from
19481 ;; line at POS.
19482 (lambda (pos)
19483 (save-excursion
19484 (goto-char pos)
19485 (while (org-at-comment-p) (forward-line))
19486 (skip-chars-forward " \r\t\n")
19487 (point-at-bol)))))
19488 beg end toggled)
19489 ;; Determine boundaries of changes. If a universal prefix has
19490 ;; been given, put the list in a region. If region ends at a bol,
19491 ;; do not consider the last line to be in the region.
19493 (when (and current-prefix-arg (org-at-item-p))
19494 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19495 (org-mark-element))
19497 (if (org-region-active-p)
19498 (setq beg (funcall skip-blanks (region-beginning))
19499 end (copy-marker (save-excursion
19500 (goto-char (region-end))
19501 (if (bolp) (point) (point-at-eol)))))
19502 (setq beg (funcall skip-blanks (point-at-bol))
19503 end (copy-marker (point-at-eol))))
19504 ;; Ensure inline tasks don't count as headings.
19505 (org-with-limited-levels
19506 (save-excursion
19507 (goto-char beg)
19508 (cond
19509 ;; Case 1. Started at an heading: de-star headings.
19510 ((org-at-heading-p)
19511 (while (< (point) end)
19512 (when (org-at-heading-p t)
19513 (looking-at org-outline-regexp) (replace-match "")
19514 (setq toggled t))
19515 (forward-line)))
19516 ;; Case 2. Started at an item: change items into headlines.
19517 ;; One star will be added by `org-list-to-subtree'.
19518 ((org-at-item-p)
19519 (let* ((stars (make-string
19520 (if nstars
19521 ;; subtract the star that will be added again by
19522 ;; `org-list-to-subtree'
19523 (1- (prefix-numeric-value current-prefix-arg))
19524 (or (org-current-level) 0))
19525 ?*))
19526 (add-stars
19527 (cond (nstars "") ; stars from prefix only
19528 ((equal stars "") "") ; before first heading
19529 (org-odd-levels-only "*") ; inside heading, odd
19530 (t "")))) ; inside heading, oddeven
19531 (while (< (point) end)
19532 (when (org-at-item-p)
19533 ;; Pay attention to cases when region ends before list.
19534 (let* ((struct (org-list-struct))
19535 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19536 (save-restriction
19537 (narrow-to-region (point) list-end)
19538 (insert
19539 (org-list-to-subtree
19540 (org-list-parse-list t)
19541 '(:istart (concat stars add-stars (funcall get-stars depth))
19542 :icount (concat stars add-stars (funcall get-stars depth)))))))
19543 (setq toggled t))
19544 (forward-line))))
19545 ;; Case 3. Started at normal text: make every line an heading,
19546 ;; skipping headlines and items.
19547 (t (let* ((stars (make-string
19548 (if nstars
19549 (prefix-numeric-value current-prefix-arg)
19550 (or (org-current-level) 0))
19551 ?*))
19552 (add-stars
19553 (cond (nstars "") ; stars from prefix only
19554 ((equal stars "") "*") ; before first heading
19555 (org-odd-levels-only "**") ; inside heading, odd
19556 (t "*"))) ; inside heading, oddeven
19557 (rpl (concat stars add-stars " ")))
19558 (while (< (point) end)
19559 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19560 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19561 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19562 (forward-line)))))))
19563 (unless toggled (message "Cannot toggle heading from here"))))
19565 (defun org-meta-return (&optional arg)
19566 "Insert a new heading or wrap a region in a table.
19567 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19568 See the individual commands for more information."
19569 (interactive "P")
19570 (cond
19571 ((run-hook-with-args-until-success 'org-metareturn-hook))
19572 ((or (org-at-drawer-p) (org-at-property-p))
19573 (newline-and-indent))
19574 ((org-at-table-p)
19575 (call-interactively 'org-table-wrap-region))
19576 (t (call-interactively 'org-insert-heading))))
19578 ;;; Menu entries
19580 (defsubst org-in-subtree-not-table-p ()
19581 "Are we in a subtree and not in a table?"
19582 (and (not (org-before-first-heading-p))
19583 (not (org-at-table-p))))
19585 ;; Define the Org-mode menus
19586 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19587 '("Tbl"
19588 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19589 ["Next Field" org-cycle (org-at-table-p)]
19590 ["Previous Field" org-shifttab (org-at-table-p)]
19591 ["Next Row" org-return (org-at-table-p)]
19592 "--"
19593 ["Blank Field" org-table-blank-field (org-at-table-p)]
19594 ["Edit Field" org-table-edit-field (org-at-table-p)]
19595 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19596 "--"
19597 ("Column"
19598 ["Move Column Left" org-metaleft (org-at-table-p)]
19599 ["Move Column Right" org-metaright (org-at-table-p)]
19600 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19601 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19602 ("Row"
19603 ["Move Row Up" org-metaup (org-at-table-p)]
19604 ["Move Row Down" org-metadown (org-at-table-p)]
19605 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19606 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19607 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19608 "--"
19609 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19610 ("Rectangle"
19611 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19612 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19613 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19614 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19615 "--"
19616 ("Calculate"
19617 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19618 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19619 ["Edit Formulas" org-edit-special (org-at-table-p)]
19620 "--"
19621 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19622 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19623 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19624 "--"
19625 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19626 "--"
19627 ["Sum Column/Rectangle" org-table-sum
19628 (or (org-at-table-p) (org-region-active-p))]
19629 ["Which Column?" org-table-current-column (org-at-table-p)])
19630 ["Debug Formulas"
19631 org-table-toggle-formula-debugger
19632 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19633 ["Show Col/Row Numbers"
19634 org-table-toggle-coordinate-overlays
19635 :style toggle
19636 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19637 "--"
19638 ["Create" org-table-create (and (not (org-at-table-p))
19639 org-enable-table-editor)]
19640 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19641 ["Import from File" org-table-import (not (org-at-table-p))]
19642 ["Export to File" org-table-export (org-at-table-p)]
19643 "--"
19644 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19646 (easy-menu-define org-org-menu org-mode-map "Org menu"
19647 '("Org"
19648 ("Show/Hide"
19649 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19650 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19651 ["Sparse Tree..." org-sparse-tree t]
19652 ["Reveal Context" org-reveal t]
19653 ["Show All" show-all t]
19654 "--"
19655 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19656 "--"
19657 ["New Heading" org-insert-heading t]
19658 ("Navigate Headings"
19659 ["Up" outline-up-heading t]
19660 ["Next" outline-next-visible-heading t]
19661 ["Previous" outline-previous-visible-heading t]
19662 ["Next Same Level" outline-forward-same-level t]
19663 ["Previous Same Level" outline-backward-same-level t]
19664 "--"
19665 ["Jump" org-goto t])
19666 ("Edit Structure"
19667 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19668 "--"
19669 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19670 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19671 "--"
19672 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19673 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19674 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19675 "--"
19676 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19677 "--"
19678 ["Copy visible text" org-copy-visible t]
19679 "--"
19680 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19681 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19682 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19683 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19684 "--"
19685 ["Sort Region/Children" org-sort t]
19686 "--"
19687 ["Convert to odd levels" org-convert-to-odd-levels t]
19688 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19689 ("Editing"
19690 ["Emphasis..." org-emphasize t]
19691 ["Edit Source Example" org-edit-special t]
19692 "--"
19693 ["Footnote new/jump" org-footnote-action t]
19694 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19695 ("Archive"
19696 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19697 "--"
19698 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19699 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19700 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19702 "--"
19703 ("Hyperlinks"
19704 ["Store Link (Global)" org-store-link t]
19705 ["Find existing link to here" org-occur-link-in-agenda-files t]
19706 ["Insert Link" org-insert-link t]
19707 ["Follow Link" org-open-at-point t]
19708 "--"
19709 ["Next link" org-next-link t]
19710 ["Previous link" org-previous-link t]
19711 "--"
19712 ["Descriptive Links"
19713 org-toggle-link-display
19714 :style radio
19715 :selected org-descriptive-links
19717 ["Literal Links"
19718 org-toggle-link-display
19719 :style radio
19720 :selected (not org-descriptive-links)])
19721 "--"
19722 ("TODO Lists"
19723 ["TODO/DONE/-" org-todo t]
19724 ("Select keyword"
19725 ["Next keyword" org-shiftright (org-at-heading-p)]
19726 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19727 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19728 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19729 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19730 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19731 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19732 "--"
19733 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19734 :selected org-enforce-todo-dependencies :style toggle :active t]
19735 "Settings for tree at point"
19736 ["Do Children sequentially" org-toggle-ordered-property :style radio
19737 :selected (org-entry-get nil "ORDERED")
19738 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19739 ["Do Children parallel" org-toggle-ordered-property :style radio
19740 :selected (not (org-entry-get nil "ORDERED"))
19741 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19742 "--"
19743 ["Set Priority" org-priority t]
19744 ["Priority Up" org-shiftup t]
19745 ["Priority Down" org-shiftdown t]
19746 "--"
19747 ["Get news from all feeds" org-feed-update-all t]
19748 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19749 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19750 ("TAGS and Properties"
19751 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19752 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19753 "--"
19754 ["Set property" org-set-property (not (org-before-first-heading-p))]
19755 ["Column view of properties" org-columns t]
19756 ["Insert Column View DBlock" org-insert-columns-dblock t])
19757 ("Dates and Scheduling"
19758 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19759 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19760 ("Change Date"
19761 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19762 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19763 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19764 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19765 ["Compute Time Range" org-evaluate-time-range t]
19766 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19767 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19768 "--"
19769 ["Custom time format" org-toggle-time-stamp-overlays
19770 :style radio :selected org-display-custom-times]
19771 "--"
19772 ["Goto Calendar" org-goto-calendar t]
19773 ["Date from Calendar" org-date-from-calendar t]
19774 "--"
19775 ["Start/Restart Timer" org-timer-start t]
19776 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19777 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19778 ["Insert Timer String" org-timer t]
19779 ["Insert Timer Item" org-timer-item t])
19780 ("Logging work"
19781 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19782 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19783 ["Clock out" org-clock-out t]
19784 ["Clock cancel" org-clock-cancel t]
19785 "--"
19786 ["Mark as default task" org-clock-mark-default-task t]
19787 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19788 ["Goto running clock" org-clock-goto t]
19789 "--"
19790 ["Display times" org-clock-display t]
19791 ["Create clock table" org-clock-report t]
19792 "--"
19793 ["Record DONE time"
19794 (progn (setq org-log-done (not org-log-done))
19795 (message "Switching to %s will %s record a timestamp"
19796 (car org-done-keywords)
19797 (if org-log-done "automatically" "not")))
19798 :style toggle :selected org-log-done])
19799 "--"
19800 ["Agenda Command..." org-agenda t]
19801 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19802 ("File List for Agenda")
19803 ("Special views current file"
19804 ["TODO Tree" org-show-todo-tree t]
19805 ["Check Deadlines" org-check-deadlines t]
19806 ["Timeline" org-timeline t]
19807 ["Tags/Property tree" org-match-sparse-tree t])
19808 "--"
19809 ["Export/Publish..." org-export t]
19810 ("LaTeX"
19811 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19812 :selected org-cdlatex-mode]
19813 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19814 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19815 ["Modify math symbol" org-cdlatex-math-modify
19816 (org-inside-LaTeX-fragment-p)]
19817 ["Insert citation" org-reftex-citation t]
19818 "--"
19819 ["Template for BEAMER" (progn (require 'org-beamer)
19820 (org-insert-beamer-options-template)) t])
19821 "--"
19822 ("MobileOrg"
19823 ["Push Files and Views" org-mobile-push t]
19824 ["Get Captured and Flagged" org-mobile-pull t]
19825 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19826 "--"
19827 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19828 "--"
19829 ("Documentation"
19830 ["Show Version" org-version t]
19831 ["Info Documentation" org-info t])
19832 ("Customize"
19833 ["Browse Org Group" org-customize t]
19834 "--"
19835 ["Expand This Menu" org-create-customize-menu
19836 (fboundp 'customize-menu-create)])
19837 ["Send bug report" org-submit-bug-report t]
19838 "--"
19839 ("Refresh/Reload"
19840 ["Refresh setup current buffer" org-mode-restart t]
19841 ["Reload Org (after update)" org-reload t]
19842 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19845 (defun org-info (&optional node)
19846 "Read documentation for Org-mode in the info system.
19847 With optional NODE, go directly to that node."
19848 (interactive)
19849 (info (format "(org)%s" (or node ""))))
19851 ;;;###autoload
19852 (defun org-submit-bug-report ()
19853 "Submit a bug report on Org-mode via mail.
19855 Don't hesitate to report any problems or inaccurate documentation.
19857 If you don't have setup sending mail from (X)Emacs, please copy the
19858 output buffer into your mail program, as it gives us important
19859 information about your Org-mode version and configuration."
19860 (interactive)
19861 (require 'reporter)
19862 (org-load-modules-maybe)
19863 (org-require-autoloaded-modules)
19864 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19865 (reporter-submit-bug-report
19866 "emacs-orgmode@gnu.org"
19867 (org-version nil 'full)
19868 (let (list)
19869 (save-window-excursion
19870 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19871 (delete-other-windows)
19872 (erase-buffer)
19873 (insert "You are about to submit a bug report to the Org-mode mailing list.
19875 We would like to add your full Org-mode and Outline configuration to the
19876 bug report. This greatly simplifies the work of the maintainer and
19877 other experts on the mailing list.
19879 HOWEVER, some variables you have customized may contain private
19880 information. The names of customers, colleagues, or friends, might
19881 appear in the form of file names, tags, todo states, or search strings.
19882 If you answer yes to the prompt, you might want to check and remove
19883 such private information before sending the email.")
19884 (add-text-properties (point-min) (point-max) '(face org-warning))
19885 (when (yes-or-no-p "Include your Org-mode configuration ")
19886 (mapatoms
19887 (lambda (v)
19888 (and (boundp v)
19889 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19890 (or (and (symbol-value v)
19891 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19892 (and
19893 (get v 'custom-type) (get v 'standard-value)
19894 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19895 (push v list)))))
19896 (kill-buffer (get-buffer "*Warn about privacy*"))
19897 list))
19898 nil nil
19899 "Remember to cover the basics, that is, what you expected to happen and
19900 what in fact did happen. You don't know how to make a good report? See
19902 http://orgmode.org/manual/Feedback.html#Feedback
19904 Your bug report will be posted to the Org-mode mailing list.
19905 ------------------------------------------------------------------------")
19906 (save-excursion
19907 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19908 (replace-match "\\1Bug: \\3 [\\2]")))))
19911 (defun org-install-agenda-files-menu ()
19912 (let ((bl (buffer-list)))
19913 (save-excursion
19914 (while bl
19915 (set-buffer (pop bl))
19916 (if (derived-mode-p 'org-mode) (setq bl nil)))
19917 (when (derived-mode-p 'org-mode)
19918 (easy-menu-change
19919 '("Org") "File List for Agenda"
19920 (append
19921 (list
19922 ["Edit File List" (org-edit-agenda-file-list) t]
19923 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19924 ["Remove Current File from List" org-remove-file t]
19925 ["Cycle through agenda files" org-cycle-agenda-files t]
19926 ["Occur in all agenda files" org-occur-in-agenda-files t]
19927 "--")
19928 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19930 ;;;; Documentation
19932 (defun org-require-autoloaded-modules ()
19933 (interactive)
19934 (mapc 'require
19935 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19936 org-docbook org-exp org-html org-icalendar
19937 org-id org-latex
19938 org-publish org-remember org-table
19939 org-timer org-xoxo)))
19941 ;;;###autoload
19942 (defun org-reload (&optional uncompiled)
19943 "Reload all org lisp files.
19944 With prefix arg UNCOMPILED, load the uncompiled versions."
19945 (interactive "P")
19946 (require 'find-func)
19947 (let* ((file-re "^org\\(-.*\\)?\\.el")
19948 (dir-org (file-name-directory (org-find-library-dir "org")))
19949 (dir-org-contrib (ignore-errors
19950 (file-name-directory
19951 (org-find-library-dir "org-contribdir"))))
19952 (babel-files
19953 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19954 (append (list nil "comint" "eval" "exp" "keys"
19955 "lob" "ref" "table" "tangle")
19956 (delq nil
19957 (mapcar
19958 (lambda (lang)
19959 (when (cdr lang) (symbol-name (car lang))))
19960 org-babel-load-languages)))))
19961 (files
19962 (append babel-files
19963 (and dir-org-contrib
19964 (directory-files dir-org-contrib t file-re))
19965 (directory-files dir-org t file-re)))
19966 (remove-re (concat (if (featurep 'xemacs)
19967 "org-colview" "org-colview-xemacs")
19968 "\\'")))
19969 (setq files (mapcar 'file-name-sans-extension files))
19970 (setq files (mapcar
19971 (lambda (x) (if (string-match remove-re x) nil x))
19972 files))
19973 (setq files (delq nil files))
19974 (mapc
19975 (lambda (f)
19976 (when (featurep (intern (file-name-nondirectory f)))
19977 (if (and (not uncompiled)
19978 (file-exists-p (concat f ".elc")))
19979 (load (concat f ".elc") nil nil 'nosuffix)
19980 (load (concat f ".el") nil nil 'nosuffix))))
19981 files)
19982 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19983 (org-version nil 'full 'message))
19985 ;;;###autoload
19986 (defun org-customize ()
19987 "Call the customize function with org as argument."
19988 (interactive)
19989 (org-load-modules-maybe)
19990 (org-require-autoloaded-modules)
19991 (customize-browse 'org))
19993 (defun org-create-customize-menu ()
19994 "Create a full customization menu for Org-mode, insert it into the menu."
19995 (interactive)
19996 (org-load-modules-maybe)
19997 (org-require-autoloaded-modules)
19998 (if (fboundp 'customize-menu-create)
19999 (progn
20000 (easy-menu-change
20001 '("Org") "Customize"
20002 `(["Browse Org group" org-customize t]
20003 "--"
20004 ,(customize-menu-create 'org)
20005 ["Set" Custom-set t]
20006 ["Save" Custom-save t]
20007 ["Reset to Current" Custom-reset-current t]
20008 ["Reset to Saved" Custom-reset-saved t]
20009 ["Reset to Standard Settings" Custom-reset-standard t]))
20010 (message "\"Org\"-menu now contains full customization menu"))
20011 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20013 ;;;; Miscellaneous stuff
20015 ;;; Generally useful functions
20017 (defun org-get-at-bol (property)
20018 "Get text property PROPERTY at beginning of line."
20019 (get-text-property (point-at-bol) property))
20021 (defun org-find-text-property-in-string (prop s)
20022 "Return the first non-nil value of property PROP in string S."
20023 (or (get-text-property 0 prop s)
20024 (get-text-property (or (next-single-property-change 0 prop s) 0)
20025 prop s)))
20027 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20028 "Display the given MESSAGE as a warning."
20029 (if (fboundp 'display-warning)
20030 (display-warning 'org message
20031 (if (featurep 'xemacs) 'warning :warning))
20032 (let ((buf (get-buffer-create "*Org warnings*")))
20033 (with-current-buffer buf
20034 (goto-char (point-max))
20035 (insert "Warning (Org): " message)
20036 (unless (bolp)
20037 (newline)))
20038 (display-buffer buf)
20039 (sit-for 0))))
20041 (defun org-eval (form)
20042 "Eval FORM and return result."
20043 (condition-case error
20044 (eval form)
20045 (error (format "%%![Error: %s]" error))))
20047 (defun org-in-clocktable-p ()
20048 "Check if the cursor is in a clocktable."
20049 (let ((pos (point)) start)
20050 (save-excursion
20051 (end-of-line 1)
20052 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20053 (setq start (match-beginning 0))
20054 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20055 (>= (match-end 0) pos)
20056 start))))
20058 (defun org-in-commented-line ()
20059 "Is point in a line starting with `#'?"
20060 (equal (char-after (point-at-bol)) ?#))
20062 (defun org-in-indented-comment-line ()
20063 "Is point in a line starting with `#' after some white space?"
20064 (save-excursion
20065 (save-match-data
20066 (goto-char (point-at-bol))
20067 (looking-at "[ \t]*#"))))
20069 (defun org-in-verbatim-emphasis ()
20070 (save-match-data
20071 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20073 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20074 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20075 (if (and marker (marker-buffer marker)
20076 (buffer-live-p (marker-buffer marker)))
20077 (progn
20078 (org-pop-to-buffer-same-window (marker-buffer marker))
20079 (if (or (> marker (point-max)) (< marker (point-min)))
20080 (widen))
20081 (goto-char marker)
20082 (org-show-context 'org-goto))
20083 (if bookmark
20084 (bookmark-jump bookmark)
20085 (error "Cannot find location"))))
20087 (defun org-quote-csv-field (s)
20088 "Quote field for inclusion in CSV material."
20089 (if (string-match "[\",]" s)
20090 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20093 (defun org-force-self-insert (N)
20094 "Needed to enforce self-insert under remapping."
20095 (interactive "p")
20096 (self-insert-command N))
20098 (defun org-string-width (s)
20099 "Compute width of string, ignoring invisible characters.
20100 This ignores character with invisibility property `org-link', and also
20101 characters with property `org-cwidth', because these will become invisible
20102 upon the next fontification round."
20103 (let (b l)
20104 (when (or (eq t buffer-invisibility-spec)
20105 (assq 'org-link buffer-invisibility-spec))
20106 (while (setq b (text-property-any 0 (length s)
20107 'invisible 'org-link s))
20108 (setq s (concat (substring s 0 b)
20109 (substring s (or (next-single-property-change
20110 b 'invisible s) (length s)))))))
20111 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20112 (setq s (concat (substring s 0 b)
20113 (substring s (or (next-single-property-change
20114 b 'org-cwidth s) (length s))))))
20115 (setq l (string-width s) b -1)
20116 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20117 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20120 (defun org-shorten-string (s maxlength)
20121 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20122 If the string is shorter or has length MAXLENGTH, just return the
20123 original string. If it is longer, the functions finds a space in the
20124 string, breaks this string off at that locations and adds three dots
20125 as ellipsis. Including the ellipsis, the string will not be longer
20126 than MAXLENGTH. If finding a good breaking point in the string does
20127 not work, the string is just chopped off in the middle of a word
20128 if necessary."
20129 (if (<= (length s) maxlength)
20131 (let* ((n (max (- maxlength 4) 1))
20132 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20133 (if (string-match re s)
20134 (concat (match-string 1 s) "...")
20135 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20137 (defun org-get-indentation (&optional line)
20138 "Get the indentation of the current line, interpreting tabs.
20139 When LINE is given, assume it represents a line and compute its indentation."
20140 (if line
20141 (if (string-match "^ *" (org-remove-tabs line))
20142 (match-end 0))
20143 (save-excursion
20144 (beginning-of-line 1)
20145 (skip-chars-forward " \t")
20146 (current-column))))
20148 (defun org-get-string-indentation (s)
20149 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20150 (let ((n -1) (i 0) (w tab-width) c)
20151 (catch 'exit
20152 (while (< (setq n (1+ n)) (length s))
20153 (setq c (aref s n))
20154 (cond ((= c ?\ ) (setq i (1+ i)))
20155 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20156 (t (throw 'exit t)))))
20159 (defun org-remove-tabs (s &optional width)
20160 "Replace tabulators in S with spaces.
20161 Assumes that s is a single line, starting in column 0."
20162 (setq width (or width tab-width))
20163 (while (string-match "\t" s)
20164 (setq s (replace-match
20165 (make-string
20166 (- (* width (/ (+ (match-beginning 0) width) width))
20167 (match-beginning 0)) ?\ )
20168 t t s)))
20171 (defun org-fix-indentation (line ind)
20172 "Fix indentation in LINE.
20173 IND is a cons cell with target and minimum indentation.
20174 If the current indentation in LINE is smaller than the minimum,
20175 leave it alone. If it is larger than ind, set it to the target."
20176 (let* ((l (org-remove-tabs line))
20177 (i (org-get-indentation l))
20178 (i1 (car ind)) (i2 (cdr ind)))
20179 (if (>= i i2) (setq l (substring line i2)))
20180 (if (> i1 0)
20181 (concat (make-string i1 ?\ ) l)
20182 l)))
20184 (defun org-remove-indentation (code &optional n)
20185 "Remove the maximum common indentation from the lines in CODE.
20186 N may optionally be the number of spaces to remove."
20187 (with-temp-buffer
20188 (insert code)
20189 (org-do-remove-indentation n)
20190 (buffer-string)))
20192 (defun org-do-remove-indentation (&optional n)
20193 "Remove the maximum common indentation from the buffer."
20194 (untabify (point-min) (point-max))
20195 (let ((min 10000) re)
20196 (if n
20197 (setq min n)
20198 (goto-char (point-min))
20199 (while (re-search-forward "^ *[^ \n]" nil t)
20200 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20201 (unless (or (= min 0) (= min 10000))
20202 (setq re (format "^ \\{%d\\}" min))
20203 (goto-char (point-min))
20204 (while (re-search-forward re nil t)
20205 (replace-match "")
20206 (end-of-line 1))
20207 min)))
20209 (defun org-fill-template (template alist)
20210 "Find each %key of ALIST in TEMPLATE and replace it."
20211 (let ((case-fold-search nil)
20212 entry key value)
20213 (setq alist (sort (copy-sequence alist)
20214 (lambda (a b) (< (length (car a)) (length (car b))))))
20215 (while (setq entry (pop alist))
20216 (setq template
20217 (replace-regexp-in-string
20218 (concat "%" (regexp-quote (car entry)))
20219 (or (cdr entry) "") template t t)))
20220 template))
20222 (defun org-base-buffer (buffer)
20223 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20224 (if (not buffer)
20225 buffer
20226 (or (buffer-base-buffer buffer)
20227 buffer)))
20229 (defun org-trim (s)
20230 "Remove whitespace at beginning and end of string."
20231 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20232 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20235 (defun org-wrap (string &optional width lines)
20236 "Wrap string to either a number of lines, or a width in characters.
20237 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20238 that costs. If there is a word longer than WIDTH, the text is actually
20239 wrapped to the length of that word.
20240 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20241 many lines, whatever width that takes.
20242 The return value is a list of lines, without newlines at the end."
20243 (let* ((words (org-split-string string "[ \t\n]+"))
20244 (maxword (apply 'max (mapcar 'org-string-width words)))
20245 w ll)
20246 (cond (width
20247 (org-do-wrap words (max maxword width)))
20248 (lines
20249 (setq w maxword)
20250 (setq ll (org-do-wrap words maxword))
20251 (if (<= (length ll) lines)
20253 (setq ll words)
20254 (while (> (length ll) lines)
20255 (setq w (1+ w))
20256 (setq ll (org-do-wrap words w)))
20257 ll))
20258 (t (error "Cannot wrap this")))))
20260 (defun org-do-wrap (words width)
20261 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20262 (let (lines line)
20263 (while words
20264 (setq line (pop words))
20265 (while (and words (< (+ (length line) (length (car words))) width))
20266 (setq line (concat line " " (pop words))))
20267 (setq lines (push line lines)))
20268 (nreverse lines)))
20270 (defun org-split-string (string &optional separators)
20271 "Splits STRING into substrings at SEPARATORS.
20272 No empty strings are returned if there are matches at the beginning
20273 and end of string."
20274 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20275 (start 0)
20276 notfirst
20277 (list nil))
20278 (while (and (string-match rexp string
20279 (if (and notfirst
20280 (= start (match-beginning 0))
20281 (< start (length string)))
20282 (1+ start) start))
20283 (< (match-beginning 0) (length string)))
20284 (setq notfirst t)
20285 (or (eq (match-beginning 0) 0)
20286 (and (eq (match-beginning 0) (match-end 0))
20287 (eq (match-beginning 0) start))
20288 (setq list
20289 (cons (substring string start (match-beginning 0))
20290 list)))
20291 (setq start (match-end 0)))
20292 (or (eq start (length string))
20293 (setq list
20294 (cons (substring string start)
20295 list)))
20296 (nreverse list)))
20298 (defun org-quote-vert (s)
20299 "Replace \"|\" with \"\\vert\"."
20300 (while (string-match "|" s)
20301 (setq s (replace-match "\\vert" t t s)))
20304 (defun org-uuidgen-p (s)
20305 "Is S an ID created by UUIDGEN?"
20306 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20308 (defun org-in-src-block-p (&optional inside)
20309 "Whether point is in a code source block.
20310 When INSIDE is non-nil, don't consider we are within a src block
20311 when point is at #+BEGIN_SRC or #+END_SRC."
20312 (let ((case-fold-search t) ov)
20313 (or (and (setq ov (overlays-at (point)))
20314 (memq 'org-block-background
20315 (overlay-properties (car ov))))
20316 (and (not inside)
20317 (save-match-data
20318 (save-excursion
20319 (beginning-of-line)
20320 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20322 (defun org-context ()
20323 "Return a list of contexts of the current cursor position.
20324 If several contexts apply, all are returned.
20325 Each context entry is a list with a symbol naming the context, and
20326 two positions indicating start and end of the context. Possible
20327 contexts are:
20329 :headline anywhere in a headline
20330 :headline-stars on the leading stars in a headline
20331 :todo-keyword on a TODO keyword (including DONE) in a headline
20332 :tags on the TAGS in a headline
20333 :priority on the priority cookie in a headline
20334 :item on the first line of a plain list item
20335 :item-bullet on the bullet/number of a plain list item
20336 :checkbox on the checkbox in a plain list item
20337 :table in an org-mode table
20338 :table-special on a special filed in a table
20339 :table-table in a table.el table
20340 :clocktable in a clocktable
20341 :src-block in a source block
20342 :link on a hyperlink
20343 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20344 :target on a <<target>>
20345 :radio-target on a <<<radio-target>>>
20346 :latex-fragment on a LaTeX fragment
20347 :latex-preview on a LaTeX fragment with overlaid preview image
20349 This function expects the position to be visible because it uses font-lock
20350 faces as a help to recognize the following contexts: :table-special, :link,
20351 and :keyword."
20352 (let* ((f (get-text-property (point) 'face))
20353 (faces (if (listp f) f (list f)))
20354 (case-fold-search t)
20355 (p (point)) clist o)
20356 ;; First the large context
20357 (cond
20358 ((org-at-heading-p t)
20359 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20360 (when (progn
20361 (beginning-of-line 1)
20362 (looking-at org-todo-line-tags-regexp))
20363 (push (org-point-in-group p 1 :headline-stars) clist)
20364 (push (org-point-in-group p 2 :todo-keyword) clist)
20365 (push (org-point-in-group p 4 :tags) clist))
20366 (goto-char p)
20367 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20368 (if (looking-at "\\[#[A-Z0-9]\\]")
20369 (push (org-point-in-group p 0 :priority) clist)))
20371 ((org-at-item-p)
20372 (push (org-point-in-group p 2 :item-bullet) clist)
20373 (push (list :item (point-at-bol)
20374 (save-excursion (org-end-of-item) (point)))
20375 clist)
20376 (and (org-at-item-checkbox-p)
20377 (push (org-point-in-group p 0 :checkbox) clist)))
20379 ((org-at-table-p)
20380 (push (list :table (org-table-begin) (org-table-end)) clist)
20381 (if (memq 'org-formula faces)
20382 (push (list :table-special
20383 (previous-single-property-change p 'face)
20384 (next-single-property-change p 'face)) clist)))
20385 ((org-at-table-p 'any)
20386 (push (list :table-table) clist)))
20387 (goto-char p)
20389 (let ((case-fold-search t))
20390 ;; New the "medium" contexts: clocktables, source blocks
20391 (cond ((org-in-clocktable-p)
20392 (push (list :clocktable
20393 (and (or (looking-at "#\\+BEGIN: clocktable")
20394 (search-backward "#+BEGIN: clocktable" nil t))
20395 (match-beginning 0))
20396 (and (re-search-forward "#\\+END:?" nil t)
20397 (match-end 0))) clist))
20398 ((org-in-src-block-p)
20399 (push (list :src-block
20400 (and (or (looking-at "#\\+BEGIN_SRC")
20401 (search-backward "#+BEGIN_SRC" nil t))
20402 (match-beginning 0))
20403 (and (search-forward "#+END_SRC" nil t)
20404 (match-beginning 0))) clist))))
20405 (goto-char p)
20407 ;; Now the small context
20408 (cond
20409 ((org-at-timestamp-p)
20410 (push (org-point-in-group p 0 :timestamp) clist))
20411 ((memq 'org-link faces)
20412 (push (list :link
20413 (previous-single-property-change p 'face)
20414 (next-single-property-change p 'face)) clist))
20415 ((memq 'org-special-keyword faces)
20416 (push (list :keyword
20417 (previous-single-property-change p 'face)
20418 (next-single-property-change p 'face)) clist))
20419 ((org-at-target-p)
20420 (push (org-point-in-group p 0 :target) clist)
20421 (goto-char (1- (match-beginning 0)))
20422 (if (looking-at org-radio-target-regexp)
20423 (push (org-point-in-group p 0 :radio-target) clist))
20424 (goto-char p))
20425 ((setq o (car (delq nil
20426 (mapcar
20427 (lambda (x)
20428 (if (memq x org-latex-fragment-image-overlays) x))
20429 (overlays-at (point))))))
20430 (push (list :latex-fragment
20431 (overlay-start o) (overlay-end o)) clist)
20432 (push (list :latex-preview
20433 (overlay-start o) (overlay-end o)) clist))
20434 ((org-inside-LaTeX-fragment-p)
20435 ;; FIXME: positions wrong.
20436 (push (list :latex-fragment (point) (point)) clist)))
20438 (setq clist (nreverse (delq nil clist)))
20439 clist))
20441 ;; FIXME: Compare with at-regexp-p Do we need both?
20442 (defun org-in-regexp (re &optional nlines visually)
20443 "Check if point is inside a match of regexp.
20444 Normally only the current line is checked, but you can include NLINES extra
20445 lines both before and after point into the search.
20446 If VISUALLY is set, require that the cursor is not after the match but
20447 really on, so that the block visually is on the match."
20448 (catch 'exit
20449 (let ((pos (point))
20450 (eol (point-at-eol (+ 1 (or nlines 0))))
20451 (inc (if visually 1 0)))
20452 (save-excursion
20453 (beginning-of-line (- 1 (or nlines 0)))
20454 (while (re-search-forward re eol t)
20455 (if (and (<= (match-beginning 0) pos)
20456 (>= (+ inc (match-end 0)) pos))
20457 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20459 (defun org-at-regexp-p (regexp)
20460 "Is point inside a match of REGEXP in the current line?"
20461 (catch 'exit
20462 (save-excursion
20463 (let ((pos (point)) (end (point-at-eol)))
20464 (beginning-of-line 1)
20465 (while (re-search-forward regexp end t)
20466 (if (and (<= (match-beginning 0) pos)
20467 (>= (match-end 0) pos))
20468 (throw 'exit t)))
20469 nil))))
20471 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20472 "Non-nil when point is between matches of START-RE and END-RE.
20474 Also return a non-nil value when point is on one of the matches.
20476 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20477 buffer positions. Default values are the positions of headlines
20478 surrounding the point.
20480 The functions returns a cons cell whose car (resp. cdr) is the
20481 position before START-RE (resp. after END-RE)."
20482 (save-match-data
20483 (let ((pos (point))
20484 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20485 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20486 beg end)
20487 (save-excursion
20488 ;; Point is on a block when on START-RE or if START-RE can be
20489 ;; found before it...
20490 (and (or (org-at-regexp-p start-re)
20491 (re-search-backward start-re limit-up t))
20492 (setq beg (match-beginning 0))
20493 ;; ... and END-RE after it...
20494 (goto-char (match-end 0))
20495 (re-search-forward end-re limit-down t)
20496 (> (setq end (match-end 0)) pos)
20497 ;; ... without another START-RE in-between.
20498 (goto-char (match-beginning 0))
20499 (not (re-search-backward start-re (1+ beg) t))
20500 ;; Return value.
20501 (cons beg end))))))
20503 (defun org-in-block-p (names)
20504 "Non-nil when point belongs to a block whose name belongs to NAMES.
20506 NAMES is a list of strings containing names of blocks.
20508 Return first block name matched, or nil. Beware that in case of
20509 nested blocks, the returned name may not belong to the closest
20510 block from point."
20511 (save-match-data
20512 (catch 'exit
20513 (let ((case-fold-search t)
20514 (lim-up (save-excursion (outline-previous-heading)))
20515 (lim-down (save-excursion (outline-next-heading))))
20516 (mapc (lambda (name)
20517 (let ((n (regexp-quote name)))
20518 (when (org-between-regexps-p
20519 (concat "^[ \t]*#\\+begin_" n)
20520 (concat "^[ \t]*#\\+end_" n)
20521 lim-up lim-down)
20522 (throw 'exit n))))
20523 names))
20524 nil)))
20526 (defun org-occur-in-agenda-files (regexp &optional nlines)
20527 "Call `multi-occur' with buffers for all agenda files."
20528 (interactive "sOrg-files matching: \np")
20529 (let* ((files (org-agenda-files))
20530 (tnames (mapcar 'file-truename files))
20531 (extra org-agenda-text-search-extra-files)
20533 (when (eq (car extra) 'agenda-archives)
20534 (setq extra (cdr extra))
20535 (setq files (org-add-archive-files files)))
20536 (while (setq f (pop extra))
20537 (unless (member (file-truename f) tnames)
20538 (add-to-list 'files f 'append)
20539 (add-to-list 'tnames (file-truename f) 'append)))
20540 (multi-occur
20541 (mapcar (lambda (x)
20542 (with-current-buffer
20543 (or (get-file-buffer x) (find-file-noselect x))
20544 (widen)
20545 (current-buffer)))
20546 files)
20547 regexp)))
20549 (if (boundp 'occur-mode-find-occurrence-hook)
20550 ;; Emacs 23
20551 (add-hook 'occur-mode-find-occurrence-hook
20552 (lambda ()
20553 (when (derived-mode-p 'org-mode)
20554 (org-reveal))))
20555 ;; Emacs 22
20556 (defadvice occur-mode-goto-occurrence
20557 (after org-occur-reveal activate)
20558 (and (derived-mode-p 'org-mode) (org-reveal)))
20559 (defadvice occur-mode-goto-occurrence-other-window
20560 (after org-occur-reveal activate)
20561 (and (derived-mode-p 'org-mode) (org-reveal)))
20562 (defadvice occur-mode-display-occurrence
20563 (after org-occur-reveal activate)
20564 (when (derived-mode-p 'org-mode)
20565 (let ((pos (occur-mode-find-occurrence)))
20566 (with-current-buffer (marker-buffer pos)
20567 (save-excursion
20568 (goto-char pos)
20569 (org-reveal)))))))
20571 (defun org-occur-link-in-agenda-files ()
20572 "Create a link and search for it in the agendas.
20573 The link is not stored in `org-stored-links', it is just created
20574 for the search purpose."
20575 (interactive)
20576 (let ((link (condition-case nil
20577 (org-store-link nil)
20578 (error "Unable to create a link to here"))))
20579 (org-occur-in-agenda-files (regexp-quote link))))
20581 (defun org-uniquify (list)
20582 "Remove duplicate elements from LIST."
20583 (let (res)
20584 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20585 res))
20587 (defun org-delete-all (elts list)
20588 "Remove all elements in ELTS from LIST."
20589 (while elts
20590 (setq list (delete (pop elts) list)))
20591 list)
20593 (defun org-count (cl-item cl-seq)
20594 "Count the number of occurrences of ITEM in SEQ.
20595 Taken from `count' in cl-seq.el with all keyword arguments removed."
20596 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20597 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20598 (while (< cl-start cl-end)
20599 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20600 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20601 (setq cl-start (1+ cl-start)))
20602 cl-count))
20604 (defun org-remove-if (predicate seq)
20605 "Remove everything from SEQ that fulfills PREDICATE."
20606 (let (res e)
20607 (while seq
20608 (setq e (pop seq))
20609 (if (not (funcall predicate e)) (push e res)))
20610 (nreverse res)))
20612 (defun org-remove-if-not (predicate seq)
20613 "Remove everything from SEQ that does not fulfill PREDICATE."
20614 (let (res e)
20615 (while seq
20616 (setq e (pop seq))
20617 (if (funcall predicate e) (push e res)))
20618 (nreverse res)))
20620 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20621 "Reduce two-argument FUNCTION across SEQ.
20622 Taken from `reduce' in cl-seq.el with all keyword arguments but
20623 \":initial-value\" removed."
20624 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20625 (cadr (memq :initial-value cl-keys)))
20626 (cl-seq (pop cl-seq))
20627 (t (funcall cl-func)))))
20628 (while cl-seq
20629 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20630 cl-accum))
20632 (defun org-back-over-empty-lines ()
20633 "Move backwards over whitespace, to the beginning of the first empty line.
20634 Returns the number of empty lines passed."
20635 (let ((pos (point)))
20636 (if (cdr (assoc 'heading org-blank-before-new-entry))
20637 (skip-chars-backward " \t\n\r")
20638 (unless (eobp)
20639 (forward-line -1)))
20640 (beginning-of-line 2)
20641 (goto-char (min (point) pos))
20642 (count-lines (point) pos)))
20644 (defun org-skip-whitespace ()
20645 (skip-chars-forward " \t\n\r"))
20647 (defun org-point-in-group (point group &optional context)
20648 "Check if POINT is in match-group GROUP.
20649 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20650 match. If the match group does not exist or point is not inside it,
20651 return nil."
20652 (and (match-beginning group)
20653 (>= point (match-beginning group))
20654 (<= point (match-end group))
20655 (if context
20656 (list context (match-beginning group) (match-end group))
20657 t)))
20659 (defun org-switch-to-buffer-other-window (&rest args)
20660 "Switch to buffer in a second window on the current frame.
20661 In particular, do not allow pop-up frames.
20662 Returns the newly created buffer."
20663 (org-no-popups
20664 (apply 'switch-to-buffer-other-window args)))
20666 (defun org-combine-plists (&rest plists)
20667 "Create a single property list from all plists in PLISTS.
20668 The process starts by copying the first list, and then setting properties
20669 from the other lists. Settings in the last list are the most significant
20670 ones and overrule settings in the other lists."
20671 (let ((rtn (copy-sequence (pop plists)))
20672 p v ls)
20673 (while plists
20674 (setq ls (pop plists))
20675 (while ls
20676 (setq p (pop ls) v (pop ls))
20677 (setq rtn (plist-put rtn p v))))
20678 rtn))
20680 (defun org-replace-escapes (string table)
20681 "Replace %-escapes in STRING with values in TABLE.
20682 TABLE is an association list with keys like \"%a\" and string values.
20683 The sequences in STRING may contain normal field width and padding information,
20684 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20685 so values can contain further %-escapes if they are define later in TABLE."
20686 (let ((tbl (copy-alist table))
20687 (case-fold-search nil)
20688 (pchg 0)
20689 e re rpl)
20690 (while (setq e (pop tbl))
20691 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20692 (when (and (cdr e) (string-match re (cdr e)))
20693 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20694 (safe "SREF"))
20695 (add-text-properties 0 3 (list 'sref sref) safe)
20696 (setcdr e (replace-match safe t t (cdr e)))))
20697 (while (string-match re string)
20698 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20699 (cdr e)))
20700 (setq string (replace-match rpl t t string))))
20701 (while (setq pchg (next-property-change pchg string))
20702 (let ((sref (get-text-property pchg 'sref string)))
20703 (when (and sref (string-match "SREF" string pchg))
20704 (setq string (replace-match sref t t string)))))
20705 string))
20707 (defun org-sublist (list start end)
20708 "Return a section of LIST, from START to END.
20709 Counting starts at 1."
20710 (let (rtn (c start))
20711 (setq list (nthcdr (1- start) list))
20712 (while (and list (<= c end))
20713 (push (pop list) rtn)
20714 (setq c (1+ c)))
20715 (nreverse rtn)))
20717 (defun org-find-base-buffer-visiting (file)
20718 "Like `find-buffer-visiting' but always return the base buffer and
20719 not an indirect buffer."
20720 (let ((buf (or (get-file-buffer file)
20721 (find-buffer-visiting file))))
20722 (if buf
20723 (or (buffer-base-buffer buf) buf)
20724 nil)))
20726 (defun org-image-file-name-regexp (&optional extensions)
20727 "Return regexp matching the file names of images.
20728 If EXTENSIONS is given, only match these."
20729 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20730 (image-file-name-regexp)
20731 (let ((image-file-name-extensions
20732 (or extensions
20733 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20734 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20735 (concat "\\."
20736 (regexp-opt (nconc (mapcar 'upcase
20737 image-file-name-extensions)
20738 image-file-name-extensions)
20740 "\\'"))))
20742 (defun org-file-image-p (file &optional extensions)
20743 "Return non-nil if FILE is an image."
20744 (save-match-data
20745 (string-match (org-image-file-name-regexp extensions) file)))
20747 (defun org-get-cursor-date ()
20748 "Return the date at cursor in as a time.
20749 This works in the calendar and in the agenda, anywhere else it just
20750 returns the current time."
20751 (let (date day defd)
20752 (cond
20753 ((eq major-mode 'calendar-mode)
20754 (setq date (calendar-cursor-to-date)
20755 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20756 ((eq major-mode 'org-agenda-mode)
20757 (setq day (get-text-property (point) 'day))
20758 (if day
20759 (setq date (calendar-gregorian-from-absolute day)
20760 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20761 (nth 2 date))))))
20762 (or defd (current-time))))
20764 (defun org-mark-subtree (&optional up)
20765 "Mark the current subtree.
20766 This puts point at the start of the current subtree, and mark at
20767 the end. If a numeric prefix UP is given, move up into the
20768 hierarchy of headlines by UP levels before marking the subtree."
20769 (interactive "P")
20770 (org-with-limited-levels
20771 (cond ((org-at-heading-p) (beginning-of-line))
20772 ((org-before-first-heading-p) (error "Not in a subtree"))
20773 (t (outline-previous-visible-heading 1))))
20774 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20775 (if (org-called-interactively-p 'any)
20776 (call-interactively 'org-mark-element)
20777 (org-mark-element)))
20779 ;;; Indentation
20781 (defun org-indent-line ()
20782 "Indent line depending on context."
20783 (interactive)
20784 (let* ((pos (point))
20785 (itemp (org-at-item-p))
20786 (case-fold-search t)
20787 (org-drawer-regexp (or org-drawer-regexp "\000"))
20788 (inline-task-p (and (featurep 'org-inlinetask)
20789 (org-inlinetask-in-task-p)))
20790 (inline-re (and inline-task-p
20791 (org-inlinetask-outline-regexp)))
20792 column)
20793 (if (and orgstruct-is-++ (eq pos (point)))
20794 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20795 (indent-according-to-mode))
20796 (beginning-of-line 1)
20797 (cond
20798 ;; Headings
20799 ((looking-at org-outline-regexp) (setq column 0))
20800 ;; Included files
20801 ((looking-at "#\\+include:") (setq column 0))
20802 ;; Footnote definition
20803 ((looking-at org-footnote-definition-re) (setq column 0))
20804 ;; Literal examples
20805 ((looking-at "[ \t]*:\\( \\|$\\)")
20806 (setq column (org-get-indentation))) ; do nothing
20807 ;; Lists
20808 ((ignore-errors (goto-char (org-in-item-p)))
20809 (setq column (if itemp
20810 (org-get-indentation)
20811 (org-list-item-body-column (point))))
20812 (goto-char pos))
20813 ;; Drawers
20814 ((and (looking-at "[ \t]*:END:")
20815 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20816 (save-excursion
20817 (goto-char (1- (match-beginning 1)))
20818 (setq column (current-column))))
20819 ;; Special blocks
20820 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20821 (save-excursion
20822 (re-search-backward
20823 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20824 (setq column (org-get-indentation (match-string 0))))
20825 ((and (not (looking-at "[ \t]*#\\+begin_"))
20826 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20827 (save-excursion
20828 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20829 (setq column
20830 (cond ((equal (downcase (match-string 1)) "src")
20831 ;; src blocks: let `org-edit-src-exit' handle them
20832 (org-get-indentation))
20833 ((equal (downcase (match-string 1)) "example")
20834 (max (org-get-indentation)
20835 (org-get-indentation (match-string 0))))
20837 (org-get-indentation (match-string 0))))))
20838 ;; This line has nothing special, look at the previous relevant
20839 ;; line to compute indentation
20841 (beginning-of-line 0)
20842 (while (and (not (bobp))
20843 (not (looking-at org-table-line-regexp))
20844 (not (looking-at org-drawer-regexp))
20845 ;; When point started in an inline task, do not move
20846 ;; above task starting line.
20847 (not (and inline-task-p (looking-at inline-re)))
20848 ;; Skip drawers, blocks, empty lines, verbatim,
20849 ;; comments, tables, footnotes definitions, lists,
20850 ;; inline tasks.
20851 (or (and (looking-at "[ \t]*:END:")
20852 (re-search-backward org-drawer-regexp nil t))
20853 (and (looking-at "[ \t]*#\\+end_")
20854 (re-search-backward "[ \t]*#\\+begin_"nil t))
20855 (looking-at "[ \t]*[\n:#|]")
20856 (looking-at org-footnote-definition-re)
20857 (and (ignore-errors (goto-char (org-in-item-p)))
20858 (goto-char
20859 (org-list-get-top-point (org-list-struct))))
20860 (and (not inline-task-p)
20861 (featurep 'org-inlinetask)
20862 (org-inlinetask-in-task-p)
20863 (or (org-inlinetask-goto-beginning) t))))
20864 (beginning-of-line 0))
20865 (cond
20866 ;; There was an heading above.
20867 ((looking-at "\\*+[ \t]+")
20868 (if (not org-adapt-indentation)
20869 (setq column 0)
20870 (goto-char (match-end 0))
20871 (setq column (current-column))))
20872 ;; A drawer had started and is unfinished
20873 ((looking-at org-drawer-regexp)
20874 (goto-char (1- (match-beginning 1)))
20875 (setq column (current-column)))
20876 ;; Else, nothing noticeable found: get indentation and go on.
20877 (t (setq column (org-get-indentation))))))
20878 ;; Now apply indentation and move cursor accordingly
20879 (goto-char pos)
20880 (if (<= (current-column) (current-indentation))
20881 (org-indent-line-to column)
20882 (save-excursion (org-indent-line-to column)))
20883 ;; Special polishing for properties, see `org-property-format'
20884 (setq column (current-column))
20885 (beginning-of-line 1)
20886 (if (looking-at
20887 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20888 (replace-match (concat (match-string 1)
20889 (format org-property-format
20890 (match-string 2) (match-string 3)))
20891 t t))
20892 (org-move-to-column column))))
20894 (defun org-indent-drawer ()
20895 "Indent the drawer at point."
20896 (interactive)
20897 (let ((p (point))
20898 (e (and (save-excursion (re-search-forward ":END:" nil t))
20899 (match-end 0)))
20900 (folded
20901 (save-excursion
20902 (end-of-line)
20903 (when (overlays-at (point))
20904 (member 'invisible (overlay-properties
20905 (car (overlays-at (point)))))))))
20906 (when folded (org-cycle))
20907 (indent-for-tab-command)
20908 (while (and (move-beginning-of-line 2) (< (point) e))
20909 (indent-for-tab-command))
20910 (goto-char p)
20911 (when folded (org-cycle)))
20912 (message "Drawer at point indented"))
20914 (defun org-indent-block ()
20915 "Indent the block at point."
20916 (interactive)
20917 (let ((p (point))
20918 (case-fold-search t)
20919 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20920 (match-end 0)))
20921 (folded
20922 (save-excursion
20923 (end-of-line)
20924 (when (overlays-at (point))
20925 (member 'invisible (overlay-properties
20926 (car (overlays-at (point)))))))))
20927 (when folded (org-cycle))
20928 (indent-for-tab-command)
20929 (while (and (move-beginning-of-line 2) (< (point) e))
20930 (indent-for-tab-command))
20931 (goto-char p)
20932 (when folded (org-cycle)))
20933 (message "Block at point indented"))
20935 (defun org-indent-region (start end)
20936 "Indent region."
20937 (interactive "r")
20938 (save-excursion
20939 (let ((line-end (org-current-line end)))
20940 (goto-char start)
20941 (while (< (org-current-line) line-end)
20942 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20943 (t (call-interactively 'org-indent-line)))
20944 (move-beginning-of-line 2)))))
20947 ;;; Filling
20949 ;; We use our own fill-paragraph and auto-fill functions.
20951 ;; `org-fill-paragraph' relies on adaptive filling and context
20952 ;; checking. Appropriate `fill-prefix' is computed with
20953 ;; `org-adaptive-fill-function'.
20955 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20956 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20957 ;; `org-adaptive-fill-function' value. Internally,
20958 ;; `org-comment-line-break-function' breaks the line.
20960 ;; `org-setup-filling' installs filling and auto-filling related
20961 ;; variables during `org-mode' initialization.
20963 (defun org-setup-filling ()
20964 (interactive)
20965 ;; Prevent auto-fill from inserting unwanted new items.
20966 (when (boundp 'fill-nobreak-predicate)
20967 (org-set-local
20968 'fill-nobreak-predicate
20969 (org-uniquify
20970 (append fill-nobreak-predicate
20971 '(org-fill-paragraph-separate-nobreak-p
20972 org-fill-line-break-nobreak-p)))))
20973 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20974 (org-set-local 'auto-fill-inhibit-regexp nil)
20975 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20976 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20977 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20979 (defvar org-element-paragraph-separate) ; org-element.el
20980 (defun org-fill-paragraph-separate-nobreak-p ()
20981 "Non-nil when a line break at point would insert a new item."
20982 (looking-at (substring org-element-paragraph-separate 1)))
20984 (defun org-fill-line-break-nobreak-p ()
20985 "Non-nil when a line break at point would create an Org line break."
20986 (save-excursion
20987 (skip-chars-backward "[ \t]")
20988 (skip-chars-backward "\\\\")
20989 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20991 (declare-function message-in-body-p "message" ())
20992 (defvar org-element--affiliated-re) ; From org-element.el
20993 (defvar orgtbl-line-start-regexp) ; From org-table.el
20994 (defun org-adaptive-fill-function ()
20995 "Compute a fill prefix for the current line.
20996 Return fill prefix, as a string, or nil if current line isn't
20997 meant to be filled."
20998 (let (prefix)
20999 (catch 'exit
21000 (when (derived-mode-p 'message-mode)
21001 (save-excursion
21002 (beginning-of-line)
21003 (cond ((or (not (message-in-body-p))
21004 (looking-at orgtbl-line-start-regexp))
21005 (throw 'exit nil))
21006 ((looking-at message-cite-prefix-regexp)
21007 (throw 'exit (match-string-no-properties 0)))
21008 ((looking-at org-outline-regexp)
21009 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21010 (org-with-wide-buffer
21011 (let* ((p (line-beginning-position))
21012 (element (save-excursion (beginning-of-line) (org-element-at-point)))
21013 (type (org-element-type element))
21014 (post-affiliated
21015 (save-excursion
21016 (goto-char (org-element-property :begin element))
21017 (while (looking-at org-element--affiliated-re) (forward-line))
21018 (point))))
21019 (unless (< p post-affiliated)
21020 (case type
21021 (comment (looking-at "[ \t]*# ?") (match-string 0))
21022 (footnote-definition "")
21023 ((item plain-list)
21024 (make-string (org-list-item-body-column post-affiliated) ? ))
21025 (paragraph
21026 ;; Fill prefix is usually the same as the current line,
21027 ;; except if the paragraph is at the beginning of an item.
21028 (let ((parent (org-element-property :parent element)))
21029 (cond ((eq (org-element-type parent) 'item)
21030 (make-string (org-list-item-body-column
21031 (org-element-property :begin parent))
21032 ? ))
21033 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21034 (match-string 0))
21035 (t ""))))
21036 (comment-block
21037 ;; Only fill contents if P is within block boundaries.
21038 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21039 (forward-line)
21040 (point)))
21041 (cend (save-excursion
21042 (goto-char (org-element-property :end element))
21043 (skip-chars-backward " \r\t\n")
21044 (line-beginning-position))))
21045 (when (and (>= p cbeg) (< p cend))
21046 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21047 (match-string 0)
21048 "")))))))))))
21050 (declare-function message-goto-body "message" ())
21051 (defvar message-cite-prefix-regexp) ; From message.el
21052 (defvar org-element-all-objects) ; From org-element.el
21053 (defun org-fill-paragraph (&optional justify)
21054 "Fill element at point, when applicable.
21056 This function only applies to comment blocks, comments, example
21057 blocks and paragraphs. Also, as a special case, re-align table
21058 when point is at one.
21060 If JUSTIFY is non-nil (interactively, with prefix argument),
21061 justify as well. If `sentence-end-double-space' is non-nil, then
21062 period followed by one space does not end a sentence, so don't
21063 break a line there. The variable `fill-column' controls the
21064 width for filling.
21066 For convenience, when point is at a plain list, an item or
21067 a footnote definition, try to fill the first paragraph within."
21068 (interactive)
21069 (if (and (derived-mode-p 'message-mode)
21070 (or (not (message-in-body-p))
21071 (save-excursion (move-beginning-of-line 1)
21072 (looking-at message-cite-prefix-regexp))))
21073 ;; First ensure filling is correct in message-mode.
21074 (let ((fill-paragraph-function
21075 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21076 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21077 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21078 (paragraph-separate
21079 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21080 (fill-paragraph nil))
21081 (save-excursion
21082 ;; Move to end of line in order to get the first paragraph
21083 ;; within a plain list or a footnote definition.
21084 (end-of-line)
21085 (let ((element (org-element-at-point)))
21086 ;; First check if point is in a blank line at the beginning of
21087 ;; the buffer. In that case, ignore filling.
21088 (if (< (point) (org-element-property :begin element)) t
21089 (case (org-element-type element)
21090 ;; Use major mode filling function is src blocks.
21091 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21092 ;; Align Org tables, leave table.el tables as-is.
21093 (table-row (org-table-align) t)
21094 (table
21095 (when (eq (org-element-property :type element) 'org)
21096 (org-table-align))
21098 (paragraph
21099 ;; Paragraphs may contain `line-break' type objects.
21100 (let ((beg (max (point-min)
21101 (org-element-property :contents-begin element)))
21102 (end (min (point-max)
21103 (org-element-property :contents-end element))))
21104 ;; Do nothing if point is at an affiliated keyword.
21105 (if (< (point) beg) t
21106 (when (derived-mode-p 'message-mode)
21107 ;; In `message-mode', do not fill following
21108 ;; citation in current paragraph nor text before
21109 ;; message body.
21110 (let ((body-start (save-excursion (message-goto-body))))
21111 (when body-start (setq beg (max body-start beg))))
21112 (when (save-excursion
21113 (re-search-forward
21114 (concat "^" message-cite-prefix-regexp) end t))
21115 (setq end (match-beginning 0))))
21116 ;; Fill paragraph, taking line breaks into
21117 ;; consideration. For that, slice the paragraph
21118 ;; using line breaks as separators, and fill the
21119 ;; parts in reverse order to avoid messing with
21120 ;; markers.
21121 (save-excursion
21122 (goto-char end)
21123 (mapc
21124 (lambda (pos)
21125 (fill-region-as-paragraph pos (point) justify)
21126 (goto-char pos))
21127 ;; Find the list of ending positions for line
21128 ;; breaks in the current paragraph. Add paragraph
21129 ;; beginning to include first slice.
21130 (nreverse
21131 (cons
21133 (org-element-map
21134 (org-element--parse-objects
21135 beg end nil org-element-all-objects)
21136 'line-break
21137 (lambda (lb) (org-element-property :end lb)))))))
21138 t)))
21139 ;; Contents of `comment-block' type elements should be
21140 ;; filled as plain text, but only if point is within block
21141 ;; markers.
21142 (comment-block
21143 (let* ((case-fold-search t)
21144 (beg (save-excursion
21145 (goto-char (org-element-property :begin element))
21146 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21147 (forward-line)
21148 (point)))
21149 (end (save-excursion
21150 (goto-char (org-element-property :end element))
21151 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21152 (line-beginning-position))))
21153 (when (and (>= (point) beg) (< (point) end))
21154 (fill-region-as-paragraph
21155 (save-excursion
21156 (end-of-line)
21157 (re-search-backward "^[ \t]*$" beg 'move)
21158 (line-beginning-position))
21159 (save-excursion
21160 (beginning-of-line)
21161 (re-search-forward "^[ \t]*$" end 'move)
21162 (line-beginning-position))
21163 justify)))
21165 ;; Fill comments.
21166 (comment (fill-comment-paragraph justify))
21167 ;; Ignore every other element.
21168 (otherwise t)))))))
21170 (defun org-auto-fill-function ()
21171 "Auto-fill function."
21172 ;; Check if auto-filling is meaningful.
21173 (let ((fc (current-fill-column)))
21174 (when (and fc (> (current-column) fc))
21175 (let* ((fill-prefix (org-adaptive-fill-function))
21176 ;; Enforce empty fill prefix, if required. Otherwise, it
21177 ;; will be computed again.
21178 (adaptive-fill-mode (not (equal fill-prefix ""))))
21179 (when fill-prefix (do-auto-fill))))))
21181 (defun org-comment-line-break-function (&optional soft)
21182 "Break line at point and indent, continuing comment if within one.
21183 The inserted newline is marked hard if variable
21184 `use-hard-newlines' is true, unless optional argument SOFT is
21185 non-nil."
21186 (if soft (insert-and-inherit ?\n) (newline 1))
21187 (save-excursion (forward-char -1) (delete-horizontal-space))
21188 (delete-horizontal-space)
21189 (indent-to-left-margin)
21190 (insert-before-markers-and-inherit fill-prefix))
21193 ;;; Comments
21195 ;; Org comments syntax is quite complex. It requires the entire line
21196 ;; to be just a comment. Also, even with the right syntax at the
21197 ;; beginning of line, some some elements (i.e. verse-block or
21198 ;; example-block) don't accept comments. Usual Emacs comment commands
21199 ;; cannot cope with those requirements. Therefore, Org replaces them.
21201 ;; Org still relies on `comment-dwim', but cannot trust
21202 ;; `comment-only-p'. So, `comment-region-function' and
21203 ;; `uncomment-region-function' both point
21204 ;; to`org-comment-or-uncomment-region'. Eventually,
21205 ;; `org-insert-comment' takes care of insertion of comments at the
21206 ;; beginning of line.
21208 ;; `org-setup-comments-handling' install comments related variables
21209 ;; during `org-mode' initialization.
21211 (defun org-setup-comments-handling ()
21212 (interactive)
21213 (org-set-local 'comment-use-syntax nil)
21214 (org-set-local 'comment-start "# ")
21215 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21216 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21217 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21218 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21220 (defun org-insert-comment ()
21221 "Insert an empty comment above current line.
21222 If the line is empty, insert comment at its beginning."
21223 (beginning-of-line)
21224 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21225 (org-indent-line)
21226 (insert "# "))
21228 (defvar comment-empty-lines) ; From newcomment.el.
21229 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21230 "Comment or uncomment each non-blank line in the region.
21231 Uncomment each non-blank line between BEG and END if it only
21232 contains commented lines. Otherwise, comment them."
21233 (save-restriction
21234 ;; Restrict region
21235 (narrow-to-region (save-excursion (goto-char beg)
21236 (skip-chars-forward " \r\t\n" end)
21237 (line-beginning-position))
21238 (save-excursion (goto-char end)
21239 (skip-chars-backward " \r\t\n" beg)
21240 (line-end-position)))
21241 (let ((uncommentp
21242 ;; UNCOMMENTP is non-nil when every non blank line between
21243 ;; BEG and END is a comment.
21244 (save-excursion
21245 (goto-char (point-min))
21246 (while (and (not (eobp))
21247 (let ((element (org-element-at-point)))
21248 (and (eq (org-element-type element) 'comment)
21249 (goto-char (min (point-max)
21250 (org-element-property
21251 :end element)))))))
21252 (eobp))))
21253 (if uncommentp
21254 ;; Only blank lines and comments in region: uncomment it.
21255 (save-excursion
21256 (goto-char (point-min))
21257 (while (not (eobp))
21258 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21259 (replace-match "" nil nil nil 1))
21260 (forward-line)))
21261 ;; Comment each line in region.
21262 (let ((min-indent (point-max)))
21263 ;; First find the minimum indentation across all lines.
21264 (save-excursion
21265 (goto-char (point-min))
21266 (while (and (not (eobp)) (not (zerop min-indent)))
21267 (unless (looking-at "[ \t]*$")
21268 (setq min-indent (min min-indent (current-indentation))))
21269 (forward-line)))
21270 ;; Then loop over all lines.
21271 (save-excursion
21272 (goto-char (point-min))
21273 (while (not (eobp))
21274 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21275 (org-move-to-column min-indent t)
21276 (insert comment-start))
21277 (forward-line))))))))
21280 ;;; Other stuff.
21282 (defun org-toggle-fixed-width-section (arg)
21283 "Toggle the fixed-width export.
21284 If there is no active region, the QUOTE keyword at the current headline is
21285 inserted or removed. When present, it causes the text between this headline
21286 and the next to be exported as fixed-width text, and unmodified.
21287 If there is an active region, this command adds or removes a colon as the
21288 first character of this line. If the first character of a line is a colon,
21289 this line is also exported in fixed-width font."
21290 (interactive "P")
21291 (let* ((cc 0)
21292 (regionp (org-region-active-p))
21293 (beg (if regionp (region-beginning) (point)))
21294 (end (if regionp (region-end)))
21295 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21296 (case-fold-search nil)
21297 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21298 off)
21299 (if regionp
21300 (save-excursion
21301 (goto-char beg)
21302 (setq cc (current-column))
21303 (beginning-of-line 1)
21304 (setq off (looking-at re))
21305 (while (> nlines 0)
21306 (setq nlines (1- nlines))
21307 (beginning-of-line 1)
21308 (cond
21309 (arg
21310 (org-move-to-column cc t)
21311 (insert ": \n")
21312 (forward-line -1))
21313 ((and off (looking-at re))
21314 (replace-match "" t t nil 1))
21315 ((not off) (org-move-to-column cc t) (insert ": ")))
21316 (forward-line 1)))
21317 (save-excursion
21318 (org-back-to-heading)
21319 (cond
21320 ((looking-at (format org-heading-keyword-regexp-format
21321 org-quote-string))
21322 (goto-char (match-end 1))
21323 (looking-at (concat " +" org-quote-string))
21324 (replace-match "" t t)
21325 (when (eolp) (insert " ")))
21326 ((looking-at org-outline-regexp)
21327 (goto-char (match-end 0))
21328 (insert org-quote-string " ")))))))
21330 (defun org-reftex-citation ()
21331 "Use reftex-citation to insert a citation into the buffer.
21332 This looks for a line like
21334 #+BIBLIOGRAPHY: foo plain option:-d
21336 and derives from it that foo.bib is the bibliography file relevant
21337 for this document. It then installs the necessary environment for RefTeX
21338 to work in this buffer and calls `reftex-citation' to insert a citation
21339 into the buffer.
21341 Export of such citations to both LaTeX and HTML is handled by the contributed
21342 package org-exp-bibtex by Taru Karttunen."
21343 (interactive)
21344 (let ((reftex-docstruct-symbol 'rds)
21345 (reftex-cite-format "\\cite{%l}")
21346 rds bib)
21347 (save-excursion
21348 (save-restriction
21349 (widen)
21350 (let ((case-fold-search t)
21351 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21352 (if (not (save-excursion
21353 (or (re-search-forward re nil t)
21354 (re-search-backward re nil t))))
21355 (error "No bibliography defined in file")
21356 (setq bib (concat (match-string 1) ".bib")
21357 rds (list (list 'bib bib)))))))
21358 (call-interactively 'reftex-citation)))
21360 ;;;; Functions extending outline functionality
21362 (defun org-beginning-of-line (&optional arg)
21363 "Go to the beginning of the current line. If that is invisible, continue
21364 to a visible line beginning. This makes the function of C-a more intuitive.
21365 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21366 first attempt, and only move to after the tags when the cursor is already
21367 beyond the end of the headline."
21368 (interactive "P")
21369 (let ((pos (point))
21370 (special (if (consp org-special-ctrl-a/e)
21371 (car org-special-ctrl-a/e)
21372 org-special-ctrl-a/e))
21373 refpos)
21374 (if (org-bound-and-true-p visual-line-mode)
21375 (beginning-of-visual-line 1)
21376 (beginning-of-line 1))
21377 (if (and arg (fboundp 'move-beginning-of-line))
21378 (call-interactively 'move-beginning-of-line)
21379 (if (bobp)
21381 (backward-char 1)
21382 (if (org-truely-invisible-p)
21383 (while (and (not (bobp)) (org-truely-invisible-p))
21384 (backward-char 1)
21385 (beginning-of-line 1))
21386 (forward-char 1))))
21387 (when special
21388 (cond
21389 ((and (looking-at org-complex-heading-regexp)
21390 (= (char-after (match-end 1)) ?\ ))
21391 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21392 (point-at-eol)))
21393 (goto-char
21394 (if (eq special t)
21395 (cond ((> pos refpos) refpos)
21396 ((= pos (point)) refpos)
21397 (t (point)))
21398 (cond ((> pos (point)) (point))
21399 ((not (eq last-command this-command)) (point))
21400 (t refpos)))))
21401 ((org-at-item-p)
21402 ;; Being at an item and not looking at an the item means point
21403 ;; was previously moved to beginning of a visual line, which
21404 ;; doesn't contain the item. Therefore, do nothing special,
21405 ;; just stay here.
21406 (when (looking-at org-list-full-item-re)
21407 ;; Set special position at first white space character after
21408 ;; bullet, and check-box, if any.
21409 (let ((after-bullet
21410 (let ((box (match-end 3)))
21411 (if (not box) (match-end 1)
21412 (let ((after (char-after box)))
21413 (if (and after (= after ? )) (1+ box) box))))))
21414 ;; Special case: Move point to special position when
21415 ;; currently after it or at beginning of line.
21416 (if (eq special t)
21417 (when (or (> pos after-bullet) (= (point) pos))
21418 (goto-char after-bullet))
21419 ;; Reversed case: Move point to special position when
21420 ;; point was already at beginning of line and command is
21421 ;; repeated.
21422 (when (and (= (point) pos) (eq last-command this-command))
21423 (goto-char after-bullet))))))))
21424 (org-no-warnings
21425 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21427 (defun org-end-of-line (&optional arg)
21428 "Go to the end of the line.
21429 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21430 tags on the first attempt, and only move to after the tags when
21431 the cursor is already beyond the end of the headline."
21432 (interactive "P")
21433 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21434 org-special-ctrl-a/e))
21435 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21436 'end-of-visual-line)
21437 ((fboundp 'move-end-of-line) 'move-end-of-line)
21438 (t 'end-of-line))))
21439 (if (or (not special) arg) (call-interactively move-fun)
21440 (let* ((element (save-excursion (beginning-of-line)
21441 (org-element-at-point)))
21442 (type (org-element-type element)))
21443 (cond
21444 ((memq type '(headline inlinetask))
21445 (let ((pos (point)))
21446 (beginning-of-line 1)
21447 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21448 (if (eq special t)
21449 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21450 (goto-char (match-beginning 1))
21451 (goto-char (match-end 0)))
21452 (if (or (< pos (match-end 0))
21453 (not (eq this-command last-command)))
21454 (goto-char (match-end 0))
21455 (goto-char (match-beginning 1))))
21456 (call-interactively move-fun))))
21457 ((org-element-property :hiddenp element)
21458 ;; If element is hidden, `move-end-of-line' would put point
21459 ;; after it. Use `end-of-line' to stay on current line.
21460 (call-interactively 'end-of-line))
21461 (t (call-interactively move-fun)))))
21462 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21464 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21465 (define-key org-mode-map "\C-e" 'org-end-of-line)
21467 (defun org-backward-sentence (&optional arg)
21468 "Go to beginning of sentence, or beginning of table field.
21469 This will call `backward-sentence' or `org-table-beginning-of-field',
21470 depending on context."
21471 (interactive "P")
21472 (cond
21473 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21474 (t (call-interactively 'backward-sentence))))
21476 (defun org-forward-sentence (&optional arg)
21477 "Go to end of sentence, or end of table field.
21478 This will call `forward-sentence' or `org-table-end-of-field',
21479 depending on context."
21480 (interactive "P")
21481 (cond
21482 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21483 (t (call-interactively 'forward-sentence))))
21485 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21486 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21488 (defun org-kill-line (&optional arg)
21489 "Kill line, to tags or end of line."
21490 (interactive "P")
21491 (cond
21492 ((or (not org-special-ctrl-k)
21493 (bolp)
21494 (not (org-at-heading-p)))
21495 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21496 org-ctrl-k-protect-subtree)
21497 (if (or (eq org-ctrl-k-protect-subtree 'error)
21498 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21499 (error "C-k aborted - would kill hidden subtree")))
21500 (call-interactively
21501 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21502 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21503 (kill-region (point) (match-beginning 1))
21504 (org-set-tags nil t))
21505 (t (kill-region (point) (point-at-eol)))))
21507 (define-key org-mode-map "\C-k" 'org-kill-line)
21509 (defun org-yank (&optional arg)
21510 "Yank. If the kill is a subtree, treat it specially.
21511 This command will look at the current kill and check if is a single
21512 subtree, or a series of subtrees[1]. If it passes the test, and if the
21513 cursor is at the beginning of a line or after the stars of a currently
21514 empty headline, then the yank is handled specially. How exactly depends
21515 on the value of the following variables, both set by default.
21517 org-yank-folded-subtrees
21518 When set, the subtree(s) will be folded after insertion, but only
21519 if doing so would now swallow text after the yanked text.
21521 org-yank-adjusted-subtrees
21522 When set, the subtree will be promoted or demoted in order to
21523 fit into the local outline tree structure, which means that the level
21524 will be adjusted so that it becomes the smaller one of the two
21525 *visible* surrounding headings.
21527 Any prefix to this command will cause `yank' to be called directly with
21528 no special treatment. In particular, a simple \\[universal-argument] prefix \
21529 will just
21530 plainly yank the text as it is.
21532 \[1] The test checks if the first non-white line is a heading
21533 and if there are no other headings with fewer stars."
21534 (interactive "P")
21535 (org-yank-generic 'yank arg))
21537 (defun org-yank-generic (command arg)
21538 "Perform some yank-like command.
21540 This function implements the behavior described in the `org-yank'
21541 documentation. However, it has been generalized to work for any
21542 interactive command with similar behavior."
21544 ;; pretend to be command COMMAND
21545 (setq this-command command)
21547 (if arg
21548 (call-interactively command)
21550 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21551 (and (org-kill-is-subtree-p)
21552 (or (bolp)
21553 (and (looking-at "[ \t]*$")
21554 (string-match
21555 "\\`\\*+\\'"
21556 (buffer-substring (point-at-bol) (point)))))))
21557 swallowp)
21558 (cond
21559 ((and subtreep org-yank-folded-subtrees)
21560 (let ((beg (point))
21561 end)
21562 (if (and subtreep org-yank-adjusted-subtrees)
21563 (org-paste-subtree nil nil 'for-yank)
21564 (call-interactively command))
21566 (setq end (point))
21567 (goto-char beg)
21568 (when (and (bolp) subtreep
21569 (not (setq swallowp
21570 (org-yank-folding-would-swallow-text beg end))))
21571 (org-with-limited-levels
21572 (or (looking-at org-outline-regexp)
21573 (re-search-forward org-outline-regexp-bol end t))
21574 (while (and (< (point) end) (looking-at org-outline-regexp))
21575 (hide-subtree)
21576 (org-cycle-show-empty-lines 'folded)
21577 (condition-case nil
21578 (outline-forward-same-level 1)
21579 (error (goto-char end))))))
21580 (when swallowp
21581 (message
21582 "Inserted text not folded because that would swallow text"))
21584 (goto-char end)
21585 (skip-chars-forward " \t\n\r")
21586 (beginning-of-line 1)
21587 (push-mark beg 'nomsg)))
21588 ((and subtreep org-yank-adjusted-subtrees)
21589 (let ((beg (point-at-bol)))
21590 (org-paste-subtree nil nil 'for-yank)
21591 (push-mark beg 'nomsg)))
21593 (call-interactively command))))))
21595 (defun org-yank-folding-would-swallow-text (beg end)
21596 "Would hide-subtree at BEG swallow any text after END?"
21597 (let (level)
21598 (org-with-limited-levels
21599 (save-excursion
21600 (goto-char beg)
21601 (when (or (looking-at org-outline-regexp)
21602 (re-search-forward org-outline-regexp-bol end t))
21603 (setq level (org-outline-level)))
21604 (goto-char end)
21605 (skip-chars-forward " \t\r\n\v\f")
21606 (if (or (eobp)
21607 (and (bolp) (looking-at org-outline-regexp)
21608 (<= (org-outline-level) level)))
21609 nil ; Nothing would be swallowed
21610 t))))) ; something would swallow
21612 (define-key org-mode-map "\C-y" 'org-yank)
21614 (defun org-truely-invisible-p ()
21615 "Check if point is at a character currently not visible.
21616 This version does not only check the character property, but also
21617 `visible-mode'."
21618 ;; Early versions of noutline don't have `outline-invisible-p'.
21619 (if (org-bound-and-true-p visible-mode)
21621 (outline-invisible-p)))
21623 (defun org-invisible-p2 ()
21624 "Check if point is at a character currently not visible."
21625 (save-excursion
21626 (if (and (eolp) (not (bobp))) (backward-char 1))
21627 ;; Early versions of noutline don't have `outline-invisible-p'.
21628 (outline-invisible-p)))
21630 (defun org-back-to-heading (&optional invisible-ok)
21631 "Call `outline-back-to-heading', but provide a better error message."
21632 (condition-case nil
21633 (outline-back-to-heading invisible-ok)
21634 (error (error "Before first headline at position %d in buffer %s"
21635 (point) (current-buffer)))))
21637 (defun org-before-first-heading-p ()
21638 "Before first heading?"
21639 (save-excursion
21640 (end-of-line)
21641 (null (re-search-backward org-outline-regexp-bol nil t))))
21643 (defun org-at-heading-p (&optional ignored)
21644 (outline-on-heading-p t))
21645 ;; Compatibility alias with Org versions < 7.8.03
21646 (defalias 'org-on-heading-p 'org-at-heading-p)
21648 (defun org-at-comment-p nil
21649 "Is cursor in a line starting with a # character?"
21650 (save-excursion
21651 (beginning-of-line)
21652 (looking-at "^#")))
21654 (defun org-at-drawer-p nil
21655 "Is cursor at a drawer keyword?"
21656 (save-excursion
21657 (move-beginning-of-line 1)
21658 (looking-at org-drawer-regexp)))
21660 (defun org-at-block-p nil
21661 "Is cursor at a block keyword?"
21662 (save-excursion
21663 (move-beginning-of-line 1)
21664 (looking-at org-block-regexp)))
21666 (defun org-point-at-end-of-empty-headline ()
21667 "If point is at the end of an empty headline, return t, else nil.
21668 If the heading only contains a TODO keyword, it is still still considered
21669 empty."
21670 (and (looking-at "[ \t]*$")
21671 (when org-todo-line-regexp
21672 (save-excursion
21673 (beginning-of-line 1)
21674 (let ((case-fold-search nil))
21675 (looking-at org-todo-line-regexp)
21676 (string= (match-string 3) ""))))))
21678 (defun org-at-heading-or-item-p ()
21679 (or (org-at-heading-p) (org-at-item-p)))
21681 (defun org-at-target-p ()
21682 (or (org-in-regexp org-radio-target-regexp)
21683 (org-in-regexp org-target-regexp)))
21684 ;; Compatibility alias with Org versions < 7.8.03
21685 (defalias 'org-on-target-p 'org-at-target-p)
21687 (defun org-up-heading-all (arg)
21688 "Move to the heading line of which the present line is a subheading.
21689 This function considers both visible and invisible heading lines.
21690 With argument, move up ARG levels."
21691 (if (fboundp 'outline-up-heading-all)
21692 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21693 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21695 (defun org-up-heading-safe ()
21696 "Move to the heading line of which the present line is a subheading.
21697 This version will not throw an error. It will return the level of the
21698 headline found, or nil if no higher level is found.
21700 Also, this function will be a lot faster than `outline-up-heading',
21701 because it relies on stars being the outline starters. This can really
21702 make a significant difference in outlines with very many siblings."
21703 (let (start-level re)
21704 (org-back-to-heading t)
21705 (setq start-level (funcall outline-level))
21706 (if (equal start-level 1)
21708 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21709 (if (re-search-backward re nil t)
21710 (funcall outline-level)))))
21712 (defun org-first-sibling-p ()
21713 "Is this heading the first child of its parents?"
21714 (interactive)
21715 (let ((re org-outline-regexp-bol)
21716 level l)
21717 (unless (org-at-heading-p t)
21718 (error "Not at a heading"))
21719 (setq level (funcall outline-level))
21720 (save-excursion
21721 (if (not (re-search-backward re nil t))
21723 (setq l (funcall outline-level))
21724 (< l level)))))
21726 (defun org-goto-sibling (&optional previous)
21727 "Goto the next sibling, even if it is invisible.
21728 When PREVIOUS is set, go to the previous sibling instead. Returns t
21729 when a sibling was found. When none is found, return nil and don't
21730 move point."
21731 (let ((fun (if previous 're-search-backward 're-search-forward))
21732 (pos (point))
21733 (re org-outline-regexp-bol)
21734 level l)
21735 (when (condition-case nil (org-back-to-heading t) (error nil))
21736 (setq level (funcall outline-level))
21737 (catch 'exit
21738 (or previous (forward-char 1))
21739 (while (funcall fun re nil t)
21740 (setq l (funcall outline-level))
21741 (when (< l level) (goto-char pos) (throw 'exit nil))
21742 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21743 (goto-char pos)
21744 nil))))
21746 (defun org-show-siblings ()
21747 "Show all siblings of the current headline."
21748 (save-excursion
21749 (while (org-goto-sibling) (org-flag-heading nil)))
21750 (save-excursion
21751 (while (org-goto-sibling 'previous)
21752 (org-flag-heading nil))))
21754 (defun org-goto-first-child ()
21755 "Goto the first child, even if it is invisible.
21756 Return t when a child was found. Otherwise don't move point and
21757 return nil."
21758 (let (level (pos (point)) (re org-outline-regexp-bol))
21759 (when (condition-case nil (org-back-to-heading t) (error nil))
21760 (setq level (outline-level))
21761 (forward-char 1)
21762 (if (and (re-search-forward re nil t) (> (outline-level) level))
21763 (progn (goto-char (match-beginning 0)) t)
21764 (goto-char pos) nil))))
21766 (defun org-show-hidden-entry ()
21767 "Show an entry where even the heading is hidden."
21768 (save-excursion
21769 (org-show-entry)))
21771 (defun org-flag-heading (flag &optional entry)
21772 "Flag the current heading. FLAG non-nil means make invisible.
21773 When ENTRY is non-nil, show the entire entry."
21774 (save-excursion
21775 (org-back-to-heading t)
21776 ;; Check if we should show the entire entry
21777 (if entry
21778 (progn
21779 (org-show-entry)
21780 (save-excursion
21781 (and (outline-next-heading)
21782 (org-flag-heading nil))))
21783 (outline-flag-region (max (point-min) (1- (point)))
21784 (save-excursion (outline-end-of-heading) (point))
21785 flag))))
21787 (defun org-get-next-sibling ()
21788 "Move to next heading of the same level, and return point.
21789 If there is no such heading, return nil.
21790 This is like outline-next-sibling, but invisible headings are ok."
21791 (let ((level (funcall outline-level)))
21792 (outline-next-heading)
21793 (while (and (not (eobp)) (> (funcall outline-level) level))
21794 (outline-next-heading))
21795 (if (or (eobp) (< (funcall outline-level) level))
21797 (point))))
21799 (defun org-get-last-sibling ()
21800 "Move to previous heading of the same level, and return point.
21801 If there is no such heading, return nil."
21802 (let ((opoint (point))
21803 (level (funcall outline-level)))
21804 (outline-previous-heading)
21805 (when (and (/= (point) opoint) (outline-on-heading-p t))
21806 (while (and (> (funcall outline-level) level)
21807 (not (bobp)))
21808 (outline-previous-heading))
21809 (if (< (funcall outline-level) level)
21811 (point)))))
21813 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21814 "Goto to the end of a subtree."
21815 ;; This contains an exact copy of the original function, but it uses
21816 ;; `org-back-to-heading', to make it work also in invisible
21817 ;; trees. And is uses an invisible-ok argument.
21818 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21819 ;; Furthermore, when used inside Org, finding the end of a large subtree
21820 ;; with many children and grandchildren etc, this can be much faster
21821 ;; than the outline version.
21822 (org-back-to-heading invisible-ok)
21823 (let ((first t)
21824 (level (funcall outline-level)))
21825 (if (and (derived-mode-p 'org-mode) (< level 1000))
21826 ;; A true heading (not a plain list item), in Org-mode
21827 ;; This means we can easily find the end by looking
21828 ;; only for the right number of stars. Using a regexp to do
21829 ;; this is so much faster than using a Lisp loop.
21830 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21831 (forward-char 1)
21832 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21833 ;; something else, do it the slow way
21834 (while (and (not (eobp))
21835 (or first (> (funcall outline-level) level)))
21836 (setq first nil)
21837 (outline-next-heading)))
21838 (unless to-heading
21839 (if (memq (preceding-char) '(?\n ?\^M))
21840 (progn
21841 ;; Go to end of line before heading
21842 (forward-char -1)
21843 (if (memq (preceding-char) '(?\n ?\^M))
21844 ;; leave blank line before heading
21845 (forward-char -1))))))
21846 (point))
21848 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21849 "Use Org version in org-mode, for dramatic speed-up."
21850 (if (derived-mode-p 'org-mode)
21851 (progn
21852 (org-end-of-subtree nil t)
21853 (unless (eobp) (backward-char 1)))
21854 ad-do-it))
21856 (defun org-end-of-meta-data-and-drawers ()
21857 "Jump to the first text after meta data and drawers in the current entry.
21858 This will move over empty lines, lines with planning time stamps,
21859 clocking lines, and drawers."
21860 (org-back-to-heading t)
21861 (let ((end (save-excursion (outline-next-heading) (point)))
21862 (re (concat "\\(" org-drawer-regexp "\\)"
21863 "\\|" "[ \t]*" org-keyword-time-regexp)))
21864 (forward-line 1)
21865 (while (re-search-forward re end t)
21866 (if (not (match-end 1))
21867 ;; empty or planning line
21868 (forward-line 1)
21869 ;; a drawer, find the end
21870 (re-search-forward "^[ \t]*:END:" end 'move)
21871 (forward-line 1)))
21872 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21873 (point)))
21875 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21876 "Move forward to the arg'th subheading at same level as this one.
21877 Stop at the first and last subheadings of a superior heading.
21878 Normally this only looks at visible headings, but when INVISIBLE-OK is
21879 non-nil it will also look at invisible ones."
21880 (interactive "p")
21881 (org-back-to-heading invisible-ok)
21882 (org-at-heading-p)
21883 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21884 (re (format "^\\*\\{1,%d\\} " level))
21886 (forward-char 1)
21887 (while (> arg 0)
21888 (while (and (re-search-forward re nil 'move)
21889 (setq l (- (match-end 0) (match-beginning 0) 1))
21890 (= l level)
21891 (not invisible-ok)
21892 (progn (backward-char 1) (outline-invisible-p)))
21893 (if (< l level) (setq arg 1)))
21894 (setq arg (1- arg)))
21895 (beginning-of-line 1)))
21897 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21898 "Move backward to the arg'th subheading at same level as this one.
21899 Stop at the first and last subheadings of a superior heading."
21900 (interactive "p")
21901 (org-back-to-heading)
21902 (org-at-heading-p)
21903 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21904 (re (format "^\\*\\{1,%d\\} " level))
21906 (while (> arg 0)
21907 (while (and (re-search-backward re nil 'move)
21908 (setq l (- (match-end 0) (match-beginning 0) 1))
21909 (= l level)
21910 (not invisible-ok)
21911 (outline-invisible-p))
21912 (if (< l level) (setq arg 1)))
21913 (setq arg (1- arg)))))
21915 (defun org-forward-element ()
21916 "Move forward by one element.
21917 Move to the next element at the same level, when possible."
21918 (interactive)
21919 (cond ((eobp) (error "Cannot move further down"))
21920 ((org-with-limited-levels (org-at-heading-p))
21921 (let ((origin (point)))
21922 (org-forward-heading-same-level 1)
21923 (unless (org-with-limited-levels (org-at-heading-p))
21924 (goto-char origin)
21925 (error "Cannot move further down"))))
21927 (let* ((elem (org-element-at-point))
21928 (end (org-element-property :end elem))
21929 (parent (org-element-property :parent elem)))
21930 (if (and parent (= (org-element-property :contents-end parent) end))
21931 (goto-char (org-element-property :end parent))
21932 (goto-char end))))))
21934 (defun org-backward-element ()
21935 "Move backward by one element.
21936 Move to the previous element at the same level, when possible."
21937 (interactive)
21938 (cond ((bobp) (error "Cannot move further up"))
21939 ((org-with-limited-levels (org-at-heading-p))
21940 ;; At an headline, move to the previous one, if any, or stay
21941 ;; here.
21942 (let ((origin (point)))
21943 (org-backward-heading-same-level 1)
21944 (unless (org-with-limited-levels (org-at-heading-p))
21945 (goto-char origin)
21946 (error "Cannot move further up"))))
21948 (let* ((trail (org-element-at-point 'keep-trail))
21949 (elem (car trail))
21950 (prev-elem (nth 1 trail))
21951 (beg (org-element-property :begin elem)))
21952 (cond
21953 ;; Move to beginning of current element if point isn't
21954 ;; there already.
21955 ((/= (point) beg) (goto-char beg))
21956 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21957 ((org-before-first-heading-p) (goto-char (point-min)))
21958 (t (org-back-to-heading)))))))
21960 (defun org-up-element ()
21961 "Move to upper element."
21962 (interactive)
21963 (if (org-with-limited-levels (org-at-heading-p))
21964 (unless (org-up-heading-safe) (error "No surrounding element"))
21965 (let* ((elem (org-element-at-point))
21966 (parent (org-element-property :parent elem)))
21967 (if parent (goto-char (org-element-property :begin parent))
21968 (if (org-with-limited-levels (org-before-first-heading-p))
21969 (error "No surrounding element")
21970 (org-with-limited-levels (org-back-to-heading)))))))
21972 (defvar org-element-greater-elements)
21973 (defun org-down-element ()
21974 "Move to inner element."
21975 (interactive)
21976 (let ((element (org-element-at-point)))
21977 (cond
21978 ((memq (org-element-type element) '(plain-list table))
21979 (goto-char (org-element-property :contents-begin element))
21980 (forward-char))
21981 ((memq (org-element-type element) org-element-greater-elements)
21982 ;; If contents are hidden, first disclose them.
21983 (when (org-element-property :hiddenp element) (org-cycle))
21984 (goto-char (or (org-element-property :contents-begin element)
21985 (error "No content for this element"))))
21986 (t (error "No inner element")))))
21988 (defun org-drag-element-backward ()
21989 "Move backward element at point."
21990 (interactive)
21991 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21992 (let* ((trail (org-element-at-point 'keep-trail))
21993 (elem (car trail))
21994 (prev-elem (nth 1 trail)))
21995 ;; Error out if no previous element or previous element is
21996 ;; a parent of the current one.
21997 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21998 (error "Cannot drag element backward")
21999 (let ((pos (point)))
22000 (org-element-swap-A-B prev-elem elem)
22001 (goto-char (+ (org-element-property :begin prev-elem)
22002 (- pos (org-element-property :begin elem)))))))))
22004 (defun org-drag-element-forward ()
22005 "Move forward element at point."
22006 (interactive)
22007 (let* ((pos (point))
22008 (elem (org-element-at-point)))
22009 (when (= (point-max) (org-element-property :end elem))
22010 (error "Cannot drag element forward"))
22011 (goto-char (org-element-property :end elem))
22012 (let ((next-elem (org-element-at-point)))
22013 (when (or (org-element-nested-p elem next-elem)
22014 (and (eq (org-element-type next-elem) 'headline)
22015 (not (eq (org-element-type elem) 'headline))))
22016 (goto-char pos)
22017 (error "Cannot drag element forward"))
22018 ;; Compute new position of point: it's shifted by NEXT-ELEM
22019 ;; body's length (without final blanks) and by the length of
22020 ;; blanks between ELEM and NEXT-ELEM.
22021 (let ((size-next (- (save-excursion
22022 (goto-char (org-element-property :end next-elem))
22023 (skip-chars-backward " \r\t\n")
22024 (forward-line)
22025 ;; Small correction if buffer doesn't end
22026 ;; with a newline character.
22027 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22028 (org-element-property :begin next-elem)))
22029 (size-blank (- (org-element-property :end elem)
22030 (save-excursion
22031 (goto-char (org-element-property :end elem))
22032 (skip-chars-backward " \r\t\n")
22033 (forward-line)
22034 (point)))))
22035 (org-element-swap-A-B elem next-elem)
22036 (goto-char (+ pos size-next size-blank))))))
22038 (defun org-mark-element ()
22039 "Put point at beginning of this element, mark at end.
22041 Interactively, if this command is repeated or (in Transient Mark
22042 mode) if the mark is active, it marks the next element after the
22043 ones already marked."
22044 (interactive)
22045 (let (deactivate-mark)
22046 (if (and (org-called-interactively-p 'any)
22047 (or (and (eq last-command this-command) (mark t))
22048 (and transient-mark-mode mark-active)))
22049 (set-mark
22050 (save-excursion
22051 (goto-char (mark))
22052 (goto-char (org-element-property :end (org-element-at-point)))))
22053 (let ((element (org-element-at-point)))
22054 (end-of-line)
22055 (push-mark (org-element-property :end element) t t)
22056 (goto-char (org-element-property :begin element))))))
22058 (defun org-narrow-to-element ()
22059 "Narrow buffer to current element."
22060 (interactive)
22061 (let ((elem (org-element-at-point)))
22062 (cond
22063 ((eq (car elem) 'headline)
22064 (narrow-to-region
22065 (org-element-property :begin elem)
22066 (org-element-property :end elem)))
22067 ((memq (car elem) org-element-greater-elements)
22068 (narrow-to-region
22069 (org-element-property :contents-begin elem)
22070 (org-element-property :contents-end elem)))
22072 (narrow-to-region
22073 (org-element-property :begin elem)
22074 (org-element-property :end elem))))))
22076 (defun org-transpose-element ()
22077 "Transpose current and previous elements, keeping blank lines between.
22078 Point is moved after both elements."
22079 (interactive)
22080 (org-skip-whitespace)
22081 (let ((end (org-element-property :end (org-element-at-point))))
22082 (org-drag-element-backward)
22083 (goto-char end)))
22085 (defun org-unindent-buffer ()
22086 "Un-indent the visible part of the buffer.
22087 Relative indentation (between items, inside blocks, etc.) isn't
22088 modified."
22089 (interactive)
22090 (unless (eq major-mode 'org-mode)
22091 (error "Cannot un-indent a buffer not in Org mode"))
22092 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22093 unindent-tree ; For byte-compiler.
22094 (unindent-tree
22095 (function
22096 (lambda (contents)
22097 (mapc
22098 (lambda (element)
22099 (if (memq (org-element-type element) '(headline section))
22100 (funcall unindent-tree (org-element-contents element))
22101 (save-excursion
22102 (save-restriction
22103 (narrow-to-region
22104 (org-element-property :begin element)
22105 (org-element-property :end element))
22106 (org-do-remove-indentation)))))
22107 (reverse contents))))))
22108 (funcall unindent-tree (org-element-contents parse-tree))))
22110 (defun org-show-subtree ()
22111 "Show everything after this heading at deeper levels."
22112 (interactive)
22113 (outline-flag-region
22114 (point)
22115 (save-excursion
22116 (org-end-of-subtree t t))
22117 nil))
22119 (defun org-show-entry ()
22120 "Show the body directly following this heading.
22121 Show the heading too, if it is currently invisible."
22122 (interactive)
22123 (save-excursion
22124 (condition-case nil
22125 (progn
22126 (org-back-to-heading t)
22127 (outline-flag-region
22128 (max (point-min) (1- (point)))
22129 (save-excursion
22130 (if (re-search-forward
22131 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22132 (match-beginning 1)
22133 (point-max)))
22134 nil)
22135 (org-cycle-hide-drawers 'children))
22136 (error nil))))
22138 (defun org-make-options-regexp (kwds &optional extra)
22139 "Make a regular expression for keyword lines."
22140 (concat
22141 "^#\\+\\("
22142 (mapconcat 'regexp-quote kwds "\\|")
22143 (if extra (concat "\\|" extra))
22144 "\\):[ \t]*\\(.*\\)"))
22146 ;; Make isearch reveal the necessary context
22147 (defun org-isearch-end ()
22148 "Reveal context after isearch exits."
22149 (when isearch-success ; only if search was successful
22150 (if (featurep 'xemacs)
22151 ;; Under XEmacs, the hook is run in the correct place,
22152 ;; we directly show the context.
22153 (org-show-context 'isearch)
22154 ;; In Emacs the hook runs *before* restoring the overlays.
22155 ;; So we have to use a one-time post-command-hook to do this.
22156 ;; (Emacs 22 has a special variable, see function `org-mode')
22157 (unless (and (boundp 'isearch-mode-end-hook-quit)
22158 isearch-mode-end-hook-quit)
22159 ;; Only when the isearch was not quitted.
22160 (org-add-hook 'post-command-hook 'org-isearch-post-command
22161 'append 'local)))))
22163 (defun org-isearch-post-command ()
22164 "Remove self from hook, and show context."
22165 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22166 (org-show-context 'isearch))
22169 ;;;; Integration with and fixes for other packages
22171 ;;; Imenu support
22173 (defvar org-imenu-markers nil
22174 "All markers currently used by Imenu.")
22175 (make-variable-buffer-local 'org-imenu-markers)
22177 (defun org-imenu-new-marker (&optional pos)
22178 "Return a new marker for use by Imenu, and remember the marker."
22179 (let ((m (make-marker)))
22180 (move-marker m (or pos (point)))
22181 (push m org-imenu-markers)
22184 (defun org-imenu-get-tree ()
22185 "Produce the index for Imenu."
22186 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22187 (setq org-imenu-markers nil)
22188 (let* ((n org-imenu-depth)
22189 (re (concat "^" (org-get-limited-outline-regexp)))
22190 (subs (make-vector (1+ n) nil))
22191 (last-level 0)
22192 m level head)
22193 (save-excursion
22194 (save-restriction
22195 (widen)
22196 (goto-char (point-max))
22197 (while (re-search-backward re nil t)
22198 (setq level (org-reduced-level (funcall outline-level)))
22199 (when (and (<= level n)
22200 (looking-at org-complex-heading-regexp))
22201 (setq head (org-link-display-format
22202 (org-match-string-no-properties 4))
22203 m (org-imenu-new-marker))
22204 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22205 (if (>= level last-level)
22206 (push (cons head m) (aref subs level))
22207 (push (cons head (aref subs (1+ level))) (aref subs level))
22208 (loop for i from (1+ level) to n do (aset subs i nil)))
22209 (setq last-level level)))))
22210 (aref subs 1)))
22212 (eval-after-load "imenu"
22213 '(progn
22214 (add-hook 'imenu-after-jump-hook
22215 (lambda ()
22216 (if (derived-mode-p 'org-mode)
22217 (org-show-context 'org-goto))))))
22219 (defun org-link-display-format (link)
22220 "Replace a link with either the description, or the link target
22221 if no description is present"
22222 (save-match-data
22223 (if (string-match org-bracket-link-analytic-regexp link)
22224 (replace-match (if (match-end 5)
22225 (match-string 5 link)
22226 (concat (match-string 1 link)
22227 (match-string 3 link)))
22228 nil t link)
22229 link)))
22231 (defun org-toggle-link-display ()
22232 "Toggle the literal or descriptive display of links."
22233 (interactive)
22234 (if org-descriptive-links
22235 (progn (org-remove-from-invisibility-spec '(org-link))
22236 (org-restart-font-lock)
22237 (setq org-descriptive-links nil))
22238 (progn (add-to-invisibility-spec '(org-link))
22239 (org-restart-font-lock)
22240 (setq org-descriptive-links t))))
22242 ;; Speedbar support
22244 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22245 "Overlay marking the agenda restriction line in speedbar.")
22246 (overlay-put org-speedbar-restriction-lock-overlay
22247 'face 'org-agenda-restriction-lock)
22248 (overlay-put org-speedbar-restriction-lock-overlay
22249 'help-echo "Agendas are currently limited to this item.")
22250 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22252 (defun org-speedbar-set-agenda-restriction ()
22253 "Restrict future agenda commands to the location at point in speedbar.
22254 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22255 (interactive)
22256 (require 'org-agenda)
22257 (let (p m tp np dir txt)
22258 (cond
22259 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22260 'org-imenu t))
22261 (setq m (get-text-property p 'org-imenu-marker))
22262 (with-current-buffer (marker-buffer m)
22263 (goto-char m)
22264 (org-agenda-set-restriction-lock 'subtree)))
22265 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22266 'speedbar-function 'speedbar-find-file))
22267 (setq tp (previous-single-property-change
22268 (1+ p) 'speedbar-function)
22269 np (next-single-property-change
22270 tp 'speedbar-function)
22271 dir (speedbar-line-directory)
22272 txt (buffer-substring-no-properties (or tp (point-min))
22273 (or np (point-max))))
22274 (with-current-buffer (find-file-noselect
22275 (let ((default-directory dir))
22276 (expand-file-name txt)))
22277 (unless (derived-mode-p 'org-mode)
22278 (error "Cannot restrict to non-Org-mode file"))
22279 (org-agenda-set-restriction-lock 'file)))
22280 (t (error "Don't know how to restrict Org-mode's agenda")))
22281 (move-overlay org-speedbar-restriction-lock-overlay
22282 (point-at-bol) (point-at-eol))
22283 (setq current-prefix-arg nil)
22284 (org-agenda-maybe-redo)))
22286 (eval-after-load "speedbar"
22287 '(progn
22288 (speedbar-add-supported-extension ".org")
22289 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22290 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22291 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22292 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22293 (add-hook 'speedbar-visiting-tag-hook
22294 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22296 ;;; Fixes and Hacks for problems with other packages
22298 ;; Make flyspell not check words in links, to not mess up our keymap
22299 (defun org-mode-flyspell-verify ()
22300 "Don't let flyspell put overlays at active buttons, or on
22301 {todo,all-time,additional-option-like}-keywords."
22302 (let ((pos (max (1- (point)) (point-min)))
22303 (word (thing-at-point 'word)))
22304 (and (not (get-text-property pos 'keymap))
22305 (not (get-text-property pos 'org-no-flyspell))
22306 (not (member word org-todo-keywords-1))
22307 (not (member word org-all-time-keywords))
22308 (not (member word org-options-keywords))
22309 (not (member word (mapcar 'car org-startup-options)))
22310 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22312 (defun org-remove-flyspell-overlays-in (beg end)
22313 "Remove flyspell overlays in region."
22314 (and (org-bound-and-true-p flyspell-mode)
22315 (fboundp 'flyspell-delete-region-overlays)
22316 (flyspell-delete-region-overlays beg end))
22317 (add-text-properties beg end '(org-no-flyspell t)))
22319 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22320 (eval-after-load "bookmark"
22321 '(if (boundp 'bookmark-after-jump-hook)
22322 ;; We can use the hook
22323 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22324 ;; Hook not available, use advice
22325 (defadvice bookmark-jump (after org-make-visible activate)
22326 "Make the position visible."
22327 (org-bookmark-jump-unhide))))
22329 ;; Make sure saveplace shows the location if it was hidden
22330 (eval-after-load "saveplace"
22331 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22332 "Make the position visible."
22333 (org-bookmark-jump-unhide)))
22335 ;; Make sure ecb shows the location if it was hidden
22336 (eval-after-load "ecb"
22337 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22338 "Make hierarchy visible when jumping into location from ECB tree buffer."
22339 (if (derived-mode-p 'org-mode)
22340 (org-show-context))))
22342 (defun org-bookmark-jump-unhide ()
22343 "Unhide the current position, to show the bookmark location."
22344 (and (derived-mode-p 'org-mode)
22345 (or (outline-invisible-p)
22346 (save-excursion (goto-char (max (point-min) (1- (point))))
22347 (outline-invisible-p)))
22348 (org-show-context 'bookmark-jump)))
22350 ;; Make session.el ignore our circular variable
22351 (eval-after-load "session"
22352 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22354 ;;;; Experimental code
22356 (defun org-closed-in-range ()
22357 "Sparse tree of items closed in a certain time range.
22358 Still experimental, may disappear in the future."
22359 (interactive)
22360 ;; Get the time interval from the user.
22361 (let* ((time1 (org-float-time
22362 (org-read-date nil 'to-time nil "Starting date: ")))
22363 (time2 (org-float-time
22364 (org-read-date nil 'to-time nil "End date:")))
22365 ;; callback function
22366 (callback (lambda ()
22367 (let ((time
22368 (org-float-time
22369 (apply 'encode-time
22370 (org-parse-time-string
22371 (match-string 1))))))
22372 ;; check if time in interval
22373 (and (>= time time1) (<= time time2))))))
22374 ;; make tree, check each match with the callback
22375 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22377 ;;;; Finish up
22379 (provide 'org)
22381 (run-hooks 'org-load-hook)
22383 ;;; org.el ends here