contrib/org-toc.el: add forward and back commands
[org-mode.git] / lisp / org.el
blob3e6678ac6d74993834f824c259fdcc765e48931a
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-clock-timestamps-up "org-clock" ())
118 (declare-function org-clock-timestamps-down "org-clock" ())
119 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
121 (declare-function orgtbl-mode "org-table" (&optional arg))
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-beamer-mode "org-beamer" ())
124 (declare-function org-table-edit-field "org-table" (arg))
125 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
126 (declare-function org-id-get-create "org-id" (&optional force))
127 (declare-function org-id-find-id-file "org-id" (id))
128 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
129 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
130 (declare-function org-table-align "org-table" ())
131 (declare-function org-table-paste-rectangle "org-table" ())
132 (declare-function org-table-maybe-eval-formula "org-table" ())
133 (declare-function org-table-maybe-recalculate-line "org-table" ())
135 ;; load languages based on value of `org-babel-load-languages'
136 (defvar org-babel-load-languages)
138 ;;;###autoload
139 (defun org-babel-do-load-languages (sym value)
140 "Load the languages defined in `org-babel-load-languages'."
141 (set-default sym value)
142 (mapc (lambda (pair)
143 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
144 (if active
145 (progn
146 (require (intern (concat "ob-" lang))))
147 (progn
148 (funcall 'fmakunbound
149 (intern (concat "org-babel-execute:" lang)))
150 (funcall 'fmakunbound
151 (intern (concat "org-babel-expand-body:" lang)))))))
152 org-babel-load-languages))
154 (defcustom org-babel-load-languages '((emacs-lisp . t))
155 "Languages which can be evaluated in Org-mode buffers.
156 This list can be used to load support for any of the languages
157 below, note that each language will depend on a different set of
158 system executables and/or Emacs modes. When a language is
159 \"loaded\", then code blocks in that language can be evaluated
160 with `org-babel-execute-src-block' bound by default to C-c
161 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
162 be set to remove code block evaluation from the C-c C-c
163 keybinding. By default only Emacs Lisp (which has no
164 requirements) is loaded."
165 :group 'org-babel
166 :set 'org-babel-do-load-languages
167 :version "24.1"
168 :type '(alist :tag "Babel Languages"
169 :key-type
170 (choice
171 (const :tag "Awk" awk)
172 (const :tag "C" C)
173 (const :tag "R" R)
174 (const :tag "Asymptote" asymptote)
175 (const :tag "Calc" calc)
176 (const :tag "Clojure" clojure)
177 (const :tag "CSS" css)
178 (const :tag "Ditaa" ditaa)
179 (const :tag "Dot" dot)
180 (const :tag "Emacs Lisp" emacs-lisp)
181 (const :tag "Fortran" fortran)
182 (const :tag "Gnuplot" gnuplot)
183 (const :tag "Haskell" haskell)
184 (const :tag "IO" io)
185 (const :tag "Java" java)
186 (const :tag "Javascript" js)
187 (const :tag "LaTeX" latex)
188 (const :tag "Ledger" ledger)
189 (const :tag "Lilypond" lilypond)
190 (const :tag "Lisp" lisp)
191 (const :tag "Maxima" maxima)
192 (const :tag "Matlab" matlab)
193 (const :tag "Mscgen" mscgen)
194 (const :tag "Ocaml" ocaml)
195 (const :tag "Octave" octave)
196 (const :tag "Org" org)
197 (const :tag "Perl" perl)
198 (const :tag "Pico Lisp" picolisp)
199 (const :tag "PlantUML" plantuml)
200 (const :tag "Python" python)
201 (const :tag "Ruby" ruby)
202 (const :tag "Sass" sass)
203 (const :tag "Scala" scala)
204 (const :tag "Scheme" scheme)
205 (const :tag "Screen" screen)
206 (const :tag "Shell Script" sh)
207 (const :tag "Shen" shen)
208 (const :tag "Sql" sql)
209 (const :tag "Sqlite" sqlite))
210 :value-type (boolean :tag "Activate" :value t)))
212 ;;;; Customization variables
213 (defcustom org-clone-delete-id nil
214 "Remove ID property of clones of a subtree.
215 When non-nil, clones of a subtree don't inherit the ID property.
216 Otherwise they inherit the ID property with a new unique
217 identifier."
218 :type 'boolean
219 :version "24.1"
220 :group 'org-id)
222 ;;; Version
223 (require 'org-compat)
224 (org-check-version)
226 ;;;###autoload
227 (defun org-version (&optional here full message)
228 "Show the org-mode version in the echo area.
229 With prefix argument HERE, insert it at point.
230 When FULL is non-nil, use a verbose version string.
231 When MESSAGE is non-nil, display a message with the version."
232 (interactive "P")
233 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
234 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
235 (org-trash (or
236 (and (fboundp 'org-release) (fboundp 'org-git-version))
237 (load (concat org-dir "org-version.el")
238 'noerror 'nomessage 'nosuffix)))
239 (org-version (org-release))
240 (git-version (org-git-version))
241 (version (format "Org-mode version %s (%s @ %s)"
242 org-version
243 git-version
244 (if org-install-dir
245 (if (string= org-dir org-install-dir)
246 org-install-dir
247 (concat "mixed installation! " org-install-dir " and " org-dir))
248 "org-loaddefs.el can not be found!")))
249 (_version (if full version org-version)))
250 (if (org-called-interactively-p 'interactive)
251 (if here
252 (insert version)
253 (message version))
254 (if message (message _version))
255 _version)))
257 (defconst org-version (org-version))
259 ;;; Compatibility constants
261 ;;; The custom variables
263 (defgroup org nil
264 "Outline-based notes management and organizer."
265 :tag "Org"
266 :group 'outlines
267 :group 'calendar)
269 (defcustom org-mode-hook nil
270 "Mode hook for Org-mode, run after the mode was turned on."
271 :group 'org
272 :type 'hook)
274 (defcustom org-load-hook nil
275 "Hook that is run after org.el has been loaded."
276 :group 'org
277 :type 'hook)
279 (defcustom org-log-buffer-setup-hook nil
280 "Hook that is run after an Org log buffer is created."
281 :group 'org
282 :version "24.1"
283 :type 'hook)
285 (defvar org-modules) ; defined below
286 (defvar org-modules-loaded nil
287 "Have the modules been loaded already?")
289 (defun org-load-modules-maybe (&optional force)
290 "Load all extensions listed in `org-modules'."
291 (when (or force (not org-modules-loaded))
292 (mapc (lambda (ext)
293 (condition-case nil (require ext)
294 (error (message "Problems while trying to load feature `%s'" ext))))
295 org-modules)
296 (setq org-modules-loaded t)))
298 (defun org-set-modules (var value)
299 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
300 (set var value)
301 (when (featurep 'org)
302 (org-load-modules-maybe 'force)))
304 (when (org-bound-and-true-p org-modules)
305 (let ((a (member 'org-infojs org-modules)))
306 (and a (setcar a 'org-jsinfo))))
308 (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)
309 "Modules that should always be loaded together with org.el.
310 If a description starts with <C>, the file is not part of Emacs
311 and loading it will require that you have downloaded and properly installed
312 the org-mode distribution.
314 You can also use this system to load external packages (i.e. neither Org
315 core modules, nor modules from the CONTRIB directory). Just add symbols
316 to the end of the list. If the package is called org-xyz.el, then you need
317 to add the symbol `xyz', and the package must have a call to
319 (provide 'org-xyz)"
320 :group 'org
321 :set 'org-set-modules
322 :type
323 '(set :greedy t
324 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
325 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
326 (const :tag " crypt: Encryption of subtrees" org-crypt)
327 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
328 (const :tag " docview: Links to doc-view buffers" org-docview)
329 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
330 (const :tag " id: Global IDs for identifying entries" org-id)
331 (const :tag " info: Links to Info nodes" org-info)
332 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
333 (const :tag " habit: Track your consistency with habits" org-habit)
334 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
335 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
336 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
337 (const :tag " mew Links to Mew folders/messages" org-mew)
338 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
339 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
340 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
341 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
342 (const :tag " vm: Links to VM folders/messages" org-vm)
343 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
344 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
345 (const :tag " mouse: Additional mouse support" org-mouse)
346 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
348 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
349 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
350 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
351 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
352 (const :tag "C collector: Collect properties into tables" org-collector)
353 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
354 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
355 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
356 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
357 (const :tag "C eval: Include command output as text" org-eval)
358 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
359 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
360 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
361 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
362 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
364 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
366 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
367 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
368 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
369 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
370 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
371 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
372 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
373 (const :tag "C mtags: Support for muse-like tags" org-mtags)
374 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
375 (const :tag "C registry: A registry for Org-mode links" org-registry)
376 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
377 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
378 (const :tag "C secretary: Team management with org-mode" org-secretary)
379 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
380 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
381 (const :tag "C track: Keep up with Org-mode development" org-track)
382 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
383 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
384 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
386 (defcustom org-support-shift-select nil
387 "Non-nil means make shift-cursor commands select text when possible.
389 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
390 start selecting a region, or enlarge regions started in this way.
391 In Org-mode, in special contexts, these same keys are used for
392 other purposes, important enough to compete with shift selection.
393 Org tries to balance these needs by supporting `shift-select-mode'
394 outside these special contexts, under control of this variable.
396 The default of this variable is nil, to avoid confusing behavior. Shifted
397 cursor keys will then execute Org commands in the following contexts:
398 - on a headline, changing TODO state (left/right) and priority (up/down)
399 - on a time stamp, changing the time
400 - in a plain list item, changing the bullet type
401 - in a property definition line, switching between allowed values
402 - in the BEGIN line of a clock table (changing the time block).
403 Outside these contexts, the commands will throw an error.
405 When this variable is t and the cursor is not in a special
406 context, Org-mode will support shift-selection for making and
407 enlarging regions. To make this more effective, the bullet
408 cycling will no longer happen anywhere in an item line, but only
409 if the cursor is exactly on the bullet.
411 If you set this variable to the symbol `always', then the keys
412 will not be special in headlines, property lines, and item lines,
413 to make shift selection work there as well. If this is what you
414 want, you can use the following alternative commands: `C-c C-t'
415 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
416 can be used to switch TODO sets, `C-c -' to cycle item bullet
417 types, and properties can be edited by hand or in column view.
419 However, when the cursor is on a timestamp, shift-cursor commands
420 will still edit the time stamp - this is just too good to give up.
422 XEmacs user should have this variable set to nil, because
423 `shift-select-mode' is in Emacs 23 or later only."
424 :group 'org
425 :type '(choice
426 (const :tag "Never" nil)
427 (const :tag "When outside special context" t)
428 (const :tag "Everywhere except timestamps" always)))
430 (defcustom org-loop-over-headlines-in-active-region nil
431 "Shall some commands act upon headlines in the active region?
433 When set to `t', some commands will be performed in all headlines
434 within the active region.
436 When set to `start-level', some commands will be performed in all
437 headlines within the active region, provided that these headlines
438 are of the same level than the first one.
440 When set to a string, those commands will be performed on the
441 matching headlines within the active region. Such string must be
442 a tags/property/todo match as it is used in the agenda tags view.
444 The list of commands is: `org-schedule', `org-deadline',
445 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
446 `org-archive-to-archive-sibling'. The archiving commands skip
447 already archived entries."
448 :type '(choice (const :tag "Don't loop" nil)
449 (const :tag "All headlines in active region" t)
450 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
451 (string :tag "Tags/Property/Todo matcher"))
452 :version "24.1"
453 :group 'org-todo
454 :group 'org-archive)
456 (defgroup org-startup nil
457 "Options concerning startup of Org-mode."
458 :tag "Org Startup"
459 :group 'org)
461 (defcustom org-startup-folded t
462 "Non-nil means entering Org-mode will switch to OVERVIEW.
463 This can also be configured on a per-file basis by adding one of
464 the following lines anywhere in the buffer:
466 #+STARTUP: fold (or `overview', this is equivalent)
467 #+STARTUP: nofold (or `showall', this is equivalent)
468 #+STARTUP: content
469 #+STARTUP: showeverything
471 By default, this option is ignored when Org opens agenda files
472 for the first time. If you want the agenda to honor the startup
473 option, set `org-agenda-inhibit-startup' to nil."
474 :group 'org-startup
475 :type '(choice
476 (const :tag "nofold: show all" nil)
477 (const :tag "fold: overview" t)
478 (const :tag "content: all headlines" content)
479 (const :tag "show everything, even drawers" showeverything)))
481 (defcustom org-startup-truncated t
482 "Non-nil means entering Org-mode will set `truncate-lines'.
483 This is useful since some lines containing links can be very long and
484 uninteresting. Also tables look terrible when wrapped."
485 :group 'org-startup
486 :type 'boolean)
488 (defcustom org-startup-indented nil
489 "Non-nil means turn on `org-indent-mode' on startup.
490 This can also be configured on a per-file basis by adding one of
491 the following lines anywhere in the buffer:
493 #+STARTUP: indent
494 #+STARTUP: noindent"
495 :group 'org-structure
496 :type '(choice
497 (const :tag "Not" nil)
498 (const :tag "Globally (slow on startup in large files)" t)))
500 (defcustom org-use-sub-superscripts t
501 "Non-nil means interpret \"_\" and \"^\" for export.
502 When this option is turned on, you can use TeX-like syntax for sub- and
503 superscripts. Several characters after \"_\" or \"^\" will be
504 considered as a single item - so grouping with {} is normally not
505 needed. For example, the following things will be parsed as single
506 sub- or superscripts.
508 10^24 or 10^tau several digits will be considered 1 item.
509 10^-12 or 10^-tau a leading sign with digits or a word
510 x^2-y^3 will be read as x^2 - y^3, because items are
511 terminated by almost any nonword/nondigit char.
512 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
514 Still, ambiguity is possible - so when in doubt use {} to enclose the
515 sub/superscript. If you set this variable to the symbol `{}',
516 the braces are *required* in order to trigger interpretations as
517 sub/superscript. This can be helpful in documents that need \"_\"
518 frequently in plain text.
520 Not all export backends support this, but HTML does.
522 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
523 :group 'org-startup
524 :group 'org-export-translation
525 :version "24.1"
526 :type '(choice
527 (const :tag "Always interpret" t)
528 (const :tag "Only with braces" {})
529 (const :tag "Never interpret" nil)))
531 (if (fboundp 'defvaralias)
532 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
535 (defcustom org-startup-with-beamer-mode nil
536 "Non-nil means turn on `org-beamer-mode' on startup.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
540 #+STARTUP: beamer"
541 :group 'org-startup
542 :version "24.1"
543 :type 'boolean)
545 (defcustom org-startup-align-all-tables nil
546 "Non-nil means align all tables when visiting a file.
547 This is useful when the column width in tables is forced with <N> cookies
548 in table fields. Such tables will look correct only after the first re-align.
549 This can also be configured on a per-file basis by adding one of
550 the following lines anywhere in the buffer:
551 #+STARTUP: align
552 #+STARTUP: noalign"
553 :group 'org-startup
554 :type 'boolean)
556 (defcustom org-startup-with-inline-images nil
557 "Non-nil means show inline images when loading a new Org file.
558 This can also be configured on a per-file basis by adding one of
559 the following lines anywhere in the buffer:
560 #+STARTUP: inlineimages
561 #+STARTUP: noinlineimages"
562 :group 'org-startup
563 :version "24.1"
564 :type 'boolean)
566 (defcustom org-insert-mode-line-in-empty-file nil
567 "Non-nil means insert the first line setting Org-mode in empty files.
568 When the function `org-mode' is called interactively in an empty file, this
569 normally means that the file name does not automatically trigger Org-mode.
570 To ensure that the file will always be in Org-mode in the future, a
571 line enforcing Org-mode will be inserted into the buffer, if this option
572 has been set."
573 :group 'org-startup
574 :type 'boolean)
576 (defcustom org-replace-disputed-keys nil
577 "Non-nil means use alternative key bindings for some keys.
578 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
579 These keys are also used by other packages like shift-selection-mode'
580 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
581 If you want to use Org-mode together with one of these other modes,
582 or more generally if you would like to move some Org-mode commands to
583 other keys, set this variable and configure the keys with the variable
584 `org-disputed-keys'.
586 This option is only relevant at load-time of Org-mode, and must be set
587 *before* org.el is loaded. Changing it requires a restart of Emacs to
588 become effective."
589 :group 'org-startup
590 :type 'boolean)
592 (defcustom org-use-extra-keys nil
593 "Non-nil means use extra key sequence definitions for certain commands.
594 This happens automatically if you run XEmacs or if `window-system'
595 is nil. This variable lets you do the same manually. You must
596 set it before loading org.
598 Example: on Carbon Emacs 22 running graphically, with an external
599 keyboard on a Powerbook, the default way of setting M-left might
600 not work for either Alt or ESC. Setting this variable will make
601 it work for ESC."
602 :group 'org-startup
603 :type 'boolean)
605 (if (fboundp 'defvaralias)
606 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
608 (defcustom org-disputed-keys
609 '(([(shift up)] . [(meta p)])
610 ([(shift down)] . [(meta n)])
611 ([(shift left)] . [(meta -)])
612 ([(shift right)] . [(meta +)])
613 ([(control shift right)] . [(meta shift +)])
614 ([(control shift left)] . [(meta shift -)]))
615 "Keys for which Org-mode and other modes compete.
616 This is an alist, cars are the default keys, second element specifies
617 the alternative to use when `org-replace-disputed-keys' is t.
619 Keys can be specified in any syntax supported by `define-key'.
620 The value of this option takes effect only at Org-mode's startup,
621 therefore you'll have to restart Emacs to apply it after changing."
622 :group 'org-startup
623 :type 'alist)
625 (defun org-key (key)
626 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
627 Or return the original if not disputed.
628 Also apply the translations defined in `org-xemacs-key-equivalents'."
629 (when org-replace-disputed-keys
630 (let* ((nkey (key-description key))
631 (x (org-find-if (lambda (x)
632 (equal (key-description (car x)) nkey))
633 org-disputed-keys)))
634 (setq key (if x (cdr x) key))))
635 (when (featurep 'xemacs)
636 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
637 key)
639 (defun org-find-if (predicate seq)
640 (catch 'exit
641 (while seq
642 (if (funcall predicate (car seq))
643 (throw 'exit (car seq))
644 (pop seq)))))
646 (defun org-defkey (keymap key def)
647 "Define a key, possibly translated, as returned by `org-key'."
648 (define-key keymap (org-key key) def))
650 (defcustom org-ellipsis nil
651 "The ellipsis to use in the Org-mode outline.
652 When nil, just use the standard three dots. When a string, use that instead,
653 When a face, use the standard 3 dots, but with the specified face.
654 The change affects only Org-mode (which will then use its own display table).
655 Changing this requires executing `M-x org-mode' in a buffer to become
656 effective."
657 :group 'org-startup
658 :type '(choice (const :tag "Default" nil)
659 (face :tag "Face" :value org-warning)
660 (string :tag "String" :value "...#")))
662 (defvar org-display-table nil
663 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
665 (defgroup org-keywords nil
666 "Keywords in Org-mode."
667 :tag "Org Keywords"
668 :group 'org)
670 (defcustom org-deadline-string "DEADLINE:"
671 "String to mark deadline entries.
672 A deadline is this string, followed by a time stamp. Should be a word,
673 terminated by a colon. You can insert a schedule keyword and
674 a timestamp with \\[org-deadline].
675 Changes become only effective after restarting Emacs."
676 :group 'org-keywords
677 :type 'string)
679 (defcustom org-scheduled-string "SCHEDULED:"
680 "String to mark scheduled TODO entries.
681 A schedule is this string, followed by a time stamp. Should be a word,
682 terminated by a colon. You can insert a schedule keyword and
683 a timestamp with \\[org-schedule].
684 Changes become only effective after restarting Emacs."
685 :group 'org-keywords
686 :type 'string)
688 (defcustom org-closed-string "CLOSED:"
689 "String used as the prefix for timestamps logging closing a TODO entry."
690 :group 'org-keywords
691 :type 'string)
693 (defcustom org-clock-string "CLOCK:"
694 "String used as prefix for timestamps clocking work hours on an item."
695 :group 'org-keywords
696 :type 'string)
698 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
699 org-scheduled-string "\\|"
700 org-deadline-string "\\|"
701 org-closed-string "\\|"
702 org-clock-string "\\)")
703 "Matches a line with planning or clock info.")
705 (defcustom org-comment-string "COMMENT"
706 "Entries starting with this keyword will never be exported.
707 An entry can be toggled between COMMENT and normal with
708 \\[org-toggle-comment].
709 Changes become only effective after restarting Emacs."
710 :group 'org-keywords
711 :type 'string)
713 (defcustom org-quote-string "QUOTE"
714 "Entries starting with this keyword will be exported in fixed-width font.
715 Quoting applies only to the text in the entry following the headline, and does
716 not extend beyond the next headline, even if that is lower level.
717 An entry can be toggled between QUOTE and normal with
718 \\[org-toggle-fixed-width-section]."
719 :group 'org-keywords
720 :type 'string)
722 (defconst org-repeat-re
723 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
724 "Regular expression for specifying repeated events.
725 After a match, group 1 contains the repeat expression.")
727 (defgroup org-structure nil
728 "Options concerning the general structure of Org-mode files."
729 :tag "Org Structure"
730 :group 'org)
732 (defgroup org-reveal-location nil
733 "Options about how to make context of a location visible."
734 :tag "Org Reveal Location"
735 :group 'org-structure)
737 (defconst org-context-choice
738 '(choice
739 (const :tag "Always" t)
740 (const :tag "Never" nil)
741 (repeat :greedy t :tag "Individual contexts"
742 (cons
743 (choice :tag "Context"
744 (const agenda)
745 (const org-goto)
746 (const occur-tree)
747 (const tags-tree)
748 (const link-search)
749 (const mark-goto)
750 (const bookmark-jump)
751 (const isearch)
752 (const default))
753 (boolean))))
754 "Contexts for the reveal options.")
756 (defcustom org-show-hierarchy-above '((default . t))
757 "Non-nil means show full hierarchy when revealing a location.
758 Org-mode often shows locations in an org-mode file which might have
759 been invisible before. When this is set, the hierarchy of headings
760 above the exposed location is shown.
761 Turning this off for example for sparse trees makes them very compact.
762 Instead of t, this can also be an alist specifying this option for different
763 contexts. Valid contexts are
764 agenda when exposing an entry from the agenda
765 org-goto when using the command `org-goto' on key C-c C-j
766 occur-tree when using the command `org-occur' on key C-c /
767 tags-tree when constructing a sparse tree based on tags matches
768 link-search when exposing search matches associated with a link
769 mark-goto when exposing the jump goal of a mark
770 bookmark-jump when exposing a bookmark location
771 isearch when exiting from an incremental search
772 default default for all contexts not set explicitly"
773 :group 'org-reveal-location
774 :type org-context-choice)
776 (defcustom org-show-following-heading '((default . nil))
777 "Non-nil means show following heading when revealing a location.
778 Org-mode often shows locations in an org-mode file which might have
779 been invisible before. When this is set, the heading following the
780 match is shown.
781 Turning this off for example for sparse trees makes them very compact,
782 but makes it harder to edit the location of the match. In such a case,
783 use the command \\[org-reveal] to show more context.
784 Instead of t, this can also be an alist specifying this option for different
785 contexts. See `org-show-hierarchy-above' for valid contexts."
786 :group 'org-reveal-location
787 :type org-context-choice)
789 (defcustom org-show-siblings '((default . nil) (isearch t))
790 "Non-nil means show all sibling heading when revealing a location.
791 Org-mode often shows locations in an org-mode file which might have
792 been invisible before. When this is set, the sibling of the current entry
793 heading are all made visible. If `org-show-hierarchy-above' is t,
794 the same happens on each level of the hierarchy above the current entry.
796 By default this is on for the isearch context, off for all other contexts.
797 Turning this off for example for sparse trees makes them very compact,
798 but makes it harder to edit the location of the match. In such a case,
799 use the command \\[org-reveal] to show more context.
800 Instead of t, this can also be an alist specifying this option for different
801 contexts. See `org-show-hierarchy-above' for valid contexts."
802 :group 'org-reveal-location
803 :type org-context-choice)
805 (defcustom org-show-entry-below '((default . nil))
806 "Non-nil means show the entry below a headline when revealing a location.
807 Org-mode often shows locations in an org-mode file which might have
808 been invisible before. When this is set, the text below the headline that is
809 exposed is also shown.
811 By default this is off for all contexts.
812 Instead of t, this can also be an alist specifying this option for different
813 contexts. See `org-show-hierarchy-above' for valid contexts."
814 :group 'org-reveal-location
815 :type org-context-choice)
817 (defcustom org-indirect-buffer-display 'other-window
818 "How should indirect tree buffers be displayed?
819 This applies to indirect buffers created with the commands
820 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
821 Valid values are:
822 current-window Display in the current window
823 other-window Just display in another window.
824 dedicated-frame Create one new frame, and re-use it each time.
825 new-frame Make a new frame each time. Note that in this case
826 previously-made indirect buffers are kept, and you need to
827 kill these buffers yourself."
828 :group 'org-structure
829 :group 'org-agenda-windows
830 :type '(choice
831 (const :tag "In current window" current-window)
832 (const :tag "In current frame, other window" other-window)
833 (const :tag "Each time a new frame" new-frame)
834 (const :tag "One dedicated frame" dedicated-frame)))
836 (defcustom org-use-speed-commands nil
837 "Non-nil means activate single letter commands at beginning of a headline.
838 This may also be a function to test for appropriate locations where speed
839 commands should be active."
840 :group 'org-structure
841 :type '(choice
842 (const :tag "Never" nil)
843 (const :tag "At beginning of headline stars" t)
844 (function)))
846 (defcustom org-speed-commands-user nil
847 "Alist of additional speed commands.
848 This list will be checked before `org-speed-commands-default'
849 when the variable `org-use-speed-commands' is non-nil
850 and when the cursor is at the beginning of a headline.
851 The car if each entry is a string with a single letter, which must
852 be assigned to `self-insert-command' in the global map.
853 The cdr is either a command to be called interactively, a function
854 to be called, or a form to be evaluated.
855 An entry that is just a list with a single string will be interpreted
856 as a descriptive headline that will be added when listing the speed
857 commands in the Help buffer using the `?' speed command."
858 :group 'org-structure
859 :type '(repeat :value ("k" . ignore)
860 (choice :value ("k" . ignore)
861 (list :tag "Descriptive Headline" (string :tag "Headline"))
862 (cons :tag "Letter and Command"
863 (string :tag "Command letter")
864 (choice
865 (function)
866 (sexp))))))
868 (defgroup org-cycle nil
869 "Options concerning visibility cycling in Org-mode."
870 :tag "Org Cycle"
871 :group 'org-structure)
873 (defcustom org-cycle-skip-children-state-if-no-children t
874 "Non-nil means skip CHILDREN state in entries that don't have any."
875 :group 'org-cycle
876 :type 'boolean)
878 (defcustom org-cycle-max-level nil
879 "Maximum level which should still be subject to visibility cycling.
880 Levels higher than this will, for cycling, be treated as text, not a headline.
881 When `org-odd-levels-only' is set, a value of N in this variable actually
882 means 2N-1 stars as the limiting headline.
883 When nil, cycle all levels.
884 Note that the limiting level of cycling is also influenced by
885 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
886 `org-inlinetask-min-level' is, cycling will be limited to levels one less
887 than its value."
888 :group 'org-cycle
889 :type '(choice
890 (const :tag "No limit" nil)
891 (integer :tag "Maximum level")))
893 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
894 "Names of drawers. Drawers are not opened by cycling on the headline above.
895 Drawers only open with a TAB on the drawer line itself. A drawer looks like
896 this:
897 :DRAWERNAME:
898 .....
899 :END:
900 The drawer \"PROPERTIES\" is special for capturing properties through
901 the property API.
903 Drawers can be defined on the per-file basis with a line like:
905 #+DRAWERS: HIDDEN STATE PROPERTIES"
906 :group 'org-structure
907 :group 'org-cycle
908 :type '(repeat (string :tag "Drawer Name")))
910 (defcustom org-hide-block-startup nil
911 "Non-nil means entering Org-mode will fold all blocks.
912 This can also be set in on a per-file basis with
914 #+STARTUP: hideblocks
915 #+STARTUP: showblocks"
916 :group 'org-startup
917 :group 'org-cycle
918 :type 'boolean)
920 (defcustom org-cycle-global-at-bob nil
921 "Cycle globally if cursor is at beginning of buffer and not at a headline.
922 This makes it possible to do global cycling without having to use S-TAB or
923 \\[universal-argument] TAB. For this special case to work, the first line
924 of the buffer must not be a headline -- it may be empty or some other text.
925 When used in this way, `org-cycle-hook' is disabled temporarily to make
926 sure the cursor stays at the beginning of the buffer. When this option is
927 nil, don't do anything special at the beginning of the buffer."
928 :group 'org-cycle
929 :type 'boolean)
931 (defcustom org-cycle-level-after-item/entry-creation t
932 "Non-nil means cycle entry level or item indentation in new empty entries.
934 When the cursor is at the end of an empty headline, i.e., with only stars
935 and maybe a TODO keyword, TAB will then switch the entry to become a child,
936 and then all possible ancestor states, before returning to the original state.
937 This makes data entry extremely fast: M-RET to create a new headline,
938 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
940 When the cursor is at the end of an empty plain list item, one TAB will
941 make it a subitem, two or more tabs will back up to make this an item
942 higher up in the item hierarchy."
943 :group 'org-cycle
944 :type 'boolean)
946 (defcustom org-cycle-emulate-tab t
947 "Where should `org-cycle' emulate TAB.
948 nil Never
949 white Only in completely white lines
950 whitestart Only at the beginning of lines, before the first non-white char
951 t Everywhere except in headlines
952 exc-hl-bol Everywhere except at the start of a headline
953 If TAB is used in a place where it does not emulate TAB, the current subtree
954 visibility is cycled."
955 :group 'org-cycle
956 :type '(choice (const :tag "Never" nil)
957 (const :tag "Only in completely white lines" white)
958 (const :tag "Before first char in a line" whitestart)
959 (const :tag "Everywhere except in headlines" t)
960 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
963 (defcustom org-cycle-separator-lines 2
964 "Number of empty lines needed to keep an empty line between collapsed trees.
965 If you leave an empty line between the end of a subtree and the following
966 headline, this empty line is hidden when the subtree is folded.
967 Org-mode will leave (exactly) one empty line visible if the number of
968 empty lines is equal or larger to the number given in this variable.
969 So the default 2 means at least 2 empty lines after the end of a subtree
970 are needed to produce free space between a collapsed subtree and the
971 following headline.
973 If the number is negative, and the number of empty lines is at least -N,
974 all empty lines are shown.
976 Special case: when 0, never leave empty lines in collapsed view."
977 :group 'org-cycle
978 :type 'integer)
979 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
981 (defcustom org-pre-cycle-hook nil
982 "Hook that is run before visibility cycling is happening.
983 The function(s) in this hook must accept a single argument which indicates
984 the new state that will be set right after running this hook. The
985 argument is a symbol. Before a global state change, it can have the values
986 `overview', `content', or `all'. Before a local state change, it can have
987 the values `folded', `children', or `subtree'."
988 :group 'org-cycle
989 :type 'hook)
991 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
992 org-cycle-hide-drawers
993 org-cycle-show-empty-lines
994 org-optimize-window-after-visibility-change)
995 "Hook that is run after `org-cycle' has changed the buffer visibility.
996 The function(s) in this hook must accept a single argument which indicates
997 the new state that was set by the most recent `org-cycle' command. The
998 argument is a symbol. After a global state change, it can have the values
999 `overview', `contents', or `all'. After a local state change, it can have
1000 the values `folded', `children', or `subtree'."
1001 :group 'org-cycle
1002 :type 'hook)
1004 (defgroup org-edit-structure nil
1005 "Options concerning structure editing in Org-mode."
1006 :tag "Org Edit Structure"
1007 :group 'org-structure)
1009 (defcustom org-odd-levels-only nil
1010 "Non-nil means skip even levels and only use odd levels for the outline.
1011 This has the effect that two stars are being added/taken away in
1012 promotion/demotion commands. It also influences how levels are
1013 handled by the exporters.
1014 Changing it requires restart of `font-lock-mode' to become effective
1015 for fontification also in regions already fontified.
1016 You may also set this on a per-file basis by adding one of the following
1017 lines to the buffer:
1019 #+STARTUP: odd
1020 #+STARTUP: oddeven"
1021 :group 'org-edit-structure
1022 :group 'org-appearance
1023 :type 'boolean)
1025 (defcustom org-adapt-indentation t
1026 "Non-nil means adapt indentation to outline node level.
1028 When this variable is set, Org assumes that you write outlines by
1029 indenting text in each node to align with the headline (after the stars).
1030 The following issues are influenced by this variable:
1032 - When this is set and the *entire* text in an entry is indented, the
1033 indentation is increased by one space in a demotion command, and
1034 decreased by one in a promotion command. If any line in the entry
1035 body starts with text at column 0, indentation is not changed at all.
1037 - Property drawers and planning information is inserted indented when
1038 this variable s set. When nil, they will not be indented.
1040 - TAB indents a line relative to context. The lines below a headline
1041 will be indented when this variable is set.
1043 Note that this is all about true indentation, by adding and removing
1044 space characters. See also `org-indent.el' which does level-dependent
1045 indentation in a virtual way, i.e. at display time in Emacs."
1046 :group 'org-edit-structure
1047 :type 'boolean)
1049 (defcustom org-special-ctrl-a/e nil
1050 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1052 When t, `C-a' will bring back the cursor to the beginning of the
1053 headline text, i.e. after the stars and after a possible TODO
1054 keyword. In an item, this will be the position after bullet and
1055 check-box, if any. When the cursor is already at that position,
1056 another `C-a' will bring it to the beginning of the line.
1058 `C-e' will jump to the end of the headline, ignoring the presence
1059 of tags in the headline. A second `C-e' will then jump to the
1060 true end of the line, after any tags. This also means that, when
1061 this variable is non-nil, `C-e' also will never jump beyond the
1062 end of the heading of a folded section, i.e. not after the
1063 ellipses.
1065 When set to the symbol `reversed', the first `C-a' or `C-e' works
1066 normally, going to the true line boundary first. Only a directly
1067 following, identical keypress will bring the cursor to the
1068 special positions.
1070 This may also be a cons cell where the behavior for `C-a' and
1071 `C-e' is set separately."
1072 :group 'org-edit-structure
1073 :type '(choice
1074 (const :tag "off" nil)
1075 (const :tag "on: after stars/bullet and before tags first" t)
1076 (const :tag "reversed: true line boundary first" reversed)
1077 (cons :tag "Set C-a and C-e separately"
1078 (choice :tag "Special C-a"
1079 (const :tag "off" nil)
1080 (const :tag "on: after stars/bullet first" t)
1081 (const :tag "reversed: before stars/bullet first" reversed))
1082 (choice :tag "Special C-e"
1083 (const :tag "off" nil)
1084 (const :tag "on: before tags first" t)
1085 (const :tag "reversed: after tags first" reversed)))))
1086 (if (fboundp 'defvaralias)
1087 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1089 (defcustom org-special-ctrl-k nil
1090 "Non-nil means `C-k' will behave specially in headlines.
1091 When nil, `C-k' will call the default `kill-line' command.
1092 When t, the following will happen while the cursor is in the headline:
1094 - When the cursor is at the beginning of a headline, kill the entire
1095 line and possible the folded subtree below the line.
1096 - When in the middle of the headline text, kill the headline up to the tags.
1097 - When after the headline text, kill the tags."
1098 :group 'org-edit-structure
1099 :type 'boolean)
1101 (defcustom org-ctrl-k-protect-subtree nil
1102 "Non-nil means, do not delete a hidden subtree with C-k.
1103 When set to the symbol `error', simply throw an error when C-k is
1104 used to kill (part-of) a headline that has hidden text behind it.
1105 Any other non-nil value will result in a query to the user, if it is
1106 OK to kill that hidden subtree. When nil, kill without remorse."
1107 :group 'org-edit-structure
1108 :version "24.1"
1109 :type '(choice
1110 (const :tag "Do not protect hidden subtrees" nil)
1111 (const :tag "Protect hidden subtrees with a security query" t)
1112 (const :tag "Never kill a hidden subtree with C-k" error)))
1114 (defcustom org-catch-invisible-edits nil
1115 "Check if in invisible region before inserting or deleting a character.
1116 Valid values are:
1118 nil Do not check, so just do invisible edits.
1119 error Throw an error and do nothing.
1120 show Make point visible, and do the requested edit.
1121 show-and-error Make point visible, then throw an error and abort the edit.
1122 smart Make point visible, and do insertion/deletion if it is
1123 adjacent to visible text and the change feels predictable.
1124 Never delete a previously invisible character or add in the
1125 middle or right after an invisible region. Basically, this
1126 allows insertion and backward-delete right before ellipses.
1127 FIXME: maybe in this case we should not even show?"
1128 :group 'org-edit-structure
1129 :version "24.1"
1130 :type '(choice
1131 (const :tag "Do not check" nil)
1132 (const :tag "Throw error when trying to edit" error)
1133 (const :tag "Unhide, but do not do the edit" show-and-error)
1134 (const :tag "Show invisible part and do the edit" show)
1135 (const :tag "Be smart and do the right thing" smart)))
1137 (defcustom org-yank-folded-subtrees t
1138 "Non-nil means when yanking subtrees, fold them.
1139 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1140 it starts with a heading and all other headings in it are either children
1141 or siblings, then fold all the subtrees. However, do this only if no
1142 text after the yank would be swallowed into a folded tree by this action."
1143 :group 'org-edit-structure
1144 :type 'boolean)
1146 (defcustom org-yank-adjusted-subtrees nil
1147 "Non-nil means when yanking subtrees, adjust the level.
1148 With this setting, `org-paste-subtree' is used to insert the subtree, see
1149 this function for details."
1150 :group 'org-edit-structure
1151 :type 'boolean)
1153 (defcustom org-M-RET-may-split-line '((default . t))
1154 "Non-nil means M-RET will split the line at the cursor position.
1155 When nil, it will go to the end of the line before making a
1156 new line.
1157 You may also set this option in a different way for different
1158 contexts. Valid contexts are:
1160 headline when creating a new headline
1161 item when creating a new item
1162 table in a table field
1163 default the value to be used for all contexts not explicitly
1164 customized"
1165 :group 'org-structure
1166 :group 'org-table
1167 :type '(choice
1168 (const :tag "Always" t)
1169 (const :tag "Never" nil)
1170 (repeat :greedy t :tag "Individual contexts"
1171 (cons
1172 (choice :tag "Context"
1173 (const headline)
1174 (const item)
1175 (const table)
1176 (const default))
1177 (boolean)))))
1180 (defcustom org-insert-heading-respect-content nil
1181 "Non-nil means insert new headings after the current subtree.
1182 When nil, the new heading is created directly after the current line.
1183 The commands \\[org-insert-heading-respect-content] and
1184 \\[org-insert-todo-heading-respect-content] turn this variable on
1185 for the duration of the command."
1186 :group 'org-structure
1187 :type 'boolean)
1189 (defcustom org-blank-before-new-entry '((heading . auto)
1190 (plain-list-item . auto))
1191 "Should `org-insert-heading' leave a blank line before new heading/item?
1192 The value is an alist, with `heading' and `plain-list-item' as CAR,
1193 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1194 which case Org will look at the surrounding headings/items and try to
1195 make an intelligent decision whether to insert a blank line or not.
1197 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1198 set, the setting here is ignored and no empty line is inserted, to avoid
1199 breaking the list structure."
1200 :group 'org-edit-structure
1201 :type '(list
1202 (cons (const heading)
1203 (choice (const :tag "Never" nil)
1204 (const :tag "Always" t)
1205 (const :tag "Auto" auto)))
1206 (cons (const plain-list-item)
1207 (choice (const :tag "Never" nil)
1208 (const :tag "Always" t)
1209 (const :tag "Auto" auto)))))
1211 (defcustom org-insert-heading-hook nil
1212 "Hook being run after inserting a new heading."
1213 :group 'org-edit-structure
1214 :type 'hook)
1216 (defcustom org-enable-fixed-width-editor t
1217 "Non-nil means lines starting with \":\" are treated as fixed-width.
1218 This currently only means they are never auto-wrapped.
1219 When nil, such lines will be treated like ordinary lines.
1220 See also the QUOTE keyword."
1221 :group 'org-edit-structure
1222 :type 'boolean)
1224 (defcustom org-goto-auto-isearch t
1225 "Non-nil means typing characters in `org-goto' starts incremental search.
1226 When nil, you can use these keybindings to navigate the buffer:
1228 q Quit the org-goto interface
1229 n Go to the next visible heading
1230 p Go to the previous visible heading
1231 f Go one heading forward on same level
1232 b Go one heading backward on same level
1233 u Go one heading up"
1234 :group 'org-edit-structure
1235 :type 'boolean)
1237 (defgroup org-sparse-trees nil
1238 "Options concerning sparse trees in Org-mode."
1239 :tag "Org Sparse Trees"
1240 :group 'org-structure)
1242 (defcustom org-highlight-sparse-tree-matches t
1243 "Non-nil means highlight all matches that define a sparse tree.
1244 The highlights will automatically disappear the next time the buffer is
1245 changed by an edit command."
1246 :group 'org-sparse-trees
1247 :type 'boolean)
1249 (defcustom org-remove-highlights-with-change t
1250 "Non-nil means any change to the buffer will remove temporary highlights.
1251 Such highlights are created by `org-occur' and `org-clock-display'.
1252 When nil, `C-c C-c needs to be used to get rid of the highlights.
1253 The highlights created by `org-preview-latex-fragment' always need
1254 `C-c C-c' to be removed."
1255 :group 'org-sparse-trees
1256 :group 'org-time
1257 :type 'boolean)
1260 (defcustom org-occur-hook '(org-first-headline-recenter)
1261 "Hook that is run after `org-occur' has constructed a sparse tree.
1262 This can be used to recenter the window to show as much of the structure
1263 as possible."
1264 :group 'org-sparse-trees
1265 :type 'hook)
1267 (defgroup org-imenu-and-speedbar nil
1268 "Options concerning imenu and speedbar in Org-mode."
1269 :tag "Org Imenu and Speedbar"
1270 :group 'org-structure)
1272 (defcustom org-imenu-depth 2
1273 "The maximum level for Imenu access to Org-mode headlines.
1274 This also applied for speedbar access."
1275 :group 'org-imenu-and-speedbar
1276 :type 'integer)
1278 (defgroup org-table nil
1279 "Options concerning tables in Org-mode."
1280 :tag "Org Table"
1281 :group 'org)
1283 (defcustom org-enable-table-editor 'optimized
1284 "Non-nil means lines starting with \"|\" are handled by the table editor.
1285 When nil, such lines will be treated like ordinary lines.
1287 When equal to the symbol `optimized', the table editor will be optimized to
1288 do the following:
1289 - Automatic overwrite mode in front of whitespace in table fields.
1290 This makes the structure of the table stay in tact as long as the edited
1291 field does not exceed the column width.
1292 - Minimize the number of realigns. Normally, the table is aligned each time
1293 TAB or RET are pressed to move to another field. With optimization this
1294 happens only if changes to a field might have changed the column width.
1295 Optimization requires replacing the functions `self-insert-command',
1296 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1297 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1298 very good at guessing when a re-align will be necessary, but you can always
1299 force one with \\[org-ctrl-c-ctrl-c].
1301 If you would like to use the optimized version in Org-mode, but the
1302 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1304 This variable can be used to turn on and off the table editor during a session,
1305 but in order to toggle optimization, a restart is required.
1307 See also the variable `org-table-auto-blank-field'."
1308 :group 'org-table
1309 :type '(choice
1310 (const :tag "off" nil)
1311 (const :tag "on" t)
1312 (const :tag "on, optimized" optimized)))
1314 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1315 (version<= emacs-version "24.1"))
1316 "Non-nil means cluster self-insert commands for undo when possible.
1317 If this is set, then, like in the Emacs command loop, 20 consecutive
1318 characters will be undone together.
1319 This is configurable, because there is some impact on typing performance."
1320 :group 'org-table
1321 :type 'boolean)
1323 (defcustom org-table-tab-recognizes-table.el t
1324 "Non-nil means TAB will automatically notice a table.el table.
1325 When it sees such a table, it moves point into it and - if necessary -
1326 calls `table-recognize-table'."
1327 :group 'org-table-editing
1328 :type 'boolean)
1330 (defgroup org-link nil
1331 "Options concerning links in Org-mode."
1332 :tag "Org Link"
1333 :group 'org)
1335 (defvar org-link-abbrev-alist-local nil
1336 "Buffer-local version of `org-link-abbrev-alist', which see.
1337 The value of this is taken from the #+LINK lines.")
1338 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1340 (defcustom org-link-abbrev-alist nil
1341 "Alist of link abbreviations.
1342 The car of each element is a string, to be replaced at the start of a link.
1343 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1344 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1346 [[linkkey:tag][description]]
1348 The 'linkkey' must be a word word, starting with a letter, followed
1349 by letters, numbers, '-' or '_'.
1351 If REPLACE is a string, the tag will simply be appended to create the link.
1352 If the string contains \"%s\", the tag will be inserted there. If the string
1353 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1354 at that point (see the function `url-hexify-string'). If the string contains
1355 the specifier \"%(my-function)\", then the custom function `my-function' will
1356 be invoked: this function takes the tag as its only argument and must return
1357 a string.
1359 REPLACE may also be a function that will be called with the tag as the
1360 only argument to create the link, which should be returned as a string.
1362 See the manual for examples."
1363 :group 'org-link
1364 :type '(repeat
1365 (cons
1366 (string :tag "Protocol")
1367 (choice
1368 (string :tag "Format")
1369 (function)))))
1371 (defcustom org-descriptive-links t
1372 "Non-nil means Org will display descriptive links.
1373 E.g. [[http://orgmode.org][Org website]] will be displayed as
1374 \"Org Website\", hiding the link itself and just displaying its
1375 description. When set to `nil', Org will display the full links
1376 literally.
1378 You can interactively set the value of this variable by calling
1379 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1380 :group 'org-link
1381 :type 'boolean)
1383 (defcustom org-link-file-path-type 'adaptive
1384 "How the path name in file links should be stored.
1385 Valid values are:
1387 relative Relative to the current directory, i.e. the directory of the file
1388 into which the link is being inserted.
1389 absolute Absolute path, if possible with ~ for home directory.
1390 noabbrev Absolute path, no abbreviation of home directory.
1391 adaptive Use relative path for files in the current directory and sub-
1392 directories of it. For other files, use an absolute path."
1393 :group 'org-link
1394 :type '(choice
1395 (const relative)
1396 (const absolute)
1397 (const noabbrev)
1398 (const adaptive)))
1400 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1401 "Types of links that should be activated in Org-mode files.
1402 This is a list of symbols, each leading to the activation of a certain link
1403 type. In principle, it does not hurt to turn on most link types - there may
1404 be a small gain when turning off unused link types. The types are:
1406 bracket The recommended [[link][description]] or [[link]] links with hiding.
1407 angle Links in angular brackets that may contain whitespace like
1408 <bbdb:Carsten Dominik>.
1409 plain Plain links in normal text, no whitespace, like http://google.com.
1410 radio Text that is matched by a radio target, see manual for details.
1411 tag Tag settings in a headline (link to tag search).
1412 date Time stamps (link to calendar).
1413 footnote Footnote labels.
1415 Changing this variable requires a restart of Emacs to become effective."
1416 :group 'org-link
1417 :type '(set :greedy t
1418 (const :tag "Double bracket links" bracket)
1419 (const :tag "Angular bracket links" angle)
1420 (const :tag "Plain text links" plain)
1421 (const :tag "Radio target matches" radio)
1422 (const :tag "Tags" tag)
1423 (const :tag "Timestamps" date)
1424 (const :tag "Footnotes" footnote)))
1426 (defcustom org-make-link-description-function nil
1427 "Function to use for generating link descriptions from links.
1428 When nil, the link location will be used. This function must take
1429 two parameters: the first one is the link, the second one is the
1430 description generated by `org-insert-link'. The function should
1431 return the description to use."
1432 :group 'org-link
1433 :type 'function)
1435 (defgroup org-link-store nil
1436 "Options concerning storing links in Org-mode."
1437 :tag "Org Store Link"
1438 :group 'org-link)
1440 (defcustom org-url-hexify-p t
1441 "When non-nil, hexify URL when creating a link."
1442 :type 'boolean
1443 :version "24.3"
1444 :group 'org-link-store)
1446 (defcustom org-email-link-description-format "Email %c: %.30s"
1447 "Format of the description part of a link to an email or usenet message.
1448 The following %-escapes will be replaced by corresponding information:
1450 %F full \"From\" field
1451 %f name, taken from \"From\" field, address if no name
1452 %T full \"To\" field
1453 %t first name in \"To\" field, address if no name
1454 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1455 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1456 %s subject
1457 %d date
1458 %m message-id.
1460 You may use normal field width specification between the % and the letter.
1461 This is for example useful to limit the length of the subject.
1463 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1464 :group 'org-link-store
1465 :type 'string)
1467 (defcustom org-from-is-user-regexp
1468 (let (r1 r2)
1469 (when (and user-mail-address (not (string= user-mail-address "")))
1470 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1471 (when (and user-full-name (not (string= user-full-name "")))
1472 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1473 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1474 "Regexp matched against the \"From:\" header of an email or usenet message.
1475 It should match if the message is from the user him/herself."
1476 :group 'org-link-store
1477 :type 'regexp)
1479 (defcustom org-context-in-file-links t
1480 "Non-nil means file links from `org-store-link' contain context.
1481 A search string will be added to the file name with :: as separator and
1482 used to find the context when the link is activated by the command
1483 `org-open-at-point'. When this option is t, the entire active region
1484 will be placed in the search string of the file link. If set to a
1485 positive integer, only the first n lines of context will be stored.
1487 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1488 negates this setting for the duration of the command."
1489 :group 'org-link-store
1490 :type '(choice boolean integer))
1492 (defcustom org-keep-stored-link-after-insertion nil
1493 "Non-nil means keep link in list for entire session.
1495 The command `org-store-link' adds a link pointing to the current
1496 location to an internal list. These links accumulate during a session.
1497 The command `org-insert-link' can be used to insert links into any
1498 Org-mode file (offering completion for all stored links). When this
1499 option is nil, every link which has been inserted once using \\[org-insert-link]
1500 will be removed from the list, to make completing the unused links
1501 more efficient."
1502 :group 'org-link-store
1503 :type 'boolean)
1505 (defgroup org-link-follow nil
1506 "Options concerning following links in Org-mode."
1507 :tag "Org Follow Link"
1508 :group 'org-link)
1510 (defcustom org-link-translation-function nil
1511 "Function to translate links with different syntax to Org syntax.
1512 This can be used to translate links created for example by the Planner
1513 or emacs-wiki packages to Org syntax.
1514 The function must accept two parameters, a TYPE containing the link
1515 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1516 which is everything after the link protocol. It should return a cons
1517 with possibly modified values of type and path.
1518 Org contains a function for this, so if you set this variable to
1519 `org-translate-link-from-planner', you should be able follow many
1520 links created by planner."
1521 :group 'org-link-follow
1522 :type 'function)
1524 (defcustom org-follow-link-hook nil
1525 "Hook that is run after a link has been followed."
1526 :group 'org-link-follow
1527 :type 'hook)
1529 (defcustom org-tab-follows-link nil
1530 "Non-nil means on links TAB will follow the link.
1531 Needs to be set before org.el is loaded.
1532 This really should not be used, it does not make sense, and the
1533 implementation is bad."
1534 :group 'org-link-follow
1535 :type 'boolean)
1537 (defcustom org-return-follows-link nil
1538 "Non-nil means on links RET will follow the link."
1539 :group 'org-link-follow
1540 :type 'boolean)
1542 (defcustom org-mouse-1-follows-link
1543 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1544 "Non-nil means mouse-1 on a link will follow the link.
1545 A longer mouse click will still set point. Does not work on XEmacs.
1546 Needs to be set before org.el is loaded."
1547 :group 'org-link-follow
1548 :type 'boolean)
1550 (defcustom org-mark-ring-length 4
1551 "Number of different positions to be recorded in the ring.
1552 Changing this requires a restart of Emacs to work correctly."
1553 :group 'org-link-follow
1554 :type 'integer)
1556 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1557 "Non-nil means internal links in Org files must exactly match a headline.
1558 When nil, the link search tries to match a phrase with all words
1559 in the search text."
1560 :group 'org-link-follow
1561 :version "24.1"
1562 :type '(choice
1563 (const :tag "Use fuzzy text search" nil)
1564 (const :tag "Match only exact headline" t)
1565 (const :tag "Match exact headline or query to create it"
1566 query-to-create)))
1568 (defcustom org-link-frame-setup
1569 '((vm . vm-visit-folder-other-frame)
1570 (vm-imap . vm-visit-imap-folder-other-frame)
1571 (gnus . org-gnus-no-new-news)
1572 (file . find-file-other-window)
1573 (wl . wl-other-frame))
1574 "Setup the frame configuration for following links.
1575 When following a link with Emacs, it may often be useful to display
1576 this link in another window or frame. This variable can be used to
1577 set this up for the different types of links.
1578 For VM, use any of
1579 `vm-visit-folder'
1580 `vm-visit-folder-other-window'
1581 `vm-visit-folder-other-frame'
1582 For Gnus, use any of
1583 `gnus'
1584 `gnus-other-frame'
1585 `org-gnus-no-new-news'
1586 For FILE, use any of
1587 `find-file'
1588 `find-file-other-window'
1589 `find-file-other-frame'
1590 For Wanderlust use any of
1591 `wl'
1592 `wl-other-frame'
1593 For the calendar, use the variable `calendar-setup'.
1594 For BBDB, it is currently only possible to display the matches in
1595 another window."
1596 :group 'org-link-follow
1597 :type '(list
1598 (cons (const vm)
1599 (choice
1600 (const vm-visit-folder)
1601 (const vm-visit-folder-other-window)
1602 (const vm-visit-folder-other-frame)))
1603 (cons (const gnus)
1604 (choice
1605 (const gnus)
1606 (const gnus-other-frame)
1607 (const org-gnus-no-new-news)))
1608 (cons (const file)
1609 (choice
1610 (const find-file)
1611 (const find-file-other-window)
1612 (const find-file-other-frame)))
1613 (cons (const wl)
1614 (choice
1615 (const wl)
1616 (const wl-other-frame)))))
1618 (defcustom org-display-internal-link-with-indirect-buffer nil
1619 "Non-nil means use indirect buffer to display infile links.
1620 Activating internal links (from one location in a file to another location
1621 in the same file) normally just jumps to the location. When the link is
1622 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1623 is displayed in
1624 another window. When this option is set, the other window actually displays
1625 an indirect buffer clone of the current buffer, to avoid any visibility
1626 changes to the current buffer."
1627 :group 'org-link-follow
1628 :type 'boolean)
1630 (defcustom org-open-non-existing-files nil
1631 "Non-nil means `org-open-file' will open non-existing files.
1632 When nil, an error will be generated.
1633 This variable applies only to external applications because they
1634 might choke on non-existing files. If the link is to a file that
1635 will be opened in Emacs, the variable is ignored."
1636 :group 'org-link-follow
1637 :type 'boolean)
1639 (defcustom org-open-directory-means-index-dot-org nil
1640 "Non-nil means a link to a directory really means to index.org.
1641 When nil, following a directory link will run dired or open a finder/explorer
1642 window on that directory."
1643 :group 'org-link-follow
1644 :type 'boolean)
1646 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1647 "Function and arguments to call for following mailto links.
1648 This is a list with the first element being a Lisp function, and the
1649 remaining elements being arguments to the function. In string arguments,
1650 %a will be replaced by the address, and %s will be replaced by the subject
1651 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1652 :group 'org-link-follow
1653 :type '(choice
1654 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1655 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1656 (const :tag "message-mail" (message-mail "%a" "%s"))
1657 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1659 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1660 "Non-nil means ask for confirmation before executing shell links.
1661 Shell links can be dangerous: just think about a link
1663 [[shell:rm -rf ~/*][Google Search]]
1665 This link would show up in your Org-mode document as \"Google Search\",
1666 but really it would remove your entire home directory.
1667 Therefore we advise against setting this variable to nil.
1668 Just change it to `y-or-n-p' if you want to confirm with a
1669 single keystroke rather than having to type \"yes\"."
1670 :group 'org-link-follow
1671 :type '(choice
1672 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1673 (const :tag "with y-or-n (faster)" y-or-n-p)
1674 (const :tag "no confirmation (dangerous)" nil)))
1675 (put 'org-confirm-shell-link-function
1676 'safe-local-variable
1677 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1679 (defcustom org-confirm-shell-link-not-regexp ""
1680 "A regexp to skip confirmation for shell links."
1681 :group 'org-link-follow
1682 :version "24.1"
1683 :type 'regexp)
1685 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1686 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1687 Elisp links can be dangerous: just think about a link
1689 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1691 This link would show up in your Org-mode document as \"Google Search\",
1692 but really it would remove your entire home directory.
1693 Therefore we advise against setting this variable to nil.
1694 Just change it to `y-or-n-p' if you want to confirm with a
1695 single keystroke rather than having to type \"yes\"."
1696 :group 'org-link-follow
1697 :type '(choice
1698 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1699 (const :tag "with y-or-n (faster)" y-or-n-p)
1700 (const :tag "no confirmation (dangerous)" nil)))
1701 (put 'org-confirm-shell-link-function
1702 'safe-local-variable
1703 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1705 (defcustom org-confirm-elisp-link-not-regexp ""
1706 "A regexp to skip confirmation for Elisp links."
1707 :group 'org-link-follow
1708 :version "24.1"
1709 :type 'regexp)
1711 (defconst org-file-apps-defaults-gnu
1712 '((remote . emacs)
1713 (system . mailcap)
1714 (t . mailcap))
1715 "Default file applications on a UNIX or GNU/Linux system.
1716 See `org-file-apps'.")
1718 (defconst org-file-apps-defaults-macosx
1719 '((remote . emacs)
1720 (t . "open %s")
1721 (system . "open %s")
1722 ("ps.gz" . "gv %s")
1723 ("eps.gz" . "gv %s")
1724 ("dvi" . "xdvi %s")
1725 ("fig" . "xfig %s"))
1726 "Default file applications on a MacOS X system.
1727 The system \"open\" is known as a default, but we use X11 applications
1728 for some files for which the OS does not have a good default.
1729 See `org-file-apps'.")
1731 (defconst org-file-apps-defaults-windowsnt
1732 (list
1733 '(remote . emacs)
1734 (cons t
1735 (list (if (featurep 'xemacs)
1736 'mswindows-shell-execute
1737 'w32-shell-execute)
1738 "open" 'file))
1739 (cons 'system
1740 (list (if (featurep 'xemacs)
1741 'mswindows-shell-execute
1742 'w32-shell-execute)
1743 "open" 'file)))
1744 "Default file applications on a Windows NT system.
1745 The system \"open\" is used for most files.
1746 See `org-file-apps'.")
1748 (defcustom org-file-apps
1750 (auto-mode . emacs)
1751 ("\\.mm\\'" . default)
1752 ("\\.x?html?\\'" . default)
1753 ("\\.pdf\\'" . default)
1755 "External applications for opening `file:path' items in a document.
1756 Org-mode uses system defaults for different file types, but
1757 you can use this variable to set the application for a given file
1758 extension. The entries in this list are cons cells where the car identifies
1759 files and the cdr the corresponding command. Possible values for the
1760 file identifier are
1761 \"string\" A string as a file identifier can be interpreted in different
1762 ways, depending on its contents:
1764 - Alphanumeric characters only:
1765 Match links with this file extension.
1766 Example: (\"pdf\" . \"evince %s\")
1767 to open PDFs with evince.
1769 - Regular expression: Match links where the
1770 filename matches the regexp. If you want to
1771 use groups here, use shy groups.
1773 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1774 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1775 to open *.html and *.xhtml with firefox.
1777 - Regular expression which contains (non-shy) groups:
1778 Match links where the whole link, including \"::\", and
1779 anything after that, matches the regexp.
1780 In a custom command string, %1, %2, etc. are replaced with
1781 the parts of the link that were matched by the groups.
1782 For backwards compatibility, if a command string is given
1783 that does not use any of the group matches, this case is
1784 handled identically to the second one (i.e. match against
1785 file name only).
1786 In a custom lisp form, you can access the group matches with
1787 (match-string n link).
1789 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1790 to open [[file:document.pdf::5]] with evince at page 5.
1792 `directory' Matches a directory
1793 `remote' Matches a remote file, accessible through tramp or efs.
1794 Remote files most likely should be visited through Emacs
1795 because external applications cannot handle such paths.
1796 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1797 so all files Emacs knows how to handle. Using this with
1798 command `emacs' will open most files in Emacs. Beware that this
1799 will also open html files inside Emacs, unless you add
1800 (\"html\" . default) to the list as well.
1801 t Default for files not matched by any of the other options.
1802 `system' The system command to open files, like `open' on Windows
1803 and Mac OS X, and mailcap under GNU/Linux. This is the command
1804 that will be selected if you call `C-c C-o' with a double
1805 \\[universal-argument] \\[universal-argument] prefix.
1807 Possible values for the command are:
1808 `emacs' The file will be visited by the current Emacs process.
1809 `default' Use the default application for this file type, which is the
1810 association for t in the list, most likely in the system-specific
1811 part.
1812 This can be used to overrule an unwanted setting in the
1813 system-specific variable.
1814 `system' Use the system command for opening files, like \"open\".
1815 This command is specified by the entry whose car is `system'.
1816 Most likely, the system-specific version of this variable
1817 does define this command, but you can overrule/replace it
1818 here.
1819 string A command to be executed by a shell; %s will be replaced
1820 by the path to the file.
1821 sexp A Lisp form which will be evaluated. The file path will
1822 be available in the Lisp variable `file'.
1823 For more examples, see the system specific constants
1824 `org-file-apps-defaults-macosx'
1825 `org-file-apps-defaults-windowsnt'
1826 `org-file-apps-defaults-gnu'."
1827 :group 'org-link-follow
1828 :type '(repeat
1829 (cons (choice :value ""
1830 (string :tag "Extension")
1831 (const :tag "System command to open files" system)
1832 (const :tag "Default for unrecognized files" t)
1833 (const :tag "Remote file" remote)
1834 (const :tag "Links to a directory" directory)
1835 (const :tag "Any files that have Emacs modes"
1836 auto-mode))
1837 (choice :value ""
1838 (const :tag "Visit with Emacs" emacs)
1839 (const :tag "Use default" default)
1840 (const :tag "Use the system command" system)
1841 (string :tag "Command")
1842 (sexp :tag "Lisp form")))))
1844 (defcustom org-doi-server-url "http://dx.doi.org/"
1845 "The URL of the DOI server."
1846 :type 'string
1847 :version "24.3"
1848 :group 'org-link-follow)
1850 (defgroup org-refile nil
1851 "Options concerning refiling entries in Org-mode."
1852 :tag "Org Refile"
1853 :group 'org)
1855 (defcustom org-directory "~/org"
1856 "Directory with org files.
1857 This is just a default location to look for Org files. There is no need
1858 at all to put your files into this directory. It is only used in the
1859 following situations:
1861 1. When a capture template specifies a target file that is not an
1862 absolute path. The path will then be interpreted relative to
1863 `org-directory'
1864 2. When a capture note is filed away in an interactive way (when exiting the
1865 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1866 with `org-directory' as the default path."
1867 :group 'org-refile
1868 :group 'org-remember
1869 :group 'org-capture
1870 :type 'directory)
1872 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1873 "Default target for storing notes.
1874 Used as a fall back file for org-remember.el and org-capture.el, for
1875 templates that do not specify a target file."
1876 :group 'org-refile
1877 :group 'org-remember
1878 :group 'org-capture
1879 :type '(choice
1880 (const :tag "Default from remember-data-file" nil)
1881 file))
1883 (defcustom org-goto-interface 'outline
1884 "The default interface to be used for `org-goto'.
1885 Allowed values are:
1886 outline The interface shows an outline of the relevant file
1887 and the correct heading is found by moving through
1888 the outline or by searching with incremental search.
1889 outline-path-completion Headlines in the current buffer are offered via
1890 completion. This is the interface also used by
1891 the refile command."
1892 :group 'org-refile
1893 :type '(choice
1894 (const :tag "Outline" outline)
1895 (const :tag "Outline-path-completion" outline-path-completion)))
1897 (defcustom org-goto-max-level 5
1898 "Maximum target level when running `org-goto' with refile interface."
1899 :group 'org-refile
1900 :type 'integer)
1902 (defcustom org-reverse-note-order nil
1903 "Non-nil means store new notes at the beginning of a file or entry.
1904 When nil, new notes will be filed to the end of a file or entry.
1905 This can also be a list with cons cells of regular expressions that
1906 are matched against file names, and values."
1907 :group 'org-remember
1908 :group 'org-capture
1909 :group 'org-refile
1910 :type '(choice
1911 (const :tag "Reverse always" t)
1912 (const :tag "Reverse never" nil)
1913 (repeat :tag "By file name regexp"
1914 (cons regexp boolean))))
1916 (defcustom org-log-refile nil
1917 "Information to record when a task is refiled.
1919 Possible values are:
1921 nil Don't add anything
1922 time Add a time stamp to the task
1923 note Prompt for a note and add it with template `org-log-note-headings'
1925 This option can also be set with on a per-file-basis with
1927 #+STARTUP: nologrefile
1928 #+STARTUP: logrefile
1929 #+STARTUP: lognoterefile
1931 You can have local logging settings for a subtree by setting the LOGGING
1932 property to one or more of these keywords.
1934 When bulk-refiling from the agenda, the value `note' is forbidden and
1935 will temporarily be changed to `time'."
1936 :group 'org-refile
1937 :group 'org-progress
1938 :version "24.1"
1939 :type '(choice
1940 (const :tag "No logging" nil)
1941 (const :tag "Record timestamp" time)
1942 (const :tag "Record timestamp with note." note)))
1944 (defcustom org-refile-targets nil
1945 "Targets for refiling entries with \\[org-refile].
1946 This is a list of cons cells. Each cell contains:
1947 - a specification of the files to be considered, either a list of files,
1948 or a symbol whose function or variable value will be used to retrieve
1949 a file name or a list of file names. If you use `org-agenda-files' for
1950 that, all agenda files will be scanned for targets. Nil means consider
1951 headings in the current buffer.
1952 - A specification of how to find candidate refile targets. This may be
1953 any of:
1954 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1955 This tag has to be present in all target headlines, inheritance will
1956 not be considered.
1957 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1958 todo keyword.
1959 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1960 headlines that are refiling targets.
1961 - a cons cell (:level . N). Any headline of level N is considered 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.
1964 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1965 Note that, when `org-odd-levels-only' is set, level corresponds to
1966 order in hierarchy, not to the number of stars.
1968 Each element of this list generates a set of possible targets.
1969 The union of these sets is presented (with completion) to
1970 the user by `org-refile'.
1972 You can set the variable `org-refile-target-verify-function' to a function
1973 to verify each headline found by the simple criteria above.
1975 When this variable is nil, all top-level headlines in the current buffer
1976 are used, equivalent to the value `((nil . (:level . 1))'."
1977 :group 'org-refile
1978 :type '(repeat
1979 (cons
1980 (choice :value org-agenda-files
1981 (const :tag "All agenda files" org-agenda-files)
1982 (const :tag "Current buffer" nil)
1983 (function) (variable) (file))
1984 (choice :tag "Identify target headline by"
1985 (cons :tag "Specific tag" (const :value :tag) (string))
1986 (cons :tag "TODO keyword" (const :value :todo) (string))
1987 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1988 (cons :tag "Level number" (const :value :level) (integer))
1989 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1991 (defcustom org-refile-target-verify-function nil
1992 "Function to verify if the headline at point should be a refile target.
1993 The function will be called without arguments, with point at the
1994 beginning of the headline. It should return t and leave point
1995 where it is if the headline is a valid target for refiling.
1997 If the target should not be selected, the function must return nil.
1998 In addition to this, it may move point to a place from where the search
1999 should be continued. For example, the function may decide that the entire
2000 subtree of the current entry should be excluded and move point to the end
2001 of the subtree."
2002 :group 'org-refile
2003 :type 'function)
2005 (defcustom org-refile-use-cache nil
2006 "Non-nil means cache refile targets to speed up the process.
2007 The cache for a particular file will be updated automatically when
2008 the buffer has been killed, or when any of the marker used for flagging
2009 refile targets no longer points at a live buffer.
2010 If you have added new entries to a buffer that might themselves be targets,
2011 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2012 find that easier, `C-u C-u C-u C-c C-w'."
2013 :group 'org-refile
2014 :version "24.1"
2015 :type 'boolean)
2017 (defcustom org-refile-use-outline-path nil
2018 "Non-nil means provide refile targets as paths.
2019 So a level 3 headline will be available as level1/level2/level3.
2021 When the value is `file', also include the file name (without directory)
2022 into the path. In this case, you can also stop the completion after
2023 the file name, to get entries inserted as top level in the file.
2025 When `full-file-path', include the full file path."
2026 :group 'org-refile
2027 :type '(choice
2028 (const :tag "Not" nil)
2029 (const :tag "Yes" t)
2030 (const :tag "Start with file name" file)
2031 (const :tag "Start with full file path" full-file-path)))
2033 (defcustom org-outline-path-complete-in-steps t
2034 "Non-nil means complete the outline path in hierarchical steps.
2035 When Org-mode uses the refile interface to select an outline path
2036 \(see variable `org-refile-use-outline-path'), the completion of
2037 the path can be done is a single go, or if can be done in steps down
2038 the headline hierarchy. Going in steps is probably the best if you
2039 do not use a special completion package like `ido' or `icicles'.
2040 However, when using these packages, going in one step can be very
2041 fast, while still showing the whole path to the entry."
2042 :group 'org-refile
2043 :type 'boolean)
2045 (defcustom org-refile-allow-creating-parent-nodes nil
2046 "Non-nil means allow to create new nodes as refile targets.
2047 New nodes are then created by adding \"/new node name\" to the completion
2048 of an existing node. When the value of this variable is `confirm',
2049 new node creation must be confirmed by the user (recommended)
2050 When nil, the completion must match an existing entry.
2052 Note that, if the new heading is not seen by the criteria
2053 listed in `org-refile-targets', multiple instances of the same
2054 heading would be created by trying again to file under the new
2055 heading."
2056 :group 'org-refile
2057 :type '(choice
2058 (const :tag "Never" nil)
2059 (const :tag "Always" t)
2060 (const :tag "Prompt for confirmation" confirm)))
2062 (defcustom org-refile-active-region-within-subtree nil
2063 "Non-nil means also refile active region within a subtree.
2065 By default `org-refile' doesn't allow refiling regions if they
2066 don't contain a set of subtrees, but it might be convenient to
2067 do so sometimes: in that case, the first line of the region is
2068 converted to a headline before refiling."
2069 :group 'org-refile
2070 :version "24.1"
2071 :type 'boolean)
2073 (defgroup org-todo nil
2074 "Options concerning TODO items in Org-mode."
2075 :tag "Org TODO"
2076 :group 'org)
2078 (defgroup org-progress nil
2079 "Options concerning Progress logging in Org-mode."
2080 :tag "Org Progress"
2081 :group 'org-time)
2083 (defvar org-todo-interpretation-widgets
2084 '((:tag "Sequence (cycling hits every state)" sequence)
2085 (:tag "Type (cycling directly to DONE)" type))
2086 "The available interpretation symbols for customizing `org-todo-keywords'.
2087 Interested libraries should add to this list.")
2089 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2090 "List of TODO entry keyword sequences and their interpretation.
2091 \\<org-mode-map>This is a list of sequences.
2093 Each sequence starts with a symbol, either `sequence' or `type',
2094 indicating if the keywords should be interpreted as a sequence of
2095 action steps, or as different types of TODO items. The first
2096 keywords are states requiring action - these states will select a headline
2097 for inclusion into the global TODO list Org-mode produces. If one of
2098 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2099 signify that no further action is necessary. If \"|\" is not found,
2100 the last keyword is treated as the only DONE state of the sequence.
2102 The command \\[org-todo] cycles an entry through these states, and one
2103 additional state where no keyword is present. For details about this
2104 cycling, see the manual.
2106 TODO keywords and interpretation can also be set on a per-file basis with
2107 the special #+SEQ_TODO and #+TYP_TODO lines.
2109 Each keyword can optionally specify a character for fast state selection
2110 \(in combination with the variable `org-use-fast-todo-selection')
2111 and specifiers for state change logging, using the same syntax that
2112 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2113 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2114 indicates to record a time stamp each time this state is selected.
2116 Each keyword may also specify if a timestamp or a note should be
2117 recorded when entering or leaving the state, by adding additional
2118 characters in the parenthesis after the keyword. This looks like this:
2119 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2120 record only the time of the state change. With X and Y being either
2121 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2122 Y when leaving the state if and only if the *target* state does not
2123 define X. You may omit any of the fast-selection key or X or /Y,
2124 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2126 For backward compatibility, this variable may also be just a list
2127 of keywords. In this case the interpretation (sequence or type) will be
2128 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2129 :group 'org-todo
2130 :group 'org-keywords
2131 :type '(choice
2132 (repeat :tag "Old syntax, just keywords"
2133 (string :tag "Keyword"))
2134 (repeat :tag "New syntax"
2135 (cons
2136 (choice
2137 :tag "Interpretation"
2138 ;;Quick and dirty way to see
2139 ;;`org-todo-interpretations'. This takes the
2140 ;;place of item arguments
2141 :convert-widget
2142 (lambda (widget)
2143 (widget-put widget
2144 :args (mapcar
2145 #'(lambda (x)
2146 (widget-convert
2147 (cons 'const x)))
2148 org-todo-interpretation-widgets))
2149 widget))
2150 (repeat
2151 (string :tag "Keyword"))))))
2153 (defvar org-todo-keywords-1 nil
2154 "All TODO and DONE keywords active in a buffer.")
2155 (make-variable-buffer-local 'org-todo-keywords-1)
2156 (defvar org-todo-keywords-for-agenda nil)
2157 (defvar org-done-keywords-for-agenda nil)
2158 (defvar org-drawers-for-agenda nil)
2159 (defvar org-todo-keyword-alist-for-agenda nil)
2160 (defvar org-tag-alist-for-agenda nil)
2161 (defvar org-agenda-contributing-files nil)
2162 (defvar org-not-done-keywords nil)
2163 (make-variable-buffer-local 'org-not-done-keywords)
2164 (defvar org-done-keywords nil)
2165 (make-variable-buffer-local 'org-done-keywords)
2166 (defvar org-todo-heads nil)
2167 (make-variable-buffer-local 'org-todo-heads)
2168 (defvar org-todo-sets nil)
2169 (make-variable-buffer-local 'org-todo-sets)
2170 (defvar org-todo-log-states nil)
2171 (make-variable-buffer-local 'org-todo-log-states)
2172 (defvar org-todo-kwd-alist nil)
2173 (make-variable-buffer-local 'org-todo-kwd-alist)
2174 (defvar org-todo-key-alist nil)
2175 (make-variable-buffer-local 'org-todo-key-alist)
2176 (defvar org-todo-key-trigger nil)
2177 (make-variable-buffer-local 'org-todo-key-trigger)
2179 (defcustom org-todo-interpretation 'sequence
2180 "Controls how TODO keywords are interpreted.
2181 This variable is in principle obsolete and is only used for
2182 backward compatibility, if the interpretation of todo keywords is
2183 not given already in `org-todo-keywords'. See that variable for
2184 more information."
2185 :group 'org-todo
2186 :group 'org-keywords
2187 :type '(choice (const sequence)
2188 (const type)))
2190 (defcustom org-use-fast-todo-selection t
2191 "Non-nil means use the fast todo selection scheme with C-c C-t.
2192 This variable describes if and under what circumstances the cycling
2193 mechanism for TODO keywords will be replaced by a single-key, direct
2194 selection scheme.
2196 When nil, fast selection is never used.
2198 When the symbol `prefix', it will be used when `org-todo' is called
2199 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2200 `C-u t' in an agenda buffer.
2202 When t, fast selection is used by default. In this case, the prefix
2203 argument forces cycling instead.
2205 In all cases, the special interface is only used if access keys have
2206 actually been assigned by the user, i.e. if keywords in the configuration
2207 are followed by a letter in parenthesis, like TODO(t)."
2208 :group 'org-todo
2209 :type '(choice
2210 (const :tag "Never" nil)
2211 (const :tag "By default" t)
2212 (const :tag "Only with C-u C-c C-t" prefix)))
2214 (defcustom org-provide-todo-statistics t
2215 "Non-nil means update todo statistics after insert and toggle.
2216 ALL-HEADLINES means update todo statistics by including headlines
2217 with no TODO keyword as well, counting them as not done.
2218 A list of TODO keywords means the same, but skip keywords that are
2219 not in this list.
2221 When this is set, todo statistics is updated in the parent of the
2222 current entry each time a todo state is changed."
2223 :group 'org-todo
2224 :type '(choice
2225 (const :tag "Yes, only for TODO entries" t)
2226 (const :tag "Yes, including all entries" 'all-headlines)
2227 (repeat :tag "Yes, for TODOs in this list"
2228 (string :tag "TODO keyword"))
2229 (other :tag "No TODO statistics" nil)))
2231 (defcustom org-hierarchical-todo-statistics t
2232 "Non-nil means TODO statistics covers just direct children.
2233 When nil, all entries in the subtree are considered.
2234 This has only an effect if `org-provide-todo-statistics' is set.
2235 To set this to nil for only a single subtree, use a COOKIE_DATA
2236 property and include the word \"recursive\" into the value."
2237 :group 'org-todo
2238 :type 'boolean)
2240 (defcustom org-after-todo-state-change-hook nil
2241 "Hook which is run after the state of a TODO item was changed.
2242 The new state (a string with a TODO keyword, or nil) is available in the
2243 Lisp variable `org-state'."
2244 :group 'org-todo
2245 :type 'hook)
2247 (defvar org-blocker-hook nil
2248 "Hook for functions that are allowed to block a state change.
2250 Functions in this hook should not modify the buffer.
2251 Each function gets as its single argument a property list,
2252 see `org-trigger-hook' for more information about this list.
2254 If any of the functions in this hook returns nil, the state change
2255 is blocked.")
2257 (defvar org-trigger-hook nil
2258 "Hook for functions that are triggered by a state change.
2260 Each function gets as its single argument a property list with at
2261 least the following elements:
2263 (:type type-of-change :position pos-at-entry-start
2264 :from old-state :to new-state)
2266 Depending on the type, more properties may be present.
2268 This mechanism is currently implemented for:
2270 TODO state changes
2271 ------------------
2272 :type todo-state-change
2273 :from previous state (keyword as a string), or nil, or a symbol
2274 'todo' or 'done', to indicate the general type of state.
2275 :to new state, like in :from")
2277 (defcustom org-enforce-todo-dependencies nil
2278 "Non-nil means undone TODO entries will block switching the parent to DONE.
2279 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2280 be blocked if any prior sibling is not yet done.
2281 Finally, if the parent is blocked because of ordered siblings of its own,
2282 the child will also be blocked."
2283 :set (lambda (var val)
2284 (set var val)
2285 (if val
2286 (add-hook 'org-blocker-hook
2287 'org-block-todo-from-children-or-siblings-or-parent)
2288 (remove-hook 'org-blocker-hook
2289 'org-block-todo-from-children-or-siblings-or-parent)))
2290 :group 'org-todo
2291 :type 'boolean)
2293 (defcustom org-enforce-todo-checkbox-dependencies nil
2294 "Non-nil means unchecked boxes will block switching the parent to DONE.
2295 When this is nil, checkboxes have no influence on switching TODO states.
2296 When non-nil, you first need to check off all check boxes before the TODO
2297 entry can be switched to DONE.
2298 This variable needs to be set before org.el is loaded, and you need to
2299 restart Emacs after a change to make the change effective. The only way
2300 to change is while Emacs is running is through the customize interface."
2301 :set (lambda (var val)
2302 (set var val)
2303 (if val
2304 (add-hook 'org-blocker-hook
2305 'org-block-todo-from-checkboxes)
2306 (remove-hook 'org-blocker-hook
2307 'org-block-todo-from-checkboxes)))
2308 :group 'org-todo
2309 :type 'boolean)
2311 (defcustom org-treat-insert-todo-heading-as-state-change nil
2312 "Non-nil means inserting a TODO heading is treated as state change.
2313 So when the command \\[org-insert-todo-heading] is used, state change
2314 logging will apply if appropriate. When nil, the new TODO item will
2315 be inserted directly, and no logging will take place."
2316 :group 'org-todo
2317 :type 'boolean)
2319 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2320 "Non-nil means switching TODO states with S-cursor counts as state change.
2321 This is the default behavior. However, setting this to nil allows a
2322 convenient way to select a TODO state and bypass any logging associated
2323 with that."
2324 :group 'org-todo
2325 :type 'boolean)
2327 (defcustom org-todo-state-tags-triggers nil
2328 "Tag changes that should be triggered by TODO state changes.
2329 This is a list. Each entry is
2331 (state-change (tag . flag) .......)
2333 State-change can be a string with a state, and empty string to indicate the
2334 state that has no TODO keyword, or it can be one of the symbols `todo'
2335 or `done', meaning any not-done or done state, respectively."
2336 :group 'org-todo
2337 :group 'org-tags
2338 :type '(repeat
2339 (cons (choice :tag "When changing to"
2340 (const :tag "Not-done state" todo)
2341 (const :tag "Done state" done)
2342 (string :tag "State"))
2343 (repeat
2344 (cons :tag "Tag action"
2345 (string :tag "Tag")
2346 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2348 (defcustom org-log-done nil
2349 "Information to record when a task moves to the DONE state.
2351 Possible values are:
2353 nil Don't add anything, just change the keyword
2354 time Add a time stamp to the task
2355 note Prompt for a note and add it with template `org-log-note-headings'
2357 This option can also be set with on a per-file-basis with
2359 #+STARTUP: nologdone
2360 #+STARTUP: logdone
2361 #+STARTUP: lognotedone
2363 You can have local logging settings for a subtree by setting the LOGGING
2364 property to one or more of these keywords."
2365 :group 'org-todo
2366 :group 'org-progress
2367 :type '(choice
2368 (const :tag "No logging" nil)
2369 (const :tag "Record CLOSED timestamp" time)
2370 (const :tag "Record CLOSED timestamp with note." note)))
2372 ;; Normalize old uses of org-log-done.
2373 (cond
2374 ((eq org-log-done t) (setq org-log-done 'time))
2375 ((and (listp org-log-done) (memq 'done org-log-done))
2376 (setq org-log-done 'note)))
2378 (defcustom org-log-reschedule nil
2379 "Information to record when the scheduling date of a tasks is modified.
2381 Possible values are:
2383 nil Don't add anything, just change the date
2384 time Add a time stamp to the task
2385 note Prompt for a note and add it with template `org-log-note-headings'
2387 This option can also be set with on a per-file-basis with
2389 #+STARTUP: nologreschedule
2390 #+STARTUP: logreschedule
2391 #+STARTUP: lognotereschedule"
2392 :group 'org-todo
2393 :group 'org-progress
2394 :type '(choice
2395 (const :tag "No logging" nil)
2396 (const :tag "Record timestamp" time)
2397 (const :tag "Record timestamp with note." note)))
2399 (defcustom org-log-redeadline nil
2400 "Information to record when the deadline date of a tasks is modified.
2402 Possible values are:
2404 nil Don't add anything, just change the date
2405 time Add a time stamp to the task
2406 note Prompt for a note and add it with template `org-log-note-headings'
2408 This option can also be set with on a per-file-basis with
2410 #+STARTUP: nologredeadline
2411 #+STARTUP: logredeadline
2412 #+STARTUP: lognoteredeadline
2414 You can have local logging settings for a subtree by setting the LOGGING
2415 property to one or more of these keywords."
2416 :group 'org-todo
2417 :group 'org-progress
2418 :type '(choice
2419 (const :tag "No logging" nil)
2420 (const :tag "Record timestamp" time)
2421 (const :tag "Record timestamp with note." note)))
2423 (defcustom org-log-note-clock-out nil
2424 "Non-nil means record a note when clocking out of an item.
2425 This can also be configured on a per-file basis by adding one of
2426 the following lines anywhere in the buffer:
2428 #+STARTUP: lognoteclock-out
2429 #+STARTUP: nolognoteclock-out"
2430 :group 'org-todo
2431 :group 'org-progress
2432 :type 'boolean)
2434 (defcustom org-log-done-with-time t
2435 "Non-nil means the CLOSED time stamp will contain date and time.
2436 When nil, only the date will be recorded."
2437 :group 'org-progress
2438 :type 'boolean)
2440 (defcustom org-log-note-headings
2441 '((done . "CLOSING NOTE %t")
2442 (state . "State %-12s from %-12S %t")
2443 (note . "Note taken on %t")
2444 (reschedule . "Rescheduled from %S on %t")
2445 (delschedule . "Not scheduled, was %S on %t")
2446 (redeadline . "New deadline from %S on %t")
2447 (deldeadline . "Removed deadline, was %S on %t")
2448 (refile . "Refiled on %t")
2449 (clock-out . ""))
2450 "Headings for notes added to entries.
2451 The value is an alist, with the car being a symbol indicating the note
2452 context, and the cdr is the heading to be used. The heading may also be the
2453 empty string.
2454 %t in the heading will be replaced by a time stamp.
2455 %T will be an active time stamp instead the default inactive one
2456 %d will be replaced by a short-format time stamp.
2457 %D will be replaced by an active short-format time stamp.
2458 %s will be replaced by the new TODO state, in double quotes.
2459 %S will be replaced by the old TODO state, in double quotes.
2460 %u will be replaced by the user name.
2461 %U will be replaced by the full user name.
2463 In fact, it is not a good idea to change the `state' entry, because
2464 agenda log mode depends on the format of these entries."
2465 :group 'org-todo
2466 :group 'org-progress
2467 :type '(list :greedy t
2468 (cons (const :tag "Heading when closing an item" done) string)
2469 (cons (const :tag
2470 "Heading when changing todo state (todo sequence only)"
2471 state) string)
2472 (cons (const :tag "Heading when just taking a note" note) string)
2473 (cons (const :tag "Heading when clocking out" clock-out) string)
2474 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2475 (cons (const :tag "Heading when rescheduling" reschedule) string)
2476 (cons (const :tag "Heading when changing deadline" redeadline) string)
2477 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2478 (cons (const :tag "Heading when refiling" refile) string)))
2480 (unless (assq 'note org-log-note-headings)
2481 (push '(note . "%t") org-log-note-headings))
2483 (defcustom org-log-into-drawer nil
2484 "Non-nil means insert state change notes and time stamps into a drawer.
2485 When nil, state changes notes will be inserted after the headline and
2486 any scheduling and clock lines, but not inside a drawer.
2488 The value of this variable should be the name of the drawer to use.
2489 LOGBOOK is proposed as the default drawer for this purpose, you can
2490 also set this to a string to define the drawer of your choice.
2492 A value of t is also allowed, representing \"LOGBOOK\".
2494 If this variable is set, `org-log-state-notes-insert-after-drawers'
2495 will be ignored.
2497 You can set the property LOG_INTO_DRAWER to overrule this setting for
2498 a subtree."
2499 :group 'org-todo
2500 :group 'org-progress
2501 :type '(choice
2502 (const :tag "Not into a drawer" nil)
2503 (const :tag "LOGBOOK" t)
2504 (string :tag "Other")))
2506 (if (fboundp 'defvaralias)
2507 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2509 (defun org-log-into-drawer ()
2510 "Return the value of `org-log-into-drawer', but let properties overrule.
2511 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2512 used instead of the default value."
2513 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2514 (cond
2515 ((not p) org-log-into-drawer)
2516 ((equal p "nil") nil)
2517 ((equal p "t") "LOGBOOK")
2518 (t p))))
2520 (defcustom org-log-state-notes-insert-after-drawers nil
2521 "Non-nil means insert state change notes after any drawers in entry.
2522 Only the drawers that *immediately* follow the headline and the
2523 deadline/scheduled line are skipped.
2524 When nil, insert notes right after the heading and perhaps the line
2525 with deadline/scheduling if present.
2527 This variable will have no effect if `org-log-into-drawer' is
2528 set."
2529 :group 'org-todo
2530 :group 'org-progress
2531 :type 'boolean)
2533 (defcustom org-log-states-order-reversed t
2534 "Non-nil means the latest state note will be directly after heading.
2535 When nil, the state change notes will be ordered according to time."
2536 :group 'org-todo
2537 :group 'org-progress
2538 :type 'boolean)
2540 (defcustom org-todo-repeat-to-state nil
2541 "The TODO state to which a repeater should return the repeating task.
2542 By default this is the first task in a TODO sequence, or the previous state
2543 in a TODO_TYP set. But you can specify another task here.
2544 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2545 :group 'org-todo
2546 :version "24.1"
2547 :type '(choice (const :tag "Head of sequence" nil)
2548 (string :tag "Specific state")))
2550 (defcustom org-log-repeat 'time
2551 "Non-nil means record moving through the DONE state when triggering repeat.
2552 An auto-repeating task is immediately switched back to TODO when
2553 marked DONE. If you are not logging state changes (by adding \"@\"
2554 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2555 record a closing note, there will be no record of the task moving
2556 through DONE. This variable forces taking a note anyway.
2558 nil Don't force a record
2559 time Record a time stamp
2560 note Prompt for a note and add it with template `org-log-note-headings'
2562 This option can also be set with on a per-file-basis with
2564 #+STARTUP: nologrepeat
2565 #+STARTUP: logrepeat
2566 #+STARTUP: lognoterepeat
2568 You can have local logging settings for a subtree by setting the LOGGING
2569 property to one or more of these keywords."
2570 :group 'org-todo
2571 :group 'org-progress
2572 :type '(choice
2573 (const :tag "Don't force a record" nil)
2574 (const :tag "Force recording the DONE state" time)
2575 (const :tag "Force recording a note with the DONE state" note)))
2578 (defgroup org-priorities nil
2579 "Priorities in Org-mode."
2580 :tag "Org Priorities"
2581 :group 'org-todo)
2583 (defcustom org-enable-priority-commands t
2584 "Non-nil means priority commands are active.
2585 When nil, these commands will be disabled, so that you never accidentally
2586 set a priority."
2587 :group 'org-priorities
2588 :type 'boolean)
2590 (defcustom org-highest-priority ?A
2591 "The highest priority of TODO items. A character like ?A, ?B etc.
2592 Must have a smaller ASCII number than `org-lowest-priority'."
2593 :group 'org-priorities
2594 :type 'character)
2596 (defcustom org-lowest-priority ?C
2597 "The lowest priority of TODO items. A character like ?A, ?B etc.
2598 Must have a larger ASCII number than `org-highest-priority'."
2599 :group 'org-priorities
2600 :type 'character)
2602 (defcustom org-default-priority ?B
2603 "The default priority of TODO items.
2604 This is the priority an item gets if no explicit priority is given.
2605 When starting to cycle on an empty priority the first step in the cycle
2606 depends on `org-priority-start-cycle-with-default'. The resulting first
2607 step priority must not exceed the range from `org-highest-priority' to
2608 `org-lowest-priority' which means that `org-default-priority' has to be
2609 in this range exclusive or inclusive the range boundaries. Else the
2610 first step refuses to set the default and the second will fall back
2611 to (depending on the command used) the highest or lowest priority."
2612 :group 'org-priorities
2613 :type 'character)
2615 (defcustom org-priority-start-cycle-with-default t
2616 "Non-nil means start with default priority when starting to cycle.
2617 When this is nil, the first step in the cycle will be (depending on the
2618 command used) one higher or lower than the default priority.
2619 See also `org-default-priority'."
2620 :group 'org-priorities
2621 :type 'boolean)
2623 (defcustom org-get-priority-function nil
2624 "Function to extract the priority from a string.
2625 The string is normally the headline. If this is nil Org computes the
2626 priority from the priority cookie like [#A] in the headline. It returns
2627 an integer, increasing by 1000 for each priority level.
2628 The user can set a different function here, which should take a string
2629 as an argument and return the numeric priority."
2630 :group 'org-priorities
2631 :version "24.1"
2632 :type 'function)
2634 (defgroup org-time nil
2635 "Options concerning time stamps and deadlines in Org-mode."
2636 :tag "Org Time"
2637 :group 'org)
2639 (defcustom org-insert-labeled-timestamps-at-point nil
2640 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2641 When nil, these labeled time stamps are forces into the second line of an
2642 entry, just after the headline. When scheduling from the global TODO list,
2643 the time stamp will always be forced into the second line."
2644 :group 'org-time
2645 :type 'boolean)
2647 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2648 "Formats for `format-time-string' which are used for time stamps.
2649 It is not recommended to change this constant.")
2651 (defcustom org-time-stamp-rounding-minutes '(0 5)
2652 "Number of minutes to round time stamps to.
2653 These are two values, the first applies when first creating a time stamp.
2654 The second applies when changing it with the commands `S-up' and `S-down'.
2655 When changing the time stamp, this means that it will change in steps
2656 of N minutes, as given by the second value.
2658 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2659 numbers should be factors of 60, so for example 5, 10, 15.
2661 When this is larger than 1, you can still force an exact time stamp by using
2662 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2663 and by using a prefix arg to `S-up/down' to specify the exact number
2664 of minutes to shift."
2665 :group 'org-time
2666 :get #'(lambda (var) ; Make sure both elements are there
2667 (if (integerp (default-value var))
2668 (list (default-value var) 5)
2669 (default-value var)))
2670 :type '(list
2671 (integer :tag "when inserting times")
2672 (integer :tag "when modifying times")))
2674 ;; Normalize old customizations of this variable.
2675 (when (integerp org-time-stamp-rounding-minutes)
2676 (setq org-time-stamp-rounding-minutes
2677 (list org-time-stamp-rounding-minutes
2678 org-time-stamp-rounding-minutes)))
2680 (defcustom org-display-custom-times nil
2681 "Non-nil means overlay custom formats over all time stamps.
2682 The formats are defined through the variable `org-time-stamp-custom-formats'.
2683 To turn this on on a per-file basis, insert anywhere in the file:
2684 #+STARTUP: customtime"
2685 :group 'org-time
2686 :set 'set-default
2687 :type 'sexp)
2688 (make-variable-buffer-local 'org-display-custom-times)
2690 (defcustom org-time-stamp-custom-formats
2691 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2692 "Custom formats for time stamps. See `format-time-string' for the syntax.
2693 These are overlaid over the default ISO format if the variable
2694 `org-display-custom-times' is set. Time like %H:%M should be at the
2695 end of the second format. The custom formats are also honored by export
2696 commands, if custom time display is turned on at the time of export."
2697 :group 'org-time
2698 :type 'sexp)
2700 (defun org-time-stamp-format (&optional long inactive)
2701 "Get the right format for a time string."
2702 (let ((f (if long (cdr org-time-stamp-formats)
2703 (car org-time-stamp-formats))))
2704 (if inactive
2705 (concat "[" (substring f 1 -1) "]")
2706 f)))
2708 (defcustom org-time-clocksum-format "%d:%02d"
2709 "The format string used when creating CLOCKSUM lines.
2710 This is also used when org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'string)
2714 (defcustom org-time-clocksum-use-fractional nil
2715 "If non-nil, \\[org-clock-display] uses fractional times.
2716 org-mode generates a time duration."
2717 :group 'org-time
2718 :type 'boolean)
2720 (defcustom org-time-clocksum-fractional-format "%.2f"
2721 "The format string used when creating CLOCKSUM lines, or when
2722 org-mode generates a time duration."
2723 :group 'org-time
2724 :type 'string)
2726 (defcustom org-deadline-warning-days 14
2727 "No. of days before expiration during which a deadline becomes active.
2728 This variable governs the display in sparse trees and in the agenda.
2729 When 0 or negative, it means use this number (the absolute value of it)
2730 even if a deadline has a different individual lead time specified.
2732 Custom commands can set this variable in the options section."
2733 :group 'org-time
2734 :group 'org-agenda-daily/weekly
2735 :type 'integer)
2737 (defcustom org-read-date-prefer-future t
2738 "Non-nil means assume future for incomplete date input from user.
2739 This affects the following situations:
2740 1. The user gives a month but not a year.
2741 For example, if it is April and you enter \"feb 2\", this will be read
2742 as Feb 2, *next* year. \"May 5\", however, will be this year.
2743 2. The user gives a day, but no month.
2744 For example, if today is the 15th, and you enter \"3\", Org-mode will
2745 read this as the third of *next* month. However, if you enter \"17\",
2746 it will be considered as *this* month.
2748 If you set this variable to the symbol `time', then also the following
2749 will work:
2751 3. If the user gives a time.
2752 If the time is before now, it will be interpreted as tomorrow.
2754 Currently none of this works for ISO week specifications.
2756 When this option is nil, the current day, month and year will always be
2757 used as defaults.
2759 See also `org-agenda-jump-prefer-future'."
2760 :group 'org-time
2761 :type '(choice
2762 (const :tag "Never" nil)
2763 (const :tag "Check month and day" t)
2764 (const :tag "Check month, day, and time" time)))
2766 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2767 "Should the agenda jump command prefer the future for incomplete dates?
2768 The default is to do the same as configured in `org-read-date-prefer-future'.
2769 But you can also set a deviating value here.
2770 This may t or nil, or the symbol `org-read-date-prefer-future'."
2771 :group 'org-agenda
2772 :group 'org-time
2773 :version "24.1"
2774 :type '(choice
2775 (const :tag "Use org-read-date-prefer-future"
2776 org-read-date-prefer-future)
2777 (const :tag "Never" nil)
2778 (const :tag "Always" t)))
2780 (defcustom org-read-date-force-compatible-dates t
2781 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2783 Depending on the system Emacs is running on, certain dates cannot
2784 be represented with the type used internally to represent time.
2785 Dates between 1970-1-1 and 2038-1-1 can always be represented
2786 correctly. Some systems allow for earlier dates, some for later,
2787 some for both. One way to find out it to insert any date into an
2788 Org buffer, putting the cursor on the year and hitting S-up and
2789 S-down to test the range.
2791 When this variable is set to t, the date/time prompt will not let
2792 you specify dates outside the 1970-2037 range, so it is certain that
2793 these dates will work in whatever version of Emacs you are
2794 running, and also that you can move a file from one Emacs implementation
2795 to another. WHenever Org is forcing the year for you, it will display
2796 a message and beep.
2798 When this variable is nil, Org will check if the date is
2799 representable in the specific Emacs implementation you are using.
2800 If not, it will force a year, usually the current year, and beep
2801 to remind you. Currently this setting is not recommended because
2802 the likelihood that you will open your Org files in an Emacs that
2803 has limited date range is not negligible.
2805 A workaround for this problem is to use diary sexp dates for time
2806 stamps outside of this range."
2807 :group 'org-time
2808 :version "24.1"
2809 :type 'boolean)
2811 (defcustom org-read-date-display-live t
2812 "Non-nil means display current interpretation of date prompt live.
2813 This display will be in an overlay, in the minibuffer."
2814 :group 'org-time
2815 :type 'boolean)
2817 (defcustom org-read-date-popup-calendar t
2818 "Non-nil means pop up a calendar when prompting for a date.
2819 In the calendar, the date can be selected with mouse-1. However, the
2820 minibuffer will also be active, and you can simply enter the date as well.
2821 When nil, only the minibuffer will be available."
2822 :group 'org-time
2823 :type 'boolean)
2824 (if (fboundp 'defvaralias)
2825 (defvaralias 'org-popup-calendar-for-date-prompt
2826 'org-read-date-popup-calendar))
2828 (defcustom org-read-date-minibuffer-setup-hook nil
2829 "Hook to be used to set up keys for the date/time interface.
2830 Add key definitions to `minibuffer-local-map', which will be a temporary
2831 copy."
2832 :group 'org-time
2833 :type 'hook)
2835 (defcustom org-extend-today-until 0
2836 "The hour when your day really ends. Must be an integer.
2837 This has influence for the following applications:
2838 - When switching the agenda to \"today\". It it is still earlier than
2839 the time given here, the day recognized as TODAY is actually yesterday.
2840 - When a date is read from the user and it is still before the time given
2841 here, the current date and time will be assumed to be yesterday, 23:59.
2842 Also, timestamps inserted in capture templates follow this rule.
2844 IMPORTANT: This is a feature whose implementation is and likely will
2845 remain incomplete. Really, it is only here because past midnight seems to
2846 be the favorite working time of John Wiegley :-)"
2847 :group 'org-time
2848 :type 'integer)
2850 (defcustom org-use-effective-time nil
2851 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2852 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2853 \"effective time\" of any timestamps between midnight and 8am will be
2854 23:59 of the previous day."
2855 :group 'org-time
2856 :version "24.1"
2857 :type 'boolean)
2859 (defcustom org-edit-timestamp-down-means-later nil
2860 "Non-nil means S-down will increase the time in a time stamp.
2861 When nil, S-up will increase."
2862 :group 'org-time
2863 :type 'boolean)
2865 (defcustom org-calendar-follow-timestamp-change t
2866 "Non-nil means make the calendar window follow timestamp changes.
2867 When a timestamp is modified and the calendar window is visible, it will be
2868 moved to the new date."
2869 :group 'org-time
2870 :type 'boolean)
2872 (defgroup org-tags nil
2873 "Options concerning tags in Org-mode."
2874 :tag "Org Tags"
2875 :group 'org)
2877 (defcustom org-tag-alist nil
2878 "List of tags allowed in Org-mode files.
2879 When this list is nil, Org-mode will base TAG input on what is already in the
2880 buffer.
2881 The value of this variable is an alist, the car of each entry must be a
2882 keyword as a string, the cdr may be a character that is used to select
2883 that tag through the fast-tag-selection interface.
2884 See the manual for details."
2885 :group 'org-tags
2886 :type '(repeat
2887 (choice
2888 (cons (string :tag "Tag name")
2889 (character :tag "Access char"))
2890 (list :tag "Start radio group"
2891 (const :startgroup)
2892 (option (string :tag "Group description")))
2893 (list :tag "End radio group"
2894 (const :endgroup)
2895 (option (string :tag "Group description")))
2896 (const :tag "New line" (:newline)))))
2898 (defcustom org-tag-persistent-alist nil
2899 "List of tags that will always appear in all Org-mode files.
2900 This is in addition to any in buffer settings or customizations
2901 of `org-tag-alist'.
2902 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2903 The value of this variable is an alist, the car of each entry must be a
2904 keyword as a string, the cdr may be a character that is used to select
2905 that tag through the fast-tag-selection interface.
2906 See the manual for details.
2907 To disable these tags on a per-file basis, insert anywhere in the file:
2908 #+STARTUP: noptag"
2909 :group 'org-tags
2910 :type '(repeat
2911 (choice
2912 (cons (string :tag "Tag name")
2913 (character :tag "Access char"))
2914 (const :tag "Start radio group" (:startgroup))
2915 (const :tag "End radio group" (:endgroup))
2916 (const :tag "New line" (:newline)))))
2918 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2919 "If non-nil, always offer completion for all tags of all agenda files.
2920 Instead of customizing this variable directly, you might want to
2921 set it locally for capture buffers, because there no list of
2922 tags in that file can be created dynamically (there are none).
2924 (add-hook 'org-capture-mode-hook
2925 (lambda ()
2926 (set (make-local-variable
2927 'org-complete-tags-always-offer-all-agenda-tags)
2928 t)))"
2929 :group 'org-tags
2930 :version "24.1"
2931 :type 'boolean)
2933 (defvar org-file-tags nil
2934 "List of tags that can be inherited by all entries in the file.
2935 The tags will be inherited if the variable `org-use-tag-inheritance'
2936 says they should be.
2937 This variable is populated from #+FILETAGS lines.")
2939 (defcustom org-use-fast-tag-selection 'auto
2940 "Non-nil means use fast tag selection scheme.
2941 This is a special interface to select and deselect tags with single keys.
2942 When nil, fast selection is never used.
2943 When the symbol `auto', fast selection is used if and only if selection
2944 characters for tags have been configured, either through the variable
2945 `org-tag-alist' or through a #+TAGS line in the buffer.
2946 When t, fast selection is always used and selection keys are assigned
2947 automatically if necessary."
2948 :group 'org-tags
2949 :type '(choice
2950 (const :tag "Always" t)
2951 (const :tag "Never" nil)
2952 (const :tag "When selection characters are configured" 'auto)))
2954 (defcustom org-fast-tag-selection-single-key nil
2955 "Non-nil means fast tag selection exits after first change.
2956 When nil, you have to press RET to exit it.
2957 During fast tag selection, you can toggle this flag with `C-c'.
2958 This variable can also have the value `expert'. In this case, the window
2959 displaying the tags menu is not even shown, until you press C-c again."
2960 :group 'org-tags
2961 :type '(choice
2962 (const :tag "No" nil)
2963 (const :tag "Yes" t)
2964 (const :tag "Expert" expert)))
2966 (defvar org-fast-tag-selection-include-todo nil
2967 "Non-nil means fast tags selection interface will also offer TODO states.
2968 This is an undocumented feature, you should not rely on it.")
2970 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2971 "The column to which tags should be indented in a headline.
2972 If this number is positive, it specifies the column. If it is negative,
2973 it means that the tags should be flushright to that column. For example,
2974 -80 works well for a normal 80 character screen.
2975 When 0, place tags directly after headline text, with only one space in
2976 between."
2977 :group 'org-tags
2978 :type 'integer)
2980 (defcustom org-auto-align-tags t
2981 "Non-nil keeps tags aligned when modifying headlines.
2982 Some operations (i.e. demoting) change the length of a headline and
2983 therefore shift the tags around. With this option turned on, after
2984 each such operation the tags are again aligned to `org-tags-column'."
2985 :group 'org-tags
2986 :type 'boolean)
2988 (defcustom org-use-tag-inheritance t
2989 "Non-nil means tags in levels apply also for sublevels.
2990 When nil, only the tags directly given in a specific line apply there.
2991 This may also be a list of tags that should be inherited, or a regexp that
2992 matches tags that should be inherited. Additional control is possible
2993 with the variable `org-tags-exclude-from-inheritance' which gives an
2994 explicit list of tags to be excluded from inheritance, even if the value of
2995 `org-use-tag-inheritance' would select it for inheritance.
2997 If this option is t, a match early-on in a tree can lead to a large
2998 number of matches in the subtree when constructing the agenda or creating
2999 a sparse tree. If you only want to see the first match in a tree during
3000 a search, check out the variable `org-tags-match-list-sublevels'."
3001 :group 'org-tags
3002 :type '(choice
3003 (const :tag "Not" nil)
3004 (const :tag "Always" t)
3005 (repeat :tag "Specific tags" (string :tag "Tag"))
3006 (regexp :tag "Tags matched by regexp")))
3008 (defcustom org-tags-exclude-from-inheritance nil
3009 "List of tags that should never be inherited.
3010 This is a way to exclude a few tags from inheritance. For way to do
3011 the opposite, to actively allow inheritance for selected tags,
3012 see the variable `org-use-tag-inheritance'."
3013 :group 'org-tags
3014 :type '(repeat (string :tag "Tag")))
3016 (defun org-tag-inherit-p (tag)
3017 "Check if TAG is one that should be inherited."
3018 (cond
3019 ((member tag org-tags-exclude-from-inheritance) nil)
3020 ((eq org-use-tag-inheritance t) t)
3021 ((not org-use-tag-inheritance) nil)
3022 ((stringp org-use-tag-inheritance)
3023 (string-match org-use-tag-inheritance tag))
3024 ((listp org-use-tag-inheritance)
3025 (member tag org-use-tag-inheritance))
3026 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3028 (defcustom org-tags-match-list-sublevels t
3029 "Non-nil means list also sublevels of headlines matching a search.
3030 This variable applies to tags/property searches, and also to stuck
3031 projects because this search is based on a tags match as well.
3033 When set to the symbol `indented', sublevels are indented with
3034 leading dots.
3036 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3037 the sublevels of a headline matching a tag search often also match
3038 the same search. Listing all of them can create very long lists.
3039 Setting this variable to nil causes subtrees of a match to be skipped.
3041 This variable is semi-obsolete and probably should always be true. It
3042 is better to limit inheritance to certain tags using the variables
3043 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3044 :group 'org-tags
3045 :type '(choice
3046 (const :tag "No, don't list them" nil)
3047 (const :tag "Yes, do list them" t)
3048 (const :tag "List them, indented with leading dots" indented)))
3050 (defcustom org-tags-sort-function nil
3051 "When set, tags are sorted using this function as a comparator."
3052 :group 'org-tags
3053 :type '(choice
3054 (const :tag "No sorting" nil)
3055 (const :tag "Alphabetical" string<)
3056 (const :tag "Reverse alphabetical" string>)
3057 (function :tag "Custom function" nil)))
3059 (defvar org-tags-history nil
3060 "History of minibuffer reads for tags.")
3061 (defvar org-last-tags-completion-table nil
3062 "The last used completion table for tags.")
3063 (defvar org-after-tags-change-hook nil
3064 "Hook that is run after the tags in a line have changed.")
3066 (defgroup org-properties nil
3067 "Options concerning properties in Org-mode."
3068 :tag "Org Properties"
3069 :group 'org)
3071 (defcustom org-property-format "%-10s %s"
3072 "How property key/value pairs should be formatted by `indent-line'.
3073 When `indent-line' hits a property definition, it will format the line
3074 according to this format, mainly to make sure that the values are
3075 lined-up with respect to each other."
3076 :group 'org-properties
3077 :type 'string)
3079 (defcustom org-properties-postprocess-alist nil
3080 "Alist of properties and functions to adjust inserted values.
3081 Elements of this alist must be of the form
3083 ([string] [function])
3085 where [string] must be a property name and [function] must be a
3086 lambda expression: this lambda expression must take one argument,
3087 the value to adjust, and return the new value as a string.
3089 For example, this element will allow the property \"Remaining\"
3090 to be updated wrt the relation between the \"Effort\" property
3091 and the clock summary:
3093 ((\"Remaining\" (lambda(value)
3094 (let ((clocksum (org-clock-sum-current-item))
3095 (effort (org-duration-string-to-minutes
3096 (org-entry-get (point) \"Effort\"))))
3097 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3098 :group 'org-properties
3099 :version "24.1"
3100 :type '(alist :key-type (string :tag "Property")
3101 :value-type (function :tag "Function")))
3103 (defcustom org-use-property-inheritance nil
3104 "Non-nil means properties apply also for sublevels.
3106 This setting is chiefly used during property searches. Turning it on can
3107 cause significant overhead when doing a search, which is why it is not
3108 on by default.
3110 When nil, only the properties directly given in the current entry count.
3111 When t, every property is inherited. The value may also be a list of
3112 properties that should have inheritance, or a regular expression matching
3113 properties that should be inherited.
3115 However, note that some special properties use inheritance under special
3116 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3117 and the properties ending in \"_ALL\" when they are used as descriptor
3118 for valid values of a property.
3120 Note for programmers:
3121 When querying an entry with `org-entry-get', you can control if inheritance
3122 should be used. By default, `org-entry-get' looks only at the local
3123 properties. You can request inheritance by setting the inherit argument
3124 to t (to force inheritance) or to `selective' (to respect the setting
3125 in this variable)."
3126 :group 'org-properties
3127 :type '(choice
3128 (const :tag "Not" nil)
3129 (const :tag "Always" t)
3130 (repeat :tag "Specific properties" (string :tag "Property"))
3131 (regexp :tag "Properties matched by regexp")))
3133 (defun org-property-inherit-p (property)
3134 "Check if PROPERTY is one that should be inherited."
3135 (cond
3136 ((eq org-use-property-inheritance t) t)
3137 ((not org-use-property-inheritance) nil)
3138 ((stringp org-use-property-inheritance)
3139 (string-match org-use-property-inheritance property))
3140 ((listp org-use-property-inheritance)
3141 (member property org-use-property-inheritance))
3142 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3144 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3145 "The default column format, if no other format has been defined.
3146 This variable can be set on the per-file basis by inserting a line
3148 #+COLUMNS: %25ITEM ....."
3149 :group 'org-properties
3150 :type 'string)
3152 (defcustom org-columns-ellipses ".."
3153 "The ellipses to be used when a field in column view is truncated.
3154 When this is the empty string, as many characters as possible are shown,
3155 but then there will be no visual indication that the field has been truncated.
3156 When this is a string of length N, the last N characters of a truncated
3157 field are replaced by this string. If the column is narrower than the
3158 ellipses string, only part of the ellipses string will be shown."
3159 :group 'org-properties
3160 :type 'string)
3162 (defcustom org-columns-modify-value-for-display-function nil
3163 "Function that modifies values for display in column view.
3164 For example, it can be used to cut out a certain part from a time stamp.
3165 The function must take 2 arguments:
3167 column-title The title of the column (*not* the property name)
3168 value The value that should be modified.
3170 The function should return the value that should be displayed,
3171 or nil if the normal value should be used."
3172 :group 'org-properties
3173 :type 'function)
3175 (defcustom org-effort-property "Effort"
3176 "The property that is being used to keep track of effort estimates.
3177 Effort estimates given in this property need to have the format H:MM."
3178 :group 'org-properties
3179 :group 'org-progress
3180 :type '(string :tag "Property"))
3182 (defconst org-global-properties-fixed
3183 '(("VISIBILITY_ALL" . "folded children content all")
3184 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3185 "List of property/value pairs that can be inherited by any entry.
3187 These are fixed values, for the preset properties. The user variable
3188 that can be used to add to this list is `org-global-properties'.
3190 The entries in this list are cons cells where the car is a property
3191 name and cdr is a string with the value. If the value represents
3192 multiple items like an \"_ALL\" property, separate the items by
3193 spaces.")
3195 (defcustom org-global-properties nil
3196 "List of property/value pairs that can be inherited by any entry.
3198 This list will be combined with the constant `org-global-properties-fixed'.
3200 The entries in this list are cons cells where the car is a property
3201 name and cdr is a string with the value.
3203 You can set buffer-local values for the same purpose in the variable
3204 `org-file-properties' this by adding lines like
3206 #+PROPERTY: NAME VALUE"
3207 :group 'org-properties
3208 :type '(repeat
3209 (cons (string :tag "Property")
3210 (string :tag "Value"))))
3212 (defvar org-file-properties nil
3213 "List of property/value pairs that can be inherited by any entry.
3214 Valid for the current buffer.
3215 This variable is populated from #+PROPERTY lines.")
3216 (make-variable-buffer-local 'org-file-properties)
3218 (defgroup org-agenda nil
3219 "Options concerning agenda views in Org-mode."
3220 :tag "Org Agenda"
3221 :group 'org)
3223 (defvar org-category nil
3224 "Variable used by org files to set a category for agenda display.
3225 Such files should use a file variable to set it, for example
3227 # -*- mode: org; org-category: \"ELisp\"
3229 or contain a special line
3231 #+CATEGORY: ELisp
3233 If the file does not specify a category, then file's base name
3234 is used instead.")
3235 (make-variable-buffer-local 'org-category)
3236 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3238 (defcustom org-agenda-files nil
3239 "The files to be used for agenda display.
3240 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3241 \\[org-remove-file]. You can also use customize to edit the list.
3243 If an entry is a directory, all files in that directory that are matched by
3244 `org-agenda-file-regexp' will be part of the file list.
3246 If the value of the variable is not a list but a single file name, then
3247 the list of agenda files is actually stored and maintained in that file, one
3248 agenda file per line. In this file paths can be given relative to
3249 `org-directory'. Tilde expansion and environment variable substitution
3250 are also made."
3251 :group 'org-agenda
3252 :type '(choice
3253 (repeat :tag "List of files and directories" file)
3254 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3256 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3257 "Regular expression to match files for `org-agenda-files'.
3258 If any element in the list in that variable contains a directory instead
3259 of a normal file, all files in that directory that are matched by this
3260 regular expression will be included."
3261 :group 'org-agenda
3262 :type 'regexp)
3264 (defcustom org-agenda-text-search-extra-files nil
3265 "List of extra files to be searched by text search commands.
3266 These files will be search in addition to the agenda files by the
3267 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3268 Note that these files will only be searched for text search commands,
3269 not for the other agenda views like todo lists, tag searches or the weekly
3270 agenda. This variable is intended to list notes and possibly archive files
3271 that should also be searched by these two commands.
3272 In fact, if the first element in the list is the symbol `agenda-archives',
3273 than all archive files of all agenda files will be added to the search
3274 scope."
3275 :group 'org-agenda
3276 :type '(set :greedy t
3277 (const :tag "Agenda Archives" agenda-archives)
3278 (repeat :inline t (file))))
3280 (if (fboundp 'defvaralias)
3281 (defvaralias 'org-agenda-multi-occur-extra-files
3282 'org-agenda-text-search-extra-files))
3284 (defcustom org-agenda-skip-unavailable-files nil
3285 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3286 A nil value means to remove them, after a query, from the list."
3287 :group 'org-agenda
3288 :type 'boolean)
3290 (defcustom org-calendar-to-agenda-key [?c]
3291 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3292 The command `org-calendar-goto-agenda' will be bound to this key. The
3293 default is the character `c' because then `c' can be used to switch back and
3294 forth between agenda and calendar."
3295 :group 'org-agenda
3296 :type 'sexp)
3298 (defcustom org-calendar-insert-diary-entry-key [?i]
3299 "The key to be installed in `calendar-mode-map' for adding diary entries.
3300 This option is irrelevant until `org-agenda-diary-file' has been configured
3301 to point to an Org-mode file. When that is the case, the command
3302 `org-agenda-diary-entry' will be bound to the key given here, by default
3303 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3304 if you want to continue doing this, you need to change this to a different
3305 key."
3306 :group 'org-agenda
3307 :type 'sexp)
3309 (defcustom org-agenda-diary-file 'diary-file
3310 "File to which to add new entries with the `i' key in agenda and calendar.
3311 When this is the symbol `diary-file', the functionality in the Emacs
3312 calendar will be used to add entries to the `diary-file'. But when this
3313 points to a file, `org-agenda-diary-entry' will be used instead."
3314 :group 'org-agenda
3315 :type '(choice
3316 (const :tag "The standard Emacs diary file" diary-file)
3317 (file :tag "Special Org file diary entries")))
3319 (eval-after-load "calendar"
3320 '(progn
3321 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3322 'org-calendar-goto-agenda)
3323 (add-hook 'calendar-mode-hook
3324 (lambda ()
3325 (unless (eq org-agenda-diary-file 'diary-file)
3326 (define-key calendar-mode-map
3327 org-calendar-insert-diary-entry-key
3328 'org-agenda-diary-entry))))))
3330 (defgroup org-latex nil
3331 "Options for embedding LaTeX code into Org-mode."
3332 :tag "Org LaTeX"
3333 :group 'org)
3335 (defcustom org-format-latex-options
3336 '(:foreground default :background default :scale 1.0
3337 :html-foreground "Black" :html-background "Transparent"
3338 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3339 "Options for creating images from LaTeX fragments.
3340 This is a property list with the following properties:
3341 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3342 `default' means use the foreground of the default face.
3343 :background the background color, or \"Transparent\".
3344 `default' means use the background of the default face.
3345 :scale a scaling factor for the size of the images, to get more pixels
3346 :html-foreground, :html-background, :html-scale
3347 the same numbers for HTML export.
3348 :matchers a list indicating which matchers should be used to
3349 find LaTeX fragments. Valid members of this list are:
3350 \"begin\" find environments
3351 \"$1\" find single characters surrounded by $.$
3352 \"$\" find math expressions surrounded by $...$
3353 \"$$\" find math expressions surrounded by $$....$$
3354 \"\\(\" find math expressions surrounded by \\(...\\)
3355 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3356 :group 'org-latex
3357 :type 'plist)
3359 (defcustom org-format-latex-signal-error t
3360 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3361 When nil, just push out a message."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-latex-to-mathml-jar-file nil
3367 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3368 Use this to specify additional executable file say a jar file.
3370 When using MathToWeb as the converter, specify the full-path to
3371 your mathtoweb.jar file."
3372 :group 'org-latex
3373 :version "24.1"
3374 :type '(choice
3375 (const :tag "None" nil)
3376 (file :tag "JAR file" :must-match t)))
3378 (defcustom org-latex-to-mathml-convert-command nil
3379 "Command to convert LaTeX fragments to MathML.
3380 Replace format-specifiers in the command as noted below and use
3381 `shell-command' to convert LaTeX to MathML.
3382 %j: Executable file in fully expanded form as specified by
3383 `org-latex-to-mathml-jar-file'.
3384 %I: Input LaTeX file in fully expanded form
3385 %o: Output MathML file
3386 This command is used by `org-create-math-formula'.
3388 When using MathToWeb as the converter, set this to
3389 \"java -jar %j -unicode -force -df %o %I\"."
3390 :group 'org-latex
3391 :version "24.1"
3392 :type '(choice
3393 (const :tag "None" nil)
3394 (string :tag "\nShell command")))
3396 (defcustom org-latex-create-formula-image-program 'dvipng
3397 "Program to convert LaTeX fragments with.
3399 dvipng Process the LaTeX fragments to dvi file, then convert
3400 dvi files to png files using dvipng.
3401 This will also include processing of non-math environments.
3402 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3403 to convert pdf files to png files"
3404 :group 'org-latex
3405 :version "24.1"
3406 :type '(choice
3407 (const :tag "dvipng" dvipng)
3408 (const :tag "imagemagick" imagemagick)))
3410 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3411 "Path to store latex preview images. A relative path here creates many
3412 directories relative to the processed org files paths. An absolute path
3413 puts all preview images at the same place."
3414 :group 'org-latex
3415 :version "24.3"
3416 :type 'string)
3418 (defun org-format-latex-mathml-available-p ()
3419 "Return t if `org-latex-to-mathml-convert-command' is usable."
3420 (save-match-data
3421 (when (and (boundp 'org-latex-to-mathml-convert-command)
3422 org-latex-to-mathml-convert-command)
3423 (let ((executable (car (split-string
3424 org-latex-to-mathml-convert-command))))
3425 (when (executable-find executable)
3426 (if (string-match
3427 "%j" org-latex-to-mathml-convert-command)
3428 (file-readable-p org-latex-to-mathml-jar-file)
3429 t))))))
3431 (defcustom org-format-latex-header "\\documentclass{article}
3432 \\usepackage[usenames]{color}
3433 \\usepackage{amsmath}
3434 \\usepackage[mathscr]{eucal}
3435 \\pagestyle{empty} % do not remove
3436 \[PACKAGES]
3437 \[DEFAULT-PACKAGES]
3438 % The settings below are copied from fullpage.sty
3439 \\setlength{\\textwidth}{\\paperwidth}
3440 \\addtolength{\\textwidth}{-3cm}
3441 \\setlength{\\oddsidemargin}{1.5cm}
3442 \\addtolength{\\oddsidemargin}{-2.54cm}
3443 \\setlength{\\evensidemargin}{\\oddsidemargin}
3444 \\setlength{\\textheight}{\\paperheight}
3445 \\addtolength{\\textheight}{-\\headheight}
3446 \\addtolength{\\textheight}{-\\headsep}
3447 \\addtolength{\\textheight}{-\\footskip}
3448 \\addtolength{\\textheight}{-3cm}
3449 \\setlength{\\topmargin}{1.5cm}
3450 \\addtolength{\\topmargin}{-2.54cm}"
3451 "The document header used for processing LaTeX fragments.
3452 It is imperative that this header make sure that no page number
3453 appears on the page. The package defined in the variables
3454 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3455 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3456 will be appended."
3457 :group 'org-latex
3458 :type 'string)
3460 (defvar org-format-latex-header-extra nil)
3462 (defun org-set-packages-alist (var val)
3463 "Set the packages alist and make sure it has 3 elements per entry."
3464 (set var (mapcar (lambda (x)
3465 (if (and (consp x) (= (length x) 2))
3466 (list (car x) (nth 1 x) t)
3468 val)))
3470 (defun org-get-packages-alist (var)
3472 "Get the packages alist and make sure it has 3 elements per entry."
3473 (mapcar (lambda (x)
3474 (if (and (consp x) (= (length x) 2))
3475 (list (car x) (nth 1 x) t)
3477 (default-value var)))
3479 ;; The following variables are defined here because is it also used
3480 ;; when formatting latex fragments. Originally it was part of the
3481 ;; LaTeX exporter, which is why the name includes "export".
3482 (defcustom org-export-latex-default-packages-alist
3483 '(("AUTO" "inputenc" t)
3484 ("T1" "fontenc" t)
3485 ("" "fixltx2e" nil)
3486 ("" "graphicx" t)
3487 ("" "longtable" nil)
3488 ("" "float" nil)
3489 ("" "wrapfig" nil)
3490 ("" "soul" t)
3491 ("" "textcomp" t)
3492 ("" "marvosym" t)
3493 ("" "wasysym" t)
3494 ("" "latexsym" t)
3495 ("" "amssymb" t)
3496 ("" "hyperref" nil)
3497 "\\tolerance=1000"
3499 "Alist of default packages to be inserted in the header.
3500 Change this only if one of the packages here causes an incompatibility
3501 with another package you are using.
3502 The packages in this list are needed by one part or another of Org-mode
3503 to function properly.
3505 - inputenc, fontenc: for basic font and character selection
3506 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3507 for interpreting the entities in `org-entities'. You can skip some of these
3508 packages if you don't use any of the symbols in it.
3509 - graphicx: for including images
3510 - float, wrapfig: for figure placement
3511 - longtable: for long tables
3512 - hyperref: for cross references
3514 Therefore you should not modify this variable unless you know what you
3515 are doing. The one reason to change it anyway is that you might be loading
3516 some other package that conflicts with one of the default packages.
3517 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3518 If SNIPPET-FLAG is t, the package also needs to be included when
3519 compiling LaTeX snippets into images for inclusion into HTML."
3520 :group 'org-export-latex
3521 :set 'org-set-packages-alist
3522 :get 'org-get-packages-alist
3523 :version "24.1"
3524 :type '(repeat
3525 (choice
3526 (list :tag "options/package pair"
3527 (string :tag "options")
3528 (string :tag "package")
3529 (boolean :tag "Snippet"))
3530 (string :tag "A line of LaTeX"))))
3532 (defcustom org-export-latex-packages-alist nil
3533 "Alist of packages to be inserted in every LaTeX header.
3534 These will be inserted after `org-export-latex-default-packages-alist'.
3535 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3536 SNIPPET-FLAG, when t, indicates that this package is also needed when
3537 turning LaTeX snippets into images for inclusion into HTML.
3538 Make sure that you only list packages here which:
3539 - you want in every file
3540 - do not conflict with the default packages in
3541 `org-export-latex-default-packages-alist'
3542 - do not conflict with the setup in `org-format-latex-header'."
3543 :group 'org-export-latex
3544 :set 'org-set-packages-alist
3545 :get 'org-get-packages-alist
3546 :type '(repeat
3547 (choice
3548 (list :tag "options/package pair"
3549 (string :tag "options")
3550 (string :tag "package")
3551 (boolean :tag "Snippet"))
3552 (string :tag "A line of LaTeX"))))
3555 (defgroup org-appearance nil
3556 "Settings for Org-mode appearance."
3557 :tag "Org Appearance"
3558 :group 'org)
3560 (defcustom org-level-color-stars-only nil
3561 "Non-nil means fontify only the stars in each headline.
3562 When nil, the entire headline is fontified.
3563 Changing it requires restart of `font-lock-mode' to become effective
3564 also in regions already fontified."
3565 :group 'org-appearance
3566 :type 'boolean)
3568 (defcustom org-hide-leading-stars nil
3569 "Non-nil means hide the first N-1 stars in a headline.
3570 This works by using the face `org-hide' for these stars. This
3571 face is white for a light background, and black for a dark
3572 background. You may have to customize the face `org-hide' to
3573 make this work.
3574 Changing it requires restart of `font-lock-mode' to become effective
3575 also in regions already fontified.
3576 You may also set this on a per-file basis by adding one of the following
3577 lines to the buffer:
3579 #+STARTUP: hidestars
3580 #+STARTUP: showstars"
3581 :group 'org-appearance
3582 :type 'boolean)
3584 (defcustom org-hidden-keywords nil
3585 "List of symbols corresponding to keywords to be hidden the org buffer.
3586 For example, a value '(title) for this list will make the document's title
3587 appear in the buffer without the initial #+TITLE: keyword."
3588 :group 'org-appearance
3589 :version "24.1"
3590 :type '(set (const :tag "#+AUTHOR" author)
3591 (const :tag "#+DATE" date)
3592 (const :tag "#+EMAIL" email)
3593 (const :tag "#+TITLE" title)))
3595 (defcustom org-custom-properties nil
3596 "List of properties (as strings) with a special meaning.
3597 The default use of these custom properties is to let the user
3598 hide them with `org-toggle-custom-properties-visibility'."
3599 :group 'org-properties
3600 :group 'org-appearance
3601 :version "24.3"
3602 :type '(repeat (string :tag "Property Name")))
3604 (defcustom org-fontify-done-headline nil
3605 "Non-nil means change the face of a headline if it is marked DONE.
3606 Normally, only the TODO/DONE keyword indicates the state of a headline.
3607 When this is non-nil, the headline after the keyword is set to the
3608 `org-headline-done' as an additional indication."
3609 :group 'org-appearance
3610 :type 'boolean)
3612 (defcustom org-fontify-emphasized-text t
3613 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3614 Changing this variable requires a restart of Emacs to take effect."
3615 :group 'org-appearance
3616 :type 'boolean)
3618 (defcustom org-fontify-whole-heading-line nil
3619 "Non-nil means fontify the whole line for headings.
3620 This is useful when setting a background color for the
3621 org-level-* faces."
3622 :group 'org-appearance
3623 :type 'boolean)
3625 (defcustom org-highlight-latex-fragments-and-specials nil
3626 "Non-nil means fontify what is treated specially by the exporters."
3627 :group 'org-appearance
3628 :type 'boolean)
3630 (defcustom org-hide-emphasis-markers nil
3631 "Non-nil mean font-lock should hide the emphasis marker characters."
3632 :group 'org-appearance
3633 :type 'boolean)
3635 (defcustom org-pretty-entities nil
3636 "Non-nil means show entities as UTF8 characters.
3637 When nil, the \\name form remains in the buffer."
3638 :group 'org-appearance
3639 :version "24.1"
3640 :type 'boolean)
3642 (defcustom org-pretty-entities-include-sub-superscripts t
3643 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3644 :group 'org-appearance
3645 :version "24.1"
3646 :type 'boolean)
3648 (defvar org-emph-re nil
3649 "Regular expression for matching emphasis.
3650 After a match, the match groups contain these elements:
3651 0 The match of the full regular expression, including the characters
3652 before and after the proper match
3653 1 The character before the proper match, or empty at beginning of line
3654 2 The proper match, including the leading and trailing markers
3655 3 The leading marker like * or /, indicating the type of highlighting
3656 4 The text between the emphasis markers, not including the markers
3657 5 The character after the match, empty at the end of a line")
3658 (defvar org-verbatim-re nil
3659 "Regular expression for matching verbatim text.")
3660 (defvar org-emphasis-regexp-components) ; defined just below
3661 (defvar org-emphasis-alist) ; defined just below
3662 (defun org-set-emph-re (var val)
3663 "Set variable and compute the emphasis regular expression."
3664 (set var val)
3665 (when (and (boundp 'org-emphasis-alist)
3666 (boundp 'org-emphasis-regexp-components)
3667 org-emphasis-alist org-emphasis-regexp-components)
3668 (let* ((e org-emphasis-regexp-components)
3669 (pre (car e))
3670 (post (nth 1 e))
3671 (border (nth 2 e))
3672 (body (nth 3 e))
3673 (nl (nth 4 e))
3674 (body1 (concat body "*?"))
3675 (markers (mapconcat 'car org-emphasis-alist ""))
3676 (vmarkers (mapconcat
3677 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3678 org-emphasis-alist "")))
3679 ;; make sure special characters appear at the right position in the class
3680 (if (string-match "\\^" markers)
3681 (setq markers (concat (replace-match "" t t markers) "^")))
3682 (if (string-match "-" markers)
3683 (setq markers (concat (replace-match "" t t markers) "-")))
3684 (if (string-match "\\^" vmarkers)
3685 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3686 (if (string-match "-" vmarkers)
3687 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3688 (if (> nl 0)
3689 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3690 (int-to-string nl) "\\}")))
3691 ;; Make the regexp
3692 (setq org-emph-re
3693 (concat "\\([" pre "]\\|^\\)"
3694 "\\("
3695 "\\([" markers "]\\)"
3696 "\\("
3697 "[^" border "]\\|"
3698 "[^" border "]"
3699 body1
3700 "[^" border "]"
3701 "\\)"
3702 "\\3\\)"
3703 "\\([" post "]\\|$\\)"))
3704 (setq org-verbatim-re
3705 (concat "\\([" pre "]\\|^\\)"
3706 "\\("
3707 "\\([" vmarkers "]\\)"
3708 "\\("
3709 "[^" border "]\\|"
3710 "[^" border "]"
3711 body1
3712 "[^" border "]"
3713 "\\)"
3714 "\\3\\)"
3715 "\\([" post "]\\|$\\)")))))
3717 (defcustom org-emphasis-regexp-components
3718 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3719 "Components used to build the regular expression for emphasis.
3720 This is a list with five entries. Terminology: In an emphasis string
3721 like \" *strong word* \", we call the initial space PREMATCH, the final
3722 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3723 and \"trong wor\" is the body. The different components in this variable
3724 specify what is allowed/forbidden in each part:
3726 pre Chars allowed as prematch. Beginning of line will be allowed too.
3727 post Chars allowed as postmatch. End of line will be allowed too.
3728 border The chars *forbidden* as border characters.
3729 body-regexp A regexp like \".\" to match a body character. Don't use
3730 non-shy groups here, and don't allow newline here.
3731 newline The maximum number of newlines allowed in an emphasis exp.
3733 Use customize to modify this, or restart Emacs after changing it."
3734 :group 'org-appearance
3735 :set 'org-set-emph-re
3736 :type '(list
3737 (sexp :tag "Allowed chars in pre ")
3738 (sexp :tag "Allowed chars in post ")
3739 (sexp :tag "Forbidden chars in border ")
3740 (sexp :tag "Regexp for body ")
3741 (integer :tag "number of newlines allowed")
3742 (option (boolean :tag "Please ignore this button"))))
3744 (defcustom org-emphasis-alist
3745 `(("*" bold "<b>" "</b>")
3746 ("/" italic "<i>" "</i>")
3747 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3748 ("=" org-code "<code>" "</code>" verbatim)
3749 ("~" org-verbatim "<code>" "</code>" verbatim)
3750 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3751 "<del>" "</del>")
3753 "Special syntax for emphasized text.
3754 Text starting and ending with a special character will be emphasized, for
3755 example *bold*, _underlined_ and /italic/. This variable sets the marker
3756 characters, the face to be used by font-lock for highlighting in Org-mode
3757 Emacs buffers, and the HTML tags to be used for this.
3758 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3759 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3760 Use customize to modify this, or restart Emacs after changing it."
3761 :group 'org-appearance
3762 :set 'org-set-emph-re
3763 :type '(repeat
3764 (list
3765 (string :tag "Marker character")
3766 (choice
3767 (face :tag "Font-lock-face")
3768 (plist :tag "Face property list"))
3769 (string :tag "HTML start tag")
3770 (string :tag "HTML end tag")
3771 (option (const verbatim)))))
3773 (defvar org-protecting-blocks
3774 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3775 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3776 This is needed for font-lock setup.")
3778 ;;; Miscellaneous options
3780 (defgroup org-completion nil
3781 "Completion in Org-mode."
3782 :tag "Org Completion"
3783 :group 'org)
3785 (defcustom org-completion-use-ido nil
3786 "Non-nil means use ido completion wherever possible.
3787 Note that `ido-mode' must be active for this variable to be relevant.
3788 If you decide to turn this variable on, you might well want to turn off
3789 `org-outline-path-complete-in-steps'.
3790 See also `org-completion-use-iswitchb'."
3791 :group 'org-completion
3792 :type 'boolean)
3794 (defcustom org-completion-use-iswitchb nil
3795 "Non-nil means use iswitchb completion wherever possible.
3796 Note that `iswitchb-mode' must be active for this variable to be relevant.
3797 If you decide to turn this variable on, you might well want to turn off
3798 `org-outline-path-complete-in-steps'.
3799 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3800 :group 'org-completion
3801 :type 'boolean)
3803 (defcustom org-completion-fallback-command 'hippie-expand
3804 "The expansion command called by \\[pcomplete] in normal context.
3805 Normal means, no org-mode-specific context."
3806 :group 'org-completion
3807 :type 'function)
3809 ;;; Functions and variables from their packages
3810 ;; Declared here to avoid compiler warnings
3812 ;; XEmacs only
3813 (defvar outline-mode-menu-heading)
3814 (defvar outline-mode-menu-show)
3815 (defvar outline-mode-menu-hide)
3816 (defvar zmacs-regions) ; XEmacs regions
3818 ;; Emacs only
3819 (defvar mark-active)
3821 ;; Various packages
3822 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3823 (declare-function calendar-forward-day "cal-move" (arg))
3824 (declare-function calendar-goto-date "cal-move" (date))
3825 (declare-function calendar-goto-today "cal-move" ())
3826 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3827 (defvar calc-embedded-close-formula)
3828 (defvar calc-embedded-open-formula)
3829 (declare-function cdlatex-tab "ext:cdlatex" ())
3830 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3831 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3832 (defvar font-lock-unfontify-region-function)
3833 (declare-function iswitchb-read-buffer "iswitchb"
3834 (prompt &optional default require-match start matches-set))
3835 (defvar iswitchb-temp-buflist)
3836 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3837 (defvar org-agenda-tags-todo-honor-ignore-options)
3838 (declare-function org-agenda-skip "org-agenda" ())
3839 (declare-function
3840 org-agenda-format-item "org-agenda"
3841 (extra txt &optional category tags dotime noprefix remove-re habitp))
3842 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3843 (declare-function org-agenda-change-all-lines "org-agenda"
3844 (newhead hdmarker &optional fixface just-this))
3845 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3846 (declare-function org-agenda-maybe-redo "org-agenda" ())
3847 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3848 (beg end))
3849 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3850 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3851 "org-agenda" (&optional end))
3852 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3853 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3854 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3855 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3856 (declare-function org-indent-mode "org-indent" (&optional arg))
3857 (declare-function parse-time-string "parse-time" (string))
3858 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3859 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3860 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3861 (defvar remember-data-file)
3862 (defvar texmathp-why)
3863 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3864 (declare-function table--at-cell-p "table" (position &optional object at-column))
3866 (defvar w3m-current-url)
3867 (defvar w3m-current-title)
3869 (defvar org-latex-regexps)
3871 ;;; Autoload and prepare some org modules
3873 ;; Some table stuff that needs to be defined here, because it is used
3874 ;; by the functions setting up org-mode or checking for table context.
3876 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3877 "Detect an org-type or table-type table.")
3878 (defconst org-table-line-regexp "^[ \t]*|"
3879 "Detect an org-type table line.")
3880 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3881 "Detect an org-type table line.")
3882 (defconst org-table-hline-regexp "^[ \t]*|-"
3883 "Detect an org-type table hline.")
3884 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3885 "Detect a table-type table hline.")
3886 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3887 "Detect the first line outside a table when searching from within it.
3888 This works for both table types.")
3890 ;; Autoload the functions in org-table.el that are needed by functions here.
3892 (eval-and-compile
3893 (org-autoload "org-table"
3894 '(org-table-begin org-table-blank-field org-table-end)))
3896 ;;;###autoload
3897 (defun turn-on-orgtbl ()
3898 "Unconditionally turn on `orgtbl-mode'."
3899 (require 'org-table)
3900 (orgtbl-mode 1))
3902 (defun org-at-table-p (&optional table-type)
3903 "Return t if the cursor is inside an org-type table.
3904 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3905 (if org-enable-table-editor
3906 (save-excursion
3907 (beginning-of-line 1)
3908 (looking-at (if table-type org-table-any-line-regexp
3909 org-table-line-regexp)))
3910 nil))
3911 (defsubst org-table-p () (org-at-table-p))
3913 (defun org-at-table.el-p ()
3914 "Return t if and only if we are at a table.el table."
3915 (and (org-at-table-p 'any)
3916 (save-excursion
3917 (goto-char (org-table-begin 'any))
3918 (looking-at org-table1-hline-regexp))))
3920 (defun org-table-recognize-table.el ()
3921 "If there is a table.el table nearby, recognize it and move into it."
3922 (if org-table-tab-recognizes-table.el
3923 (if (org-at-table.el-p)
3924 (progn
3925 (beginning-of-line 1)
3926 (if (looking-at org-table-dataline-regexp)
3928 (if (looking-at org-table1-hline-regexp)
3929 (progn
3930 (beginning-of-line 2)
3931 (if (looking-at org-table-any-border-regexp)
3932 (beginning-of-line -1)))))
3933 (if (re-search-forward "|" (org-table-end t) t)
3934 (progn
3935 (require 'table)
3936 (if (table--at-cell-p (point))
3938 (message "recognizing table.el table...")
3939 (table-recognize-table)
3940 (message "recognizing table.el table...done")))
3941 (error "This should not happen"))
3943 nil)
3944 nil))
3946 (defun org-at-table-hline-p ()
3947 "Return t if the cursor is inside a hline in a table."
3948 (if org-enable-table-editor
3949 (save-excursion
3950 (beginning-of-line 1)
3951 (looking-at org-table-hline-regexp))
3952 nil))
3954 (defvar org-table-clean-did-remove-column nil)
3955 (defun org-table-map-tables (function &optional quietly)
3956 "Apply FUNCTION to the start of all tables in the buffer."
3957 (save-excursion
3958 (save-restriction
3959 (widen)
3960 (goto-char (point-min))
3961 (while (re-search-forward org-table-any-line-regexp nil t)
3962 (unless quietly
3963 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3964 (beginning-of-line 1)
3965 (when (and (looking-at org-table-line-regexp)
3966 ;; Exclude tables in src/example/verbatim/clocktable blocks
3967 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
3968 (save-excursion (funcall function))
3969 (or (looking-at org-table-line-regexp)
3970 (forward-char 1)))
3971 (re-search-forward org-table-any-border-regexp nil 1))))
3972 (unless quietly (message "Mapping tables: done")))
3974 ;; Declare and autoload functions from org-exp.el & Co
3976 (declare-function org-default-export-plist "org-exp")
3977 (declare-function org-infile-export-plist "org-exp")
3978 (declare-function org-get-current-options "org-exp")
3980 ;; Declare and autoload functions from org-agenda.el
3982 (eval-and-compile
3983 (org-autoload "org-agenda"
3984 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3986 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3987 (declare-function org-clock-update-mode-line "org-clock" ())
3988 (declare-function org-resolve-clocks "org-clock"
3989 (&optional also-non-dangling-p prompt last-valid))
3990 (defvar org-clock-start-time)
3991 (defvar org-clock-marker (make-marker)
3992 "Marker recording the last clock-in.")
3993 (defvar org-clock-hd-marker (make-marker)
3994 "Marker recording the last clock-in, but the headline position.")
3995 (defvar org-clock-heading ""
3996 "The heading of the current clock entry.")
3997 (defun org-clock-is-active ()
3998 "Return non-nil if clock is currently running.
3999 The return value is actually the clock marker."
4000 (marker-buffer org-clock-marker))
4002 (eval-and-compile
4003 (org-autoload "org-clock" '(org-clock-remove-overlays
4004 org-clock-update-time-maybe
4005 org-clocktable-shift)))
4007 (defun org-check-running-clock ()
4008 "Check if the current buffer contains the running clock.
4009 If yes, offer to stop it and to save the buffer with the changes."
4010 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4011 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4012 (buffer-name))))
4013 (org-clock-out)
4014 (when (y-or-n-p "Save changed buffer?")
4015 (save-buffer))))
4017 (defun org-clocktable-try-shift (dir n)
4018 "Check if this line starts a clock table, if yes, shift the time block."
4019 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4020 (org-clocktable-shift dir n)))
4022 ;;;###autoload
4023 (defun org-clock-persistence-insinuate ()
4024 "Set up hooks for clock persistence."
4025 (require 'org-clock)
4026 (add-hook 'org-mode-hook 'org-clock-load)
4027 (add-hook 'kill-emacs-hook 'org-clock-save))
4029 ;; Define the variable already here, to make sure we have it.
4030 (defvar org-indent-mode nil
4031 "Non-nil if Org-Indent mode is enabled.
4032 Use the command `org-indent-mode' to change this variable.")
4034 ;; Autoload archiving code
4035 ;; The stuff that is needed for cycling and tags has to be defined here.
4037 (defgroup org-archive nil
4038 "Options concerning archiving in Org-mode."
4039 :tag "Org Archive"
4040 :group 'org-structure)
4042 (defcustom org-archive-location "%s_archive::"
4043 "The location where subtrees should be archived.
4045 The value of this variable is a string, consisting of two parts,
4046 separated by a double-colon. The first part is a filename and
4047 the second part is a headline.
4049 When the filename is omitted, archiving happens in the same file.
4050 %s in the filename will be replaced by the current file
4051 name (without the directory part). Archiving to a different file
4052 is useful to keep archived entries from contributing to the
4053 Org-mode Agenda.
4055 The archived entries will be filed as subtrees of the specified
4056 headline. When the headline is omitted, the subtrees are simply
4057 filed away at the end of the file, as top-level entries. Also in
4058 the heading you can use %s to represent the file name, this can be
4059 useful when using the same archive for a number of different files.
4061 Here are a few examples:
4062 \"%s_archive::\"
4063 If the current file is Projects.org, archive in file
4064 Projects.org_archive, as top-level trees. This is the default.
4066 \"::* Archived Tasks\"
4067 Archive in the current file, under the top-level headline
4068 \"* Archived Tasks\".
4070 \"~/org/archive.org::\"
4071 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4073 \"~/org/archive.org::* From %s\"
4074 Archive in file ~/org/archive.org (absolute path), under headlines
4075 \"From FILENAME\" where file name is the current file name.
4077 \"~/org/datetree.org::datetree/* Finished Tasks\"
4078 The \"datetree/\" string is special, signifying to archive
4079 items to the datetree. Items are placed in either the CLOSED
4080 date of the item, or the current date if there is no CLOSED date.
4081 The heading will be a subentry to the current date. There doesn't
4082 need to be a heading, but there always needs to be a slash after
4083 datetree. For example, to store archived items directly in the
4084 datetree, use \"~/org/datetree.org::datetree/\".
4086 \"basement::** Finished Tasks\"
4087 Archive in file ./basement (relative path), as level 3 trees
4088 below the level 2 heading \"** Finished Tasks\".
4090 You may set this option on a per-file basis by adding to the buffer a
4091 line like
4093 #+ARCHIVE: basement::** Finished Tasks
4095 You may also define it locally for a subtree by setting an ARCHIVE property
4096 in the entry. If such a property is found in an entry, or anywhere up
4097 the hierarchy, it will be used."
4098 :group 'org-archive
4099 :type 'string)
4101 (defcustom org-archive-tag "ARCHIVE"
4102 "The tag that marks a subtree as archived.
4103 An archived subtree does not open during visibility cycling, and does
4104 not contribute to the agenda listings.
4105 After changing this, font-lock must be restarted in the relevant buffers to
4106 get the proper fontification."
4107 :group 'org-archive
4108 :group 'org-keywords
4109 :type 'string)
4111 (defcustom org-agenda-skip-archived-trees t
4112 "Non-nil means the agenda will skip any items located in archived trees.
4113 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4114 variable is no longer recommended, you should leave it at the value t.
4115 Instead, use the key `v' to cycle the archives-mode in the agenda."
4116 :group 'org-archive
4117 :group 'org-agenda-skip
4118 :type 'boolean)
4120 (defcustom org-columns-skip-archived-trees t
4121 "Non-nil means ignore archived trees when creating column view."
4122 :group 'org-archive
4123 :group 'org-properties
4124 :type 'boolean)
4126 (defcustom org-cycle-open-archived-trees nil
4127 "Non-nil means `org-cycle' will open archived trees.
4128 An archived tree is a tree marked with the tag ARCHIVE.
4129 When nil, archived trees will stay folded. You can still open them with
4130 normal outline commands like `show-all', but not with the cycling commands."
4131 :group 'org-archive
4132 :group 'org-cycle
4133 :type 'boolean)
4135 (defcustom org-sparse-tree-open-archived-trees nil
4136 "Non-nil means sparse tree construction shows matches in archived trees.
4137 When nil, matches in these trees are highlighted, but the trees are kept in
4138 collapsed state."
4139 :group 'org-archive
4140 :group 'org-sparse-trees
4141 :type 'boolean)
4143 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4144 "The default date type when building a sparse tree.
4145 When this is nil, a date is a scheduled or a deadline timestamp.
4146 Otherwise, these types are allowed:
4148 all: all timestamps
4149 active: only active timestamps (<...>)
4150 inactive: only inactive timestamps (<...)
4151 scheduled: only scheduled timestamps
4152 deadline: only deadline timestamps"
4153 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4154 (const :tag "All timestamps" all)
4155 (const :tag "Only active timestamps" active)
4156 (const :tag "Only inactive timestamps" inactive)
4157 (const :tag "Only scheduled timestamps" scheduled)
4158 (const :tag "Only deadline timestamps" deadline))
4159 :version "24.3"
4160 :group 'org-sparse-trees)
4162 (defun org-cycle-hide-archived-subtrees (state)
4163 "Re-hide all archived subtrees after a visibility state change."
4164 (when (and (not org-cycle-open-archived-trees)
4165 (not (memq state '(overview folded))))
4166 (save-excursion
4167 (let* ((globalp (memq state '(contents all)))
4168 (beg (if globalp (point-min) (point)))
4169 (end (if globalp (point-max) (org-end-of-subtree t))))
4170 (org-hide-archived-subtrees beg end)
4171 (goto-char beg)
4172 (if (looking-at (concat ".*:" org-archive-tag ":"))
4173 (message "%s" (substitute-command-keys
4174 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4176 (defun org-force-cycle-archived ()
4177 "Cycle subtree even if it is archived."
4178 (interactive)
4179 (setq this-command 'org-cycle)
4180 (let ((org-cycle-open-archived-trees t))
4181 (call-interactively 'org-cycle)))
4183 (defun org-hide-archived-subtrees (beg end)
4184 "Re-hide all archived subtrees after a visibility state change."
4185 (save-excursion
4186 (let* ((re (concat ":" org-archive-tag ":")))
4187 (goto-char beg)
4188 (while (re-search-forward re end t)
4189 (when (org-at-heading-p)
4190 (org-flag-subtree t)
4191 (org-end-of-subtree t))))))
4193 (declare-function outline-end-of-heading "outline" ())
4194 (declare-function outline-flag-region "outline" (from to flag))
4195 (defun org-flag-subtree (flag)
4196 (save-excursion
4197 (org-back-to-heading t)
4198 (outline-end-of-heading)
4199 (outline-flag-region (point)
4200 (progn (org-end-of-subtree t) (point))
4201 flag)))
4203 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4205 (eval-and-compile
4206 (org-autoload "org-archive"
4207 '(org-add-archive-files)))
4209 ;; Autoload Column View Code
4211 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4212 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4213 (declare-function org-columns-compute "org-colview" (property))
4215 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4216 '(org-columns-number-to-string
4217 org-columns-get-format-and-top-level
4218 org-columns-compute
4219 org-columns-remove-overlays))
4221 ;; Autoload ID code
4223 (declare-function org-id-store-link "org-id")
4224 (declare-function org-id-locations-load "org-id")
4225 (declare-function org-id-locations-save "org-id")
4226 (defvar org-id-track-globally)
4227 (org-autoload "org-id"
4228 '(org-id-new
4229 org-id-copy
4230 org-id-get-with-outline-path-completion
4231 org-id-get-with-outline-drilling))
4233 ;;; Variables for pre-computed regular expressions, all buffer local
4235 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4236 "Matches first line of a hidden block.")
4237 (make-variable-buffer-local 'org-drawer-regexp)
4238 (defvar org-todo-regexp nil
4239 "Matches any of the TODO state keywords.")
4240 (make-variable-buffer-local 'org-todo-regexp)
4241 (defvar org-not-done-regexp nil
4242 "Matches any of the TODO state keywords except the last one.")
4243 (make-variable-buffer-local 'org-not-done-regexp)
4244 (defvar org-not-done-heading-regexp nil
4245 "Matches a TODO headline that is not done.")
4246 (make-variable-buffer-local 'org-not-done-regexp)
4247 (defvar org-todo-line-regexp nil
4248 "Matches a headline and puts TODO state into group 2 if present.")
4249 (make-variable-buffer-local 'org-todo-line-regexp)
4250 (defvar org-complex-heading-regexp nil
4251 "Matches a headline and puts everything into groups:
4252 group 1: the stars
4253 group 2: The todo keyword, maybe
4254 group 3: Priority cookie
4255 group 4: True headline
4256 group 5: Tags")
4257 (make-variable-buffer-local 'org-complex-heading-regexp)
4258 (defvar org-complex-heading-regexp-format nil
4259 "Printf format to make regexp to match an exact headline.
4260 This regexp will match the headline of any node which has the
4261 exact headline text that is put into the format, but may have any
4262 TODO state, priority and tags.")
4263 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4264 (defvar org-todo-line-tags-regexp nil
4265 "Matches a headline and puts TODO state into group 2 if present.
4266 Also put tags into group 4 if tags are present.")
4267 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4268 (defvar org-ds-keyword-length 12
4269 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4270 (make-variable-buffer-local 'org-ds-keyword-length)
4271 (defvar org-deadline-regexp nil
4272 "Matches the DEADLINE keyword.")
4273 (make-variable-buffer-local 'org-deadline-regexp)
4274 (defvar org-deadline-time-regexp nil
4275 "Matches the DEADLINE keyword together with a time stamp.")
4276 (make-variable-buffer-local 'org-deadline-time-regexp)
4277 (defvar org-deadline-line-regexp nil
4278 "Matches the DEADLINE keyword and the rest of the line.")
4279 (make-variable-buffer-local 'org-deadline-line-regexp)
4280 (defvar org-scheduled-regexp nil
4281 "Matches the SCHEDULED keyword.")
4282 (make-variable-buffer-local 'org-scheduled-regexp)
4283 (defvar org-scheduled-time-regexp nil
4284 "Matches the SCHEDULED keyword together with a time stamp.")
4285 (make-variable-buffer-local 'org-scheduled-time-regexp)
4286 (defvar org-closed-time-regexp nil
4287 "Matches the CLOSED keyword together with a time stamp.")
4288 (make-variable-buffer-local 'org-closed-time-regexp)
4290 (defvar org-keyword-time-regexp nil
4291 "Matches any of the 4 keywords, together with the time stamp.")
4292 (make-variable-buffer-local 'org-keyword-time-regexp)
4293 (defvar org-keyword-time-not-clock-regexp nil
4294 "Matches any of the 3 keywords, together with the time stamp.")
4295 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4296 (defvar org-maybe-keyword-time-regexp nil
4297 "Matches a timestamp, possibly preceded by a keyword.")
4298 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4299 (defvar org-all-time-keywords nil
4300 "List of time keywords.")
4301 (make-variable-buffer-local 'org-all-time-keywords)
4303 (defconst org-plain-time-of-day-regexp
4304 (concat
4305 "\\(\\<[012]?[0-9]"
4306 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4307 "\\(--?"
4308 "\\(\\<[012]?[0-9]"
4309 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4310 "\\)?")
4311 "Regular expression to match a plain time or time range.
4312 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4313 groups carry important information:
4314 0 the full match
4315 1 the first time, range or not
4316 8 the second time, if it is a range.")
4318 (defconst org-plain-time-extension-regexp
4319 (concat
4320 "\\(\\<[012]?[0-9]"
4321 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4322 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4323 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4324 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4325 groups carry important information:
4326 0 the full match
4327 7 hours of duration
4328 9 minutes of duration")
4330 (defconst org-stamp-time-of-day-regexp
4331 (concat
4332 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4333 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4334 "\\(--?"
4335 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4336 "Regular expression to match a timestamp time or time range.
4337 After a match, the following groups carry important information:
4338 0 the full match
4339 1 date plus weekday, for back referencing to make sure both times are on the same day
4340 2 the first time, range or not
4341 4 the second time, if it is a range.")
4343 (defconst org-startup-options
4344 '(("fold" org-startup-folded t)
4345 ("overview" org-startup-folded t)
4346 ("nofold" org-startup-folded nil)
4347 ("showall" org-startup-folded nil)
4348 ("showeverything" org-startup-folded showeverything)
4349 ("content" org-startup-folded content)
4350 ("indent" org-startup-indented t)
4351 ("noindent" org-startup-indented nil)
4352 ("hidestars" org-hide-leading-stars t)
4353 ("showstars" org-hide-leading-stars nil)
4354 ("odd" org-odd-levels-only t)
4355 ("oddeven" org-odd-levels-only nil)
4356 ("align" org-startup-align-all-tables t)
4357 ("noalign" org-startup-align-all-tables nil)
4358 ("inlineimages" org-startup-with-inline-images t)
4359 ("noinlineimages" org-startup-with-inline-images nil)
4360 ("customtime" org-display-custom-times t)
4361 ("logdone" org-log-done time)
4362 ("lognotedone" org-log-done note)
4363 ("nologdone" org-log-done nil)
4364 ("lognoteclock-out" org-log-note-clock-out t)
4365 ("nolognoteclock-out" org-log-note-clock-out nil)
4366 ("logrepeat" org-log-repeat state)
4367 ("lognoterepeat" org-log-repeat note)
4368 ("nologrepeat" org-log-repeat nil)
4369 ("logreschedule" org-log-reschedule time)
4370 ("lognotereschedule" org-log-reschedule note)
4371 ("nologreschedule" org-log-reschedule nil)
4372 ("logredeadline" org-log-redeadline time)
4373 ("lognoteredeadline" org-log-redeadline note)
4374 ("nologredeadline" org-log-redeadline nil)
4375 ("logrefile" org-log-refile time)
4376 ("lognoterefile" org-log-refile note)
4377 ("nologrefile" org-log-refile nil)
4378 ("fninline" org-footnote-define-inline t)
4379 ("nofninline" org-footnote-define-inline nil)
4380 ("fnlocal" org-footnote-section nil)
4381 ("fnauto" org-footnote-auto-label t)
4382 ("fnprompt" org-footnote-auto-label nil)
4383 ("fnconfirm" org-footnote-auto-label confirm)
4384 ("fnplain" org-footnote-auto-label plain)
4385 ("fnadjust" org-footnote-auto-adjust t)
4386 ("nofnadjust" org-footnote-auto-adjust nil)
4387 ("constcgs" constants-unit-system cgs)
4388 ("constSI" constants-unit-system SI)
4389 ("noptag" org-tag-persistent-alist nil)
4390 ("hideblocks" org-hide-block-startup t)
4391 ("nohideblocks" org-hide-block-startup nil)
4392 ("beamer" org-startup-with-beamer-mode t)
4393 ("entitiespretty" org-pretty-entities t)
4394 ("entitiesplain" org-pretty-entities nil))
4395 "Variable associated with STARTUP options for org-mode.
4396 Each element is a list of three items: the startup options (as written
4397 in the #+STARTUP line), the corresponding variable, and the value to set
4398 this variable to if the option is found. An optional forth element PUSH
4399 means to push this value onto the list in the variable.")
4401 (defun org-update-property-plist (key val props)
4402 "Update PROPS with KEY and VAL."
4403 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4404 (key (if appending (substring key 0 (- (length key) 1)) key))
4405 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4406 (previous (cdr (assoc key props))))
4407 (if appending
4408 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4409 (cons (cons key val) remainder))))
4411 (defconst org-block-regexp
4412 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4413 "Regular expression for hiding blocks.")
4414 (defconst org-heading-keyword-regexp-format
4415 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4416 "Printf format for a regexp matching an headline with some keyword.
4417 This regexp will match the headline of any node which has the
4418 exact keyword that is put into the format. The keyword isn't in
4419 any group by default, but the stars and the body are.")
4420 (defconst org-heading-keyword-maybe-regexp-format
4421 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4422 "Printf format for a regexp matching an headline, possibly with some keyword.
4423 This regexp can match any headline with the specified keyword, or
4424 without a keyword. The keyword isn't in any group by default,
4425 but the stars and the body are.")
4427 (defun org-set-regexps-and-options ()
4428 "Precompute regular expressions for current buffer."
4429 (when (derived-mode-p 'org-mode)
4430 (org-set-local 'org-todo-kwd-alist nil)
4431 (org-set-local 'org-todo-key-alist nil)
4432 (org-set-local 'org-todo-key-trigger nil)
4433 (org-set-local 'org-todo-keywords-1 nil)
4434 (org-set-local 'org-done-keywords nil)
4435 (org-set-local 'org-todo-heads nil)
4436 (org-set-local 'org-todo-sets nil)
4437 (org-set-local 'org-todo-log-states nil)
4438 (org-set-local 'org-file-properties nil)
4439 (org-set-local 'org-file-tags nil)
4440 (let ((re (org-make-options-regexp
4441 '("CATEGORY" "TODO" "COLUMNS"
4442 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4443 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4444 "OPTIONS")
4445 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4446 (splitre "[ \t]+")
4447 (scripts org-use-sub-superscripts)
4448 kwds kws0 kwsa key log value cat arch tags const links hw dws
4449 tail sep kws1 prio props ftags drawers beamer-p
4450 ext-setup-or-nil setup-contents (start 0))
4451 (save-excursion
4452 (save-restriction
4453 (widen)
4454 (goto-char (point-min))
4455 (while (or (and ext-setup-or-nil
4456 (string-match re ext-setup-or-nil start)
4457 (setq start (match-end 0)))
4458 (and (setq ext-setup-or-nil nil start 0)
4459 (re-search-forward re nil t)))
4460 (setq key (upcase (match-string 1 ext-setup-or-nil))
4461 value (org-match-string-no-properties 2 ext-setup-or-nil))
4462 (if (stringp value) (setq value (org-trim value)))
4463 (cond
4464 ((equal key "CATEGORY")
4465 (setq cat value))
4466 ((member key '("SEQ_TODO" "TODO"))
4467 (push (cons 'sequence (org-split-string value splitre)) kwds))
4468 ((equal key "TYP_TODO")
4469 (push (cons 'type (org-split-string value splitre)) kwds))
4470 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4471 ;; general TODO-like setup
4472 (push (cons (intern (downcase (match-string 1 key)))
4473 (org-split-string value splitre)) kwds))
4474 ((equal key "TAGS")
4475 (setq tags (append tags (if tags '("\\n") nil)
4476 (org-split-string value splitre))))
4477 ((equal key "COLUMNS")
4478 (org-set-local 'org-columns-default-format value))
4479 ((equal key "LINK")
4480 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4481 (push (cons (match-string 1 value)
4482 (org-trim (match-string 2 value)))
4483 links)))
4484 ((equal key "PRIORITIES")
4485 (setq prio (org-split-string value " +")))
4486 ((equal key "PROPERTY")
4487 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4488 (setq props (org-update-property-plist (match-string 1 value)
4489 (match-string 2 value)
4490 props))))
4491 ((equal key "FILETAGS")
4492 (when (string-match "\\S-" value)
4493 (setq ftags
4494 (append
4495 ftags
4496 (apply 'append
4497 (mapcar (lambda (x) (org-split-string x ":"))
4498 (org-split-string value)))))))
4499 ((equal key "DRAWERS")
4500 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4501 ((equal key "CONSTANTS")
4502 (setq const (append const (org-split-string value splitre))))
4503 ((equal key "STARTUP")
4504 (let ((opts (org-split-string value splitre))
4505 l var val)
4506 (while (setq l (pop opts))
4507 (when (setq l (assoc l org-startup-options))
4508 (setq var (nth 1 l) val (nth 2 l))
4509 (if (not (nth 3 l))
4510 (set (make-local-variable var) val)
4511 (if (not (listp (symbol-value var)))
4512 (set (make-local-variable var) nil))
4513 (set (make-local-variable var) (symbol-value var))
4514 (add-to-list var val))))))
4515 ((equal key "ARCHIVE")
4516 (setq arch value)
4517 (remove-text-properties 0 (length arch)
4518 '(face t fontified t) arch))
4519 ((equal key "LATEX_CLASS")
4520 (setq beamer-p (equal value "beamer")))
4521 ((equal key "OPTIONS")
4522 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4523 (setq scripts (read (match-string 2 value)))))
4524 ((equal key "SETUPFILE")
4525 (setq setup-contents (org-file-contents
4526 (expand-file-name
4527 (org-remove-double-quotes value))
4528 'noerror))
4529 (if (not ext-setup-or-nil)
4530 (setq ext-setup-or-nil setup-contents start 0)
4531 (setq ext-setup-or-nil
4532 (concat (substring ext-setup-or-nil 0 start)
4533 "\n" setup-contents "\n"
4534 (substring ext-setup-or-nil start)))))))
4535 ;; search for property blocks
4536 (goto-char (point-min))
4537 (while (re-search-forward org-block-regexp nil t)
4538 (when (equal "PROPERTY" (upcase (match-string 1)))
4539 (setq value (replace-regexp-in-string
4540 "[\n\r]" " " (match-string 4)))
4541 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4542 (setq props (org-update-property-plist (match-string 1 value)
4543 (match-string 2 value)
4544 props)))))))
4545 (org-set-local 'org-use-sub-superscripts scripts)
4546 (when cat
4547 (org-set-local 'org-category (intern cat))
4548 (push (cons "CATEGORY" cat) props))
4549 (when prio
4550 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4551 (setq prio (mapcar 'string-to-char prio))
4552 (org-set-local 'org-highest-priority (nth 0 prio))
4553 (org-set-local 'org-lowest-priority (nth 1 prio))
4554 (org-set-local 'org-default-priority (nth 2 prio)))
4555 (and props (org-set-local 'org-file-properties (nreverse props)))
4556 (and ftags (org-set-local 'org-file-tags
4557 (mapcar 'org-add-prop-inherited ftags)))
4558 (and drawers (org-set-local 'org-drawers drawers))
4559 (and arch (org-set-local 'org-archive-location arch))
4560 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4561 ;; Process the TODO keywords
4562 (unless kwds
4563 ;; Use the global values as if they had been given locally.
4564 (setq kwds (default-value 'org-todo-keywords))
4565 (if (stringp (car kwds))
4566 (setq kwds (list (cons org-todo-interpretation
4567 (default-value 'org-todo-keywords)))))
4568 (setq kwds (reverse kwds)))
4569 (setq kwds (nreverse kwds))
4570 (let (inter kws kw)
4571 (while (setq kws (pop kwds))
4572 (let ((kws (or
4573 (run-hook-with-args-until-success
4574 'org-todo-setup-filter-hook kws)
4575 kws)))
4576 (setq inter (pop kws) sep (member "|" kws)
4577 kws0 (delete "|" (copy-sequence kws))
4578 kwsa nil
4579 kws1 (mapcar
4580 (lambda (x)
4581 ;; 1 2
4582 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4583 (progn
4584 (setq kw (match-string 1 x)
4585 key (and (match-end 2) (match-string 2 x))
4586 log (org-extract-log-state-settings x))
4587 (push (cons kw (and key (string-to-char key))) kwsa)
4588 (and log (push log org-todo-log-states))
4590 (error "Invalid TODO keyword %s" x)))
4591 kws0)
4592 kwsa (if kwsa (append '((:startgroup))
4593 (nreverse kwsa)
4594 '((:endgroup))))
4595 hw (car kws1)
4596 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4597 tail (list inter hw (car dws) (org-last dws))))
4598 (add-to-list 'org-todo-heads hw 'append)
4599 (push kws1 org-todo-sets)
4600 (setq org-done-keywords (append org-done-keywords dws nil))
4601 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4602 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4603 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4604 (setq org-todo-sets (nreverse org-todo-sets)
4605 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4606 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4607 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4608 ;; Process the constants
4609 (when const
4610 (let (e cst)
4611 (while (setq e (pop const))
4612 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4613 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4614 (setq org-table-formula-constants-local cst)))
4616 ;; Process the tags.
4617 (when tags
4618 (let (e tgs)
4619 (while (setq e (pop tags))
4620 (cond
4621 ((equal e "{") (push '(:startgroup) tgs))
4622 ((equal e "}") (push '(:endgroup) tgs))
4623 ((equal e "\\n") (push '(:newline) tgs))
4624 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4625 (push (cons (match-string 1 e)
4626 (string-to-char (match-string 2 e)))
4627 tgs))
4628 (t (push (list e) tgs))))
4629 (org-set-local 'org-tag-alist nil)
4630 (while (setq e (pop tgs))
4631 (or (and (stringp (car e))
4632 (assoc (car e) org-tag-alist))
4633 (push e org-tag-alist)))))
4635 ;; Compute the regular expressions and other local variables.
4636 ;; Using `org-outline-regexp-bol' would complicate them much,
4637 ;; because of the fixed white space at the end of that string.
4638 (if (not org-done-keywords)
4639 (setq org-done-keywords (and org-todo-keywords-1
4640 (list (org-last org-todo-keywords-1)))))
4641 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4642 (length org-scheduled-string)
4643 (length org-clock-string)
4644 (length org-closed-string)))
4645 org-drawer-regexp
4646 (concat "^[ \t]*:\\("
4647 (mapconcat 'regexp-quote org-drawers "\\|")
4648 "\\):[ \t]*$")
4649 org-not-done-keywords
4650 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4651 org-todo-regexp
4652 (concat "\\("
4653 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4654 "\\)")
4655 org-not-done-regexp
4656 (concat "\\("
4657 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4658 "\\)")
4659 org-not-done-heading-regexp
4660 (format org-heading-keyword-regexp-format org-not-done-regexp)
4661 org-todo-line-regexp
4662 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4663 org-complex-heading-regexp
4664 (concat "^\\(\\*+\\)"
4665 "\\(?: +" org-todo-regexp "\\)?"
4666 "\\(?: +\\(\\[#.\\]\\)\\)?"
4667 "\\(?: +\\(.*?\\)\\)??"
4668 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4669 "[ \t]*$")
4670 org-complex-heading-regexp-format
4671 (concat "^\\(\\*+\\)"
4672 "\\(?: +" org-todo-regexp "\\)?"
4673 "\\(?: +\\(\\[#.\\]\\)\\)?"
4674 "\\(?: +"
4675 ;; Stats cookies can be stuck to body.
4676 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4677 "\\(%s\\)"
4678 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4679 "\\)"
4680 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4681 "[ \t]*$")
4682 org-todo-line-tags-regexp
4683 (concat "^\\(\\*+\\)"
4684 "\\(?: +" org-todo-regexp "\\)?"
4685 "\\(?: +\\(.*?\\)\\)??"
4686 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4687 "[ \t]*$")
4688 org-deadline-regexp (concat "\\<" org-deadline-string)
4689 org-deadline-time-regexp
4690 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4691 org-deadline-line-regexp
4692 (concat "\\<\\(" org-deadline-string "\\).*")
4693 org-scheduled-regexp
4694 (concat "\\<" org-scheduled-string)
4695 org-scheduled-time-regexp
4696 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4697 org-closed-time-regexp
4698 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4699 org-keyword-time-regexp
4700 (concat "\\<\\(" org-scheduled-string
4701 "\\|" org-deadline-string
4702 "\\|" org-closed-string
4703 "\\|" org-clock-string "\\)"
4704 " *[[<]\\([^]>]+\\)[]>]")
4705 org-keyword-time-not-clock-regexp
4706 (concat "\\<\\(" org-scheduled-string
4707 "\\|" org-deadline-string
4708 "\\|" org-closed-string
4709 "\\)"
4710 " *[[<]\\([^]>]+\\)[]>]")
4711 org-maybe-keyword-time-regexp
4712 (concat "\\(\\<\\(" org-scheduled-string
4713 "\\|" org-deadline-string
4714 "\\|" org-closed-string
4715 "\\|" org-clock-string "\\)\\)?"
4716 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4717 org-all-time-keywords
4718 (mapcar (lambda (w) (substring w 0 -1))
4719 (list org-scheduled-string org-deadline-string
4720 org-clock-string org-closed-string))
4722 (org-compute-latex-and-specials-regexp)
4723 (org-set-font-lock-defaults))))
4725 (defun org-file-contents (file &optional noerror)
4726 "Return the contents of FILE, as a string."
4727 (if (or (not file)
4728 (not (file-readable-p file)))
4729 (if noerror
4730 (progn
4731 (message "Cannot read file \"%s\"" file)
4732 (ding) (sit-for 2)
4734 (error "Cannot read file \"%s\"" file))
4735 (with-temp-buffer
4736 (insert-file-contents file)
4737 (buffer-string))))
4739 (defun org-extract-log-state-settings (x)
4740 "Extract the log state setting from a TODO keyword string.
4741 This will extract info from a string like \"WAIT(w@/!)\"."
4742 (let (kw key log1 log2)
4743 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4744 (setq kw (match-string 1 x)
4745 key (and (match-end 2) (match-string 2 x))
4746 log1 (and (match-end 3) (match-string 3 x))
4747 log2 (and (match-end 4) (match-string 4 x)))
4748 (and (or log1 log2)
4749 (list kw
4750 (and log1 (if (equal log1 "!") 'time 'note))
4751 (and log2 (if (equal log2 "!") 'time 'note)))))))
4753 (defun org-remove-keyword-keys (list)
4754 "Remove a pair of parenthesis at the end of each string in LIST."
4755 (mapcar (lambda (x)
4756 (if (string-match "(.*)$" x)
4757 (substring x 0 (match-beginning 0))
4759 list))
4761 (defun org-assign-fast-keys (alist)
4762 "Assign fast keys to a keyword-key alist.
4763 Respect keys that are already there."
4764 (let (new e (alt ?0))
4765 (while (setq e (pop alist))
4766 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4767 (cdr e)) ;; Key already assigned.
4768 (push e new)
4769 (let ((clist (string-to-list (downcase (car e))))
4770 (used (append new alist)))
4771 (when (= (car clist) ?@)
4772 (pop clist))
4773 (while (and clist (rassoc (car clist) used))
4774 (pop clist))
4775 (unless clist
4776 (while (rassoc alt used)
4777 (incf alt)))
4778 (push (cons (car e) (or (car clist) alt)) new))))
4779 (nreverse new)))
4781 ;;; Some variables used in various places
4783 (defvar org-window-configuration nil
4784 "Used in various places to store a window configuration.")
4785 (defvar org-selected-window nil
4786 "Used in various places to store a window configuration.")
4787 (defvar org-finish-function nil
4788 "Function to be called when `C-c C-c' is used.
4789 This is for getting out of special buffers like capture.")
4792 ;; FIXME: Occasionally check by commenting these, to make sure
4793 ;; no other functions uses these, forgetting to let-bind them.
4794 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4795 (defvar org-last-state)
4796 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4798 ;; Defined somewhere in this file, but used before definition.
4799 (defvar org-entities) ;; defined in org-entities.el
4800 (defvar org-struct-menu)
4801 (defvar org-org-menu)
4802 (defvar org-tbl-menu)
4804 ;;;; Define the Org-mode
4806 ;; We use a before-change function to check if a table might need
4807 ;; an update.
4808 (defvar org-table-may-need-update t
4809 "Indicates that a table might need an update.
4810 This variable is set by `org-before-change-function'.
4811 `org-table-align' sets it back to nil.")
4812 (defun org-before-change-function (beg end)
4813 "Every change indicates that a table might need an update."
4814 (setq org-table-may-need-update t))
4815 (defvar org-mode-map)
4816 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4817 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4818 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4819 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4820 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4821 (defvar org-table-buffer-is-an nil)
4823 (defvar bidi-paragraph-direction)
4824 (defvar buffer-face-mode-face)
4826 (require 'outline)
4827 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4828 (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"))
4829 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4831 ;; Other stuff we need.
4832 (require 'time-date)
4833 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4834 (require 'easymenu)
4835 (require 'overlay)
4837 (require 'org-macs)
4838 (require 'org-entities)
4839 ;; (require 'org-compat) moved higher up in the file before it is first used
4840 (require 'org-faces)
4841 (require 'org-list)
4842 (require 'org-pcomplete)
4843 (require 'org-src)
4844 (require 'org-footnote)
4846 ;; babel
4847 (require 'ob)
4848 (require 'ob-table)
4849 (require 'ob-lob)
4850 (require 'ob-ref)
4851 (require 'ob-tangle)
4852 (require 'ob-comint)
4853 (require 'ob-keys)
4855 ;;;###autoload
4856 (define-derived-mode org-mode outline-mode "Org"
4857 "Outline-based notes management and organizer, alias
4858 \"Carsten's outline-mode for keeping track of everything.\"
4860 Org-mode develops organizational tasks around a NOTES file which
4861 contains information about projects as plain text. Org-mode is
4862 implemented on top of outline-mode, which is ideal to keep the content
4863 of large files well structured. It supports ToDo items, deadlines and
4864 time stamps, which magically appear in the diary listing of the Emacs
4865 calendar. Tables are easily created with a built-in table editor.
4866 Plain text URL-like links connect to websites, emails (VM), Usenet
4867 messages (Gnus), BBDB entries, and any files related to the project.
4868 For printing and sharing of notes, an Org-mode file (or a part of it)
4869 can be exported as a structured ASCII or HTML file.
4871 The following commands are available:
4873 \\{org-mode-map}"
4875 ;; Get rid of Outline menus, they are not needed
4876 ;; Need to do this here because define-derived-mode sets up
4877 ;; the keymap so late. Still, it is a waste to call this each time
4878 ;; we switch another buffer into org-mode.
4879 (if (featurep 'xemacs)
4880 (when (boundp 'outline-mode-menu-heading)
4881 ;; Assume this is Greg's port, it uses easymenu
4882 (easy-menu-remove outline-mode-menu-heading)
4883 (easy-menu-remove outline-mode-menu-show)
4884 (easy-menu-remove outline-mode-menu-hide))
4885 (define-key org-mode-map [menu-bar headings] 'undefined)
4886 (define-key org-mode-map [menu-bar hide] 'undefined)
4887 (define-key org-mode-map [menu-bar show] 'undefined))
4889 (org-load-modules-maybe)
4890 (easy-menu-add org-org-menu)
4891 (easy-menu-add org-tbl-menu)
4892 (org-install-agenda-files-menu)
4893 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4894 (add-to-invisibility-spec '(org-cwidth))
4895 (add-to-invisibility-spec '(org-hide-block . t))
4896 (when (featurep 'xemacs)
4897 (org-set-local 'line-move-ignore-invisible t))
4898 (org-set-local 'outline-regexp org-outline-regexp)
4899 (org-set-local 'outline-level 'org-outline-level)
4900 (setq bidi-paragraph-direction 'left-to-right)
4901 (when (and org-ellipsis
4902 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4903 (fboundp 'make-glyph-code))
4904 (unless org-display-table
4905 (setq org-display-table (make-display-table)))
4906 (set-display-table-slot
4907 org-display-table 4
4908 (vconcat (mapcar
4909 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4910 org-ellipsis)))
4911 (if (stringp org-ellipsis) org-ellipsis "..."))))
4912 (setq buffer-display-table org-display-table))
4913 (org-set-regexps-and-options)
4914 (when (and org-tag-faces (not org-tags-special-faces-re))
4915 ;; tag faces set outside customize.... force initialization.
4916 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4917 ;; Calc embedded
4918 (org-set-local 'calc-embedded-open-mode "# ")
4919 (modify-syntax-entry ?@ "w")
4920 (if org-startup-truncated (setq truncate-lines t))
4921 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
4922 (org-set-local 'font-lock-unfontify-region-function
4923 'org-unfontify-region)
4924 ;; Activate before-change-function
4925 (org-set-local 'org-table-may-need-update t)
4926 (org-add-hook 'before-change-functions 'org-before-change-function nil
4927 'local)
4928 ;; Check for running clock before killing a buffer
4929 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4930 ;; Indentation.
4931 (org-set-local 'indent-line-function 'org-indent-line)
4932 (org-set-local 'indent-region-function 'org-indent-region)
4933 ;; Initialize radio targets.
4934 (org-update-radio-target-regexp)
4935 ;; Filling and auto-filling.
4936 (org-setup-filling)
4937 ;; Comments.
4938 (org-setup-comments-handling)
4939 ;; Beginning/end of defun
4940 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4941 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4942 ;; Next error for sparse trees
4943 (org-set-local 'next-error-function 'org-occur-next-match)
4944 ;; Make sure dependence stuff works reliably, even for users who set it
4945 ;; too late :-(
4946 (if org-enforce-todo-dependencies
4947 (add-hook 'org-blocker-hook
4948 'org-block-todo-from-children-or-siblings-or-parent)
4949 (remove-hook 'org-blocker-hook
4950 'org-block-todo-from-children-or-siblings-or-parent))
4951 (if org-enforce-todo-checkbox-dependencies
4952 (add-hook 'org-blocker-hook
4953 'org-block-todo-from-checkboxes)
4954 (remove-hook 'org-blocker-hook
4955 'org-block-todo-from-checkboxes))
4957 ;; Align options lines
4958 (org-set-local
4959 'align-mode-rules-list
4960 '((org-in-buffer-settings
4961 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4962 (modes . '(org-mode)))))
4964 ;; Imenu
4965 (org-set-local 'imenu-create-index-function
4966 'org-imenu-get-tree)
4968 ;; Make isearch reveal context
4969 (if (or (featurep 'xemacs)
4970 (not (boundp 'outline-isearch-open-invisible-function)))
4971 ;; Emacs 21 and XEmacs make use of the hook
4972 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4973 ;; Emacs 22 deals with this through a special variable
4974 (org-set-local 'outline-isearch-open-invisible-function
4975 (lambda (&rest ignore) (org-show-context 'isearch))))
4977 ;; Setup the pcomplete hooks
4978 (set (make-local-variable 'pcomplete-command-completion-function)
4979 'org-pcomplete-initial)
4980 (set (make-local-variable 'pcomplete-command-name-function)
4981 'org-command-at-point)
4982 (set (make-local-variable 'pcomplete-default-completion-function)
4983 'ignore)
4984 (set (make-local-variable 'pcomplete-parse-arguments-function)
4985 'org-parse-arguments)
4986 (set (make-local-variable 'pcomplete-termination-string) "")
4987 (when (>= emacs-major-version 23)
4988 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4990 ;; If empty file that did not turn on org-mode automatically, make it to.
4991 (if (and org-insert-mode-line-in-empty-file
4992 (org-called-interactively-p 'any)
4993 (= (point-min) (point-max)))
4994 (insert "# -*- mode: org -*-\n\n"))
4995 (unless org-inhibit-startup
4996 (and org-startup-with-beamer-mode (org-beamer-mode))
4997 (when org-startup-align-all-tables
4998 (let ((bmp (buffer-modified-p)))
4999 (org-table-map-tables 'org-table-align 'quietly)
5000 (set-buffer-modified-p bmp)))
5001 (when org-startup-with-inline-images
5002 (org-display-inline-images))
5003 (unless org-inhibit-startup-visibility-stuff
5004 (org-set-startup-visibility)))
5005 ;; Try to set org-hide correctly
5006 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5008 (when (fboundp 'abbrev-table-put)
5009 (abbrev-table-put org-mode-abbrev-table
5010 :parents (list text-mode-abbrev-table)))
5012 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5015 (defun org-find-invisible-foreground ()
5016 (let ((candidates (remove
5017 "unspecified-bg"
5018 (nconc
5019 (list (face-background 'default)
5020 (face-background 'org-default))
5021 (mapcar
5022 (lambda (alist)
5023 (when (boundp alist)
5024 (cdr (assoc 'background-color (symbol-value alist)))))
5025 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5026 (list (face-foreground 'org-hide))))))
5027 (car (remove nil candidates))))
5029 (defun org-current-time ()
5030 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5031 (if (> (car org-time-stamp-rounding-minutes) 1)
5032 (let ((r (car org-time-stamp-rounding-minutes))
5033 (time (decode-time)))
5034 (apply 'encode-time
5035 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5036 (nthcdr 2 time))))
5037 (current-time)))
5039 (defun org-today ()
5040 "Return today date, considering `org-extend-today-until'."
5041 (time-to-days
5042 (time-subtract (current-time)
5043 (list 0 (* 3600 org-extend-today-until) 0))))
5045 ;;;; Font-Lock stuff, including the activators
5047 (defvar org-mouse-map (make-sparse-keymap))
5048 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5049 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5050 (when org-mouse-1-follows-link
5051 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5052 (when org-tab-follows-link
5053 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5054 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5056 (require 'font-lock)
5058 (defconst org-non-link-chars "]\t\n\r<>")
5059 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5060 "shell" "elisp" "doi" "message"))
5061 (defvar org-link-types-re nil
5062 "Matches a link that has a url-like prefix like \"http:\"")
5063 (defvar org-link-re-with-space nil
5064 "Matches a link with spaces, optional angular brackets around it.")
5065 (defvar org-link-re-with-space2 nil
5066 "Matches a link with spaces, optional angular brackets around it.")
5067 (defvar org-link-re-with-space3 nil
5068 "Matches a link with spaces, only for internal part in bracket links.")
5069 (defvar org-angle-link-re nil
5070 "Matches link with angular brackets, spaces are allowed.")
5071 (defvar org-plain-link-re nil
5072 "Matches plain link, without spaces.")
5073 (defvar org-bracket-link-regexp nil
5074 "Matches a link in double brackets.")
5075 (defvar org-bracket-link-analytic-regexp nil
5076 "Regular expression used to analyze links.
5077 Here is what the match groups contain after a match:
5078 1: http:
5079 2: http
5080 3: path
5081 4: [desc]
5082 5: desc")
5083 (defvar org-bracket-link-analytic-regexp++ nil
5084 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5085 (defvar org-any-link-re nil
5086 "Regular expression matching any link.")
5088 (defcustom org-match-sexp-depth 3
5089 "Number of stacked braces for sub/superscript matching.
5090 This has to be set before loading org.el to be effective."
5091 :group 'org-export-translation ; ??????????????????????????/
5092 :type 'integer)
5094 (defun org-create-multibrace-regexp (left right n)
5095 "Create a regular expression which will match a balanced sexp.
5096 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5097 as single character strings.
5098 The regexp returned will match the entire expression including the
5099 delimiters. It will also define a single group which contains the
5100 match except for the outermost delimiters. The maximum depth of
5101 stacked delimiters is N. Escaping delimiters is not possible."
5102 (let* ((nothing (concat "[^" left right "]*?"))
5103 (or "\\|")
5104 (re nothing)
5105 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5106 (while (> n 1)
5107 (setq n (1- n)
5108 re (concat re or next)
5109 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5110 (concat left "\\(" re "\\)" right)))
5112 (defvar org-match-substring-regexp
5113 (concat
5114 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5115 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5116 "\\|"
5117 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5118 "\\|"
5119 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5120 "The regular expression matching a sub- or superscript.")
5122 (defvar org-match-substring-with-braces-regexp
5123 (concat
5124 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5125 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5126 "\\)")
5127 "The regular expression matching a sub- or superscript, forcing braces.")
5129 (defun org-make-link-regexps ()
5130 "Update the link regular expressions.
5131 This should be called after the variable `org-link-types' has changed."
5132 (setq org-link-types-re
5133 (concat
5134 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5135 org-link-re-with-space
5136 (concat
5137 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5138 "\\([^" org-non-link-chars " ]"
5139 "[^" org-non-link-chars "]*"
5140 "[^" org-non-link-chars " ]\\)>?")
5141 org-link-re-with-space2
5142 (concat
5143 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5144 "\\([^" org-non-link-chars " ]"
5145 "[^\t\n\r]*"
5146 "[^" org-non-link-chars " ]\\)>?")
5147 org-link-re-with-space3
5148 (concat
5149 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5150 "\\([^" org-non-link-chars " ]"
5151 "[^\t\n\r]*\\)")
5152 org-angle-link-re
5153 (concat
5154 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5155 "\\([^" org-non-link-chars " ]"
5156 "[^" org-non-link-chars "]*"
5157 "\\)>")
5158 org-plain-link-re
5159 (concat
5160 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5161 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5162 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5163 org-bracket-link-regexp
5164 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5165 org-bracket-link-analytic-regexp
5166 (concat
5167 "\\[\\["
5168 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5169 "\\([^]]+\\)"
5170 "\\]"
5171 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5172 "\\]")
5173 org-bracket-link-analytic-regexp++
5174 (concat
5175 "\\[\\["
5176 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5177 "\\([^]]+\\)"
5178 "\\]"
5179 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5180 "\\]")
5181 org-any-link-re
5182 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5183 org-angle-link-re "\\)\\|\\("
5184 org-plain-link-re "\\)")))
5186 (org-make-link-regexps)
5188 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5189 "Regular expression for fast time stamp matching.")
5190 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5191 "Regular expression for fast time stamp matching.")
5192 (defconst org-ts-regexp0
5193 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5194 "Regular expression matching time strings for analysis.
5195 This one does not require the space after the date, so it can be used
5196 on a string that terminates immediately after the date.")
5197 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5198 "Regular expression matching time strings for analysis.")
5199 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5200 "Regular expression matching time stamps, with groups.")
5201 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5202 "Regular expression matching time stamps (also [..]), with groups.")
5203 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5204 "Regular expression matching a time stamp range.")
5205 (defconst org-tr-regexp-both
5206 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5207 "Regular expression matching a time stamp range.")
5208 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5209 org-ts-regexp "\\)?")
5210 "Regular expression matching a time stamp or time stamp range.")
5211 (defconst org-tsr-regexp-both
5212 (concat "[^][]\\(" ;; Don't activate dates in links
5213 org-ts-regexp-both "\\(--?-?"
5214 org-ts-regexp-both "\\)?\\)")
5215 "Regular expression matching a time stamp or time stamp range.
5216 The time stamps may be either active or inactive.")
5218 (defvar org-emph-face nil)
5220 (defun org-do-emphasis-faces (limit)
5221 "Run through the buffer and add overlays to emphasized strings."
5222 (let (rtn a)
5223 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5224 (if (not (= (char-after (match-beginning 3))
5225 (char-after (match-beginning 4))))
5226 (progn
5227 (setq rtn t)
5228 (setq a (assoc (match-string 3) org-emphasis-alist))
5229 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5230 'face
5231 (nth 1 a))
5232 (and (nth 4 a)
5233 (org-remove-flyspell-overlays-in
5234 (match-beginning 0) (match-end 0)))
5235 (add-text-properties (match-beginning 2) (match-end 2)
5236 '(font-lock-multiline t org-emphasis t))
5237 (when org-hide-emphasis-markers
5238 (add-text-properties (match-end 4) (match-beginning 5)
5239 '(invisible org-link))
5240 (add-text-properties (match-beginning 3) (match-end 3)
5241 '(invisible org-link)))))
5242 (backward-char 1))
5243 rtn))
5245 (defun org-emphasize (&optional char)
5246 "Insert or change an emphasis, i.e. a font like bold or italic.
5247 If there is an active region, change that region to a new emphasis.
5248 If there is no region, just insert the marker characters and position
5249 the cursor between them.
5250 CHAR should be either the marker character, or the first character of the
5251 HTML tag associated with that emphasis. If CHAR is a space, the means
5252 to remove the emphasis of the selected region.
5253 If char is not given (for example in an interactive call) it
5254 will be prompted for."
5255 (interactive)
5256 (let ((eal org-emphasis-alist) e det
5257 (erc org-emphasis-regexp-components)
5258 (prompt "")
5259 (string "") beg end move tag c s)
5260 (if (org-region-active-p)
5261 (setq beg (region-beginning) end (region-end)
5262 string (buffer-substring beg end))
5263 (setq move t))
5265 (while (setq e (pop eal))
5266 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5267 c (aref tag 0))
5268 (push (cons c (string-to-char (car e))) det)
5269 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5270 (substring tag 1)))))
5271 (setq det (nreverse det))
5272 (unless char
5273 (message "%s" (concat "Emphasis marker or tag:" prompt))
5274 (setq char (read-char-exclusive)))
5275 (setq char (or (cdr (assoc char det)) char))
5276 (if (equal char ?\ )
5277 (setq s "" move nil)
5278 (unless (assoc (char-to-string char) org-emphasis-alist)
5279 (error "No such emphasis marker: \"%c\"" char))
5280 (setq s (char-to-string char)))
5281 (while (and (> (length string) 1)
5282 (equal (substring string 0 1) (substring string -1))
5283 (assoc (substring string 0 1) org-emphasis-alist))
5284 (setq string (substring string 1 -1)))
5285 (setq string (concat s string s))
5286 (if beg (delete-region beg end))
5287 (unless (or (bolp)
5288 (string-match (concat "[" (nth 0 erc) "\n]")
5289 (char-to-string (char-before (point)))))
5290 (insert " "))
5291 (unless (or (eobp)
5292 (string-match (concat "[" (nth 1 erc) "\n]")
5293 (char-to-string (char-after (point)))))
5294 (insert " ") (backward-char 1))
5295 (insert string)
5296 (and move (backward-char 1))))
5298 (defconst org-nonsticky-props
5299 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5301 (defsubst org-rear-nonsticky-at (pos)
5302 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5304 (defun org-activate-plain-links (limit)
5305 "Run through the buffer and add overlays to links."
5306 (let (f)
5307 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5308 (not (org-in-src-block-p)))
5309 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5310 (setq f (get-text-property (match-beginning 0) 'face))
5311 (unless (or (org-in-src-block-p)
5312 (eq f 'org-tag)
5313 (and (listp f) (memq 'org-tag f)))
5314 (add-text-properties (match-beginning 0) (match-end 0)
5315 (list 'mouse-face 'highlight
5316 'face 'org-link
5317 'keymap org-mouse-map))
5318 (org-rear-nonsticky-at (match-end 0)))
5319 t)))
5321 (defun org-activate-code (limit)
5322 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5323 (progn
5324 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5325 (remove-text-properties (match-beginning 0) (match-end 0)
5326 '(display t invisible t intangible t))
5327 t)))
5329 (defcustom org-src-fontify-natively nil
5330 "When non-nil, fontify code in code blocks."
5331 :type 'boolean
5332 :version "24.1"
5333 :group 'org-appearance
5334 :group 'org-babel)
5336 (defcustom org-allow-promoting-top-level-subtree nil
5337 "When non-nil, allow promoting a top level subtree.
5338 The leading star of the top level headline will be replaced
5339 by a #."
5340 :type 'boolean
5341 :version "24.1"
5342 :group 'org-appearance)
5344 (defun org-fontify-meta-lines-and-blocks (limit)
5345 (condition-case nil
5346 (org-fontify-meta-lines-and-blocks-1 limit)
5347 (error (message "org-mode fontification error"))))
5349 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5350 "Fontify #+ lines and blocks, in the correct ways."
5351 (let ((case-fold-search t))
5352 (if (re-search-forward
5353 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5354 limit t)
5355 (let ((beg (match-beginning 0))
5356 (block-start (match-end 0))
5357 (block-end nil)
5358 (lang (match-string 7))
5359 (beg1 (line-beginning-position 2))
5360 (dc1 (downcase (match-string 2)))
5361 (dc3 (downcase (match-string 3)))
5362 end end1 quoting block-type ovl)
5363 (cond
5364 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5365 ;; a single line of backend-specific content
5366 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5367 (remove-text-properties (match-beginning 0) (match-end 0)
5368 '(display t invisible t intangible t))
5369 (add-text-properties (match-beginning 1) (match-end 3)
5370 '(font-lock-fontified t face org-meta-line))
5371 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5372 '(font-lock-fontified t face org-block))
5373 ; for backend-specific code
5375 ((and (match-end 4) (equal dc3 "+begin"))
5376 ;; Truly a block
5377 (setq block-type (downcase (match-string 5))
5378 quoting (member block-type org-protecting-blocks))
5379 (when (re-search-forward
5380 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5381 nil t) ;; on purpose, we look further than LIMIT
5382 (setq end (min (point-max) (match-end 0))
5383 end1 (min (point-max) (1- (match-beginning 0))))
5384 (setq block-end (match-beginning 0))
5385 (when quoting
5386 (remove-text-properties beg end
5387 '(display t invisible t intangible t)))
5388 (add-text-properties
5389 beg end
5390 '(font-lock-fontified t font-lock-multiline t))
5391 (add-text-properties beg beg1 '(face org-meta-line))
5392 (add-text-properties end1 (min (point-max) (1+ end))
5393 '(face org-meta-line)) ; for end_src
5394 (cond
5395 ((and lang (not (string= lang "")) org-src-fontify-natively)
5396 (org-src-font-lock-fontify-block lang block-start block-end)
5397 ;; remove old background overlays
5398 (mapc (lambda (ov)
5399 (if (eq (overlay-get ov 'face) 'org-block-background)
5400 (delete-overlay ov)))
5401 (overlays-at (/ (+ beg1 block-end) 2)))
5402 ;; add a background overlay
5403 (setq ovl (make-overlay beg1 block-end))
5404 (overlay-put ovl 'face 'org-block-background)
5405 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5406 (quoting
5407 (add-text-properties beg1 (min (point-max) (1+ end1))
5408 '(face org-block))) ; end of source block
5409 ((not org-fontify-quote-and-verse-blocks))
5410 ((string= block-type "quote")
5411 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5412 ((string= block-type "verse")
5413 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5414 (add-text-properties beg beg1 '(face org-block-begin-line))
5415 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5416 '(face org-block-end-line))
5418 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5419 (add-text-properties
5420 beg (match-end 3)
5421 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5422 '(font-lock-fontified t invisible t)
5423 '(font-lock-fontified t face org-document-info-keyword)))
5424 (add-text-properties
5425 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5426 (if (string-equal dc1 "+title:")
5427 '(font-lock-fontified t face org-document-title)
5428 '(font-lock-fontified t face org-document-info))))
5429 ((or (equal dc1 "+results")
5430 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5431 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5432 "+call:" "+header:" "+headers:" "+name:"))
5433 (and (match-end 4) (equal dc3 "+attr")))
5434 (add-text-properties
5435 beg (match-end 0)
5436 '(font-lock-fontified t face org-meta-line))
5438 ((member dc3 '(" " ""))
5439 (add-text-properties
5440 beg (match-end 0)
5441 '(font-lock-fontified t face font-lock-comment-face)))
5442 ((not (member (char-after beg) '(?\ ?\t)))
5443 ;; just any other in-buffer setting, but not indented
5444 (add-text-properties
5445 beg (match-end 0)
5446 '(font-lock-fontified t face org-meta-line))
5448 (t nil))))))
5450 (defun org-activate-angle-links (limit)
5451 "Run through the buffer and add overlays to links."
5452 (if (and (re-search-forward org-angle-link-re limit t)
5453 (not (org-in-src-block-p)))
5454 (progn
5455 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5456 (add-text-properties (match-beginning 0) (match-end 0)
5457 (list 'mouse-face 'highlight
5458 'keymap org-mouse-map))
5459 (org-rear-nonsticky-at (match-end 0))
5460 t)))
5462 (defun org-activate-footnote-links (limit)
5463 "Run through the buffer and add overlays to footnotes."
5464 (let ((fn (org-footnote-next-reference-or-definition limit)))
5465 (when fn
5466 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5467 (org-remove-flyspell-overlays-in beg end)
5468 (add-text-properties beg end
5469 (list 'mouse-face 'highlight
5470 'keymap org-mouse-map
5471 'help-echo
5472 (if (= (point-at-bol) beg)
5473 "Footnote definition"
5474 "Footnote reference")
5475 'font-lock-fontified t
5476 'font-lock-multiline t
5477 'face 'org-footnote))))))
5479 (defun org-activate-bracket-links (limit)
5480 "Run through the buffer and add overlays to bracketed links."
5481 (if (and (re-search-forward org-bracket-link-regexp limit t)
5482 (not (org-in-src-block-p)))
5483 (let* ((help (concat "LINK: "
5484 (org-match-string-no-properties 1)))
5485 ;; FIXME: above we should remove the escapes.
5486 ;; but that requires another match, protecting match data,
5487 ;; a lot of overhead for font-lock.
5488 (ip (org-maybe-intangible
5489 (list 'invisible 'org-link
5490 'keymap org-mouse-map 'mouse-face 'highlight
5491 'font-lock-multiline t 'help-echo help)))
5492 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5493 'font-lock-multiline t 'help-echo help)))
5494 ;; We need to remove the invisible property here. Table narrowing
5495 ;; may have made some of this invisible.
5496 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5497 (remove-text-properties (match-beginning 0) (match-end 0)
5498 '(invisible nil))
5499 (if (match-end 3)
5500 (progn
5501 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5502 (org-rear-nonsticky-at (match-beginning 3))
5503 (add-text-properties (match-beginning 3) (match-end 3) vp)
5504 (org-rear-nonsticky-at (match-end 3))
5505 (add-text-properties (match-end 3) (match-end 0) ip)
5506 (org-rear-nonsticky-at (match-end 0)))
5507 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5508 (org-rear-nonsticky-at (match-beginning 1))
5509 (add-text-properties (match-beginning 1) (match-end 1) vp)
5510 (org-rear-nonsticky-at (match-end 1))
5511 (add-text-properties (match-end 1) (match-end 0) ip)
5512 (org-rear-nonsticky-at (match-end 0)))
5513 t)))
5515 (defun org-activate-dates (limit)
5516 "Run through the buffer and add overlays to dates."
5517 (if (re-search-forward org-tsr-regexp-both limit t)
5518 (progn
5519 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5520 (add-text-properties (match-beginning 1) (match-end 1)
5521 (list 'mouse-face 'highlight
5522 'keymap org-mouse-map))
5523 (org-rear-nonsticky-at (match-end 1))
5524 (when org-display-custom-times
5525 (if (match-end 4)
5526 (org-display-custom-time (match-beginning 4) (match-end 4)))
5527 (org-display-custom-time (match-beginning 2) (match-end 2)))
5528 t)))
5530 (defvar org-target-link-regexp nil
5531 "Regular expression matching radio targets in plain text.")
5532 (make-variable-buffer-local 'org-target-link-regexp)
5533 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5534 "Regular expression matching a link target.")
5535 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5536 "Regular expression matching a radio target.")
5537 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5538 "Regular expression matching any target.")
5540 (defun org-activate-target-links (limit)
5541 "Run through the buffer and add overlays to target matches."
5542 (when org-target-link-regexp
5543 (let ((case-fold-search t))
5544 (if (re-search-forward org-target-link-regexp limit t)
5545 (progn
5546 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5547 (add-text-properties (match-beginning 0) (match-end 0)
5548 (list 'mouse-face 'highlight
5549 'keymap org-mouse-map
5550 'help-echo "Radio target link"
5551 'org-linked-text t))
5552 (org-rear-nonsticky-at (match-end 0))
5553 t)))))
5555 (defun org-update-radio-target-regexp ()
5556 "Find all radio targets in this file and update the regular expression."
5557 (interactive)
5558 (when (memq 'radio org-activate-links)
5559 (setq org-target-link-regexp
5560 (org-make-target-link-regexp (org-all-targets 'radio)))
5561 (org-restart-font-lock)))
5563 (defun org-hide-wide-columns (limit)
5564 (let (s e)
5565 (setq s (text-property-any (point) (or limit (point-max))
5566 'org-cwidth t))
5567 (when s
5568 (setq e (next-single-property-change s 'org-cwidth))
5569 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5570 (goto-char e)
5571 t)))
5573 (defvar org-latex-and-specials-regexp nil
5574 "Regular expression for highlighting export special stuff.")
5575 (defvar org-match-substring-regexp)
5576 (defvar org-match-substring-with-braces-regexp)
5578 ;; This should be with the exporter code, but we also use if for font-locking
5579 (defconst org-export-html-special-string-regexps
5580 '(("\\\\-" . "&shy;")
5581 ("---\\([^-]\\)" . "&mdash;\\1")
5582 ("--\\([^-]\\)" . "&ndash;\\1")
5583 ("\\.\\.\\." . "&hellip;"))
5584 "Regular expressions for special string conversion.")
5587 (defun org-compute-latex-and-specials-regexp ()
5588 "Compute regular expression for stuff treated specially by exporters."
5589 (if (not org-highlight-latex-fragments-and-specials)
5590 (org-set-local 'org-latex-and-specials-regexp nil)
5591 (require 'org-exp)
5592 (let*
5593 ((matchers (plist-get org-format-latex-options :matchers))
5594 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5595 org-latex-regexps)))
5596 (org-export-allow-BIND nil)
5597 (options (org-combine-plists (org-default-export-plist)
5598 (org-infile-export-plist)))
5599 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5600 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5601 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5602 (org-export-html-expand (plist-get options :expand-quoted-html))
5603 (org-export-with-special-strings (plist-get options :special-strings))
5604 (re-sub
5605 (cond
5606 ((equal org-export-with-sub-superscripts '{})
5607 (list org-match-substring-with-braces-regexp))
5608 (org-export-with-sub-superscripts
5609 (list org-match-substring-regexp))))
5610 (re-latex
5611 (if org-export-with-LaTeX-fragments
5612 (mapcar (lambda (x) (nth 1 x)) latexs)))
5613 (re-macros
5614 (if org-export-with-TeX-macros
5615 (list (concat "\\\\"
5616 (regexp-opt
5617 (append
5619 (delq nil
5620 (mapcar 'car-safe
5621 (append org-entities-user
5622 org-entities)))
5623 (if (boundp 'org-latex-entities)
5624 (mapcar (lambda (x)
5625 (or (car-safe x) x))
5626 org-latex-entities)
5627 nil))
5628 'words))) ; FIXME
5630 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5631 (re-special (if org-export-with-special-strings
5632 (mapcar (lambda (x) (car x))
5633 org-export-html-special-string-regexps)))
5634 (re-rest
5635 (delq nil
5636 (list
5637 (if org-export-html-expand "@<[^>\n]+>")
5638 ))))
5639 (org-set-local
5640 'org-latex-and-specials-regexp
5641 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5642 re-rest) "\\|")))))
5644 (defun org-do-latex-and-special-faces (limit)
5645 "Run through the buffer and add overlays to links."
5646 (when org-latex-and-specials-regexp
5647 (let (rtn d)
5648 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5649 limit t))
5650 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5651 'face))
5652 '(org-code org-verbatim underline)))
5653 (progn
5654 (setq rtn t
5655 d (cond ((member (char-after (1+ (match-beginning 0)))
5656 '(?_ ?^)) 1)
5657 (t 0)))
5658 (font-lock-prepend-text-property
5659 (+ d (match-beginning 0)) (match-end 0)
5660 'face 'org-latex-and-export-specials)
5661 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5662 '(font-lock-multiline t)))))
5663 rtn)))
5665 (defun org-restart-font-lock ()
5666 "Restart `font-lock-mode', to force refontification."
5667 (when (and (boundp 'font-lock-mode) font-lock-mode)
5668 (font-lock-mode -1)
5669 (font-lock-mode 1)))
5671 (defun org-all-targets (&optional radio)
5672 "Return a list of all targets in this file.
5673 With optional argument RADIO, only find radio targets."
5674 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5675 rtn)
5676 (save-excursion
5677 (goto-char (point-min))
5678 (while (re-search-forward re nil t)
5679 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5680 rtn)))
5682 (defun org-make-target-link-regexp (targets)
5683 "Make regular expression matching all strings in TARGETS.
5684 The regular expression finds the targets also if there is a line break
5685 between words."
5686 (and targets
5687 (concat
5688 "\\<\\("
5689 (mapconcat
5690 (lambda (x)
5691 (setq x (regexp-quote x))
5692 (while (string-match " +" x)
5693 (setq x (replace-match "\\s-+" t t x)))
5695 targets
5696 "\\|")
5697 "\\)\\>")))
5699 (defun org-activate-tags (limit)
5700 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5701 (progn
5702 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5703 (add-text-properties (match-beginning 1) (match-end 1)
5704 (list 'mouse-face 'highlight
5705 'keymap org-mouse-map))
5706 (org-rear-nonsticky-at (match-end 1))
5707 t)))
5709 (defun org-outline-level ()
5710 "Compute the outline level of the heading at point.
5711 This function assumes that the cursor is at the beginning of a line matched
5712 by `outline-regexp'. Otherwise it returns garbage.
5713 If this is called at a normal headline, the level is the number of stars.
5714 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5715 (save-excursion
5716 (looking-at org-outline-regexp)
5717 (1- (- (match-end 0) (match-beginning 0)))))
5719 (defvar org-font-lock-keywords nil)
5721 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5722 "Regular expression matching a property line.")
5724 (defvar org-font-lock-hook nil
5725 "Functions to be called for special font lock stuff.")
5727 (defvar org-font-lock-set-keywords-hook nil
5728 "Functions that can manipulate `org-font-lock-extra-keywords'.
5729 This is called after `org-font-lock-extra-keywords' is defined, but before
5730 it is installed to be used by font lock. This can be useful if something
5731 needs to be inserted at a specific position in the font-lock sequence.")
5733 (defun org-font-lock-hook (limit)
5734 "Run `org-font-lock-hook' within LIMIT."
5735 (run-hook-with-args 'org-font-lock-hook limit))
5737 (defun org-set-font-lock-defaults ()
5738 "Set font lock defaults for the current buffer."
5739 (let* ((em org-fontify-emphasized-text)
5740 (lk org-activate-links)
5741 (org-font-lock-extra-keywords
5742 (list
5743 ;; Call the hook
5744 '(org-font-lock-hook)
5745 ;; Headlines
5746 `(,(if org-fontify-whole-heading-line
5747 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5748 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5749 (1 (org-get-level-face 1))
5750 (2 (org-get-level-face 2))
5751 (3 (org-get-level-face 3)))
5752 ;; Table lines
5753 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5754 (1 'org-table t))
5755 ;; Table internals
5756 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5757 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5758 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5759 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5760 ;; Drawers
5761 (list org-drawer-regexp '(0 'org-special-keyword t))
5762 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5763 ;; Properties
5764 (list org-property-re
5765 '(1 'org-special-keyword t)
5766 '(3 'org-property-value t))
5767 ;; Links
5768 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5769 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5770 (if (memq 'plain lk) '(org-activate-plain-links))
5771 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5772 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5773 (if (memq 'date lk) '(org-activate-dates (1 'org-date t)))
5774 (if (memq 'footnote lk) '(org-activate-footnote-links))
5775 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5776 '(org-hide-wide-columns (0 nil append))
5777 ;; TODO keyword
5778 (list (format org-heading-keyword-regexp-format
5779 org-todo-regexp)
5780 '(2 (org-get-todo-face 2) t))
5781 ;; DONE
5782 (if org-fontify-done-headline
5783 (list (format org-heading-keyword-regexp-format
5784 (concat
5785 "\\(?:"
5786 (mapconcat 'regexp-quote org-done-keywords "\\|")
5787 "\\)"))
5788 '(2 'org-headline-done t))
5789 nil)
5790 ;; Priorities
5791 '(org-font-lock-add-priority-faces)
5792 ;; Tags
5793 '(org-font-lock-add-tag-faces)
5794 ;; Special keywords
5795 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5796 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5797 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5798 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5799 ;; Emphasis
5800 (if em
5801 (if (featurep 'xemacs)
5802 '(org-do-emphasis-faces (0 nil append))
5803 '(org-do-emphasis-faces)))
5804 ;; Checkboxes
5805 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5806 1 'org-checkbox prepend)
5807 (if (cdr (assq 'checkbox org-list-automatic-rules))
5808 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5809 (0 (org-get-checkbox-statistics-face) t)))
5810 ;; Description list items
5811 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5812 1 'org-list-dt prepend)
5813 ;; ARCHIVEd headings
5814 (list (concat
5815 org-outline-regexp-bol
5816 "\\(.*:" org-archive-tag ":.*\\)")
5817 '(1 'org-archived prepend))
5818 ;; Specials
5819 '(org-do-latex-and-special-faces)
5820 '(org-fontify-entities)
5821 '(org-raise-scripts)
5822 ;; Code
5823 '(org-activate-code (1 'org-code t))
5824 ;; COMMENT
5825 (list (format org-heading-keyword-regexp-format
5826 (concat "\\("
5827 org-comment-string "\\|" org-quote-string
5828 "\\)"))
5829 '(2 'org-special-keyword t))
5830 ;; Blocks and meta lines
5831 '(org-fontify-meta-lines-and-blocks)
5833 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5834 (run-hooks 'org-font-lock-set-keywords-hook)
5835 ;; Now set the full font-lock-keywords
5836 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5837 (org-set-local 'font-lock-defaults
5838 '(org-font-lock-keywords t nil nil backward-paragraph))
5839 (kill-local-variable 'font-lock-keywords) nil))
5841 (defun org-toggle-pretty-entities ()
5842 "Toggle the composition display of entities as UTF8 characters."
5843 (interactive)
5844 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5845 (org-restart-font-lock)
5846 (if org-pretty-entities
5847 (message "Entities are displayed as UTF8 characters")
5848 (save-restriction
5849 (widen)
5850 (org-decompose-region (point-min) (point-max))
5851 (message "Entities are displayed plain"))))
5853 (defvar org-custom-properties-overlays nil
5854 "List of overlays used for custom properties.")
5855 (make-variable-buffer-local 'org-custom-properties-overlays)
5857 (defun org-toggle-custom-properties-visibility ()
5858 "Display or hide properties in `org-custom-properties'."
5859 (interactive)
5860 (if org-custom-properties-overlays
5861 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5862 (setq org-custom-properties-overlays nil))
5863 (unless (not org-custom-properties)
5864 (save-excursion
5865 (save-restriction
5866 (widen)
5867 (goto-char (point-min))
5868 (while (re-search-forward org-property-re nil t)
5869 (mapc (lambda(p)
5870 (when (equal p (substring (match-string 1) 1 -1))
5871 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5872 (overlay-put o 'invisible t)
5873 (overlay-put o 'org-custom-property t)
5874 (push o org-custom-properties-overlays))))
5875 org-custom-properties)))))))
5877 (defun org-fontify-entities (limit)
5878 "Find an entity to fontify."
5879 (let (ee)
5880 (when org-pretty-entities
5881 (catch 'match
5882 (while (re-search-forward
5883 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5884 limit t)
5885 (if (and (not (org-in-indented-comment-line))
5886 (setq ee (org-entity-get (match-string 1)))
5887 (= (length (nth 6 ee)) 1))
5888 (let*
5889 ((end (if (equal (match-string 2) "{}")
5890 (match-end 2)
5891 (match-end 1))))
5892 (add-text-properties
5893 (match-beginning 0) end
5894 (list 'font-lock-fontified t))
5895 (compose-region (match-beginning 0) end
5896 (nth 6 ee) nil)
5897 (backward-char 1)
5898 (throw 'match t))))
5899 nil))))
5901 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5902 "Fontify string S like in Org-mode."
5903 (with-temp-buffer
5904 (insert s)
5905 (let ((org-odd-levels-only odd-levels))
5906 (org-mode)
5907 (font-lock-fontify-buffer)
5908 (buffer-string))))
5910 (defvar org-m nil)
5911 (defvar org-l nil)
5912 (defvar org-f nil)
5913 (defun org-get-level-face (n)
5914 "Get the right face for match N in font-lock matching of headlines."
5915 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5916 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5917 (if org-cycle-level-faces
5918 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5919 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5920 (cond
5921 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5922 ((eq n 2) org-f)
5923 (t (if org-level-color-stars-only nil org-f))))
5926 (defun org-get-todo-face (kwd)
5927 "Get the right face for a TODO keyword KWD.
5928 If KWD is a number, get the corresponding match group."
5929 (if (numberp kwd) (setq kwd (match-string kwd)))
5930 (or (org-face-from-face-or-color
5931 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5932 (and (member kwd org-done-keywords) 'org-done)
5933 'org-todo))
5935 (defun org-face-from-face-or-color (context inherit face-or-color)
5936 "Create a face list that inherits INHERIT, but sets the foreground color.
5937 When FACE-OR-COLOR is not a string, just return it."
5938 (if (stringp face-or-color)
5939 (list :inherit inherit
5940 (cdr (assoc context org-faces-easy-properties))
5941 face-or-color)
5942 face-or-color))
5944 (defun org-font-lock-add-tag-faces (limit)
5945 "Add the special tag faces."
5946 (when (and org-tag-faces org-tags-special-faces-re)
5947 (while (re-search-forward org-tags-special-faces-re limit t)
5948 (add-text-properties (match-beginning 1) (match-end 1)
5949 (list 'face (org-get-tag-face 1)
5950 'font-lock-fontified t))
5951 (backward-char 1))))
5953 (defun org-font-lock-add-priority-faces (limit)
5954 "Add the special priority faces."
5955 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5956 (when (save-match-data (org-at-heading-p))
5957 (add-text-properties
5958 (match-beginning 0) (match-end 0)
5959 (list 'face (or (org-face-from-face-or-color
5960 'priority 'org-special-keyword
5961 (cdr (assoc (char-after (match-beginning 1))
5962 org-priority-faces)))
5963 'org-special-keyword)
5964 'font-lock-fontified t)))))
5966 (defun org-get-tag-face (kwd)
5967 "Get the right face for a TODO keyword KWD.
5968 If KWD is a number, get the corresponding match group."
5969 (if (numberp kwd) (setq kwd (match-string kwd)))
5970 (or (org-face-from-face-or-color
5971 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5972 'org-tag))
5974 (defun org-unfontify-region (beg end &optional maybe_loudly)
5975 "Remove fontification and activation overlays from links."
5976 (font-lock-default-unfontify-region beg end)
5977 (let* ((buffer-undo-list t)
5978 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5979 (inhibit-modification-hooks t)
5980 deactivate-mark buffer-file-name buffer-file-truename)
5981 (org-decompose-region beg end)
5982 (remove-text-properties beg end
5983 '(mouse-face t keymap t org-linked-text t
5984 invisible t intangible t
5985 org-no-flyspell t org-emphasis t))
5986 (org-remove-font-lock-display-properties beg end)))
5988 (defconst org-script-display '(((raise -0.3) (height 0.7))
5989 ((raise 0.3) (height 0.7))
5990 ((raise -0.5))
5991 ((raise 0.5)))
5992 "Display properties for showing superscripts and subscripts.")
5994 (defun org-remove-font-lock-display-properties (beg end)
5995 "Remove specific display properties that have been added by font lock.
5996 The will remove the raise properties that are used to show superscripts
5997 and subscripts."
5998 (let (next prop)
5999 (while (< beg end)
6000 (setq next (next-single-property-change beg 'display nil end)
6001 prop (get-text-property beg 'display))
6002 (if (member prop org-script-display)
6003 (put-text-property beg next 'display nil))
6004 (setq beg next))))
6006 (defun org-raise-scripts (limit)
6007 "Add raise properties to sub/superscripts."
6008 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6009 (if (re-search-forward
6010 (if (eq org-use-sub-superscripts t)
6011 org-match-substring-regexp
6012 org-match-substring-with-braces-regexp)
6013 limit t)
6014 (let* ((pos (point)) table-p comment-p
6015 (mpos (match-beginning 3))
6016 (emph-p (get-text-property mpos 'org-emphasis))
6017 (link-p (get-text-property mpos 'mouse-face))
6018 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6019 (goto-char (point-at-bol))
6020 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6021 comment-p (org-looking-at-p "[ \t]*#"))
6022 (goto-char pos)
6023 ;; FIXME: Should we go back one character here, for a_b^c
6024 ;; (goto-char (1- pos)) ;????????????????????
6025 (if (or comment-p emph-p link-p keyw-p)
6027 (put-text-property (match-beginning 3) (match-end 0)
6028 'display
6029 (if (equal (char-after (match-beginning 2)) ?^)
6030 (nth (if table-p 3 1) org-script-display)
6031 (nth (if table-p 2 0) org-script-display)))
6032 (add-text-properties (match-beginning 2) (match-end 2)
6033 (list 'invisible t
6034 'org-dwidth t 'org-dwidth-n 1))
6035 (if (and (eq (char-after (match-beginning 3)) ?{)
6036 (eq (char-before (match-end 3)) ?}))
6037 (progn
6038 (add-text-properties
6039 (match-beginning 3) (1+ (match-beginning 3))
6040 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6041 (add-text-properties
6042 (1- (match-end 3)) (match-end 3)
6043 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6044 t)))))
6046 ;;;; Visibility cycling, including org-goto and indirect buffer
6048 ;;; Cycling
6050 (defvar org-cycle-global-status nil)
6051 (make-variable-buffer-local 'org-cycle-global-status)
6052 (defvar org-cycle-subtree-status nil)
6053 (make-variable-buffer-local 'org-cycle-subtree-status)
6055 (defvar org-inlinetask-min-level)
6057 ;;;###autoload
6058 (defun org-cycle (&optional arg)
6059 "TAB-action and visibility cycling for Org-mode.
6061 This is the command invoked in Org-mode by the TAB key. Its main purpose
6062 is outline visibility cycling, but it also invokes other actions
6063 in special contexts.
6065 - When this function is called with a prefix argument, rotate the entire
6066 buffer through 3 states (global cycling)
6067 1. OVERVIEW: Show only top-level headlines.
6068 2. CONTENTS: Show all headlines of all levels, but no body text.
6069 3. SHOW ALL: Show everything.
6070 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6071 determined by the variable `org-startup-folded', and by any VISIBILITY
6072 properties in the buffer.
6073 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6074 including any drawers.
6076 - When inside a table, re-align the table and move to the next field.
6078 - When point is at the beginning of a headline, rotate the subtree started
6079 by this line through 3 different states (local cycling)
6080 1. FOLDED: Only the main headline is shown.
6081 2. CHILDREN: The main headline and the direct children are shown.
6082 From this state, you can move to one of the children
6083 and zoom in further.
6084 3. SUBTREE: Show the entire subtree, including body text.
6085 If there is no subtree, switch directly from CHILDREN to FOLDED.
6087 - When point is at the beginning of an empty headline and the variable
6088 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6089 of the headline by demoting and promoting it to likely levels. This
6090 speeds up creation document structure by pressing TAB once or several
6091 times right after creating a new headline.
6093 - When there is a numeric prefix, go up to a heading with level ARG, do
6094 a `show-subtree' and return to the previous cursor position. If ARG
6095 is negative, go up that many levels.
6097 - When point is not at the beginning of a headline, execute the global
6098 binding for TAB, which is re-indenting the line. See the option
6099 `org-cycle-emulate-tab' for details.
6101 - Special case: if point is at the beginning of the buffer and there is
6102 no headline in line 1, this function will act as if called with prefix arg
6103 (C-u TAB, same as S-TAB) also when called without prefix arg.
6104 But only if also the variable `org-cycle-global-at-bob' is t."
6105 (interactive "P")
6106 (org-load-modules-maybe)
6107 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6108 (and org-cycle-level-after-item/entry-creation
6109 (or (org-cycle-level)
6110 (org-cycle-item-indentation))))
6111 (let* ((limit-level
6112 (or org-cycle-max-level
6113 (and (boundp 'org-inlinetask-min-level)
6114 org-inlinetask-min-level
6115 (1- org-inlinetask-min-level))))
6116 (nstars (and limit-level
6117 (if org-odd-levels-only
6118 (and limit-level (1- (* limit-level 2)))
6119 limit-level)))
6120 (org-outline-regexp
6121 (if (not (derived-mode-p 'org-mode))
6122 outline-regexp
6123 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6124 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6125 (not (looking-at org-outline-regexp))))
6126 (org-cycle-hook
6127 (if bob-special
6128 (delq 'org-optimize-window-after-visibility-change
6129 (copy-sequence org-cycle-hook))
6130 org-cycle-hook))
6131 (pos (point)))
6133 (if (or bob-special (equal arg '(4)))
6134 ;; special case: use global cycling
6135 (setq arg t))
6137 (cond
6139 ((equal arg '(16))
6140 (setq last-command 'dummy)
6141 (org-set-startup-visibility)
6142 (message "Startup visibility, plus VISIBILITY properties"))
6144 ((equal arg '(64))
6145 (show-all)
6146 (message "Entire buffer visible, including drawers"))
6148 ;; Table: enter it or move to the next field.
6149 ((org-at-table-p 'any)
6150 (if (org-at-table.el-p)
6151 (message "Use C-c ' to edit table.el tables")
6152 (if arg (org-table-edit-field t)
6153 (org-table-justify-field-maybe)
6154 (call-interactively 'org-table-next-field))))
6156 ((run-hook-with-args-until-success
6157 'org-tab-after-check-for-table-hook))
6159 ;; Global cycling: delegate to `org-cycle-internal-global'.
6160 ((eq arg t) (org-cycle-internal-global))
6162 ;; Drawers: delegate to `org-flag-drawer'.
6163 ((and org-drawers org-drawer-regexp
6164 (save-excursion
6165 (beginning-of-line 1)
6166 (looking-at org-drawer-regexp)))
6167 (org-flag-drawer ; toggle block visibility
6168 (not (get-char-property (match-end 0) 'invisible))))
6170 ;; Show-subtree, ARG levels up from here.
6171 ((integerp arg)
6172 (save-excursion
6173 (org-back-to-heading)
6174 (outline-up-heading (if (< arg 0) (- arg)
6175 (- (funcall outline-level) arg)))
6176 (org-show-subtree)))
6178 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6179 ((and (featurep 'org-inlinetask)
6180 (org-inlinetask-at-task-p)
6181 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6182 (org-inlinetask-toggle-visibility))
6184 ((org-try-cdlatex-tab))
6186 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6187 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6188 (save-excursion (beginning-of-line 1)
6189 (looking-at org-outline-regexp)))
6190 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6191 (org-cycle-internal-local))
6193 ;; From there: TAB emulation and template completion.
6194 (buffer-read-only (org-back-to-heading))
6196 ((run-hook-with-args-until-success
6197 'org-tab-after-check-for-cycling-hook))
6199 ((org-try-structure-completion))
6201 ((run-hook-with-args-until-success
6202 'org-tab-before-tab-emulation-hook))
6204 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6205 (or (not (bolp))
6206 (not (looking-at org-outline-regexp))))
6207 (call-interactively (global-key-binding "\t")))
6209 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6210 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6211 (or (and (eq org-cycle-emulate-tab 'white)
6212 (= (match-end 0) (point-at-eol)))
6213 (and (eq org-cycle-emulate-tab 'whitestart)
6214 (>= (match-end 0) pos))))
6216 (eq org-cycle-emulate-tab t))
6217 (call-interactively (global-key-binding "\t")))
6219 (t (save-excursion
6220 (org-back-to-heading)
6221 (org-cycle)))))))
6223 (defun org-cycle-internal-global ()
6224 "Do the global cycling action."
6225 ;; Hack to avoid display of messages for .org attachments in Gnus
6226 (let ((ga (string-match "\\*fontification" (buffer-name))))
6227 (cond
6228 ((and (eq last-command this-command)
6229 (eq org-cycle-global-status 'overview))
6230 ;; We just created the overview - now do table of contents
6231 ;; This can be slow in very large buffers, so indicate action
6232 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6233 (unless ga (message "CONTENTS..."))
6234 (org-content)
6235 (unless ga (message "CONTENTS...done"))
6236 (setq org-cycle-global-status 'contents)
6237 (run-hook-with-args 'org-cycle-hook 'contents))
6239 ((and (eq last-command this-command)
6240 (eq org-cycle-global-status 'contents))
6241 ;; We just showed the table of contents - now show everything
6242 (run-hook-with-args 'org-pre-cycle-hook 'all)
6243 (show-all)
6244 (unless ga (message "SHOW ALL"))
6245 (setq org-cycle-global-status 'all)
6246 (run-hook-with-args 'org-cycle-hook 'all))
6249 ;; Default action: go to overview
6250 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6251 (org-overview)
6252 (unless ga (message "OVERVIEW"))
6253 (setq org-cycle-global-status 'overview)
6254 (run-hook-with-args 'org-cycle-hook 'overview)))))
6256 (defun org-cycle-internal-local ()
6257 "Do the local cycling action."
6258 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6259 ;; First, determine end of headline (EOH), end of subtree or item
6260 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6261 (save-excursion
6262 (if (org-at-item-p)
6263 (progn
6264 (beginning-of-line)
6265 (setq struct (org-list-struct))
6266 (setq eoh (point-at-eol))
6267 (setq eos (org-list-get-item-end-before-blank (point) struct))
6268 (setq has-children (org-list-has-child-p (point) struct)))
6269 (org-back-to-heading)
6270 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6271 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6272 (setq has-children
6273 (or (save-excursion
6274 (let ((level (funcall outline-level)))
6275 (outline-next-heading)
6276 (and (org-at-heading-p t)
6277 (> (funcall outline-level) level))))
6278 (save-excursion
6279 (org-list-search-forward (org-item-beginning-re) eos t)))))
6280 ;; Determine end invisible part of buffer (EOL)
6281 (beginning-of-line 2)
6282 ;; XEmacs doesn't have `next-single-char-property-change'
6283 (if (featurep 'xemacs)
6284 (while (and (not (eobp)) ;; this is like `next-line'
6285 (get-char-property (1- (point)) 'invisible))
6286 (beginning-of-line 2))
6287 (while (and (not (eobp)) ;; this is like `next-line'
6288 (get-char-property (1- (point)) 'invisible))
6289 (goto-char (next-single-char-property-change (point) 'invisible))
6290 (and (eolp) (beginning-of-line 2))))
6291 (setq eol (point)))
6292 ;; Find out what to do next and set `this-command'
6293 (cond
6294 ((= eos eoh)
6295 ;; Nothing is hidden behind this heading
6296 (unless (org-before-first-heading-p)
6297 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6298 (message "EMPTY ENTRY")
6299 (setq org-cycle-subtree-status nil)
6300 (save-excursion
6301 (goto-char eos)
6302 (outline-next-heading)
6303 (if (outline-invisible-p) (org-flag-heading nil))))
6304 ((and (or (>= eol eos)
6305 (not (string-match "\\S-" (buffer-substring eol eos))))
6306 (or has-children
6307 (not (setq children-skipped
6308 org-cycle-skip-children-state-if-no-children))))
6309 ;; Entire subtree is hidden in one line: children view
6310 (unless (org-before-first-heading-p)
6311 (run-hook-with-args 'org-pre-cycle-hook 'children))
6312 (if (org-at-item-p)
6313 (org-list-set-item-visibility (point-at-bol) struct 'children)
6314 (org-show-entry)
6315 (org-with-limited-levels (show-children))
6316 ;; FIXME: This slows down the func way too much.
6317 ;; How keep drawers hidden in subtree anyway?
6318 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6319 ;; (org-cycle-hide-drawers 'subtree))
6321 ;; Fold every list in subtree to top-level items.
6322 (when (eq org-cycle-include-plain-lists 'integrate)
6323 (save-excursion
6324 (org-back-to-heading)
6325 (while (org-list-search-forward (org-item-beginning-re) eos t)
6326 (beginning-of-line 1)
6327 (let* ((struct (org-list-struct))
6328 (prevs (org-list-prevs-alist struct))
6329 (end (org-list-get-bottom-point struct)))
6330 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6331 (org-list-get-all-items (point) struct prevs))
6332 (goto-char end))))))
6333 (message "CHILDREN")
6334 (save-excursion
6335 (goto-char eos)
6336 (outline-next-heading)
6337 (if (outline-invisible-p) (org-flag-heading nil)))
6338 (setq org-cycle-subtree-status 'children)
6339 (unless (org-before-first-heading-p)
6340 (run-hook-with-args 'org-cycle-hook 'children)))
6341 ((or children-skipped
6342 (and (eq last-command this-command)
6343 (eq org-cycle-subtree-status 'children)))
6344 ;; We just showed the children, or no children are there,
6345 ;; now show everything.
6346 (unless (org-before-first-heading-p)
6347 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6348 (outline-flag-region eoh eos nil)
6349 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6350 (setq org-cycle-subtree-status 'subtree)
6351 (unless (org-before-first-heading-p)
6352 (run-hook-with-args 'org-cycle-hook 'subtree)))
6354 ;; Default action: hide the subtree.
6355 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6356 (outline-flag-region eoh eos t)
6357 (message "FOLDED")
6358 (setq org-cycle-subtree-status 'folded)
6359 (unless (org-before-first-heading-p)
6360 (run-hook-with-args 'org-cycle-hook 'folded))))))
6362 ;;;###autoload
6363 (defun org-global-cycle (&optional arg)
6364 "Cycle the global visibility. For details see `org-cycle'.
6365 With \\[universal-argument] prefix arg, switch to startup visibility.
6366 With a numeric prefix, show all headlines up to that level."
6367 (interactive "P")
6368 (let ((org-cycle-include-plain-lists
6369 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6370 (cond
6371 ((integerp arg)
6372 (show-all)
6373 (hide-sublevels arg)
6374 (setq org-cycle-global-status 'contents))
6375 ((equal arg '(4))
6376 (org-set-startup-visibility)
6377 (message "Startup visibility, plus VISIBILITY properties."))
6379 (org-cycle '(4))))))
6381 (defun org-set-startup-visibility ()
6382 "Set the visibility required by startup options and properties."
6383 (cond
6384 ((eq org-startup-folded t)
6385 (org-cycle '(4)))
6386 ((eq org-startup-folded 'content)
6387 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6388 (org-cycle '(4)) (org-cycle '(4)))))
6389 (unless (eq org-startup-folded 'showeverything)
6390 (if org-hide-block-startup (org-hide-block-all))
6391 (org-set-visibility-according-to-property 'no-cleanup)
6392 (org-cycle-hide-archived-subtrees 'all)
6393 (org-cycle-hide-drawers 'all)
6394 (org-cycle-show-empty-lines t)))
6396 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6397 "Switch subtree visibilities according to :VISIBILITY: property."
6398 (interactive)
6399 (let (org-show-entry-below state)
6400 (save-excursion
6401 (goto-char (point-min))
6402 (while (re-search-forward
6403 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6404 nil t)
6405 (setq state (match-string 1))
6406 (save-excursion
6407 (org-back-to-heading t)
6408 (hide-subtree)
6409 (org-reveal)
6410 (cond
6411 ((equal state '("fold" "folded"))
6412 (hide-subtree))
6413 ((equal state "children")
6414 (org-show-hidden-entry)
6415 (show-children))
6416 ((equal state "content")
6417 (save-excursion
6418 (save-restriction
6419 (org-narrow-to-subtree)
6420 (org-content))))
6421 ((member state '("all" "showall"))
6422 (show-subtree)))))
6423 (unless no-cleanup
6424 (org-cycle-hide-archived-subtrees 'all)
6425 (org-cycle-hide-drawers 'all)
6426 (org-cycle-show-empty-lines 'all)))))
6428 ;; This function uses outline-regexp instead of the more fundamental
6429 ;; org-outline-regexp so that org-cycle-global works outside of Org
6430 ;; buffers, where outline-regexp is needed.
6431 (defun org-overview ()
6432 "Switch to overview mode, showing only top-level headlines.
6433 Really, this shows all headlines with level equal or greater than the level
6434 of the first headline in the buffer. This is important, because if the
6435 first headline is not level one, then (hide-sublevels 1) gives confusing
6436 results."
6437 (interactive)
6438 (let ((l (org-current-line))
6439 (level (save-excursion
6440 (goto-char (point-min))
6441 (if (re-search-forward (concat "^" outline-regexp) nil t)
6442 (progn
6443 (goto-char (match-beginning 0))
6444 (funcall outline-level))))))
6445 (and level (hide-sublevels level))
6446 (recenter '(4))
6447 (org-goto-line l)))
6449 (defun org-content (&optional arg)
6450 "Show all headlines in the buffer, like a table of contents.
6451 With numerical argument N, show content up to level N."
6452 (interactive "P")
6453 (save-excursion
6454 ;; Visit all headings and show their offspring
6455 (and (integerp arg) (org-overview))
6456 (goto-char (point-max))
6457 (catch 'exit
6458 (while (and (progn (condition-case nil
6459 (outline-previous-visible-heading 1)
6460 (error (goto-char (point-min))))
6462 (looking-at org-outline-regexp))
6463 (if (integerp arg)
6464 (show-children (1- arg))
6465 (show-branches))
6466 (if (bobp) (throw 'exit nil))))))
6469 (defun org-optimize-window-after-visibility-change (state)
6470 "Adjust the window after a change in outline visibility.
6471 This function is the default value of the hook `org-cycle-hook'."
6472 (when (get-buffer-window (current-buffer))
6473 (cond
6474 ((eq state 'content) nil)
6475 ((eq state 'all) nil)
6476 ((eq state 'folded) nil)
6477 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6478 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6480 (defun org-remove-empty-overlays-at (pos)
6481 "Remove outline overlays that do not contain non-white stuff."
6482 (mapc
6483 (lambda (o)
6484 (and (eq 'outline (overlay-get o 'invisible))
6485 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6486 (overlay-end o))))
6487 (delete-overlay o)))
6488 (overlays-at pos)))
6490 (defun org-clean-visibility-after-subtree-move ()
6491 "Fix visibility issues after moving a subtree."
6492 ;; First, find a reasonable region to look at:
6493 ;; Start two siblings above, end three below
6494 (let* ((beg (save-excursion
6495 (and (org-get-last-sibling)
6496 (org-get-last-sibling))
6497 (point)))
6498 (end (save-excursion
6499 (and (org-get-next-sibling)
6500 (org-get-next-sibling)
6501 (org-get-next-sibling))
6502 (if (org-at-heading-p)
6503 (point-at-eol)
6504 (point))))
6505 (level (looking-at "\\*+"))
6506 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6507 (save-excursion
6508 (save-restriction
6509 (narrow-to-region beg end)
6510 (when re
6511 ;; Properly fold already folded siblings
6512 (goto-char (point-min))
6513 (while (re-search-forward re nil t)
6514 (if (and (not (outline-invisible-p))
6515 (save-excursion
6516 (goto-char (point-at-eol)) (outline-invisible-p)))
6517 (hide-entry))))
6518 (org-cycle-show-empty-lines 'overview)
6519 (org-cycle-hide-drawers 'overview)))))
6521 (defun org-cycle-show-empty-lines (state)
6522 "Show empty lines above all visible headlines.
6523 The region to be covered depends on STATE when called through
6524 `org-cycle-hook'. Lisp program can use t for STATE to get the
6525 entire buffer covered. Note that an empty line is only shown if there
6526 are at least `org-cycle-separator-lines' empty lines before the headline."
6527 (when (not (= org-cycle-separator-lines 0))
6528 (save-excursion
6529 (let* ((n (abs org-cycle-separator-lines))
6530 (re (cond
6531 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6532 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6533 (t (let ((ns (number-to-string (- n 2))))
6534 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6535 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6536 beg end b e)
6537 (cond
6538 ((memq state '(overview contents t))
6539 (setq beg (point-min) end (point-max)))
6540 ((memq state '(children folded))
6541 (setq beg (point) end (progn (org-end-of-subtree t t)
6542 (beginning-of-line 2)
6543 (point)))))
6544 (when beg
6545 (goto-char beg)
6546 (while (re-search-forward re end t)
6547 (unless (get-char-property (match-end 1) 'invisible)
6548 (setq e (match-end 1))
6549 (if (< org-cycle-separator-lines 0)
6550 (setq b (save-excursion
6551 (goto-char (match-beginning 0))
6552 (org-back-over-empty-lines)
6553 (if (save-excursion
6554 (goto-char (max (point-min) (1- (point))))
6555 (org-at-heading-p))
6556 (1- (point))
6557 (point))))
6558 (setq b (match-beginning 1)))
6559 (outline-flag-region b e nil)))))))
6560 ;; Never hide empty lines at the end of the file.
6561 (save-excursion
6562 (goto-char (point-max))
6563 (outline-previous-heading)
6564 (outline-end-of-heading)
6565 (if (and (looking-at "[ \t\n]+")
6566 (= (match-end 0) (point-max)))
6567 (outline-flag-region (point) (match-end 0) nil))))
6569 (defun org-show-empty-lines-in-parent ()
6570 "Move to the parent and re-show empty lines before visible headlines."
6571 (save-excursion
6572 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6573 (org-cycle-show-empty-lines context))))
6575 (defun org-files-list ()
6576 "Return `org-agenda-files' list, plus all open org-mode files.
6577 This is useful for operations that need to scan all of a user's
6578 open and agenda-wise Org files."
6579 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6580 (dolist (buf (buffer-list))
6581 (with-current-buffer buf
6582 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6583 (let ((file (expand-file-name (buffer-file-name))))
6584 (unless (member file files)
6585 (push file files))))))
6586 files))
6588 (defsubst org-entry-beginning-position ()
6589 "Return the beginning position of the current entry."
6590 (save-excursion (outline-back-to-heading t) (point)))
6592 (defsubst org-entry-end-position ()
6593 "Return the end position of the current entry."
6594 (save-excursion (outline-next-heading) (point)))
6596 (defun org-cycle-hide-drawers (state)
6597 "Re-hide all drawers after a visibility state change."
6598 (when (and (derived-mode-p 'org-mode)
6599 (not (memq state '(overview folded contents))))
6600 (save-excursion
6601 (let* ((globalp (memq state '(contents all)))
6602 (beg (if globalp (point-min) (point)))
6603 (end (if globalp (point-max)
6604 (if (eq state 'children)
6605 (save-excursion (outline-next-heading) (point))
6606 (org-end-of-subtree t)))))
6607 (goto-char beg)
6608 (while (re-search-forward org-drawer-regexp end t)
6609 (org-flag-drawer t))))))
6611 (defun org-flag-drawer (flag)
6612 "When FLAG is non-nil, hide the drawer we are within.
6613 Otherwise make it visible."
6614 (save-excursion
6615 (beginning-of-line 1)
6616 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6617 (let ((b (match-end 0)))
6618 (if (re-search-forward
6619 "^[ \t]*:END:"
6620 (save-excursion (outline-next-heading) (point)) t)
6621 (outline-flag-region b (point-at-eol) flag)
6622 (error ":END: line missing at position %s" b))))))
6624 (defun org-subtree-end-visible-p ()
6625 "Is the end of the current subtree visible?"
6626 (pos-visible-in-window-p
6627 (save-excursion (org-end-of-subtree t) (point))))
6629 (defun org-first-headline-recenter (&optional N)
6630 "Move cursor to the first headline and recenter the headline.
6631 Optional argument N means put the headline into the Nth line of the window."
6632 (goto-char (point-min))
6633 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6634 (beginning-of-line)
6635 (recenter (prefix-numeric-value N))))
6637 ;;; Saving and restoring visibility
6639 (defun org-outline-overlay-data (&optional use-markers)
6640 "Return a list of the locations of all outline overlays.
6641 These are overlays with the `invisible' property value `outline'.
6642 The return value is a list of cons cells, with start and stop
6643 positions for each overlay.
6644 If USE-MARKERS is set, return the positions as markers."
6645 (let (beg end)
6646 (save-excursion
6647 (save-restriction
6648 (widen)
6649 (delq nil
6650 (mapcar (lambda (o)
6651 (when (eq (overlay-get o 'invisible) 'outline)
6652 (setq beg (overlay-start o)
6653 end (overlay-end o))
6654 (and beg end (> end beg)
6655 (if use-markers
6656 (cons (move-marker (make-marker) beg)
6657 (move-marker (make-marker) end))
6658 (cons beg end)))))
6659 (overlays-in (point-min) (point-max))))))))
6661 (defun org-set-outline-overlay-data (data)
6662 "Create visibility overlays for all positions in DATA.
6663 DATA should have been made by `org-outline-overlay-data'."
6664 (let (o)
6665 (save-excursion
6666 (save-restriction
6667 (widen)
6668 (show-all)
6669 (mapc (lambda (c)
6670 (outline-flag-region (car c) (cdr c) t))
6671 data)))))
6673 ;;; Folding of blocks
6675 (defvar org-hide-block-overlays nil
6676 "Overlays hiding blocks.")
6677 (make-variable-buffer-local 'org-hide-block-overlays)
6679 (defun org-block-map (function &optional start end)
6680 "Call FUNCTION at the head of all source blocks in the current buffer.
6681 Optional arguments START and END can be used to limit the range."
6682 (let ((start (or start (point-min)))
6683 (end (or end (point-max))))
6684 (save-excursion
6685 (goto-char start)
6686 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6687 (save-excursion
6688 (save-match-data
6689 (goto-char (match-beginning 0))
6690 (funcall function)))))))
6692 (defun org-hide-block-toggle-all ()
6693 "Toggle the visibility of all blocks in the current buffer."
6694 (org-block-map #'org-hide-block-toggle))
6696 (defun org-hide-block-all ()
6697 "Fold all blocks in the current buffer."
6698 (interactive)
6699 (org-show-block-all)
6700 (org-block-map #'org-hide-block-toggle-maybe))
6702 (defun org-show-block-all ()
6703 "Unfold all blocks in the current buffer."
6704 (interactive)
6705 (mapc 'delete-overlay org-hide-block-overlays)
6706 (setq org-hide-block-overlays nil))
6708 (defun org-hide-block-toggle-maybe ()
6709 "Toggle visibility of block at point."
6710 (interactive)
6711 (let ((case-fold-search t))
6712 (if (save-excursion
6713 (beginning-of-line 1)
6714 (looking-at org-block-regexp))
6715 (progn (org-hide-block-toggle)
6716 t) ;; to signal that we took action
6717 nil))) ;; to signal that we did not
6719 (defun org-hide-block-toggle (&optional force)
6720 "Toggle the visibility of the current block."
6721 (interactive)
6722 (save-excursion
6723 (beginning-of-line)
6724 (if (re-search-forward org-block-regexp nil t)
6725 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6726 (end (match-end 0)) ;; end of entire body
6728 (if (memq t (mapcar (lambda (overlay)
6729 (eq (overlay-get overlay 'invisible)
6730 'org-hide-block))
6731 (overlays-at start)))
6732 (if (or (not force) (eq force 'off))
6733 (mapc (lambda (ov)
6734 (when (member ov org-hide-block-overlays)
6735 (setq org-hide-block-overlays
6736 (delq ov org-hide-block-overlays)))
6737 (when (eq (overlay-get ov 'invisible)
6738 'org-hide-block)
6739 (delete-overlay ov)))
6740 (overlays-at start)))
6741 (setq ov (make-overlay start end))
6742 (overlay-put ov 'invisible 'org-hide-block)
6743 ;; make the block accessible to isearch
6744 (overlay-put
6745 ov 'isearch-open-invisible
6746 (lambda (ov)
6747 (when (member ov org-hide-block-overlays)
6748 (setq org-hide-block-overlays
6749 (delq ov org-hide-block-overlays)))
6750 (when (eq (overlay-get ov 'invisible)
6751 'org-hide-block)
6752 (delete-overlay ov))))
6753 (push ov org-hide-block-overlays)))
6754 (error "Not looking at a source block"))))
6756 ;; org-tab-after-check-for-cycling-hook
6757 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6758 ;; Remove overlays when changing major mode
6759 (add-hook 'org-mode-hook
6760 (lambda () (org-add-hook 'change-major-mode-hook
6761 'org-show-block-all 'append 'local)))
6763 ;;; Org-goto
6765 (defvar org-goto-window-configuration nil)
6766 (defvar org-goto-marker nil)
6767 (defvar org-goto-map)
6768 (defun org-goto-map ()
6769 "Set the keymap `org-goto'."
6770 (setq org-goto-map
6771 (let ((map (make-sparse-keymap)))
6772 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6773 mouse-drag-region universal-argument org-occur))
6774 cmd)
6775 (while (setq cmd (pop cmds))
6776 (substitute-key-definition cmd cmd map global-map)))
6777 (suppress-keymap map)
6778 (org-defkey map "\C-m" 'org-goto-ret)
6779 (org-defkey map [(return)] 'org-goto-ret)
6780 (org-defkey map [(left)] 'org-goto-left)
6781 (org-defkey map [(right)] 'org-goto-right)
6782 (org-defkey map [(control ?g)] 'org-goto-quit)
6783 (org-defkey map "\C-i" 'org-cycle)
6784 (org-defkey map [(tab)] 'org-cycle)
6785 (org-defkey map [(down)] 'outline-next-visible-heading)
6786 (org-defkey map [(up)] 'outline-previous-visible-heading)
6787 (if org-goto-auto-isearch
6788 (if (fboundp 'define-key-after)
6789 (define-key-after map [t] 'org-goto-local-auto-isearch)
6790 nil)
6791 (org-defkey map "q" 'org-goto-quit)
6792 (org-defkey map "n" 'outline-next-visible-heading)
6793 (org-defkey map "p" 'outline-previous-visible-heading)
6794 (org-defkey map "f" 'outline-forward-same-level)
6795 (org-defkey map "b" 'outline-backward-same-level)
6796 (org-defkey map "u" 'outline-up-heading))
6797 (org-defkey map "/" 'org-occur)
6798 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6799 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6800 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6801 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6802 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6803 map)))
6805 (defconst org-goto-help
6806 "Browse buffer copy, to find location or copy text.%s
6807 RET=jump to location C-g=quit and return to previous location
6808 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6810 (defvar org-goto-start-pos) ; dynamically scoped parameter
6812 ;; FIXME: Docstring does not mention both interfaces
6813 (defun org-goto (&optional alternative-interface)
6814 "Look up a different location in the current file, keeping current visibility.
6816 When you want look-up or go to a different location in a
6817 document, the fastest way is often to fold the entire buffer and
6818 then dive into the tree. This method has the disadvantage, that
6819 the previous location will be folded, which may not be what you
6820 want.
6822 This command works around this by showing a copy of the current
6823 buffer in an indirect buffer, in overview mode. You can dive
6824 into the tree in that copy, use org-occur and incremental search
6825 to find a location. When pressing RET or `Q', the command
6826 returns to the original buffer in which the visibility is still
6827 unchanged. After RET it will also jump to the location selected
6828 in the indirect buffer and expose the headline hierarchy above.
6830 With a prefix argument, use the alternative interface: e.g. if
6831 `org-goto-interface' is 'outline use 'outline-path-completion."
6832 (interactive "P")
6833 (org-goto-map)
6834 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6835 (org-refile-use-outline-path t)
6836 (org-refile-target-verify-function nil)
6837 (interface
6838 (if (not alternative-interface)
6839 org-goto-interface
6840 (if (eq org-goto-interface 'outline)
6841 'outline-path-completion
6842 'outline)))
6843 (org-goto-start-pos (point))
6844 (selected-point
6845 (if (eq interface 'outline)
6846 (car (org-get-location (current-buffer) org-goto-help))
6847 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6848 (org-refile-check-position pa)
6849 (nth 3 pa)))))
6850 (if selected-point
6851 (progn
6852 (org-mark-ring-push org-goto-start-pos)
6853 (goto-char selected-point)
6854 (if (or (outline-invisible-p) (org-invisible-p2))
6855 (org-show-context 'org-goto)))
6856 (message "Quit"))))
6858 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6859 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6860 (defvar org-goto-local-auto-isearch-map) ; defined below
6862 (defun org-get-location (buf help)
6863 "Let the user select a location in the Org-mode buffer BUF.
6864 This function uses a recursive edit. It returns the selected position
6865 or nil."
6866 (org-no-popups
6867 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6868 (isearch-hide-immediately nil)
6869 (isearch-search-fun-function
6870 (lambda () 'org-goto-local-search-headings))
6871 (org-goto-selected-point org-goto-exit-command))
6872 (save-excursion
6873 (save-window-excursion
6874 (delete-other-windows)
6875 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6876 (org-pop-to-buffer-same-window
6877 (condition-case nil
6878 (make-indirect-buffer (current-buffer) "*org-goto*")
6879 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6880 (with-output-to-temp-buffer "*Org Help*"
6881 (princ (format help (if org-goto-auto-isearch
6882 " Just type for auto-isearch."
6883 " n/p/f/b/u to navigate, q to quit."))))
6884 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
6885 (setq buffer-read-only nil)
6886 (let ((org-startup-truncated t)
6887 (org-startup-folded nil)
6888 (org-startup-align-all-tables nil))
6889 (org-mode)
6890 (org-overview))
6891 (setq buffer-read-only t)
6892 (if (and (boundp 'org-goto-start-pos)
6893 (integer-or-marker-p org-goto-start-pos))
6894 (let ((org-show-hierarchy-above t)
6895 (org-show-siblings t)
6896 (org-show-following-heading t))
6897 (goto-char org-goto-start-pos)
6898 (and (outline-invisible-p) (org-show-context)))
6899 (goto-char (point-min)))
6900 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6901 (message "Select location and press RET")
6902 (use-local-map org-goto-map)
6903 (recursive-edit)))
6904 (kill-buffer "*org-goto*")
6905 (cons org-goto-selected-point org-goto-exit-command))))
6907 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6908 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6909 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6910 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6912 (defun org-goto-local-search-headings (string bound noerror)
6913 "Search and make sure that any matches are in headlines."
6914 (catch 'return
6915 (while (if isearch-forward
6916 (search-forward string bound noerror)
6917 (search-backward string bound noerror))
6918 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6919 (and (member :headline context)
6920 (not (member :tags context))))
6921 (throw 'return (point))))))
6923 (defun org-goto-local-auto-isearch ()
6924 "Start isearch."
6925 (interactive)
6926 (goto-char (point-min))
6927 (let ((keys (this-command-keys)))
6928 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6929 (isearch-mode t)
6930 (isearch-process-search-char (string-to-char keys)))))
6932 (defun org-goto-ret (&optional arg)
6933 "Finish `org-goto' by going to the new location."
6934 (interactive "P")
6935 (setq org-goto-selected-point (point)
6936 org-goto-exit-command 'return)
6937 (throw 'exit nil))
6939 (defun org-goto-left ()
6940 "Finish `org-goto' by going to the new location."
6941 (interactive)
6942 (if (org-at-heading-p)
6943 (progn
6944 (beginning-of-line 1)
6945 (setq org-goto-selected-point (point)
6946 org-goto-exit-command 'left)
6947 (throw 'exit nil))
6948 (error "Not on a heading")))
6950 (defun org-goto-right ()
6951 "Finish `org-goto' by going to the new location."
6952 (interactive)
6953 (if (org-at-heading-p)
6954 (progn
6955 (setq org-goto-selected-point (point)
6956 org-goto-exit-command 'right)
6957 (throw 'exit nil))
6958 (error "Not on a heading")))
6960 (defun org-goto-quit ()
6961 "Finish `org-goto' without cursor motion."
6962 (interactive)
6963 (setq org-goto-selected-point nil)
6964 (setq org-goto-exit-command 'quit)
6965 (throw 'exit nil))
6967 ;;; Indirect buffer display of subtrees
6969 (defvar org-indirect-dedicated-frame nil
6970 "This is the frame being used for indirect tree display.")
6971 (defvar org-last-indirect-buffer nil)
6973 (defun org-tree-to-indirect-buffer (&optional arg)
6974 "Create indirect buffer and narrow it to current subtree.
6975 With a numerical prefix ARG, go up to this level and then take that tree.
6976 If ARG is negative, go up that many levels.
6978 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6979 indirect buffer previously made with this command, to avoid proliferation of
6980 indirect buffers. However, when you call the command with a \
6981 \\[universal-argument] prefix, or
6982 when `org-indirect-buffer-display' is `new-frame', the last buffer
6983 is kept so that you can work with several indirect buffers at the same time.
6984 If `org-indirect-buffer-display' is `dedicated-frame', the \
6985 \\[universal-argument] prefix also
6986 requests that a new frame be made for the new buffer, so that the dedicated
6987 frame is not changed."
6988 (interactive "P")
6989 (let ((cbuf (current-buffer))
6990 (cwin (selected-window))
6991 (pos (point))
6992 beg end level heading ibuf)
6993 (save-excursion
6994 (org-back-to-heading t)
6995 (when (numberp arg)
6996 (setq level (org-outline-level))
6997 (if (< arg 0) (setq arg (+ level arg)))
6998 (while (> (setq level (org-outline-level)) arg)
6999 (org-up-heading-safe)))
7000 (setq beg (point)
7001 heading (org-get-heading))
7002 (org-end-of-subtree t t)
7003 (if (org-at-heading-p) (backward-char 1))
7004 (setq end (point)))
7005 (if (and (buffer-live-p org-last-indirect-buffer)
7006 (not (eq org-indirect-buffer-display 'new-frame))
7007 (not arg))
7008 (kill-buffer org-last-indirect-buffer))
7009 (setq ibuf (org-get-indirect-buffer cbuf)
7010 org-last-indirect-buffer ibuf)
7011 (cond
7012 ((or (eq org-indirect-buffer-display 'new-frame)
7013 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7014 (select-frame (make-frame))
7015 (delete-other-windows)
7016 (org-pop-to-buffer-same-window ibuf)
7017 (org-set-frame-title heading))
7018 ((eq org-indirect-buffer-display 'dedicated-frame)
7019 (raise-frame
7020 (select-frame (or (and org-indirect-dedicated-frame
7021 (frame-live-p org-indirect-dedicated-frame)
7022 org-indirect-dedicated-frame)
7023 (setq org-indirect-dedicated-frame (make-frame)))))
7024 (delete-other-windows)
7025 (org-pop-to-buffer-same-window ibuf)
7026 (org-set-frame-title (concat "Indirect: " heading)))
7027 ((eq org-indirect-buffer-display 'current-window)
7028 (org-pop-to-buffer-same-window ibuf))
7029 ((eq org-indirect-buffer-display 'other-window)
7030 (pop-to-buffer ibuf))
7031 (t (error "Invalid value")))
7032 (if (featurep 'xemacs)
7033 (save-excursion (org-mode) (turn-on-font-lock)))
7034 (narrow-to-region beg end)
7035 (show-all)
7036 (goto-char pos)
7037 (run-hook-with-args 'org-cycle-hook 'all)
7038 (and (window-live-p cwin) (select-window cwin))))
7040 (defun org-get-indirect-buffer (&optional buffer)
7041 (setq buffer (or buffer (current-buffer)))
7042 (let ((n 1) (base (buffer-name buffer)) bname)
7043 (while (buffer-live-p
7044 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7045 (setq n (1+ n)))
7046 (condition-case nil
7047 (make-indirect-buffer buffer bname 'clone)
7048 (error (make-indirect-buffer buffer bname)))))
7050 (defun org-set-frame-title (title)
7051 "Set the title of the current frame to the string TITLE."
7052 ;; FIXME: how to name a single frame in XEmacs???
7053 (unless (featurep 'xemacs)
7054 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7056 ;;;; Structure editing
7058 ;;; Inserting headlines
7060 (defun org-previous-line-empty-p ()
7061 (save-excursion
7062 (and (not (bobp))
7063 (or (beginning-of-line 0) t)
7064 (save-match-data
7065 (looking-at "[ \t]*$")))))
7067 (defun org-insert-heading (&optional force-heading invisible-ok)
7068 "Insert a new heading or item with same depth at point.
7069 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7070 If point is at the beginning of a headline, insert a sibling before the
7071 current headline. If point is not at the beginning, split the line,
7072 create the new headline with the text in the current line after point
7073 \(but see also the variable `org-M-RET-may-split-line').
7075 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7076 This is important for non-interactive uses of the command."
7077 (interactive "P")
7078 (if (or (= (buffer-size) 0)
7079 (and (not (save-excursion
7080 (and (ignore-errors (org-back-to-heading invisible-ok))
7081 (org-at-heading-p))))
7082 (or force-heading (not (org-in-item-p)))))
7083 (progn
7084 (insert "\n* ")
7085 (run-hooks 'org-insert-heading-hook))
7086 (when (or force-heading (not (org-insert-item)))
7087 (let* ((empty-line-p nil)
7088 (level nil)
7089 (on-heading (org-at-heading-p))
7090 (head (save-excursion
7091 (condition-case nil
7092 (progn
7093 (org-back-to-heading invisible-ok)
7094 (when (and (not on-heading)
7095 (featurep 'org-inlinetask)
7096 (integerp org-inlinetask-min-level)
7097 (>= (length (match-string 0))
7098 org-inlinetask-min-level))
7099 ;; Find a heading level before the inline task
7100 (while (and (setq level (org-up-heading-safe))
7101 (>= level org-inlinetask-min-level)))
7102 (if (org-at-heading-p)
7103 (org-back-to-heading invisible-ok)
7104 (error "This should not happen")))
7105 (setq empty-line-p (org-previous-line-empty-p))
7106 (match-string 0))
7107 (error "*"))))
7108 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7109 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7110 pos hide-previous previous-pos)
7111 (cond
7112 ((and (org-at-heading-p) (bolp)
7113 (or (bobp)
7114 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7115 ;; insert before the current line
7116 (open-line (if blank 2 1)))
7117 ((and (bolp)
7118 (not org-insert-heading-respect-content)
7119 (or (bobp)
7120 (save-excursion
7121 (backward-char 1) (not (outline-invisible-p)))))
7122 ;; insert right here
7123 nil)
7125 ;; somewhere in the line
7126 (save-excursion
7127 (setq previous-pos (point-at-bol))
7128 (end-of-line)
7129 (setq hide-previous (outline-invisible-p)))
7130 (and org-insert-heading-respect-content (org-show-subtree))
7131 (let ((split
7132 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7133 (save-excursion
7134 (let ((p (point)))
7135 (goto-char (point-at-bol))
7136 (and (looking-at org-complex-heading-regexp)
7137 (match-beginning 4)
7138 (> p (match-beginning 4)))))))
7139 tags pos)
7140 (cond
7141 (org-insert-heading-respect-content
7142 (org-end-of-subtree nil t)
7143 (when (featurep 'org-inlinetask)
7144 (while (and (not (eobp))
7145 (looking-at "\\(\\*+\\)[ \t]+")
7146 (>= (length (match-string 1))
7147 org-inlinetask-min-level))
7148 (org-end-of-subtree nil t)))
7149 (or (bolp) (newline))
7150 (or (org-previous-line-empty-p)
7151 (and blank (newline)))
7152 (open-line 1))
7153 ((org-at-heading-p)
7154 (when hide-previous
7155 (show-children)
7156 (org-show-entry))
7157 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7158 (setq tags (and (match-end 2) (match-string 2)))
7159 (and (match-end 1)
7160 (delete-region (match-beginning 1) (match-end 1)))
7161 (setq pos (point-at-bol))
7162 (or split (end-of-line 1))
7163 (delete-horizontal-space)
7164 (if (string-match "\\`\\*+\\'"
7165 (buffer-substring (point-at-bol) (point)))
7166 (insert " "))
7167 (newline (if blank 2 1))
7168 (when tags
7169 (save-excursion
7170 (goto-char pos)
7171 (end-of-line 1)
7172 (insert " " tags)
7173 (org-set-tags nil 'align))))
7175 (or split (end-of-line 1))
7176 (newline (if blank 2 1)))))))
7177 (insert head) (just-one-space)
7178 (setq pos (point))
7179 (end-of-line 1)
7180 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7181 (when (and org-insert-heading-respect-content hide-previous)
7182 (save-excursion
7183 (goto-char previous-pos)
7184 (hide-subtree)))
7185 (run-hooks 'org-insert-heading-hook)))))
7187 (defun org-get-heading (&optional no-tags no-todo)
7188 "Return the heading of the current entry, without the stars.
7189 When NO-TAGS is non-nil, don't include tags.
7190 When NO-TODO is non-nil, don't include TODO keywords."
7191 (save-excursion
7192 (org-back-to-heading t)
7193 (cond
7194 ((and no-tags no-todo)
7195 (looking-at org-complex-heading-regexp)
7196 (match-string 4))
7197 (no-tags
7198 (looking-at (concat org-outline-regexp
7199 "\\(.*?\\)"
7200 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7201 (match-string 1))
7202 (no-todo
7203 (looking-at org-todo-line-regexp)
7204 (match-string 3))
7205 (t (looking-at org-heading-regexp)
7206 (match-string 2)))))
7208 (defun org-heading-components ()
7209 "Return the components of the current heading.
7210 This is a list with the following elements:
7211 - the level as an integer
7212 - the reduced level, different if `org-odd-levels-only' is set.
7213 - the TODO keyword, or nil
7214 - the priority character, like ?A, or nil if no priority is given
7215 - the headline text itself, or the tags string if no headline text
7216 - the tags string, or nil."
7217 (save-excursion
7218 (org-back-to-heading t)
7219 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7220 (list (length (match-string 1))
7221 (org-reduced-level (length (match-string 1)))
7222 (org-match-string-no-properties 2)
7223 (and (match-end 3) (aref (match-string 3) 2))
7224 (org-match-string-no-properties 4)
7225 (org-match-string-no-properties 5)))))
7227 (defun org-get-entry ()
7228 "Get the entry text, after heading, entire subtree."
7229 (save-excursion
7230 (org-back-to-heading t)
7231 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7233 (defun org-insert-heading-after-current ()
7234 "Insert a new heading with same level as current, after current subtree."
7235 (interactive)
7236 (org-back-to-heading)
7237 (org-insert-heading)
7238 (org-move-subtree-down)
7239 (end-of-line 1))
7241 (defun org-insert-heading-respect-content (invisible-ok)
7242 "Insert heading with `org-insert-heading-respect-content' set to t."
7243 (interactive "P")
7244 (let ((org-insert-heading-respect-content t))
7245 (org-insert-heading t invisible-ok)))
7247 (defun org-insert-todo-heading-respect-content (&optional force-state)
7248 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7249 (interactive "P")
7250 (let ((org-insert-heading-respect-content t))
7251 (org-insert-todo-heading force-state t)))
7253 (defun org-insert-todo-heading (arg &optional force-heading)
7254 "Insert a new heading with the same level and TODO state as current heading.
7255 If the heading has no TODO state, or if the state is DONE, use the first
7256 state (TODO by default). Also with prefix arg, force first state."
7257 (interactive "P")
7258 (when (or force-heading (not (org-insert-item 'checkbox)))
7259 (org-insert-heading force-heading)
7260 (save-excursion
7261 (org-back-to-heading)
7262 (outline-previous-heading)
7263 (looking-at org-todo-line-regexp))
7264 (let*
7265 ((new-mark-x
7266 (if (or arg
7267 (not (match-beginning 2))
7268 (member (match-string 2) org-done-keywords))
7269 (car org-todo-keywords-1)
7270 (match-string 2)))
7271 (new-mark
7273 (run-hook-with-args-until-success
7274 'org-todo-get-default-hook new-mark-x nil)
7275 new-mark-x)))
7276 (beginning-of-line 1)
7277 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7278 (if org-treat-insert-todo-heading-as-state-change
7279 (org-todo new-mark)
7280 (insert new-mark " "))))
7281 (when org-provide-todo-statistics
7282 (org-update-parent-todo-statistics))))
7284 (defun org-insert-subheading (arg)
7285 "Insert a new subheading and demote it.
7286 Works for outline headings and for plain lists alike."
7287 (interactive "P")
7288 (org-insert-heading arg)
7289 (cond
7290 ((org-at-heading-p) (org-do-demote))
7291 ((org-at-item-p) (org-indent-item))))
7293 (defun org-insert-todo-subheading (arg)
7294 "Insert a new subheading with TODO keyword or checkbox and demote it.
7295 Works for outline headings and for plain lists alike."
7296 (interactive "P")
7297 (org-insert-todo-heading arg)
7298 (cond
7299 ((org-at-heading-p) (org-do-demote))
7300 ((org-at-item-p) (org-indent-item))))
7302 ;;; Promotion and Demotion
7304 (defvar org-after-demote-entry-hook nil
7305 "Hook run after an entry has been demoted.
7306 The cursor will be at the beginning of the entry.
7307 When a subtree is being demoted, the hook will be called for each node.")
7309 (defvar org-after-promote-entry-hook nil
7310 "Hook run after an entry has been promoted.
7311 The cursor will be at the beginning of the entry.
7312 When a subtree is being promoted, the hook will be called for each node.")
7314 (defun org-promote-subtree ()
7315 "Promote the entire subtree.
7316 See also `org-promote'."
7317 (interactive)
7318 (save-excursion
7319 (org-with-limited-levels (org-map-tree 'org-promote)))
7320 (org-fix-position-after-promote))
7322 (defun org-demote-subtree ()
7323 "Demote the entire subtree. See `org-demote'.
7324 See also `org-promote'."
7325 (interactive)
7326 (save-excursion
7327 (org-with-limited-levels (org-map-tree 'org-demote)))
7328 (org-fix-position-after-promote))
7331 (defun org-do-promote ()
7332 "Promote the current heading higher up the tree.
7333 If the region is active in `transient-mark-mode', promote all headings
7334 in the region."
7335 (interactive)
7336 (save-excursion
7337 (if (org-region-active-p)
7338 (org-map-region 'org-promote (region-beginning) (region-end))
7339 (org-promote)))
7340 (org-fix-position-after-promote))
7342 (defun org-do-demote ()
7343 "Demote the current heading lower down the tree.
7344 If the region is active in `transient-mark-mode', demote all headings
7345 in the region."
7346 (interactive)
7347 (save-excursion
7348 (if (org-region-active-p)
7349 (org-map-region 'org-demote (region-beginning) (region-end))
7350 (org-demote)))
7351 (org-fix-position-after-promote))
7353 (defun org-fix-position-after-promote ()
7354 "Make sure that after pro/demotion cursor position is right."
7355 (let ((pos (point)))
7356 (when (save-excursion
7357 (beginning-of-line 1)
7358 (looking-at org-todo-line-regexp)
7359 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7360 (cond ((eobp) (insert " "))
7361 ((eolp) (insert " "))
7362 ((equal (char-after) ?\ ) (forward-char 1))))))
7364 (defun org-current-level ()
7365 "Return the level of the current entry, or nil if before the first headline.
7366 The level is the number of stars at the beginning of the headline."
7367 (save-excursion
7368 (org-with-limited-levels
7369 (if (ignore-errors (org-back-to-heading t))
7370 (funcall outline-level)))))
7372 (defun org-get-previous-line-level ()
7373 "Return the outline depth of the last headline before the current line.
7374 Returns 0 for the first headline in the buffer, and nil if before the
7375 first headline."
7376 (let ((current-level (org-current-level))
7377 (prev-level (when (> (line-number-at-pos) 1)
7378 (save-excursion
7379 (beginning-of-line 0)
7380 (org-current-level)))))
7381 (cond ((null current-level) nil) ; Before first headline
7382 ((null prev-level) 0) ; At first headline
7383 (prev-level))))
7385 (defun org-reduced-level (l)
7386 "Compute the effective level of a heading.
7387 This takes into account the setting of `org-odd-levels-only'."
7388 (cond
7389 ((zerop l) 0)
7390 (org-odd-levels-only (1+ (floor (/ l 2))))
7391 (t l)))
7393 (defun org-level-increment ()
7394 "Return the number of stars that will be added or removed at a
7395 time to headlines when structure editing, based on the value of
7396 `org-odd-levels-only'."
7397 (if org-odd-levels-only 2 1))
7399 (defun org-get-valid-level (level &optional change)
7400 "Rectify a level change under the influence of `org-odd-levels-only'
7401 LEVEL is a current level, CHANGE is by how much the level should be
7402 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7403 even level numbers will become the next higher odd number."
7404 (if org-odd-levels-only
7405 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7406 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7407 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7408 (max 1 (+ level (or change 0)))))
7410 (if (boundp 'define-obsolete-function-alias)
7411 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7412 (define-obsolete-function-alias 'org-get-legal-level
7413 'org-get-valid-level)
7414 (define-obsolete-function-alias 'org-get-legal-level
7415 'org-get-valid-level "23.1")))
7417 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7418 ;; ̀org-with-limited-levels'
7419 (defun org-promote ()
7420 "Promote the current heading higher up the tree.
7421 If the region is active in `transient-mark-mode', promote all headings
7422 in the region."
7423 (org-back-to-heading t)
7424 (let* ((level (save-match-data (funcall outline-level)))
7425 (after-change-functions (remove 'flyspell-after-change-function
7426 after-change-functions))
7427 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7428 (diff (abs (- level (length up-head) -1))))
7429 (cond ((and (= level 1) org-called-with-limited-levels
7430 org-allow-promoting-top-level-subtree)
7431 (replace-match "# " nil t))
7432 ((= level 1)
7433 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7434 (t (replace-match up-head nil t)))
7435 ;; Fixup tag positioning
7436 (unless (= level 1)
7437 (and org-auto-align-tags (org-set-tags nil t))
7438 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7439 (run-hooks 'org-after-promote-entry-hook)))
7441 (defun org-demote ()
7442 "Demote the current heading lower down the tree.
7443 If the region is active in `transient-mark-mode', demote all headings
7444 in the region."
7445 (org-back-to-heading t)
7446 (let* ((level (save-match-data (funcall outline-level)))
7447 (after-change-functions (remove 'flyspell-after-change-function
7448 after-change-functions))
7449 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7450 (diff (abs (- level (length down-head) -1))))
7451 (replace-match down-head nil t)
7452 ;; Fixup tag positioning
7453 (and org-auto-align-tags (org-set-tags nil t))
7454 (if org-adapt-indentation (org-fixup-indentation diff))
7455 (run-hooks 'org-after-demote-entry-hook)))
7457 (defun org-cycle-level ()
7458 "Cycle the level of an empty headline through possible states.
7459 This goes first to child, then to parent, level, then up the hierarchy.
7460 After top level, it switches back to sibling level."
7461 (interactive)
7462 (let ((org-adapt-indentation nil))
7463 (when (org-point-at-end-of-empty-headline)
7464 (setq this-command 'org-cycle-level) ; Only needed for caching
7465 (let ((cur-level (org-current-level))
7466 (prev-level (org-get-previous-line-level)))
7467 (cond
7468 ;; If first headline in file, promote to top-level.
7469 ((= prev-level 0)
7470 (loop repeat (/ (- cur-level 1) (org-level-increment))
7471 do (org-do-promote)))
7472 ;; If same level as prev, demote one.
7473 ((= prev-level cur-level)
7474 (org-do-demote))
7475 ;; If parent is top-level, promote to top level if not already.
7476 ((= prev-level 1)
7477 (loop repeat (/ (- cur-level 1) (org-level-increment))
7478 do (org-do-promote)))
7479 ;; If top-level, return to prev-level.
7480 ((= cur-level 1)
7481 (loop repeat (/ (- prev-level 1) (org-level-increment))
7482 do (org-do-demote)))
7483 ;; If less than prev-level, promote one.
7484 ((< cur-level prev-level)
7485 (org-do-promote))
7486 ;; If deeper than prev-level, promote until higher than
7487 ;; prev-level.
7488 ((> cur-level prev-level)
7489 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7490 do (org-do-promote))))
7491 t))))
7493 (defun org-map-tree (fun)
7494 "Call FUN for every heading underneath the current one."
7495 (org-back-to-heading)
7496 (let ((level (funcall outline-level)))
7497 (save-excursion
7498 (funcall fun)
7499 (while (and (progn
7500 (outline-next-heading)
7501 (> (funcall outline-level) level))
7502 (not (eobp)))
7503 (funcall fun)))))
7505 (defun org-map-region (fun beg end)
7506 "Call FUN for every heading between BEG and END."
7507 (let ((org-ignore-region t))
7508 (save-excursion
7509 (setq end (copy-marker end))
7510 (goto-char beg)
7511 (if (and (re-search-forward org-outline-regexp-bol nil t)
7512 (< (point) end))
7513 (funcall fun))
7514 (while (and (progn
7515 (outline-next-heading)
7516 (< (point) end))
7517 (not (eobp)))
7518 (funcall fun)))))
7520 (defvar org-property-end-re) ; silence byte-compiler
7521 (defun org-fixup-indentation (diff)
7522 "Change the indentation in the current entry by DIFF.
7523 However, if any line in the current entry has no indentation, or if it
7524 would end up with no indentation after the change, nothing at all is done."
7525 (save-excursion
7526 (let ((end (save-excursion (outline-next-heading)
7527 (point-marker)))
7528 (prohibit (if (> diff 0)
7529 "^\\S-"
7530 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7531 col)
7532 (unless (save-excursion (end-of-line 1)
7533 (re-search-forward prohibit end t))
7534 (while (and (< (point) end)
7535 (re-search-forward "^[ \t]+" end t))
7536 (goto-char (match-end 0))
7537 (setq col (current-column))
7538 (if (< diff 0) (replace-match ""))
7539 (org-indent-to-column (+ diff col))))
7540 (move-marker end nil))))
7542 (defun org-convert-to-odd-levels ()
7543 "Convert an org-mode file with all levels allowed to one with odd levels.
7544 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7545 level 5 etc."
7546 (interactive)
7547 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7548 (let ((outline-level 'org-outline-level)
7549 (org-odd-levels-only nil) n)
7550 (save-excursion
7551 (goto-char (point-min))
7552 (while (re-search-forward "^\\*\\*+ " nil t)
7553 (setq n (- (length (match-string 0)) 2))
7554 (while (>= (setq n (1- n)) 0)
7555 (org-demote))
7556 (end-of-line 1))))))
7558 (defun org-convert-to-oddeven-levels ()
7559 "Convert an org-mode file with only odd levels to one with odd/even levels.
7560 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7561 file contains a section with an even level, conversion would
7562 destroy the structure of the file. An error is signaled in this
7563 case."
7564 (interactive)
7565 (goto-char (point-min))
7566 ;; First check if there are no even levels
7567 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7568 (org-show-context t)
7569 (error "Not all levels are odd in this file. Conversion not possible"))
7570 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7571 (let ((outline-regexp org-outline-regexp)
7572 (outline-level 'org-outline-level)
7573 (org-odd-levels-only nil) n)
7574 (save-excursion
7575 (goto-char (point-min))
7576 (while (re-search-forward "^\\*\\*+ " nil t)
7577 (setq n (/ (1- (length (match-string 0))) 2))
7578 (while (>= (setq n (1- n)) 0)
7579 (org-promote))
7580 (end-of-line 1))))))
7582 (defun org-tr-level (n)
7583 "Make N odd if required."
7584 (if org-odd-levels-only (1+ (/ n 2)) n))
7586 ;;; Vertical tree motion, cutting and pasting of subtrees
7588 (defun org-move-subtree-up (&optional arg)
7589 "Move the current subtree up past ARG headlines of the same level."
7590 (interactive "p")
7591 (org-move-subtree-down (- (prefix-numeric-value arg))))
7593 (defun org-move-subtree-down (&optional arg)
7594 "Move the current subtree down past ARG headlines of the same level."
7595 (interactive "p")
7596 (setq arg (prefix-numeric-value arg))
7597 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7598 'org-get-last-sibling))
7599 (ins-point (make-marker))
7600 (cnt (abs arg))
7601 (col (current-column))
7602 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7603 ;; Select the tree
7604 (org-back-to-heading)
7605 (setq beg0 (point))
7606 (save-excursion
7607 (setq ne-beg (org-back-over-empty-lines))
7608 (setq beg (point)))
7609 (save-match-data
7610 (save-excursion (outline-end-of-heading)
7611 (setq folded (outline-invisible-p)))
7612 (outline-end-of-subtree))
7613 (outline-next-heading)
7614 (setq ne-end (org-back-over-empty-lines))
7615 (setq end (point))
7616 (goto-char beg0)
7617 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7618 ;; include less whitespace
7619 (save-excursion
7620 (goto-char beg)
7621 (forward-line (- ne-beg ne-end))
7622 (setq beg (point))))
7623 ;; Find insertion point, with error handling
7624 (while (> cnt 0)
7625 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7626 (progn (goto-char beg0)
7627 (error "Cannot move past superior level or buffer limit")))
7628 (setq cnt (1- cnt)))
7629 (if (> arg 0)
7630 ;; Moving forward - still need to move over subtree
7631 (progn (org-end-of-subtree t t)
7632 (save-excursion
7633 (org-back-over-empty-lines)
7634 (or (bolp) (newline)))))
7635 (setq ne-ins (org-back-over-empty-lines))
7636 (move-marker ins-point (point))
7637 (setq txt (buffer-substring beg end))
7638 (org-save-markers-in-region beg end)
7639 (delete-region beg end)
7640 (org-remove-empty-overlays-at beg)
7641 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7642 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7643 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7644 (let ((bbb (point)))
7645 (insert-before-markers txt)
7646 (org-reinstall-markers-in-region bbb)
7647 (move-marker ins-point bbb))
7648 (or (bolp) (insert "\n"))
7649 (setq ins-end (point))
7650 (goto-char ins-point)
7651 (org-skip-whitespace)
7652 (when (and (< arg 0)
7653 (org-first-sibling-p)
7654 (> ne-ins ne-beg))
7655 ;; Move whitespace back to beginning
7656 (save-excursion
7657 (goto-char ins-end)
7658 (let ((kill-whole-line t))
7659 (kill-line (- ne-ins ne-beg)) (point)))
7660 (insert (make-string (- ne-ins ne-beg) ?\n)))
7661 (move-marker ins-point nil)
7662 (if folded
7663 (hide-subtree)
7664 (org-show-entry)
7665 (show-children)
7666 (org-cycle-hide-drawers 'children))
7667 (org-clean-visibility-after-subtree-move)
7668 ;; move back to the initial column we were at
7669 (move-to-column col)))
7671 (defvar org-subtree-clip ""
7672 "Clipboard for cut and paste of subtrees.
7673 This is actually only a copy of the kill, because we use the normal kill
7674 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7676 (defvar org-subtree-clip-folded nil
7677 "Was the last copied subtree folded?
7678 This is used to fold the tree back after pasting.")
7680 (defun org-cut-subtree (&optional n)
7681 "Cut the current subtree into the clipboard.
7682 With prefix arg N, cut this many sequential subtrees.
7683 This is a short-hand for marking the subtree and then cutting it."
7684 (interactive "p")
7685 (org-copy-subtree n 'cut))
7687 (defun org-copy-subtree (&optional n cut force-store-markers)
7688 "Cut the current subtree into the clipboard.
7689 With prefix arg N, cut this many sequential subtrees.
7690 This is a short-hand for marking the subtree and then copying it.
7691 If CUT is non-nil, actually cut the subtree.
7692 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7693 of some markers in the region, even if CUT is non-nil. This is
7694 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7695 (interactive "p")
7696 (let (beg end folded (beg0 (point)))
7697 (if (org-called-interactively-p 'any)
7698 (org-back-to-heading nil) ; take what looks like a subtree
7699 (org-back-to-heading t)) ; take what is really there
7700 (setq beg (point))
7701 (skip-chars-forward " \t\r\n")
7702 (save-match-data
7703 (save-excursion (outline-end-of-heading)
7704 (setq folded (outline-invisible-p)))
7705 (condition-case nil
7706 (org-forward-heading-same-level (1- n) t)
7707 (error nil))
7708 (org-end-of-subtree t t))
7709 (setq end (point))
7710 (goto-char beg0)
7711 (when (> end beg)
7712 (setq org-subtree-clip-folded folded)
7713 (when (or cut force-store-markers)
7714 (org-save-markers-in-region beg end))
7715 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7716 (setq org-subtree-clip (current-kill 0))
7717 (message "%s: Subtree(s) with %d characters"
7718 (if cut "Cut" "Copied")
7719 (length org-subtree-clip)))))
7721 (defun org-paste-subtree (&optional level tree for-yank)
7722 "Paste the clipboard as a subtree, with modification of headline level.
7723 The entire subtree is promoted or demoted in order to match a new headline
7724 level.
7726 If the cursor is at the beginning of a headline, the same level as
7727 that headline is used to paste the tree
7729 If not, the new level is derived from the *visible* headings
7730 before and after the insertion point, and taken to be the inferior headline
7731 level of the two. So if the previous visible heading is level 3 and the
7732 next is level 4 (or vice versa), level 4 will be used for insertion.
7733 This makes sure that the subtree remains an independent subtree and does
7734 not swallow low level entries.
7736 You can also force a different level, either by using a numeric prefix
7737 argument, or by inserting the heading marker by hand. For example, if the
7738 cursor is after \"*****\", then the tree will be shifted to level 5.
7740 If optional TREE is given, use this text instead of the kill ring.
7742 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7743 move back over whitespace before inserting, and move point to the end of
7744 the inserted text when done."
7745 (interactive "P")
7746 (setq tree (or tree (and kill-ring (current-kill 0))))
7747 (unless (org-kill-is-subtree-p tree)
7748 (error "%s"
7749 (substitute-command-keys
7750 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7751 (org-with-limited-levels
7752 (let* ((visp (not (outline-invisible-p)))
7753 (txt tree)
7754 (^re_ "\\(\\*+\\)[ \t]*")
7755 (old-level (if (string-match org-outline-regexp-bol txt)
7756 (- (match-end 0) (match-beginning 0) 1)
7757 -1))
7758 (force-level (cond (level (prefix-numeric-value level))
7759 ((and (looking-at "[ \t]*$")
7760 (string-match
7761 "^\\*+$" (buffer-substring
7762 (point-at-bol) (point))))
7763 (- (match-end 1) (match-beginning 1)))
7764 ((and (bolp)
7765 (looking-at org-outline-regexp))
7766 (- (match-end 0) (point) 1))))
7767 (previous-level (save-excursion
7768 (condition-case nil
7769 (progn
7770 (outline-previous-visible-heading 1)
7771 (if (looking-at ^re_)
7772 (- (match-end 0) (match-beginning 0) 1)
7774 (error 1))))
7775 (next-level (save-excursion
7776 (condition-case nil
7777 (progn
7778 (or (looking-at org-outline-regexp)
7779 (outline-next-visible-heading 1))
7780 (if (looking-at ^re_)
7781 (- (match-end 0) (match-beginning 0) 1)
7783 (error 1))))
7784 (new-level (or force-level (max previous-level next-level)))
7785 (shift (if (or (= old-level -1)
7786 (= new-level -1)
7787 (= old-level new-level))
7789 (- new-level old-level)))
7790 (delta (if (> shift 0) -1 1))
7791 (func (if (> shift 0) 'org-demote 'org-promote))
7792 (org-odd-levels-only nil)
7793 beg end newend)
7794 ;; Remove the forced level indicator
7795 (if force-level
7796 (delete-region (point-at-bol) (point)))
7797 ;; Paste
7798 (beginning-of-line (if (bolp) 1 2))
7799 (setq beg (point))
7800 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7801 (insert-before-markers txt)
7802 (unless (string-match "\n\\'" txt) (insert "\n"))
7803 (setq newend (point))
7804 (org-reinstall-markers-in-region beg)
7805 (setq end (point))
7806 (goto-char beg)
7807 (skip-chars-forward " \t\n\r")
7808 (setq beg (point))
7809 (if (and (outline-invisible-p) visp)
7810 (save-excursion (outline-show-heading)))
7811 ;; Shift if necessary
7812 (unless (= shift 0)
7813 (save-restriction
7814 (narrow-to-region beg end)
7815 (while (not (= shift 0))
7816 (org-map-region func (point-min) (point-max))
7817 (setq shift (+ delta shift)))
7818 (goto-char (point-min))
7819 (setq newend (point-max))))
7820 (when (or (org-called-interactively-p 'interactive) for-yank)
7821 (message "Clipboard pasted as level %d subtree" new-level))
7822 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7823 kill-ring
7824 (eq org-subtree-clip (current-kill 0))
7825 org-subtree-clip-folded)
7826 ;; The tree was folded before it was killed/copied
7827 (hide-subtree))
7828 (and for-yank (goto-char newend)))))
7830 (defun org-kill-is-subtree-p (&optional txt)
7831 "Check if the current kill is an outline subtree, or a set of trees.
7832 Returns nil if kill does not start with a headline, or if the first
7833 headline level is not the largest headline level in the tree.
7834 So this will actually accept several entries of equal levels as well,
7835 which is OK for `org-paste-subtree'.
7836 If optional TXT is given, check this string instead of the current kill."
7837 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7838 (re (org-get-limited-outline-regexp))
7839 (^re (concat "^" re))
7840 (start-level (and kill
7841 (string-match
7842 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7843 kill)
7844 (- (match-end 2) (match-beginning 2) 1)))
7845 (start (1+ (or (match-beginning 2) -1))))
7846 (if (not start-level)
7847 (progn
7848 nil) ;; does not even start with a heading
7849 (catch 'exit
7850 (while (setq start (string-match ^re kill (1+ start)))
7851 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7852 (throw 'exit nil)))
7853 t))))
7855 (defvar org-markers-to-move nil
7856 "Markers that should be moved with a cut-and-paste operation.
7857 Those markers are stored together with their positions relative to
7858 the start of the region.")
7860 (defun org-save-markers-in-region (beg end)
7861 "Check markers in region.
7862 If these markers are between BEG and END, record their position relative
7863 to BEG, so that after moving the block of text, we can put the markers back
7864 into place.
7865 This function gets called just before an entry or tree gets cut from the
7866 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7867 called immediately, to move the markers with the entries."
7868 (setq org-markers-to-move nil)
7869 (when (featurep 'org-clock)
7870 (org-clock-save-markers-for-cut-and-paste beg end))
7871 (when (featurep 'org-agenda)
7872 (org-agenda-save-markers-for-cut-and-paste beg end)))
7874 (defun org-check-and-save-marker (marker beg end)
7875 "Check if MARKER is between BEG and END.
7876 If yes, remember the marker and the distance to BEG."
7877 (when (and (marker-buffer marker)
7878 (equal (marker-buffer marker) (current-buffer)))
7879 (if (and (>= marker beg) (< marker end))
7880 (push (cons marker (- marker beg)) org-markers-to-move))))
7882 (defun org-reinstall-markers-in-region (beg)
7883 "Move all remembered markers to their position relative to BEG."
7884 (mapc (lambda (x)
7885 (move-marker (car x) (+ beg (cdr x))))
7886 org-markers-to-move)
7887 (setq org-markers-to-move nil))
7889 (defun org-narrow-to-subtree ()
7890 "Narrow buffer to the current subtree."
7891 (interactive)
7892 (save-excursion
7893 (save-match-data
7894 (org-with-limited-levels
7895 (narrow-to-region
7896 (progn (org-back-to-heading t) (point))
7897 (progn (org-end-of-subtree t t)
7898 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7899 (point)))))))
7901 (defun org-narrow-to-block ()
7902 "Narrow buffer to the current block."
7903 (interactive)
7904 (let* ((case-fold-search t)
7905 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7906 "^[ \t]*#\\+end_.*")))
7907 (if blockp
7908 (narrow-to-region (car blockp) (cdr blockp))
7909 (error "Not in a block"))))
7911 (eval-when-compile
7912 (defvar org-property-drawer-re))
7914 (defvar org-property-start-re) ;; defined below
7915 (defun org-clone-subtree-with-time-shift (n &optional shift)
7916 "Clone the task (subtree) at point N times.
7917 The clones will be inserted as siblings.
7919 In interactive use, the user will be prompted for the number of
7920 clones to be produced, and for a time SHIFT, which may be a
7921 repeater as used in time stamps, for example `+3d'.
7923 When a valid repeater is given and the entry contains any time
7924 stamps, the clones will become a sequence in time, with time
7925 stamps in the subtree shifted for each clone produced. If SHIFT
7926 is nil or the empty string, time stamps will be left alone. The
7927 ID property of the original subtree is removed.
7929 If the original subtree did contain time stamps with a repeater,
7930 the following will happen:
7931 - the repeater will be removed in each clone
7932 - an additional clone will be produced, with the current, unshifted
7933 date(s) in the entry.
7934 - the original entry will be placed *after* all the clones, with
7935 repeater intact.
7936 - the start days in the repeater in the original entry will be shifted
7937 to past the last clone.
7938 In this way you can spell out a number of instances of a repeating task,
7939 and still retain the repeater to cover future instances of the task."
7940 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7941 (let (beg end template task idprop
7942 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7943 (drawer-re org-drawer-regexp))
7944 (if (not (and (integerp n) (> n 0)))
7945 (error "Invalid number of replications %s" n))
7946 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7947 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7948 shift)))
7949 (error "Invalid shift specification %s" shift))
7950 (when doshift
7951 (setq shift-n (string-to-number (match-string 1 shift))
7952 shift-what (cdr (assoc (match-string 2 shift)
7953 '(("d" . day) ("w" . week)
7954 ("m" . month) ("y" . year))))))
7955 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7956 (setq nmin 1 nmax n)
7957 (org-back-to-heading t)
7958 (setq beg (point))
7959 (setq idprop (org-entry-get nil "ID"))
7960 (org-end-of-subtree t t)
7961 (or (bolp) (insert "\n"))
7962 (setq end (point))
7963 (setq template (buffer-substring beg end))
7964 (when (and doshift
7965 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7966 (delete-region beg end)
7967 (setq end beg)
7968 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7969 (goto-char end)
7970 (loop for n from nmin to nmax do
7971 ;; prepare clone
7972 (with-temp-buffer
7973 (insert template)
7974 (org-mode)
7975 (goto-char (point-min))
7976 (org-show-subtree)
7977 (and idprop (if org-clone-delete-id
7978 (org-entry-delete nil "ID")
7979 (org-id-get-create t)))
7980 (unless (= n 0)
7981 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7982 (kill-whole-line))
7983 (goto-char (point-min))
7984 (while (re-search-forward drawer-re nil t)
7985 (mapc (lambda (d)
7986 (org-remove-empty-drawer-at d (point))) org-drawers)))
7987 (goto-char (point-min))
7988 (when doshift
7989 (while (re-search-forward org-ts-regexp-both nil t)
7990 (org-timestamp-change (* n shift-n) shift-what))
7991 (unless (= n n-no-remove)
7992 (goto-char (point-min))
7993 (while (re-search-forward org-ts-regexp nil t)
7994 (save-excursion
7995 (goto-char (match-beginning 0))
7996 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7997 (delete-region (match-beginning 1) (match-end 1)))))))
7998 (setq task (buffer-string)))
7999 (insert task))
8000 (goto-char beg)))
8002 ;;; Outline Sorting
8004 (defun org-sort (with-case)
8005 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8006 Optional argument WITH-CASE means sort case-sensitively."
8007 (interactive "P")
8008 (cond
8009 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8010 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8012 (org-call-with-arg 'org-sort-entries with-case))))
8014 (defun org-sort-remove-invisible (s)
8015 (remove-text-properties 0 (length s) org-rm-props s)
8016 (while (string-match org-bracket-link-regexp s)
8017 (setq s (replace-match (if (match-end 2)
8018 (match-string 3 s)
8019 (match-string 1 s)) t t s)))
8022 (defvar org-priority-regexp) ; defined later in the file
8024 (defvar org-after-sorting-entries-or-items-hook nil
8025 "Hook that is run after a bunch of entries or items have been sorted.
8026 When children are sorted, the cursor is in the parent line when this
8027 hook gets called. When a region or a plain list is sorted, the cursor
8028 will be in the first entry of the sorted region/list.")
8030 (defun org-sort-entries
8031 (&optional with-case sorting-type getkey-func compare-func property)
8032 "Sort entries on a certain level of an outline tree.
8033 If there is an active region, the entries in the region are sorted.
8034 Else, if the cursor is before the first entry, sort the top-level items.
8035 Else, the children of the entry at point are sorted.
8037 Sorting can be alphabetically, numerically, by date/time as given by
8038 a time stamp, by a property or by priority.
8040 The command prompts for the sorting type unless it has been given to the
8041 function through the SORTING-TYPE argument, which needs to be a character,
8042 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8043 precise meaning of each character:
8045 n Numerically, by converting the beginning of the entry/item to a number.
8046 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8047 o By order of TODO keywords.
8048 t By date/time, either the first active time stamp in the entry, or, if
8049 none exist, by the first inactive one.
8050 s By the scheduled date/time.
8051 d By deadline date/time.
8052 c By creation time, which is assumed to be the first inactive time stamp
8053 at the beginning of a line.
8054 p By priority according to the cookie.
8055 r By the value of a property.
8057 Capital letters will reverse the sort order.
8059 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8060 called with point at the beginning of the record. It must return either
8061 a string or a number that should serve as the sorting key for that record.
8063 Comparing entries ignores case by default. However, with an optional argument
8064 WITH-CASE, the sorting considers case as well."
8065 (interactive "P")
8066 (let ((case-func (if with-case 'identity 'downcase))
8067 (cmstr
8068 ;; The clock marker is lost when using `sort-subr', let's
8069 ;; store the clocking string.
8070 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8071 (save-excursion
8072 (goto-char org-clock-marker)
8073 (looking-back "^.*") (match-string-no-properties 0))))
8074 start beg end stars re re2
8075 txt what tmp)
8076 ;; Find beginning and end of region to sort
8077 (cond
8078 ((org-region-active-p)
8079 ;; we will sort the region
8080 (setq end (region-end)
8081 what "region")
8082 (goto-char (region-beginning))
8083 (if (not (org-at-heading-p)) (outline-next-heading))
8084 (setq start (point)))
8085 ((or (org-at-heading-p)
8086 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8087 ;; we will sort the children of the current headline
8088 (org-back-to-heading)
8089 (setq start (point)
8090 end (progn (org-end-of-subtree t t)
8091 (or (bolp) (insert "\n"))
8092 (org-back-over-empty-lines)
8093 (point))
8094 what "children")
8095 (goto-char start)
8096 (show-subtree)
8097 (outline-next-heading))
8099 ;; we will sort the top-level entries in this file
8100 (goto-char (point-min))
8101 (or (org-at-heading-p) (outline-next-heading))
8102 (setq start (point))
8103 (goto-char (point-max))
8104 (beginning-of-line 1)
8105 (when (looking-at ".*?\\S-")
8106 ;; File ends in a non-white line
8107 (end-of-line 1)
8108 (insert "\n"))
8109 (setq end (point-max))
8110 (setq what "top-level")
8111 (goto-char start)
8112 (show-all)))
8114 (setq beg (point))
8115 (if (>= beg end) (error "Nothing to sort"))
8117 (looking-at "\\(\\*+\\)")
8118 (setq stars (match-string 1)
8119 re (concat "^" (regexp-quote stars) " +")
8120 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8121 txt (buffer-substring beg end))
8122 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8123 (if (and (not (equal stars "*")) (string-match re2 txt))
8124 (error "Region to sort contains a level above the first entry"))
8126 (unless sorting-type
8127 (message
8128 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8129 [t]ime [s]cheduled [d]eadline [c]reated
8130 A/N/P/R/O/F/T/S/D/C means reversed:"
8131 what)
8132 (setq sorting-type (read-char-exclusive))
8134 (and (= (downcase sorting-type) ?f)
8135 (setq getkey-func
8136 (org-icompleting-read "Sort using function: "
8137 obarray 'fboundp t nil nil))
8138 (setq getkey-func (intern getkey-func)))
8140 (and (= (downcase sorting-type) ?r)
8141 (setq property
8142 (org-icompleting-read "Property: "
8143 (mapcar 'list (org-buffer-property-keys t))
8144 nil t))))
8146 (message "Sorting entries...")
8148 (save-restriction
8149 (narrow-to-region start end)
8150 (let ((dcst (downcase sorting-type))
8151 (case-fold-search nil)
8152 (now (current-time)))
8153 (sort-subr
8154 (/= dcst sorting-type)
8155 ;; This function moves to the beginning character of the "record" to
8156 ;; be sorted.
8157 (lambda nil
8158 (if (re-search-forward re nil t)
8159 (goto-char (match-beginning 0))
8160 (goto-char (point-max))))
8161 ;; This function moves to the last character of the "record" being
8162 ;; sorted.
8163 (lambda nil
8164 (save-match-data
8165 (condition-case nil
8166 (outline-forward-same-level 1)
8167 (error
8168 (goto-char (point-max))))))
8169 ;; This function returns the value that gets sorted against.
8170 (lambda nil
8171 (cond
8172 ((= dcst ?n)
8173 (if (looking-at org-complex-heading-regexp)
8174 (string-to-number (match-string 4))
8175 nil))
8176 ((= dcst ?a)
8177 (if (looking-at org-complex-heading-regexp)
8178 (funcall case-func (match-string 4))
8179 nil))
8180 ((= dcst ?t)
8181 (let ((end (save-excursion (outline-next-heading) (point))))
8182 (if (or (re-search-forward org-ts-regexp end t)
8183 (re-search-forward org-ts-regexp-both end t))
8184 (org-time-string-to-seconds (match-string 0))
8185 (org-float-time now))))
8186 ((= dcst ?c)
8187 (let ((end (save-excursion (outline-next-heading) (point))))
8188 (if (re-search-forward
8189 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8190 end t)
8191 (org-time-string-to-seconds (match-string 0))
8192 (org-float-time now))))
8193 ((= dcst ?s)
8194 (let ((end (save-excursion (outline-next-heading) (point))))
8195 (if (re-search-forward org-scheduled-time-regexp end t)
8196 (org-time-string-to-seconds (match-string 1))
8197 (org-float-time now))))
8198 ((= dcst ?d)
8199 (let ((end (save-excursion (outline-next-heading) (point))))
8200 (if (re-search-forward org-deadline-time-regexp end t)
8201 (org-time-string-to-seconds (match-string 1))
8202 (org-float-time now))))
8203 ((= dcst ?p)
8204 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8205 (string-to-char (match-string 2))
8206 org-default-priority))
8207 ((= dcst ?r)
8208 (or (org-entry-get nil property) ""))
8209 ((= dcst ?o)
8210 (if (looking-at org-complex-heading-regexp)
8211 (- 9999 (length (member (match-string 2)
8212 org-todo-keywords-1)))))
8213 ((= dcst ?f)
8214 (if getkey-func
8215 (progn
8216 (setq tmp (funcall getkey-func))
8217 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8218 tmp)
8219 (error "Invalid key function `%s'" getkey-func)))
8220 (t (error "Invalid sorting type `%c'" sorting-type))))
8222 (cond
8223 ((= dcst ?a) 'string<)
8224 ((= dcst ?f) compare-func)
8225 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8226 (run-hooks 'org-after-sorting-entries-or-items-hook)
8227 ;; Reset the clock marker if needed
8228 (when cmstr
8229 (save-excursion
8230 (goto-char start)
8231 (search-forward cmstr nil t)
8232 (move-marker org-clock-marker (point))))
8233 (message "Sorting entries...done")))
8235 (defun org-do-sort (table what &optional with-case sorting-type)
8236 "Sort TABLE of WHAT according to SORTING-TYPE.
8237 The user will be prompted for the SORTING-TYPE if the call to this
8238 function does not specify it. WHAT is only for the prompt, to indicate
8239 what is being sorted. The sorting key will be extracted from
8240 the car of the elements of the table.
8241 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8242 (unless sorting-type
8243 (message
8244 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8245 what)
8246 (setq sorting-type (read-char-exclusive)))
8247 (let ((dcst (downcase sorting-type))
8248 extractfun comparefun)
8249 ;; Define the appropriate functions
8250 (cond
8251 ((= dcst ?n)
8252 (setq extractfun 'string-to-number
8253 comparefun (if (= dcst sorting-type) '< '>)))
8254 ((= dcst ?a)
8255 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8256 (lambda(x) (downcase (org-sort-remove-invisible x))))
8257 comparefun (if (= dcst sorting-type)
8258 'string<
8259 (lambda (a b) (and (not (string< a b))
8260 (not (string= a b)))))))
8261 ((= dcst ?t)
8262 (setq extractfun
8263 (lambda (x)
8264 (if (or (string-match org-ts-regexp x)
8265 (string-match org-ts-regexp-both x))
8266 (org-float-time
8267 (org-time-string-to-time (match-string 0 x)))
8269 comparefun (if (= dcst sorting-type) '< '>)))
8270 (t (error "Invalid sorting type `%c'" sorting-type)))
8272 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8273 table)
8274 (lambda (a b) (funcall comparefun (car a) (car b))))))
8277 ;;; The orgstruct minor mode
8279 ;; Define a minor mode which can be used in other modes in order to
8280 ;; integrate the org-mode structure editing commands.
8282 ;; This is really a hack, because the org-mode structure commands use
8283 ;; keys which normally belong to the major mode. Here is how it
8284 ;; works: The minor mode defines all the keys necessary to operate the
8285 ;; structure commands, but wraps the commands into a function which
8286 ;; tests if the cursor is currently at a headline or a plain list
8287 ;; item. If that is the case, the structure command is used,
8288 ;; temporarily setting many Org-mode variables like regular
8289 ;; expressions for filling etc. However, when any of those keys is
8290 ;; used at a different location, function uses `key-binding' to look
8291 ;; up if the key has an associated command in another currently active
8292 ;; keymap (minor modes, major mode, global), and executes that
8293 ;; command. There might be problems if any of the keys is otherwise
8294 ;; used as a prefix key.
8296 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8297 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8298 ;; addresses this by checking explicitly for both bindings.
8300 (defvar orgstruct-mode-map (make-sparse-keymap)
8301 "Keymap for the minor `orgstruct-mode'.")
8303 (defvar org-local-vars nil
8304 "List of local variables, for use by `orgstruct-mode'.")
8306 ;;;###autoload
8307 (define-minor-mode orgstruct-mode
8308 "Toggle the minor mode `orgstruct-mode'.
8309 This mode is for using Org-mode structure commands in other
8310 modes. The following keys behave as if Org-mode were active, if
8311 the cursor is on a headline, or on a plain list item (both as
8312 defined by Org-mode).
8314 M-up Move entry/item up
8315 M-down Move entry/item down
8316 M-left Promote
8317 M-right Demote
8318 M-S-up Move entry/item up
8319 M-S-down Move entry/item down
8320 M-S-left Promote subtree
8321 M-S-right Demote subtree
8322 M-q Fill paragraph and items like in Org-mode
8323 C-c ^ Sort entries
8324 C-c - Cycle list bullet
8325 TAB Cycle item visibility
8326 M-RET Insert new heading/item
8327 S-M-RET Insert new TODO heading / Checkbox item
8328 C-c C-c Set tags / toggle checkbox"
8329 nil " OrgStruct" nil
8330 (org-load-modules-maybe)
8331 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8333 ;;;###autoload
8334 (defun turn-on-orgstruct ()
8335 "Unconditionally turn on `orgstruct-mode'."
8336 (orgstruct-mode 1))
8338 (defvar org-fb-vars nil)
8339 (make-variable-buffer-local 'org-fb-vars)
8340 (defun orgstruct++-mode (&optional arg)
8341 "Toggle `orgstruct-mode', the enhanced version of it.
8342 In addition to setting orgstruct-mode, this also exports all
8343 indentation and autofilling variables from org-mode into the
8344 buffer. It will also recognize item context in multiline items."
8345 (interactive "P")
8346 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8347 (if (< arg 1)
8348 (progn (orgstruct-mode -1)
8349 (mapc (lambda(v)
8350 (org-set-local (car v)
8351 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8352 org-fb-vars))
8353 (orgstruct-mode 1)
8354 (setq org-fb-vars nil)
8355 (let (var val)
8356 (mapc
8357 (lambda (x)
8358 (when (string-match
8359 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8360 (symbol-name (car x)))
8361 (setq var (car x) val (nth 1 x))
8362 (push (list var `(quote ,(eval var))) org-fb-vars)
8363 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8364 org-local-vars)
8365 (org-set-local 'orgstruct-is-++ t))))
8367 (defvar orgstruct-is-++ nil
8368 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8369 (make-variable-buffer-local 'orgstruct-is-++)
8371 ;;;###autoload
8372 (defun turn-on-orgstruct++ ()
8373 "Unconditionally turn on `orgstruct++-mode'."
8374 (orgstruct++-mode 1))
8376 (defun orgstruct-error ()
8377 "Error when there is no default binding for a structure key."
8378 (interactive)
8379 (error "This key has no function outside structure elements"))
8381 (defun orgstruct-setup ()
8382 "Setup orgstruct keymaps."
8383 (let ((nfunc 0)
8384 (bindings
8385 (list
8386 '([(meta up)] org-metaup)
8387 '([(meta down)] org-metadown)
8388 '([(meta left)] org-metaleft)
8389 '([(meta right)] org-metaright)
8390 '([(meta shift up)] org-shiftmetaup)
8391 '([(meta shift down)] org-shiftmetadown)
8392 '([(meta shift left)] org-shiftmetaleft)
8393 '([(meta shift right)] org-shiftmetaright)
8394 '([?\e (up)] org-metaup)
8395 '([?\e (down)] org-metadown)
8396 '([?\e (left)] org-metaleft)
8397 '([?\e (right)] org-metaright)
8398 '([?\e (shift up)] org-shiftmetaup)
8399 '([?\e (shift down)] org-shiftmetadown)
8400 '([?\e (shift left)] org-shiftmetaleft)
8401 '([?\e (shift right)] org-shiftmetaright)
8402 '([(shift up)] org-shiftup)
8403 '([(shift down)] org-shiftdown)
8404 '([(shift left)] org-shiftleft)
8405 '([(shift right)] org-shiftright)
8406 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8407 '("\M-q" fill-paragraph)
8408 '("\C-c^" org-sort)
8409 '("\C-c-" org-cycle-list-bullet)))
8410 elt key fun cmd)
8411 (while (setq elt (pop bindings))
8412 (setq nfunc (1+ nfunc))
8413 (setq key (org-key (car elt))
8414 fun (nth 1 elt)
8415 cmd (orgstruct-make-binding fun nfunc key))
8416 (org-defkey orgstruct-mode-map key cmd))
8418 ;; Prevent an error for users who forgot to make autoloads
8419 (require 'org-element)
8421 ;; Special treatment needed for TAB and RET
8422 (org-defkey orgstruct-mode-map [(tab)]
8423 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8424 (org-defkey orgstruct-mode-map "\C-i"
8425 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8427 (org-defkey orgstruct-mode-map "\M-\C-m"
8428 (orgstruct-make-binding 'org-insert-heading 105
8429 "\M-\C-m" [(meta return)]))
8430 (org-defkey orgstruct-mode-map [(meta return)]
8431 (orgstruct-make-binding 'org-insert-heading 106
8432 [(meta return)] "\M-\C-m"))
8434 (org-defkey orgstruct-mode-map [(shift meta return)]
8435 (orgstruct-make-binding 'org-insert-todo-heading 107
8436 [(meta return)] "\M-\C-m"))
8438 (org-defkey orgstruct-mode-map "\e\C-m"
8439 (orgstruct-make-binding 'org-insert-heading 108
8440 "\e\C-m" [?\e (return)]))
8441 (org-defkey orgstruct-mode-map [?\e (return)]
8442 (orgstruct-make-binding 'org-insert-heading 109
8443 [?\e (return)] "\e\C-m"))
8444 (org-defkey orgstruct-mode-map [?\e (shift return)]
8445 (orgstruct-make-binding 'org-insert-todo-heading 110
8446 [?\e (return)] "\e\C-m"))
8448 (unless org-local-vars
8449 (setq org-local-vars (org-get-local-variables)))
8453 (defun orgstruct-make-binding (fun n &rest keys)
8454 "Create a function for binding in the structure minor mode.
8455 FUN is the command to call inside a table. N is used to create a unique
8456 command name. KEYS are keys that should be checked in for a command
8457 to execute outside of tables."
8458 (eval
8459 (list 'defun
8460 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8461 '(arg)
8462 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8463 "Outside of structure, run the binding of `"
8464 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8465 "'.")
8466 '(interactive "p")
8467 (list 'if
8468 `(org-context-p 'headline 'item
8469 (and orgstruct-is-++
8470 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8471 'item-body))
8472 (list 'org-run-like-in-org-mode (list 'quote fun))
8473 (list 'let '(orgstruct-mode)
8474 (list 'call-interactively
8475 (append '(or)
8476 (mapcar (lambda (k)
8477 (list 'key-binding k))
8478 keys)
8479 '('orgstruct-error))))))))
8481 (defun org-contextualize-keys (alist contexts)
8482 "Return valid elements in ALIST depending on CONTEXTS.
8484 `org-agenda-custom-commands' or `org-capture-templates' are the
8485 values used for ALIST, and `org-agenda-custom-commands-contexts'
8486 or `org-capture-templates-contexts' are the associated contexts
8487 definitions."
8488 (let ((contexts
8489 ;; normalize contexts
8490 (mapcar
8491 (lambda(c) (cond ((listp (cadr c))
8492 (list (car c) (car c) (cadr c)))
8493 ((string= "" (cadr c))
8494 (list (car c) (car c) (caddr c)))
8495 (t c))) contexts))
8496 (a alist) c r s)
8497 ;; loop over all commands or templates
8498 (while (setq c (pop a))
8499 (let (vrules repl)
8500 (cond
8501 ((not (assoc (car c) contexts))
8502 (push c r))
8503 ((and (assoc (car c) contexts)
8504 (setq vrules (org-contextualize-validate-key
8505 (car c) contexts)))
8506 (mapc (lambda (vr)
8507 (when (not (equal (car vr) (cadr vr)))
8508 (setq repl vr))) vrules)
8509 (if (not repl) (push c r)
8510 (push (cadr repl) s)
8511 (push
8512 (cons (car c)
8513 (cdr (or (assoc (cadr repl) alist)
8514 (error "Undefined key `%s' as contextual replacement for `%s'"
8515 (cadr repl) (car c)))))
8516 r))))))
8517 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8518 (delq
8520 (delete-dups
8521 (mapcar (lambda (x)
8522 (let ((tpl (car x)))
8523 (when (not (delq
8525 (mapcar (lambda(y)
8526 (equal y tpl)) s))) x)))
8527 (reverse r))))))
8529 (defun org-contextualize-validate-key (key contexts)
8530 "Check CONTEXTS for agenda or capture KEY."
8531 (let (r rr res)
8532 (while (setq r (pop contexts))
8533 (mapc
8534 (lambda (rr)
8535 (when
8536 (and (equal key (car r))
8537 (if (functionp rr) (funcall rr)
8538 (or (and (eq (car rr) 'in-file)
8539 (buffer-file-name)
8540 (string-match (cdr rr) (buffer-file-name)))
8541 (and (eq (car rr) 'in-mode)
8542 (string-match (cdr rr) (symbol-name major-mode)))
8543 (when (and (eq (car rr) 'not-in-file)
8544 (buffer-file-name))
8545 (not (string-match (cdr rr) (buffer-file-name))))
8546 (when (eq (car rr) 'not-in-mode)
8547 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8548 (push r res)))
8549 (car (last r))))
8550 (delete-dups (delq nil res))))
8552 (defun org-context-p (&rest contexts)
8553 "Check if local context is any of CONTEXTS.
8554 Possible values in the list of contexts are `table', `headline', and `item'."
8555 (let ((pos (point)))
8556 (goto-char (point-at-bol))
8557 (prog1 (or (and (memq 'table contexts)
8558 (looking-at "[ \t]*|"))
8559 (and (memq 'headline contexts)
8560 (looking-at org-outline-regexp))
8561 (and (memq 'item contexts)
8562 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8563 (and (memq 'item-body contexts)
8564 (org-in-item-p)))
8565 (goto-char pos))))
8567 (defun org-get-local-variables ()
8568 "Return a list of all local variables in an Org mode buffer."
8569 (let (varlist)
8570 (with-current-buffer (get-buffer-create "*Org tmp*")
8571 (erase-buffer)
8572 (org-mode)
8573 (setq varlist (buffer-local-variables)))
8574 (kill-buffer "*Org tmp*")
8575 (delq nil
8576 (mapcar
8577 (lambda (x)
8578 (setq x
8579 (if (symbolp x)
8580 (list x)
8581 (list (car x) (list 'quote (cdr x)))))
8582 (if (string-match
8583 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8584 (symbol-name (car x)))
8585 x nil))
8586 varlist))))
8588 (defun org-clone-local-variables (from-buffer &optional regexp)
8589 "Clone local variables from FROM-BUFFER.
8590 Optional argument REGEXP selects variables to clone."
8591 (mapc
8592 (lambda (pair)
8593 (and (symbolp (car pair))
8594 (or (null regexp)
8595 (string-match regexp (symbol-name (car pair))))
8596 (set (make-local-variable (car pair))
8597 (cdr pair))))
8598 (buffer-local-variables from-buffer)))
8600 ;;;###autoload
8601 (defun org-run-like-in-org-mode (cmd)
8602 "Run a command, pretending that the current buffer is in Org-mode.
8603 This will temporarily bind local variables that are typically bound in
8604 Org-mode to the values they have in Org-mode, and then interactively
8605 call CMD."
8606 (org-load-modules-maybe)
8607 (unless org-local-vars
8608 (setq org-local-vars (org-get-local-variables)))
8609 (eval (list 'let org-local-vars
8610 (list 'call-interactively (list 'quote cmd)))))
8612 ;;;; Archiving
8614 (defun org-get-category (&optional pos force-refresh)
8615 "Get the category applying to position POS."
8616 (save-match-data
8617 (if force-refresh (org-refresh-category-properties))
8618 (let ((pos (or pos (point))))
8619 (or (get-text-property pos 'org-category)
8620 (progn (org-refresh-category-properties)
8621 (get-text-property pos 'org-category))))))
8623 (defun org-refresh-category-properties ()
8624 "Refresh category text properties in the buffer."
8625 (let ((case-fold-search t)
8626 (inhibit-read-only t)
8627 (def-cat (cond
8628 ((null org-category)
8629 (if buffer-file-name
8630 (file-name-sans-extension
8631 (file-name-nondirectory buffer-file-name))
8632 "???"))
8633 ((symbolp org-category) (symbol-name org-category))
8634 (t org-category)))
8635 beg end cat pos optionp)
8636 (org-unmodified
8637 (save-excursion
8638 (save-restriction
8639 (widen)
8640 (goto-char (point-min))
8641 (put-text-property (point) (point-max) 'org-category def-cat)
8642 (while (re-search-forward
8643 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8644 (setq pos (match-end 0)
8645 optionp (equal (char-after (match-beginning 0)) ?#)
8646 cat (org-trim (match-string 2)))
8647 (if optionp
8648 (setq beg (point-at-bol) end (point-max))
8649 (org-back-to-heading t)
8650 (setq beg (point) end (org-end-of-subtree t t)))
8651 (put-text-property beg end 'org-category cat)
8652 (put-text-property beg end 'org-category-position beg)
8653 (goto-char pos)))))))
8655 (defun org-refresh-properties (dprop tprop)
8656 "Refresh buffer text properties.
8657 DPROP is the drawer property and TPROP is the corresponding text
8658 property to set."
8659 (let ((case-fold-search t)
8660 (inhibit-read-only t) p)
8661 (org-unmodified
8662 (save-excursion
8663 (save-restriction
8664 (widen)
8665 (goto-char (point-min))
8666 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8667 (setq p (org-match-string-no-properties 1))
8668 (save-excursion
8669 (org-back-to-heading t)
8670 (put-text-property
8671 (point-at-bol) (point-at-eol) tprop p))))))))
8674 ;;;; Link Stuff
8676 ;;; Link abbreviations
8678 (defun org-link-expand-abbrev (link)
8679 "Apply replacements as defined in `org-link-abbrev-alist'."
8680 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8681 (let* ((key (match-string 1 link))
8682 (as (or (assoc key org-link-abbrev-alist-local)
8683 (assoc key org-link-abbrev-alist)))
8684 (tag (and (match-end 2) (match-string 3 link)))
8685 rpl)
8686 (if (not as)
8687 link
8688 (setq rpl (cdr as))
8689 (cond
8690 ((symbolp rpl) (funcall rpl tag))
8691 ((string-match "%(\\([^)]+\\))" rpl)
8692 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8693 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8694 ((string-match "%h" rpl)
8695 (replace-match (url-hexify-string (or tag "")) t t rpl))
8696 (t (concat rpl tag)))))
8697 link))
8699 ;;; Storing and inserting links
8701 (defvar org-insert-link-history nil
8702 "Minibuffer history for links inserted with `org-insert-link'.")
8704 (defvar org-stored-links nil
8705 "Contains the links stored with `org-store-link'.")
8707 (defvar org-store-link-plist nil
8708 "Plist with info about the most recently link created with `org-store-link'.")
8710 (defvar org-link-protocols nil
8711 "Link protocols added to Org-mode using `org-add-link-type'.")
8713 (defvar org-store-link-functions nil
8714 "List of functions that are called to create and store a link.
8715 Each function will be called in turn until one returns a non-nil
8716 value. Each function should check if it is responsible for creating
8717 this link (for example by looking at the major mode).
8718 If not, it must exit and return nil.
8719 If yes, it should return a non-nil value after a calling
8720 `org-store-link-props' with a list of properties and values.
8721 Special properties are:
8723 :type The link prefix, like \"http\". This must be given.
8724 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8725 This is obligatory as well.
8726 :description Optional default description for the second pair
8727 of brackets in an Org-mode link. The user can still change
8728 this when inserting this link into an Org-mode buffer.
8730 In addition to these, any additional properties can be specified
8731 and then used in capture templates.")
8733 (defun org-add-link-type (type &optional follow export)
8734 "Add TYPE to the list of `org-link-types'.
8735 Re-compute all regular expressions depending on `org-link-types'
8737 FOLLOW and EXPORT are two functions.
8739 FOLLOW should take the link path as the single argument and do whatever
8740 is necessary to follow the link, for example find a file or display
8741 a mail message.
8743 EXPORT should format the link path for export to one of the export formats.
8744 It should be a function accepting three arguments:
8746 path the path of the link, the text after the prefix (like \"http:\")
8747 desc the description of the link, if any, or a description added by
8748 org-export-normalize-links if there is none
8749 format the export format, a symbol like `html' or `latex' or `ascii'..
8751 The function may use the FORMAT information to return different values
8752 depending on the format. The return value will be put literally into
8753 the exported file. If the return value is nil, this means Org should
8754 do what it normally does with links which do not have EXPORT defined.
8756 Org-mode has a built-in default for exporting links. If you are happy with
8757 this default, there is no need to define an export function for the link
8758 type. For a simple example of an export function, see `org-bbdb.el'."
8759 (add-to-list 'org-link-types type t)
8760 (org-make-link-regexps)
8761 (if (assoc type org-link-protocols)
8762 (setcdr (assoc type org-link-protocols) (list follow export))
8763 (push (list type follow export) org-link-protocols)))
8765 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8766 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8768 ;;;###autoload
8769 (defun org-store-link (arg)
8770 "\\<org-mode-map>Store an org-link to the current location.
8771 This link is added to `org-stored-links' and can later be inserted
8772 into an org-buffer with \\[org-insert-link].
8774 For some link types, a prefix arg is interpreted:
8775 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8776 For file links, arg negates `org-context-in-file-links'."
8777 (interactive "P")
8778 (org-load-modules-maybe)
8779 (setq org-store-link-plist nil) ; reset
8780 (org-with-limited-levels
8781 (let (link cpltxt desc description search txt custom-id agenda-link)
8782 (cond
8784 ((run-hook-with-args-until-success 'org-store-link-functions)
8785 (setq link (plist-get org-store-link-plist :link)
8786 desc (or (plist-get org-store-link-plist :description) link)))
8788 ((org-src-edit-buffer-p)
8789 (let (label gc)
8790 (while (or (not label)
8791 (save-excursion
8792 (save-restriction
8793 (widen)
8794 (goto-char (point-min))
8795 (re-search-forward
8796 (regexp-quote (format org-coderef-label-format label))
8797 nil t))))
8798 (when label (message "Label exists already") (sit-for 2))
8799 (setq label (read-string "Code line label: " label)))
8800 (end-of-line 1)
8801 (setq link (format org-coderef-label-format label))
8802 (setq gc (- 79 (length link)))
8803 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8804 (insert link)
8805 (setq link (concat "(" label ")") desc nil)))
8807 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8808 ;; We are in the agenda, link to referenced location
8809 (let ((m (or (get-text-property (point) 'org-hd-marker)
8810 (get-text-property (point) 'org-marker))))
8811 (when m
8812 (org-with-point-at m
8813 (setq agenda-link
8814 (if (org-called-interactively-p 'any)
8815 (call-interactively 'org-store-link)
8816 (org-store-link nil)))))))
8818 ((eq major-mode 'calendar-mode)
8819 (let ((cd (calendar-cursor-to-date)))
8820 (setq link
8821 (format-time-string
8822 (car org-time-stamp-formats)
8823 (apply 'encode-time
8824 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8825 nil nil nil))))
8826 (org-store-link-props :type "calendar" :date cd)))
8828 ((eq major-mode 'help-mode)
8829 (setq link (concat "help:" (save-excursion
8830 (goto-char (point-min))
8831 (looking-at "^[^ ]+")
8832 (match-string 0))))
8833 (org-store-link-props :type "help"))
8835 ((eq major-mode 'w3-mode)
8836 (setq cpltxt (if (and (buffer-name)
8837 (not (string-match "Untitled" (buffer-name))))
8838 (buffer-name)
8839 (url-view-url t))
8840 link (url-view-url t))
8841 (org-store-link-props :type "w3" :url (url-view-url t)))
8843 ((eq major-mode 'w3m-mode)
8844 (setq cpltxt (or w3m-current-title w3m-current-url)
8845 link w3m-current-url)
8846 (org-store-link-props :type "w3m" :url (url-view-url t)))
8848 ((setq search (run-hook-with-args-until-success
8849 'org-create-file-search-functions))
8850 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8851 "::" search))
8852 (setq cpltxt (or description link)))
8854 ((eq major-mode 'image-mode)
8855 (setq cpltxt (concat "file:"
8856 (abbreviate-file-name buffer-file-name))
8857 link cpltxt)
8858 (org-store-link-props :type "image" :file buffer-file-name))
8860 ((eq major-mode 'dired-mode)
8861 ;; link to the file in the current line
8862 (let ((file (dired-get-filename nil t)))
8863 (setq file (if file
8864 (abbreviate-file-name
8865 (expand-file-name (dired-get-filename nil t)))
8866 ;; otherwise, no file so use current directory.
8867 default-directory))
8868 (setq cpltxt (concat "file:" file)
8869 link cpltxt)))
8871 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8872 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8873 (cond
8874 ((org-in-regexp "<<\\(.*?\\)>>")
8875 (setq cpltxt
8876 (concat "file:"
8877 (abbreviate-file-name
8878 (buffer-file-name (buffer-base-buffer)))
8879 "::" (match-string 1))
8880 link cpltxt))
8881 ((and (featurep 'org-id)
8882 (or (eq org-id-link-to-org-use-id t)
8883 (and (org-called-interactively-p 'any)
8884 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
8885 (and (eq org-id-link-to-org-use-id
8886 'create-if-interactive-and-no-custom-id)
8887 (not custom-id))))
8888 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
8889 ;; We can make a link using the ID.
8890 (setq link (condition-case nil
8891 (prog1 (org-id-store-link)
8892 (setq desc (plist-get org-store-link-plist :description)))
8893 (error
8894 ;; probably before first headline, link to file only
8895 (concat "file:"
8896 (abbreviate-file-name
8897 (buffer-file-name (buffer-base-buffer))))))))
8899 ;; Just link to current headline
8900 (setq cpltxt (concat "file:"
8901 (abbreviate-file-name
8902 (buffer-file-name (buffer-base-buffer)))))
8903 ;; Add a context search string
8904 (when (org-xor org-context-in-file-links arg)
8905 (setq txt (cond
8906 ((org-at-heading-p) nil)
8907 ((org-region-active-p)
8908 (buffer-substring (region-beginning) (region-end)))))
8909 (when (or (null txt) (string-match "\\S-" txt))
8910 (setq cpltxt
8911 (concat cpltxt "::"
8912 (condition-case nil
8913 (org-make-org-heading-search-string txt)
8914 (error "")))
8915 desc (or (nth 4 (ignore-errors
8916 (org-heading-components))) "NONE"))))
8917 (if (string-match "::\\'" cpltxt)
8918 (setq cpltxt (substring cpltxt 0 -2)))
8919 (setq link cpltxt))))
8921 ((buffer-file-name (buffer-base-buffer))
8922 ;; Just link to this file here.
8923 (setq cpltxt (concat "file:"
8924 (abbreviate-file-name
8925 (buffer-file-name (buffer-base-buffer)))))
8926 ;; Add a context string
8927 (when (org-xor org-context-in-file-links arg)
8928 (setq txt (if (org-region-active-p)
8929 (buffer-substring (region-beginning) (region-end))
8930 (buffer-substring (point-at-bol) (point-at-eol))))
8931 ;; Only use search option if there is some text.
8932 (when (string-match "\\S-" txt)
8933 (setq cpltxt
8934 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8935 desc "NONE")))
8936 (setq link cpltxt))
8938 ((org-called-interactively-p 'interactive)
8939 (error "Cannot link to a buffer which is not visiting a file"))
8941 (t (setq link nil)))
8943 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8944 (setq link (or link cpltxt)
8945 desc (or desc cpltxt))
8946 (if (equal desc "NONE") (setq desc nil))
8948 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8949 (progn
8950 (setq org-stored-links
8951 (cons (list link desc) org-stored-links))
8952 (message "Stored: %s" (or desc link))
8953 (when custom-id
8954 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8955 "::#" custom-id))
8956 (setq org-stored-links
8957 (cons (list link desc) org-stored-links))))
8958 (or agenda-link (and link (org-make-link-string link desc)))))))
8960 (defun org-store-link-props (&rest plist)
8961 "Store link properties, extract names and addresses."
8962 (let (x adr)
8963 (when (setq x (plist-get plist :from))
8964 (setq adr (mail-extract-address-components x))
8965 (setq plist (plist-put plist :fromname (car adr)))
8966 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8967 (when (setq x (plist-get plist :to))
8968 (setq adr (mail-extract-address-components x))
8969 (setq plist (plist-put plist :toname (car adr)))
8970 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8971 (let ((from (plist-get plist :from))
8972 (to (plist-get plist :to)))
8973 (when (and from to org-from-is-user-regexp)
8974 (setq plist
8975 (plist-put plist :fromto
8976 (if (string-match org-from-is-user-regexp from)
8977 (concat "to %t")
8978 (concat "from %f"))))))
8979 (setq org-store-link-plist plist))
8981 (defun org-add-link-props (&rest plist)
8982 "Add these properties to the link property list."
8983 (let (key value)
8984 (while plist
8985 (setq key (pop plist) value (pop plist))
8986 (setq org-store-link-plist
8987 (plist-put org-store-link-plist key value)))))
8989 (defun org-email-link-description (&optional fmt)
8990 "Return the description part of an email link.
8991 This takes information from `org-store-link-plist' and formats it
8992 according to FMT (default from `org-email-link-description-format')."
8993 (setq fmt (or fmt org-email-link-description-format))
8994 (let* ((p org-store-link-plist)
8995 (to (plist-get p :toaddress))
8996 (from (plist-get p :fromaddress))
8997 (table
8998 (list
8999 (cons "%c" (plist-get p :fromto))
9000 (cons "%F" (plist-get p :from))
9001 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9002 (cons "%T" (plist-get p :to))
9003 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9004 (cons "%s" (plist-get p :subject))
9005 (cons "%d" (plist-get p :date))
9006 (cons "%m" (plist-get p :message-id)))))
9007 (when (string-match "%c" fmt)
9008 ;; Check if the user wrote this message
9009 (if (and org-from-is-user-regexp from to
9010 (save-match-data (string-match org-from-is-user-regexp from)))
9011 (setq fmt (replace-match "to %t" t t fmt))
9012 (setq fmt (replace-match "from %f" t t fmt))))
9013 (org-replace-escapes fmt table)))
9015 (defun org-make-org-heading-search-string (&optional string heading)
9016 "Make search string for STRING or current headline."
9017 (interactive)
9018 (let ((s (or string (org-get-heading)))
9019 (lines org-context-in-file-links))
9020 (unless (and string (not heading))
9021 ;; We are using a headline, clean up garbage in there.
9022 (if (string-match org-todo-regexp s)
9023 (setq s (replace-match "" t t s)))
9024 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9025 (setq s (replace-match "" t t s)))
9026 (setq s (org-trim s))
9027 (if (string-match (concat "^\\(" org-quote-string "\\|"
9028 org-comment-string "\\)") s)
9029 (setq s (replace-match "" t t s)))
9030 (while (string-match org-ts-regexp s)
9031 (setq s (replace-match "" t t s))))
9032 (or string (setq s (concat "*" s))) ; Add * for headlines
9033 (when (and string (integerp lines) (> lines 0))
9034 (let ((slines (org-split-string s "\n")))
9035 (when (< lines (length slines))
9036 (setq s (mapconcat
9037 'identity
9038 (reverse (nthcdr (- (length slines) lines)
9039 (reverse slines))) "\n")))))
9040 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9042 (defun org-make-link-string (link &optional description)
9043 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9044 (unless (string-match "\\S-" link)
9045 (error "Empty link"))
9046 (when (and description
9047 (stringp description)
9048 (not (string-match "\\S-" description)))
9049 (setq description nil))
9050 (when (stringp description)
9051 ;; Remove brackets from the description, they are fatal.
9052 (while (string-match "\\[" description)
9053 (setq description (replace-match "{" t t description)))
9054 (while (string-match "\\]" description)
9055 (setq description (replace-match "}" t t description))))
9056 (when (equal link description)
9057 ;; No description needed, it is identical
9058 (setq description nil))
9059 (when (and (not description)
9060 (not (string-match (org-image-file-name-regexp) link))
9061 (not (equal link (org-link-escape link))))
9062 (setq description (org-extract-attributes link)))
9063 (setq link
9064 (cond ((string-match (org-image-file-name-regexp) link) link)
9065 ((string-match org-link-types-re link)
9066 (concat (match-string 1 link)
9067 (org-link-escape (substring link (match-end 1)))))
9068 (t (org-link-escape link))))
9069 (concat "[[" link "]"
9070 (if description (concat "[" description "]") "")
9071 "]"))
9073 (defconst org-link-escape-chars
9074 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9075 "List of characters that should be escaped in link.
9076 This is the list that is used for internal purposes.")
9078 (defconst org-link-escape-chars-browser
9079 '(?\ )
9080 "List of escapes for characters that are problematic in links.
9081 This is the list that is used before handing over to the browser.")
9083 (defun org-link-escape (text &optional table merge)
9084 "Return percent escaped representation of TEXT.
9085 TEXT is a string with the text to escape.
9086 Optional argument TABLE is a list with characters that should be
9087 escaped. When nil, `org-link-escape-chars' is used.
9088 If optional argument MERGE is set, merge TABLE into
9089 `org-link-escape-chars'."
9090 (cond
9091 ((and table merge)
9092 (mapc (lambda (defchr)
9093 (unless (member defchr table)
9094 (setq table (cons defchr table)))) org-link-escape-chars))
9095 ((null table)
9096 (setq table org-link-escape-chars)))
9097 (mapconcat
9098 (lambda (char)
9099 (if (or (member char table)
9100 (and (or (< char 32) (= char 37) (> char 126))
9101 org-url-hexify-p))
9102 (mapconcat (lambda (sequence-element)
9103 (format "%%%.2X" sequence-element))
9104 (or (encode-coding-char char 'utf-8)
9105 (error "Unable to percent escape character: %s"
9106 (char-to-string char))) "")
9107 (char-to-string char))) text ""))
9109 (defun org-link-unescape (str)
9110 "Unhex hexified Unicode strings as returned from the JavaScript function
9111 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9112 (unless (and (null str) (string= "" str))
9113 (let ((pos 0) (case-fold-search t) unhexed)
9114 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9115 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9116 (setq str (replace-match unhexed t t str))
9117 (setq pos (+ pos (length unhexed))))))
9118 str)
9120 (defun org-link-unescape-compound (hex)
9121 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9122 Note: this function also decodes single byte encodings like
9123 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9124 (save-match-data
9125 (let* ((bytes (cdr (split-string hex "%")))
9126 (ret "")
9127 (eat 0)
9128 (sum 0))
9129 (while bytes
9130 (let* ((val (string-to-number (pop bytes) 16))
9131 (shift-xor
9132 (if (= 0 eat)
9133 (cond
9134 ((>= val 252) (cons 6 252))
9135 ((>= val 248) (cons 5 248))
9136 ((>= val 240) (cons 4 240))
9137 ((>= val 224) (cons 3 224))
9138 ((>= val 192) (cons 2 192))
9139 (t (cons 0 0)))
9140 (cons 6 128))))
9141 (if (>= val 192) (setq eat (car shift-xor)))
9142 (setq val (logxor val (cdr shift-xor)))
9143 (setq sum (+ (lsh sum (car shift-xor)) val))
9144 (if (> eat 0) (setq eat (- eat 1)))
9145 (cond
9146 ((= 0 eat) ;multi byte
9147 (setq ret (concat ret (org-char-to-string sum)))
9148 (setq sum 0))
9149 ((not bytes) ; single byte(s)
9150 (setq ret (org-link-unescape-single-byte-sequence hex))))
9151 )) ;; end (while bytes
9152 ret )))
9154 (defun org-link-unescape-single-byte-sequence (hex)
9155 "Unhexify hex-encoded single byte character sequences."
9156 (mapconcat (lambda (byte)
9157 (char-to-string (string-to-number byte 16)))
9158 (cdr (split-string hex "%")) ""))
9160 (defun org-xor (a b)
9161 "Exclusive or."
9162 (if a (not b) b))
9164 (defun org-fixup-message-id-for-http (s)
9165 "Replace special characters in a message id, so it can be used in an http query."
9166 (when (string-match "%" s)
9167 (setq s (mapconcat (lambda (c)
9168 (if (eq c ?%)
9169 "%25"
9170 (char-to-string c)))
9171 s "")))
9172 (while (string-match "<" s)
9173 (setq s (replace-match "%3C" t t s)))
9174 (while (string-match ">" s)
9175 (setq s (replace-match "%3E" t t s)))
9176 (while (string-match "@" s)
9177 (setq s (replace-match "%40" t t s)))
9180 (defun org-link-prettify (link)
9181 "Return a human-readable representation of LINK.
9182 The car of LINK must be a raw link the cdr of LINK must be either
9183 a link description or nil."
9184 (let ((desc (or (cadr link) "<no description>")))
9185 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9186 "<" (car link) ">")))
9188 ;;;###autoload
9189 (defun org-insert-link-global ()
9190 "Insert a link like Org-mode does.
9191 This command can be called in any mode to insert a link in Org-mode syntax."
9192 (interactive)
9193 (org-load-modules-maybe)
9194 (org-run-like-in-org-mode 'org-insert-link))
9196 (defun org-insert-all-links (&optional keep)
9197 "Insert all links in `org-stored-links'."
9198 (interactive "P")
9199 (let ((links (copy-sequence org-stored-links)) l)
9200 (while (setq l (if keep (pop links) (pop org-stored-links)))
9201 (insert "- ")
9202 (org-insert-link nil (car l) (cadr l))
9203 (insert "\n"))))
9205 (defun org-link-fontify-links-to-this-file ()
9206 "Fontify links to the current file in `org-stored-links'."
9207 (let ((f (buffer-file-name)) a b)
9208 (setq a (mapcar (lambda(l)
9209 (let ((ll (car l)))
9210 (when (and (string-match "^file:\\(.+\\)::" ll)
9211 (equal f (expand-file-name (match-string 1 ll))))
9212 ll)))
9213 org-stored-links))
9214 (when (featurep 'org-id)
9215 (setq b (mapcar (lambda(l)
9216 (let ((ll (car l)))
9217 (when (and (string-match "^id:\\(.+\\)$" ll)
9218 (equal f (expand-file-name
9219 (or (org-id-find-id-file
9220 (match-string 1 ll)) ""))))
9221 ll)))
9222 org-stored-links)))
9223 (mapcar (lambda(l)
9224 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9225 (delq nil (append a b)))))
9227 (defvar org-link-links-in-this-file nil)
9228 (defun org-insert-link (&optional complete-file link-location default-description)
9229 "Insert a link. At the prompt, enter the link.
9231 Completion can be used to insert any of the link protocol prefixes like
9232 http or ftp in use.
9234 The history can be used to select a link previously stored with
9235 `org-store-link'. When the empty string is entered (i.e. if you just
9236 press RET at the prompt), the link defaults to the most recently
9237 stored link. As SPC triggers completion in the minibuffer, you need to
9238 use M-SPC or C-q SPC to force the insertion of a space character.
9240 You will also be prompted for a description, and if one is given, it will
9241 be displayed in the buffer instead of the link.
9243 If there is already a link at point, this command will allow you to edit link
9244 and description parts.
9246 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9247 be selected using completion. The path to the file will be relative to the
9248 current directory if the file is in the current directory or a subdirectory.
9249 Otherwise, the link will be the absolute path as completed in the minibuffer
9250 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9251 option `org-link-file-path-type'.
9253 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9254 the current directory or below.
9256 With three \\[universal-argument] prefixes, negate the meaning of
9257 `org-keep-stored-link-after-insertion'.
9259 If `org-make-link-description-function' is non-nil, this function will be
9260 called with the link target, and the result will be the default
9261 link description.
9263 If the LINK-LOCATION parameter is non-nil, this value will be
9264 used as the link location instead of reading one interactively.
9266 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9267 be used as the default description."
9268 (interactive "P")
9269 (let* ((wcf (current-window-configuration))
9270 (region (if (org-region-active-p)
9271 (buffer-substring (region-beginning) (region-end))))
9272 (remove (and region (list (region-beginning) (region-end))))
9273 (desc region)
9274 tmphist ; byte-compile incorrectly complains about this
9275 (link link-location)
9276 (abbrevs org-link-abbrev-alist-local)
9277 entry file all-prefixes auto-desc)
9278 (cond
9279 (link-location) ; specified by arg, just use it.
9280 ((org-in-regexp org-bracket-link-regexp 1)
9281 ;; We do have a link at point, and we are going to edit it.
9282 (setq remove (list (match-beginning 0) (match-end 0)))
9283 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9284 (setq link (read-string "Link: "
9285 (org-link-unescape
9286 (org-match-string-no-properties 1)))))
9287 ((or (org-in-regexp org-angle-link-re)
9288 (org-in-regexp org-plain-link-re))
9289 ;; Convert to bracket link
9290 (setq remove (list (match-beginning 0) (match-end 0))
9291 link (read-string "Link: "
9292 (org-remove-angle-brackets (match-string 0)))))
9293 ((member complete-file '((4) (16)))
9294 ;; Completing read for file names.
9295 (setq link (org-file-complete-link complete-file)))
9297 ;; Read link, with completion for stored links.
9298 (org-link-fontify-links-to-this-file)
9299 (org-switch-to-buffer-other-window "*Org Links*")
9300 (with-current-buffer "*Org Links*"
9301 (erase-buffer)
9302 (insert "Insert a link.
9303 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9304 (when org-stored-links
9305 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9306 (insert (mapconcat 'org-link-prettify
9307 (reverse org-stored-links) "\n")))
9308 (goto-char (point-min)))
9309 (let ((cw (selected-window)))
9310 (select-window (get-buffer-window "*Org Links*" 'visible))
9311 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9312 (unless (pos-visible-in-window-p (point-max))
9313 (org-fit-window-to-buffer))
9314 (and (window-live-p cw) (select-window cw)))
9315 ;; Fake a link history, containing the stored links.
9316 (setq tmphist (append (mapcar 'car org-stored-links)
9317 org-insert-link-history))
9318 (setq all-prefixes (append (mapcar 'car abbrevs)
9319 (mapcar 'car org-link-abbrev-alist)
9320 org-link-types))
9321 (unwind-protect
9322 (progn
9323 (setq link
9324 (let ((org-completion-use-ido nil)
9325 (org-completion-use-iswitchb nil))
9326 (org-completing-read
9327 "Link: "
9328 (append
9329 (mapcar (lambda (x) (list (concat x ":")))
9330 all-prefixes)
9331 (mapcar 'car org-stored-links)
9332 (mapcar 'cadr org-stored-links))
9333 nil nil nil
9334 'tmphist
9335 (caar org-stored-links))))
9336 (if (not (string-match "\\S-" link))
9337 (error "No link selected"))
9338 (mapc (lambda(l)
9339 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9340 org-stored-links)
9341 (if (or (member link all-prefixes)
9342 (and (equal ":" (substring link -1))
9343 (member (substring link 0 -1) all-prefixes)
9344 (setq link (substring link 0 -1))))
9345 (setq link (org-link-try-special-completion link))))
9346 (set-window-configuration wcf)
9347 (kill-buffer "*Org Links*"))
9348 (setq entry (assoc link org-stored-links))
9349 (or entry (push link org-insert-link-history))
9350 (setq desc (or desc (nth 1 entry)))))
9352 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9353 (not org-keep-stored-link-after-insertion))
9354 (setq org-stored-links (delq (assoc link org-stored-links)
9355 org-stored-links)))
9357 (if (string-match org-plain-link-re link)
9358 ;; URL-like link, normalize the use of angular brackets.
9359 (setq link (org-remove-angle-brackets link)))
9361 ;; Check if we are linking to the current file with a search
9362 ;; option If yes, simplify the link by using only the search
9363 ;; option.
9364 (when (and buffer-file-name
9365 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9366 (let* ((path (match-string 1 link))
9367 (case-fold-search nil)
9368 (search (match-string 2 link)))
9369 (save-match-data
9370 (if (equal (file-truename buffer-file-name) (file-truename path))
9371 ;; We are linking to this same file, with a search option
9372 (setq link search)))))
9374 ;; Check if we can/should use a relative path. If yes, simplify the link
9375 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9376 (let* ((type (match-string 1 link))
9377 (path (match-string 2 link))
9378 (origpath path)
9379 (case-fold-search nil))
9380 (cond
9381 ((or (eq org-link-file-path-type 'absolute)
9382 (equal complete-file '(16)))
9383 (setq path (abbreviate-file-name (expand-file-name path))))
9384 ((eq org-link-file-path-type 'noabbrev)
9385 (setq path (expand-file-name path)))
9386 ((eq org-link-file-path-type 'relative)
9387 (setq path (file-relative-name path)))
9389 (save-match-data
9390 (if (string-match (concat "^" (regexp-quote
9391 (expand-file-name
9392 (file-name-as-directory
9393 default-directory))))
9394 (expand-file-name path))
9395 ;; We are linking a file with relative path name.
9396 (setq path (substring (expand-file-name path)
9397 (match-end 0)))
9398 (setq path (abbreviate-file-name (expand-file-name path)))))))
9399 (setq link (concat type path))
9400 (if (equal desc origpath)
9401 (setq desc path))))
9403 (if org-make-link-description-function
9404 (setq desc
9405 (or (condition-case nil
9406 (funcall org-make-link-description-function link desc)
9407 (error (progn (message "Can't get link description from `%s'"
9408 (symbol-name org-make-link-description-function))
9409 (sit-for 2) nil)))
9410 (read-string "Description: " default-description)))
9411 (if default-description (setq desc default-description)
9412 (setq desc (or (and auto-desc desc)
9413 (read-string "Description: " desc)))))
9415 (unless (string-match "\\S-" desc) (setq desc nil))
9416 (if remove (apply 'delete-region remove))
9417 (insert (org-make-link-string link desc))))
9419 (defun org-link-try-special-completion (type)
9420 "If there is completion support for link type TYPE, offer it."
9421 (let ((fun (intern (concat "org-" type "-complete-link"))))
9422 (if (functionp fun)
9423 (funcall fun)
9424 (read-string "Link (no completion support): " (concat type ":")))))
9426 (defun org-file-complete-link (&optional arg)
9427 "Create a file link using completion."
9428 (let (file link)
9429 (setq file (read-file-name "File: "))
9430 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9431 (pwd1 (file-name-as-directory (abbreviate-file-name
9432 (expand-file-name ".")))))
9433 (cond
9434 ((equal arg '(16))
9435 (setq link (concat
9436 "file:"
9437 (abbreviate-file-name (expand-file-name file)))))
9438 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9439 (setq link (concat "file:" (match-string 1 file))))
9440 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9441 (expand-file-name file))
9442 (setq link (concat
9443 "file:" (match-string 1 (expand-file-name file)))))
9444 (t (setq link (concat "file:" file)))))
9445 link))
9447 (defun org-completing-read (&rest args)
9448 "Completing-read with SPACE being a normal character."
9449 (let ((enable-recursive-minibuffers t)
9450 (minibuffer-local-completion-map
9451 (copy-keymap minibuffer-local-completion-map)))
9452 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9453 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9454 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9455 (apply 'org-icompleting-read args)))
9457 (defun org-completing-read-no-i (&rest args)
9458 (let (org-completion-use-ido org-completion-use-iswitchb)
9459 (apply 'org-completing-read args)))
9461 (defun org-iswitchb-completing-read (prompt choices &rest args)
9462 "Use iswitch as a completing-read replacement to choose from choices.
9463 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9464 from."
9465 (let* ((iswitchb-use-virtual-buffers nil)
9466 (iswitchb-make-buflist-hook
9467 (lambda ()
9468 (setq iswitchb-temp-buflist choices))))
9469 (iswitchb-read-buffer prompt)))
9471 (defun org-icompleting-read (&rest args)
9472 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9473 (org-without-partial-completion
9474 (if (and org-completion-use-ido
9475 (fboundp 'ido-completing-read)
9476 (boundp 'ido-mode) ido-mode
9477 (listp (second args)))
9478 (let ((ido-enter-matching-directory nil))
9479 (apply 'ido-completing-read (concat (car args))
9480 (if (consp (car (nth 1 args)))
9481 (mapcar 'car (nth 1 args))
9482 (nth 1 args))
9483 (cddr args)))
9484 (if (and org-completion-use-iswitchb
9485 (boundp 'iswitchb-mode) iswitchb-mode
9486 (listp (second args)))
9487 (apply 'org-iswitchb-completing-read (concat (car args))
9488 (if (consp (car (nth 1 args)))
9489 (mapcar 'car (nth 1 args))
9490 (nth 1 args))
9491 (cddr args))
9492 (apply 'completing-read args)))))
9494 (defun org-extract-attributes (s)
9495 "Extract the attributes cookie from a string and set as text property."
9496 (let (a attr (start 0) key value)
9497 (save-match-data
9498 (when (string-match "{{\\([^}]+\\)}}$" s)
9499 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9500 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9501 (setq key (match-string 1 a) value (match-string 2 a)
9502 start (match-end 0)
9503 attr (plist-put attr (intern key) value))))
9504 (org-add-props s nil 'org-attr attr))
9507 (defun org-extract-attributes-from-string (tag)
9508 (let (key value attr)
9509 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9510 (setq key (match-string 1 tag) value (match-string 2 tag)
9511 tag (replace-match "" t t tag)
9512 attr (plist-put attr (intern key) value)))
9513 (cons tag attr)))
9515 (defun org-attributes-to-string (plist)
9516 "Format a property list into an HTML attribute list."
9517 (let ((s "") key value)
9518 (while plist
9519 (setq key (pop plist) value (pop plist))
9520 (and value
9521 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9524 ;;; Opening/following a link
9526 (defvar org-link-search-failed nil)
9528 (defvar org-open-link-functions nil
9529 "Hook for functions finding a plain text link.
9530 These functions must take a single argument, the link content.
9531 They will be called for links that look like [[link text][description]]
9532 when LINK TEXT does not have a protocol like \"http:\" and does not look
9533 like a filename (e.g. \"./blue.png\").
9535 These functions will be called *before* Org attempts to resolve the
9536 link by doing text searches in the current buffer - so if you want a
9537 link \"[[target]]\" to still find \"<<target>>\", your function should
9538 handle this as a special case.
9540 When the function does handle the link, it must return a non-nil value.
9541 If it decides that it is not responsible for this link, it must return
9542 nil to indicate that that Org-mode can continue with other options
9543 like exact and fuzzy text search.")
9545 (defun org-next-link ()
9546 "Move forward to the next link.
9547 If the link is in hidden text, expose it."
9548 (interactive)
9549 (when (and org-link-search-failed (eq this-command last-command))
9550 (goto-char (point-min))
9551 (message "Link search wrapped back to beginning of buffer"))
9552 (setq org-link-search-failed nil)
9553 (let* ((pos (point))
9554 (ct (org-context))
9555 (a (assoc :link ct)))
9556 (if a (goto-char (nth 2 a)))
9557 (if (re-search-forward org-any-link-re nil t)
9558 (progn
9559 (goto-char (match-beginning 0))
9560 (if (outline-invisible-p) (org-show-context)))
9561 (goto-char pos)
9562 (setq org-link-search-failed t)
9563 (error "No further link found"))))
9565 (defun org-previous-link ()
9566 "Move backward to the previous link.
9567 If the link is in hidden text, expose it."
9568 (interactive)
9569 (when (and org-link-search-failed (eq this-command last-command))
9570 (goto-char (point-max))
9571 (message "Link search wrapped back to end of buffer"))
9572 (setq org-link-search-failed nil)
9573 (let* ((pos (point))
9574 (ct (org-context))
9575 (a (assoc :link ct)))
9576 (if a (goto-char (nth 1 a)))
9577 (if (re-search-backward org-any-link-re nil t)
9578 (progn
9579 (goto-char (match-beginning 0))
9580 (if (outline-invisible-p) (org-show-context)))
9581 (goto-char pos)
9582 (setq org-link-search-failed t)
9583 (error "No further link found"))))
9585 (defun org-translate-link (s)
9586 "Translate a link string if a translation function has been defined."
9587 (if (and org-link-translation-function
9588 (fboundp org-link-translation-function)
9589 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9590 (progn
9591 (setq s (funcall org-link-translation-function
9592 (match-string 1 s) (match-string 2 s)))
9593 (concat (car s) ":" (cdr s)))
9596 (defun org-translate-link-from-planner (type path)
9597 "Translate a link from Emacs Planner syntax so that Org can follow it.
9598 This is still an experimental function, your mileage may vary."
9599 (cond
9600 ((member type '("http" "https" "news" "ftp"))
9601 ;; standard Internet links are the same.
9602 nil)
9603 ((and (equal type "irc") (string-match "^//" path))
9604 ;; Planner has two / at the beginning of an irc link, we have 1.
9605 ;; We should have zero, actually....
9606 (setq path (substring path 1)))
9607 ((and (equal type "lisp") (string-match "^/" path))
9608 ;; Planner has a slash, we do not.
9609 (setq type "elisp" path (substring path 1)))
9610 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9611 ;; A typical message link. Planner has the id after the final slash,
9612 ;; we separate it with a hash mark
9613 (setq path (concat (match-string 1 path) "#"
9614 (org-remove-angle-brackets (match-string 2 path)))))
9616 (cons type path))
9618 (defun org-find-file-at-mouse (ev)
9619 "Open file link or URL at mouse."
9620 (interactive "e")
9621 (mouse-set-point ev)
9622 (org-open-at-point 'in-emacs))
9624 (defun org-open-at-mouse (ev)
9625 "Open file link or URL at mouse.
9626 See the docstring of `org-open-file' for details."
9627 (interactive "e")
9628 (mouse-set-point ev)
9629 (if (eq major-mode 'org-agenda-mode)
9630 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9631 (org-open-at-point))
9633 (defvar org-window-config-before-follow-link nil
9634 "The window configuration before following a link.
9635 This is saved in case the need arises to restore it.")
9637 (defvar org-open-link-marker (make-marker)
9638 "Marker pointing to the location where `org-open-at-point; was called.")
9640 ;;;###autoload
9641 (defun org-open-at-point-global ()
9642 "Follow a link like Org-mode does.
9643 This command can be called in any mode to follow a link that has
9644 Org-mode syntax."
9645 (interactive)
9646 (org-run-like-in-org-mode 'org-open-at-point))
9648 ;;;###autoload
9649 (defun org-open-link-from-string (s &optional arg reference-buffer)
9650 "Open a link in the string S, as if it was in Org-mode."
9651 (interactive "sLink: \nP")
9652 (let ((reference-buffer (or reference-buffer (current-buffer))))
9653 (with-temp-buffer
9654 (let ((org-inhibit-startup (not reference-buffer)))
9655 (org-mode)
9656 (insert s)
9657 (goto-char (point-min))
9658 (when reference-buffer
9659 (setq org-link-abbrev-alist-local
9660 (with-current-buffer reference-buffer
9661 org-link-abbrev-alist-local)))
9662 (org-open-at-point arg reference-buffer)))))
9664 (defvar org-open-at-point-functions nil
9665 "Hook that is run when following a link at point.
9667 Functions in this hook must return t if they identify and follow
9668 a link at point. If they don't find anything interesting at point,
9669 they must return nil.")
9671 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9672 (defun org-open-at-point (&optional arg reference-buffer)
9673 "Open link at or after point.
9674 If there is no link at point, this function will search forward up to
9675 the end of the current line.
9676 Normally, files will be opened by an appropriate application. If the
9677 optional prefix argument ARG is non-nil, Emacs will visit the file.
9678 With a double prefix argument, try to open outside of Emacs, in the
9679 application the system uses for this file type."
9680 (interactive "P")
9681 ;; if in a code block, then open the block's results
9682 (unless (call-interactively #'org-babel-open-src-block-result)
9683 (org-load-modules-maybe)
9684 (move-marker org-open-link-marker (point))
9685 (setq org-window-config-before-follow-link (current-window-configuration))
9686 (org-remove-occur-highlights nil nil t)
9687 (cond
9688 ((and (org-at-heading-p)
9689 (not (org-at-timestamp-p t))
9690 (not (org-in-regexp
9691 (concat org-plain-link-re "\\|"
9692 org-bracket-link-regexp "\\|"
9693 org-angle-link-re "\\|"
9694 "[ \t]:[^ \t\n]+:[ \t]*$")))
9695 (not (get-text-property (point) 'org-linked-text)))
9696 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9697 (lk0 (car lkall))
9698 (lk (if (stringp lk0) (list lk0) lk0))
9699 (lkend (cdr lkall)))
9700 (mapcar (lambda(l)
9701 (search-forward l nil lkend)
9702 (goto-char (match-beginning 0))
9703 (org-open-at-point))
9704 lk))
9705 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9706 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9707 ((and (org-at-timestamp-p t)
9708 (not (org-in-regexp org-bracket-link-regexp)))
9709 (org-follow-timestamp-link))
9710 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9711 (not (org-in-regexp org-any-link-re)))
9712 (org-footnote-action))
9714 (let (type path link line search (pos (point)))
9715 (catch 'match
9716 (save-excursion
9717 (skip-chars-forward "^]\n\r")
9718 (when (org-in-regexp org-bracket-link-regexp 1)
9719 (setq link (org-extract-attributes
9720 (org-link-unescape (org-match-string-no-properties 1))))
9721 (while (string-match " *\n *" link)
9722 (setq link (replace-match " " t t link)))
9723 (setq link (org-link-expand-abbrev link))
9724 (cond
9725 ((or (file-name-absolute-p link)
9726 (string-match "^\\.\\.?/" link))
9727 (setq type "file" path link))
9728 ((string-match org-link-re-with-space3 link)
9729 (setq type (match-string 1 link) path (match-string 2 link)))
9730 ((string-match "^help:+\\(.+\\)" link)
9731 (setq type "help" path (match-string 1 link)))
9732 (t (setq type "thisfile" path link)))
9733 (throw 'match t)))
9735 (when (get-text-property (point) 'org-linked-text)
9736 (setq type "thisfile"
9737 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9738 (1+ (point)) (point))
9739 path (buffer-substring
9740 (or (previous-single-property-change pos 'org-linked-text)
9741 (point-min))
9742 (or (next-single-property-change pos 'org-linked-text)
9743 (point-max))))
9744 (throw 'match t))
9746 (save-excursion
9747 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9748 (when (or (org-in-regexp org-angle-link-re)
9749 (and plinkpos (goto-char (car plinkpos))
9750 (save-match-data (not (looking-back "\\[\\[")))))
9751 (setq type (match-string 1)
9752 path (org-link-unescape (match-string 2)))
9753 (throw 'match t))))
9754 (save-excursion
9755 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9756 (setq type "tags"
9757 path (match-string 1))
9758 (while (string-match ":" path)
9759 (setq path (replace-match "+" t t path)))
9760 (throw 'match t)))
9761 (when (org-in-regexp "<\\([^><\n]+\\)>")
9762 (setq type "tree-match"
9763 path (match-string 1))
9764 (throw 'match t)))
9765 (unless path
9766 (user-error "No link found"))
9768 ;; switch back to reference buffer
9769 ;; needed when if called in a temporary buffer through
9770 ;; org-open-link-from-string
9771 (with-current-buffer (or reference-buffer (current-buffer))
9773 ;; Remove any trailing spaces in path
9774 (if (string-match " +\\'" path)
9775 (setq path (replace-match "" t t path)))
9776 (if (and org-link-translation-function
9777 (fboundp org-link-translation-function))
9778 ;; Check if we need to translate the link
9779 (let ((tmp (funcall org-link-translation-function type path)))
9780 (setq type (car tmp) path (cdr tmp))))
9782 (cond
9784 ((assoc type org-link-protocols)
9785 (funcall (nth 1 (assoc type org-link-protocols)) path))
9787 ((equal type "help")
9788 (let ((f-or-v (intern path)))
9789 (cond ((fboundp f-or-v)
9790 (describe-function f-or-v))
9791 ((boundp f-or-v)
9792 (describe-variable f-or-v))
9793 (t (error "Not a known function or variable")))))
9795 ((equal type "mailto")
9796 (let ((cmd (car org-link-mailto-program))
9797 (args (cdr org-link-mailto-program)) args1
9798 (address path) (subject "") a)
9799 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9800 (setq address (match-string 1 path)
9801 subject (org-link-escape (match-string 2 path))))
9802 (while args
9803 (cond
9804 ((not (stringp (car args))) (push (pop args) args1))
9805 (t (setq a (pop args))
9806 (if (string-match "%a" a)
9807 (setq a (replace-match address t t a)))
9808 (if (string-match "%s" a)
9809 (setq a (replace-match subject t t a)))
9810 (push a args1))))
9811 (apply cmd (nreverse args1))))
9813 ((member type '("http" "https" "ftp" "news"))
9814 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9815 (org-link-escape
9816 path org-link-escape-chars-browser)
9817 path))))
9819 ((string= type "doi")
9820 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9821 (org-link-escape
9822 path org-link-escape-chars-browser)
9823 path))))
9825 ((member type '("message"))
9826 (browse-url (concat type ":" path)))
9828 ((string= type "tags")
9829 (org-tags-view arg path))
9831 ((string= type "tree-match")
9832 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9834 ((string= type "file")
9835 (if (string-match "::\\([0-9]+\\)\\'" path)
9836 (setq line (string-to-number (match-string 1 path))
9837 path (substring path 0 (match-beginning 0)))
9838 (if (string-match "::\\(.+\\)\\'" path)
9839 (setq search (match-string 1 path)
9840 path (substring path 0 (match-beginning 0)))))
9841 (if (string-match "[*?{]" (file-name-nondirectory path))
9842 (dired path)
9843 (org-open-file path arg line search)))
9845 ((string= type "shell")
9846 (let ((buf (generate-new-buffer "*Org Shell Output"))
9847 (cmd path))
9848 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9849 (string-match org-confirm-shell-link-not-regexp cmd))
9850 (not org-confirm-shell-link-function)
9851 (funcall org-confirm-shell-link-function
9852 (format "Execute \"%s\" in shell? "
9853 (org-add-props cmd nil
9854 'face 'org-warning))))
9855 (progn
9856 (message "Executing %s" cmd)
9857 (shell-command cmd buf)
9858 (if (featurep 'midnight)
9859 (setq clean-buffer-list-kill-buffer-names
9860 (cons buf clean-buffer-list-kill-buffer-names))))
9861 (error "Abort"))))
9863 ((string= type "elisp")
9864 (let ((cmd path))
9865 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9866 (string-match org-confirm-elisp-link-not-regexp cmd))
9867 (not org-confirm-elisp-link-function)
9868 (funcall org-confirm-elisp-link-function
9869 (format "Execute \"%s\" as elisp? "
9870 (org-add-props cmd nil
9871 'face 'org-warning))))
9872 (message "%s => %s" cmd
9873 (if (equal (string-to-char cmd) ?\()
9874 (eval (read cmd))
9875 (call-interactively (read cmd))))
9876 (error "Abort"))))
9878 ((and (string= type "thisfile")
9879 (run-hook-with-args-until-success
9880 'org-open-link-functions path)))
9882 ((string= type "thisfile")
9883 (if arg
9884 (switch-to-buffer-other-window
9885 (org-get-buffer-for-internal-link (current-buffer)))
9886 (org-mark-ring-push))
9887 (let ((cmd `(org-link-search
9888 ,path
9889 ,(cond ((equal arg '(4)) ''occur)
9890 ((equal arg '(16)) ''org-occur))
9891 ,pos)))
9892 (condition-case nil (let ((org-link-search-inhibit-query t))
9893 (eval cmd))
9894 (error (progn (widen) (eval cmd))))))
9896 (t (browse-url-at-point)))))))
9897 (move-marker org-open-link-marker nil)
9898 (run-hook-with-args 'org-follow-link-hook)))
9900 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9901 "Offer links in the current entry and return the selected link.
9902 If there is only one link, return it.
9903 If NTH is an integer, return the NTH link found.
9904 If ZERO is a string, check also this string for a link, and if
9905 there is one, return it."
9906 (with-current-buffer buffer
9907 (save-excursion
9908 (save-restriction
9909 (widen)
9910 (goto-char marker)
9911 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9912 "\\(" org-angle-link-re "\\)\\|"
9913 "\\(" org-plain-link-re "\\)"))
9914 (cnt ?0)
9915 (in-emacs (if (integerp nth) nil nth))
9916 have-zero end links link c)
9917 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9918 (push (match-string 0 zero) links)
9919 (setq cnt (1- cnt) have-zero t))
9920 (save-excursion
9921 (org-back-to-heading t)
9922 (setq end (save-excursion (outline-next-heading) (point)))
9923 (while (re-search-forward re end t)
9924 (push (match-string 0) links))
9925 (setq links (org-uniquify (reverse links))))
9926 (cond
9927 ((null links)
9928 (message "No links"))
9929 ((equal (length links) 1)
9930 (setq link (car links)))
9931 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9932 (setq link (nth (if have-zero nth (1- nth)) links)))
9933 (t ; we have to select a link
9934 (save-excursion
9935 (save-window-excursion
9936 (delete-other-windows)
9937 (with-output-to-temp-buffer "*Select Link*"
9938 (mapc (lambda (l)
9939 (if (not (string-match org-bracket-link-regexp l))
9940 (princ (format "[%c] %s\n" (incf cnt)
9941 (org-remove-angle-brackets l)))
9942 (if (match-end 3)
9943 (princ (format "[%c] %s (%s)\n" (incf cnt)
9944 (match-string 3 l) (match-string 1 l)))
9945 (princ (format "[%c] %s\n" (incf cnt)
9946 (match-string 1 l))))))
9947 links))
9948 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9949 (message "Select link to open, RET to open all:")
9950 (setq c (read-char-exclusive))
9951 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9952 (when (equal c ?q) (error "Abort"))
9953 (if (equal c ?\C-m)
9954 (setq link links)
9955 (setq nth (- c ?0))
9956 (if have-zero (setq nth (1+ nth)))
9957 (unless (and (integerp nth) (>= (length links) nth))
9958 (error "Invalid link selection"))
9959 (setq link (nth (1- nth) links)))))
9960 (cons link end))))))
9962 ;; Add special file links that specify the way of opening
9964 (org-add-link-type "file+sys" 'org-open-file-with-system)
9965 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9966 (defun org-open-file-with-system (path)
9967 "Open file at PATH using the system way of opening it."
9968 (org-open-file path 'system))
9969 (defun org-open-file-with-emacs (path)
9970 "Open file at PATH in Emacs."
9971 (org-open-file path 'emacs))
9972 (defun org-remove-file-link-modifiers ()
9973 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9974 (goto-char (point-min))
9975 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9976 (org-if-unprotected
9977 (replace-match "file:" t t))))
9978 (eval-after-load "org-exp"
9979 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9980 'org-remove-file-link-modifiers))
9982 ;;; File search
9984 (defvar org-create-file-search-functions nil
9985 "List of functions to construct the right search string for a file link.
9986 These functions are called in turn with point at the location to
9987 which the link should point.
9989 A function in the hook should first test if it would like to
9990 handle this file type, for example by checking the `major-mode'
9991 or the file extension. If it decides not to handle this file, it
9992 should just return nil to give other functions a chance. If it
9993 does handle the file, it must return the search string to be used
9994 when following the link. The search string will be part of the
9995 file link, given after a double colon, and `org-open-at-point'
9996 will automatically search for it. If special measures must be
9997 taken to make the search successful, another function should be
9998 added to the companion hook `org-execute-file-search-functions',
9999 which see.
10001 A function in this hook may also use `setq' to set the variable
10002 `description' to provide a suggestion for the descriptive text to
10003 be used for this link when it gets inserted into an Org-mode
10004 buffer with \\[org-insert-link].")
10006 (defvar org-execute-file-search-functions nil
10007 "List of functions to execute a file search triggered by a link.
10009 Functions added to this hook must accept a single argument, the
10010 search string that was part of the file link, the part after the
10011 double colon. The function must first check if it would like to
10012 handle this search, for example by checking the `major-mode' or
10013 the file extension. If it decides not to handle this search, it
10014 should just return nil to give other functions a chance. If it
10015 does handle the search, it must return a non-nil value to keep
10016 other functions from trying.
10018 Each function can access the current prefix argument through the
10019 variable `current-prefix-argument'. Note that a single prefix is
10020 used to force opening a link in Emacs, so it may be good to only
10021 use a numeric or double prefix to guide the search function.
10023 In case this is needed, a function in this hook can also restore
10024 the window configuration before `org-open-at-point' was called using:
10026 (set-window-configuration org-window-config-before-follow-link)")
10028 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10029 (defun org-link-search (s &optional type avoid-pos stealth)
10030 "Search for a link search option.
10031 If S is surrounded by forward slashes, it is interpreted as a
10032 regular expression. In org-mode files, this will create an `org-occur'
10033 sparse tree. In ordinary files, `occur' will be used to list matches.
10034 If the current buffer is in `dired-mode', grep will be used to search
10035 in all files. If AVOID-POS is given, ignore matches near that position.
10037 When optional argument STEALTH is non-nil, do not modify
10038 visibility around point, thus ignoring
10039 `org-show-hierarchy-above', `org-show-following-heading' and
10040 `org-show-siblings' variables."
10041 (let ((case-fold-search t)
10042 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10043 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10044 (append '(("") (" ") ("\t") ("\n"))
10045 org-emphasis-alist)
10046 "\\|") "\\)"))
10047 (pos (point))
10048 (pre nil) (post nil)
10049 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10050 (cond
10051 ;; First check if there are any special search functions
10052 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10053 ;; Now try the builtin stuff
10054 ((and (equal (string-to-char s0) ?#)
10055 (> (length s0) 1)
10056 (save-excursion
10057 (goto-char (point-min))
10058 (and
10059 (re-search-forward
10060 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10061 (setq type 'dedicated
10062 pos (match-beginning 0))))
10063 ;; There is an exact target for this
10064 (goto-char pos)
10065 (org-back-to-heading t)))
10066 ((save-excursion
10067 (goto-char (point-min))
10068 (and
10069 (re-search-forward
10070 (concat "<<" (regexp-quote s0) ">>") nil t)
10071 (setq type 'dedicated
10072 pos (match-beginning 0))))
10073 ;; There is an exact target for this
10074 (goto-char pos))
10075 ((save-excursion
10076 (goto-char (point-min))
10077 (and
10078 (re-search-forward
10079 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10080 (setq type 'dedicated pos (match-beginning 0))))
10081 ;; Found an invisible target.
10082 (goto-char pos))
10083 ((save-excursion
10084 (goto-char (point-min))
10085 (and
10086 (re-search-forward
10087 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10088 (setq type 'dedicated pos (match-beginning 0))))
10089 ;; Found an element with a matching #+name affiliated keyword.
10090 (goto-char pos))
10091 ((and (string-match "^(\\(.*\\))$" s0)
10092 (save-excursion
10093 (goto-char (point-min))
10094 (and
10095 (re-search-forward
10096 (concat "[^[]" (regexp-quote
10097 (format org-coderef-label-format
10098 (match-string 1 s0))))
10099 nil t)
10100 (setq type 'dedicated
10101 pos (1+ (match-beginning 0))))))
10102 ;; There is a coderef target for this
10103 (goto-char pos))
10104 ((string-match "^/\\(.*\\)/$" s)
10105 ;; A regular expression
10106 (cond
10107 ((derived-mode-p 'org-mode)
10108 (org-occur (match-string 1 s)))
10109 ;;((eq major-mode 'dired-mode)
10110 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10111 (t (org-do-occur (match-string 1 s)))))
10112 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10113 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10114 (goto-char (point-min))
10115 (cond
10116 ((let (case-fold-search)
10117 (re-search-forward (format org-complex-heading-regexp-format
10118 (regexp-quote s))
10119 nil t))
10120 ;; OK, found a match
10121 (setq type 'dedicated)
10122 (goto-char (match-beginning 0)))
10123 ((and (not org-link-search-inhibit-query)
10124 (eq org-link-search-must-match-exact-headline 'query-to-create)
10125 (y-or-n-p "No match - create this as a new heading? "))
10126 (goto-char (point-max))
10127 (or (bolp) (newline))
10128 (insert "* " s "\n")
10129 (beginning-of-line 0))
10131 (goto-char pos)
10132 (error "No match"))))
10134 ;; A normal search string
10135 (when (equal (string-to-char s) ?*)
10136 ;; Anchor on headlines, post may include tags.
10137 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10138 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10139 s (substring s 1)))
10140 (remove-text-properties
10141 0 (length s)
10142 '(face nil mouse-face nil keymap nil fontified nil) s)
10143 ;; Make a series of regular expressions to find a match
10144 (setq words (org-split-string s "[ \n\r\t]+")
10146 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10147 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10148 "\\)" markers)
10149 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10150 re2a (concat "[ \t\r\n]" re2a_)
10151 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10152 re4 (concat "[^a-zA-Z_]" re4_)
10154 re1 (concat pre re2 post)
10155 re3 (concat pre (if pre re4_ re4) post)
10156 re5 (concat pre ".*" re4)
10157 re2 (concat pre re2)
10158 re2a (concat pre (if pre re2a_ re2a))
10159 re4 (concat pre (if pre re4_ re4))
10160 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10161 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10162 re5 "\\)"
10164 (cond
10165 ((eq type 'org-occur) (org-occur reall))
10166 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10167 (t (goto-char (point-min))
10168 (setq type 'fuzzy)
10169 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10170 (org-search-not-self 1 re1 nil t)
10171 (org-search-not-self 1 re2 nil t)
10172 (org-search-not-self 1 re2a nil t)
10173 (org-search-not-self 1 re3 nil t)
10174 (org-search-not-self 1 re4 nil t)
10175 (org-search-not-self 1 re5 nil t)
10177 (goto-char (match-beginning 1))
10178 (goto-char pos)
10179 (error "No match"))))))
10180 (and (derived-mode-p 'org-mode)
10181 (not stealth)
10182 (org-show-context 'link-search))
10183 type))
10185 (defun org-search-not-self (group &rest args)
10186 "Execute `re-search-forward', but only accept matches that do not
10187 enclose the position of `org-open-link-marker'."
10188 (let ((m org-open-link-marker))
10189 (catch 'exit
10190 (while (apply 're-search-forward args)
10191 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10192 (goto-char (match-end group))
10193 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10194 (> (match-beginning 0) (marker-position m))
10195 (< (match-end 0) (marker-position m)))
10196 (save-match-data
10197 (or (not (org-in-regexp
10198 org-bracket-link-analytic-regexp 1))
10199 (not (match-end 4)) ; no description
10200 (and (<= (match-beginning 4) (point))
10201 (>= (match-end 4) (point))))))
10202 (throw 'exit (point))))))))
10204 (defun org-get-buffer-for-internal-link (buffer)
10205 "Return a buffer to be used for displaying the link target of internal links."
10206 (cond
10207 ((not org-display-internal-link-with-indirect-buffer)
10208 buffer)
10209 ((string-match "(Clone)$" (buffer-name buffer))
10210 (message "Buffer is already a clone, not making another one")
10211 ;; we also do not modify visibility in this case
10212 buffer)
10213 (t ; make a new indirect buffer for displaying the link
10214 (let* ((bn (buffer-name buffer))
10215 (ibn (concat bn "(Clone)"))
10216 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10217 (with-current-buffer ib (org-overview))
10218 ib))))
10220 (defun org-do-occur (regexp &optional cleanup)
10221 "Call the Emacs command `occur'.
10222 If CLEANUP is non-nil, remove the printout of the regular expression
10223 in the *Occur* buffer. This is useful if the regex is long and not useful
10224 to read."
10225 (occur regexp)
10226 (when cleanup
10227 (let ((cwin (selected-window)) win beg end)
10228 (when (setq win (get-buffer-window "*Occur*"))
10229 (select-window win))
10230 (goto-char (point-min))
10231 (when (re-search-forward "match[a-z]+" nil t)
10232 (setq beg (match-end 0))
10233 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10234 (setq end (1- (match-beginning 0)))))
10235 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10236 (goto-char (point-min))
10237 (select-window cwin))))
10239 ;;; The mark ring for links jumps
10241 (defvar org-mark-ring nil
10242 "Mark ring for positions before jumps in Org-mode.")
10243 (defvar org-mark-ring-last-goto nil
10244 "Last position in the mark ring used to go back.")
10245 ;; Fill and close the ring
10246 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10247 (loop for i from 1 to org-mark-ring-length do
10248 (push (make-marker) org-mark-ring))
10249 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10250 org-mark-ring)
10252 (defun org-mark-ring-push (&optional pos buffer)
10253 "Put the current position or POS into the mark ring and rotate it."
10254 (interactive)
10255 (setq pos (or pos (point)))
10256 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10257 (move-marker (car org-mark-ring)
10258 (or pos (point))
10259 (or buffer (current-buffer)))
10260 (message "%s"
10261 (substitute-command-keys
10262 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10264 (defun org-mark-ring-goto (&optional n)
10265 "Jump to the previous position in the mark ring.
10266 With prefix arg N, jump back that many stored positions. When
10267 called several times in succession, walk through the entire ring.
10268 Org-mode commands jumping to a different position in the current file,
10269 or to another Org-mode file, automatically push the old position
10270 onto the ring."
10271 (interactive "p")
10272 (let (p m)
10273 (if (eq last-command this-command)
10274 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10275 (setq p org-mark-ring))
10276 (setq org-mark-ring-last-goto p)
10277 (setq m (car p))
10278 (org-pop-to-buffer-same-window (marker-buffer m))
10279 (goto-char m)
10280 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10282 (defun org-remove-angle-brackets (s)
10283 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10284 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10286 (defun org-add-angle-brackets (s)
10287 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10288 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10290 (defun org-remove-double-quotes (s)
10291 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10292 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10295 ;;; Following specific links
10297 (defun org-follow-timestamp-link ()
10298 "Open an agenda view for the time-stamp date/range at point."
10299 (cond
10300 ((org-at-date-range-p t)
10301 (let ((org-agenda-start-on-weekday)
10302 (t1 (match-string 1))
10303 (t2 (match-string 2)) tt1 tt2)
10304 (setq tt1 (time-to-days (org-time-string-to-time t1))
10305 tt2 (time-to-days (org-time-string-to-time t2)))
10306 (let ((org-agenda-buffer-tmp-name
10307 (format "*Org Agenda(a:%s)"
10308 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10309 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10310 ((org-at-timestamp-p t)
10311 (let ((org-agenda-buffer-tmp-name
10312 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10313 (org-agenda-list nil (time-to-days (org-time-string-to-time
10314 (substring (match-string 1) 0 10)))
10315 1)))
10316 (t (error "This should not happen"))))
10319 ;;; Following file links
10320 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10321 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10322 (declare-function mailcap-mime-info
10323 "mailcap" (string &optional request no-decode))
10324 (defvar org-wait nil)
10325 (defun org-open-file (path &optional in-emacs line search)
10326 "Open the file at PATH.
10327 First, this expands any special file name abbreviations. Then the
10328 configuration variable `org-file-apps' is checked if it contains an
10329 entry for this file type, and if yes, the corresponding command is launched.
10331 If no application is found, Emacs simply visits the file.
10333 With optional prefix argument IN-EMACS, Emacs will visit the file.
10334 With a double \\[universal-argument] \\[universal-argument] \
10335 prefix arg, Org tries to avoid opening in Emacs
10336 and to use an external application to visit the file.
10338 Optional LINE specifies a line to go to, optional SEARCH a string
10339 to search for. If LINE or SEARCH is given, the file will be
10340 opened in Emacs, unless an entry from org-file-apps that makes
10341 use of groups in a regexp matches.
10343 If you want to change the way frames are used when following a
10344 link, please customize `org-link-frame-setup'.
10346 If the file does not exist, an error is thrown."
10347 (let* ((file (if (equal path "")
10348 buffer-file-name
10349 (substitute-in-file-name (expand-file-name path))))
10350 (file-apps (append org-file-apps (org-default-apps)))
10351 (apps (org-remove-if
10352 'org-file-apps-entry-match-against-dlink-p file-apps))
10353 (apps-dlink (org-remove-if-not
10354 'org-file-apps-entry-match-against-dlink-p file-apps))
10355 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10356 (dirp (if remp nil (file-directory-p file)))
10357 (file (if (and dirp org-open-directory-means-index-dot-org)
10358 (concat (file-name-as-directory file) "index.org")
10359 file))
10360 (a-m-a-p (assq 'auto-mode apps))
10361 (dfile (downcase file))
10362 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10363 (link (cond ((and (eq line nil)
10364 (eq search nil))
10365 file)
10366 (line
10367 (concat file "::" (number-to-string line)))
10368 (search
10369 (concat file "::" search))))
10370 (dlink (downcase link))
10371 (old-buffer (current-buffer))
10372 (old-pos (point))
10373 (old-mode major-mode)
10374 ext cmd link-match-data)
10375 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10376 (setq ext (match-string 1 dfile))
10377 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10378 (setq ext (match-string 1 dfile))))
10379 (cond
10380 ((member in-emacs '((16) system))
10381 (setq cmd (cdr (assoc 'system apps))))
10382 (in-emacs (setq cmd 'emacs))
10384 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10385 (and dirp (cdr (assoc 'directory apps)))
10386 ; first, try matching against apps-dlink
10387 ; if we get a match here, store the match data for later
10388 (let ((match (assoc-default dlink apps-dlink
10389 'string-match)))
10390 (if match
10391 (progn (setq link-match-data (match-data))
10392 match)
10393 (progn (setq in-emacs (or in-emacs line search))
10394 nil))) ; if we have no match in apps-dlink,
10395 ; always open the file in emacs if line or search
10396 ; is given (for backwards compatibility)
10397 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10398 'string-match)
10399 (cdr (assoc ext apps))
10400 (cdr (assoc t apps))))))
10401 (when (eq cmd 'system)
10402 (setq cmd (cdr (assoc 'system apps))))
10403 (when (eq cmd 'default)
10404 (setq cmd (cdr (assoc t apps))))
10405 (when (eq cmd 'mailcap)
10406 (require 'mailcap)
10407 (mailcap-parse-mailcaps)
10408 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10409 (command (mailcap-mime-info mime-type)))
10410 (if (stringp command)
10411 (setq cmd command)
10412 (setq cmd 'emacs))))
10413 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10414 (not (file-exists-p file))
10415 (not org-open-non-existing-files))
10416 (error "No such file: %s" file))
10417 (cond
10418 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10419 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10420 (while (string-match "['\"]%s['\"]" cmd)
10421 (setq cmd (replace-match "%s" t t cmd)))
10422 (while (string-match "%s" cmd)
10423 (setq cmd (replace-match
10424 (save-match-data
10425 (shell-quote-argument
10426 (convert-standard-filename file)))
10427 t t cmd)))
10429 ;; Replace "%1", "%2" etc. in command with group matches from regex
10430 (save-match-data
10431 (let ((match-index 1)
10432 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10433 (set-match-data link-match-data)
10434 (while (<= match-index number-of-groups)
10435 (let ((regex (concat "%" (number-to-string match-index)))
10436 (replace-with (match-string match-index dlink)))
10437 (while (string-match regex cmd)
10438 (setq cmd (replace-match replace-with t t cmd))))
10439 (setq match-index (+ match-index 1)))))
10441 (save-window-excursion
10442 (start-process-shell-command cmd nil cmd)
10443 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10445 ((or (stringp cmd)
10446 (eq cmd 'emacs))
10447 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10448 (widen)
10449 (if line (org-goto-line line)
10450 (if search (org-link-search search))))
10451 ((consp cmd)
10452 (let ((file (convert-standard-filename file)))
10453 (save-match-data
10454 (set-match-data link-match-data)
10455 (eval cmd))))
10456 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10457 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10458 (or (not (equal old-buffer (current-buffer)))
10459 (not (equal old-pos (point))))
10460 (org-mark-ring-push old-pos old-buffer))))
10462 (defun org-file-apps-entry-match-against-dlink-p (entry)
10463 "This function returns non-nil if `entry' uses a regular
10464 expression which should be matched against the whole link by
10465 org-open-file.
10467 It assumes that is the case when the entry uses a regular
10468 expression which has at least one grouping construct and the
10469 action is either a lisp form or a command string containing
10470 '%1', i.e. using at least one subexpression match as a
10471 parameter."
10472 (let ((selector (car entry))
10473 (action (cdr entry)))
10474 (if (stringp selector)
10475 (and (> (regexp-opt-depth selector) 0)
10476 (or (and (stringp action)
10477 (string-match "%[0-9]" action))
10478 (consp action)))
10479 nil)))
10481 (defun org-default-apps ()
10482 "Return the default applications for this operating system."
10483 (cond
10484 ((eq system-type 'darwin)
10485 org-file-apps-defaults-macosx)
10486 ((eq system-type 'windows-nt)
10487 org-file-apps-defaults-windowsnt)
10488 (t org-file-apps-defaults-gnu)))
10490 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10491 "Convert extensions to regular expressions in the cars of LIST.
10492 Also, weed out any non-string entries, because the return value is used
10493 only for regexp matching.
10494 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10495 point to the symbol `emacs', indicating that the file should
10496 be opened in Emacs."
10497 (append
10498 (delq nil
10499 (mapcar (lambda (x)
10500 (if (not (stringp (car x)))
10502 (if (string-match "\\W" (car x))
10504 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10505 list))
10506 (if add-auto-mode
10507 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10509 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10510 (defun org-file-remote-p (file)
10511 "Test whether FILE specifies a location on a remote system.
10512 Return non-nil if the location is indeed remote.
10514 For example, the filename \"/user@host:/foo\" specifies a location
10515 on the system \"/user@host:\"."
10516 (cond ((fboundp 'file-remote-p)
10517 (file-remote-p file))
10518 ((fboundp 'tramp-handle-file-remote-p)
10519 (tramp-handle-file-remote-p file))
10520 ((and (boundp 'ange-ftp-name-format)
10521 (string-match (car ange-ftp-name-format) file))
10522 t)))
10525 ;;;; Refiling
10527 (defun org-get-org-file ()
10528 "Read a filename, with default directory `org-directory'."
10529 (let ((default (or org-default-notes-file remember-data-file)))
10530 (read-file-name (format "File name [%s]: " default)
10531 (file-name-as-directory org-directory)
10532 default)))
10534 (defun org-notes-order-reversed-p ()
10535 "Check if the current file should receive notes in reversed order."
10536 (cond
10537 ((not org-reverse-note-order) nil)
10538 ((eq t org-reverse-note-order) t)
10539 ((not (listp org-reverse-note-order)) nil)
10540 (t (catch 'exit
10541 (let ((all org-reverse-note-order)
10542 entry)
10543 (while (setq entry (pop all))
10544 (if (string-match (car entry) buffer-file-name)
10545 (throw 'exit (cdr entry))))
10546 nil)))))
10548 (defvar org-refile-target-table nil
10549 "The list of refile targets, created by `org-refile'.")
10551 (defvar org-agenda-new-buffers nil
10552 "Buffers created to visit agenda files.")
10554 (defvar org-refile-cache nil
10555 "Cache for refile targets.")
10557 (defvar org-refile-markers nil
10558 "All the markers used for caching refile locations.")
10560 (defun org-refile-marker (pos)
10561 "Get a new refile marker, but only if caching is in use."
10562 (if (not org-refile-use-cache)
10564 (let ((m (make-marker)))
10565 (move-marker m pos)
10566 (push m org-refile-markers)
10567 m)))
10569 (defun org-refile-cache-clear ()
10570 "Clear the refile cache and disable all the markers."
10571 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10572 (setq org-refile-markers nil)
10573 (setq org-refile-cache nil)
10574 (message "Refile cache has been cleared"))
10576 (defun org-refile-cache-check-set (set)
10577 "Check if all the markers in the cache still have live buffers."
10578 (let (marker)
10579 (catch 'exit
10580 (while (and set (setq marker (nth 3 (pop set))))
10581 ;; if org-refile-use-outline-path is 'file, marker may be nil
10582 (when (and marker (null (marker-buffer marker)))
10583 (message "not found") (sit-for 3)
10584 (throw 'exit nil)))
10585 t)))
10587 (defun org-refile-cache-put (set &rest identifiers)
10588 "Push the refile targets SET into the cache, under IDENTIFIERS."
10589 (let* ((key (sha1 (prin1-to-string identifiers)))
10590 (entry (assoc key org-refile-cache)))
10591 (if entry
10592 (setcdr entry set)
10593 (push (cons key set) org-refile-cache))))
10595 (defun org-refile-cache-get (&rest identifiers)
10596 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10597 (cond
10598 ((not org-refile-cache) nil)
10599 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10601 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10602 org-refile-cache))))
10603 (and set (org-refile-cache-check-set set) set)))))
10605 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10606 "Produce a table with refile targets."
10607 (let ((case-fold-search nil)
10608 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10609 (entries (or org-refile-targets '((nil . (:level . 1)))))
10610 targets tgs txt re files f desc descre fast-path-p level pos0)
10611 (message "Getting targets...")
10612 (with-current-buffer (or default-buffer (current-buffer))
10613 (while (setq entry (pop entries))
10614 (setq files (car entry) desc (cdr entry))
10615 (setq fast-path-p nil)
10616 (cond
10617 ((null files) (setq files (list (current-buffer))))
10618 ((eq files 'org-agenda-files)
10619 (setq files (org-agenda-files 'unrestricted)))
10620 ((and (symbolp files) (fboundp files))
10621 (setq files (funcall files)))
10622 ((and (symbolp files) (boundp files))
10623 (setq files (symbol-value files))))
10624 (if (stringp files) (setq files (list files)))
10625 (cond
10626 ((eq (car desc) :tag)
10627 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10628 ((eq (car desc) :todo)
10629 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10630 ((eq (car desc) :regexp)
10631 (setq descre (cdr desc)))
10632 ((eq (car desc) :level)
10633 (setq descre (concat "^\\*\\{" (number-to-string
10634 (if org-odd-levels-only
10635 (1- (* 2 (cdr desc)))
10636 (cdr desc)))
10637 "\\}[ \t]")))
10638 ((eq (car desc) :maxlevel)
10639 (setq fast-path-p t)
10640 (setq descre (concat "^\\*\\{1," (number-to-string
10641 (if org-odd-levels-only
10642 (1- (* 2 (cdr desc)))
10643 (cdr desc)))
10644 "\\}[ \t]")))
10645 (t (error "Bad refiling target description %s" desc)))
10646 (while (setq f (pop files))
10647 (with-current-buffer
10648 (if (bufferp f) f (org-get-agenda-file-buffer f))
10650 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10651 (progn
10652 (if (bufferp f) (setq f (buffer-file-name
10653 (buffer-base-buffer f))))
10654 (setq f (and f (expand-file-name f)))
10655 (if (eq org-refile-use-outline-path 'file)
10656 (push (list (file-name-nondirectory f) f nil nil) tgs))
10657 (save-excursion
10658 (save-restriction
10659 (widen)
10660 (goto-char (point-min))
10661 (while (re-search-forward descre nil t)
10662 (goto-char (setq pos0 (point-at-bol)))
10663 (catch 'next
10664 (when org-refile-target-verify-function
10665 (save-match-data
10666 (or (funcall org-refile-target-verify-function)
10667 (throw 'next t))))
10668 (when (and (looking-at org-complex-heading-regexp)
10669 (not (member (match-string 4) excluded-entries))
10670 (match-string 4))
10671 (setq level (org-reduced-level
10672 (- (match-end 1) (match-beginning 1)))
10673 txt (org-link-display-format (match-string 4))
10674 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10675 re (format org-complex-heading-regexp-format
10676 (regexp-quote (match-string 4))))
10677 (when org-refile-use-outline-path
10678 (setq txt (mapconcat
10679 'org-protect-slash
10680 (append
10681 (if (eq org-refile-use-outline-path
10682 'file)
10683 (list (file-name-nondirectory
10684 (buffer-file-name
10685 (buffer-base-buffer))))
10686 (if (eq org-refile-use-outline-path
10687 'full-file-path)
10688 (list (buffer-file-name
10689 (buffer-base-buffer)))))
10690 (org-get-outline-path fast-path-p
10691 level txt)
10692 (list txt))
10693 "/")))
10694 (push (list txt f re (org-refile-marker (point)))
10695 tgs)))
10696 (when (= (point) pos0)
10697 ;; verification function has not moved point
10698 (goto-char (point-at-eol))))))))
10699 (when org-refile-use-cache
10700 (org-refile-cache-put tgs (buffer-file-name) descre))
10701 (setq targets (append tgs targets))
10702 ))))
10703 (message "Getting targets...done")
10704 (nreverse targets)))
10706 (defun org-protect-slash (s)
10707 (while (string-match "/" s)
10708 (setq s (replace-match "\\" t t s)))
10711 (defvar org-olpa (make-vector 20 nil))
10713 (defun org-get-outline-path (&optional fastp level heading)
10714 "Return the outline path to the current entry, as a list.
10716 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10717 routine which makes outline path derivations for an entire file,
10718 avoiding backtracing. Refile target collection makes use of that."
10719 (if fastp
10720 (progn
10721 (if (> level 19)
10722 (error "Outline path failure, more than 19 levels"))
10723 (loop for i from level upto 19 do
10724 (aset org-olpa i nil))
10725 (prog1
10726 (delq nil (append org-olpa nil))
10727 (aset org-olpa level heading)))
10728 (let (rtn case-fold-search)
10729 (save-excursion
10730 (save-restriction
10731 (widen)
10732 (while (org-up-heading-safe)
10733 (when (looking-at org-complex-heading-regexp)
10734 (push (org-match-string-no-properties 4) rtn)))
10735 rtn)))))
10737 (defun org-format-outline-path (path &optional width prefix)
10738 "Format the outline path PATH for display.
10739 Width is the maximum number of characters that is available.
10740 Prefix is a prefix to be included in the returned string,
10741 such as the file name."
10742 (setq width (or width 79))
10743 (if prefix (setq width (- width (length prefix))))
10744 (if (not path)
10745 (or prefix "")
10746 (let* ((nsteps (length path))
10747 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10748 (maxwidth (if (<= total-width width)
10749 10000 ;; everything fits
10750 ;; we need to shorten the level headings
10751 (/ (- width nsteps) nsteps)))
10752 (org-odd-levels-only nil)
10753 (n 0)
10754 (total (1+ (length prefix))))
10755 (setq maxwidth (max maxwidth 10))
10756 (concat prefix
10757 (mapconcat
10758 (lambda (h)
10759 (setq n (1+ n))
10760 (if (and (= n nsteps) (< maxwidth 10000))
10761 (setq maxwidth (- total-width total)))
10762 (if (< (length h) maxwidth)
10763 (progn (setq total (+ total (length h) 1)) h)
10764 (setq h (substring h 0 (- maxwidth 2))
10765 total (+ total maxwidth 1))
10766 (if (string-match "[ \t]+\\'" h)
10767 (setq h (substring h 0 (match-beginning 0))))
10768 (setq h (concat h "..")))
10769 (org-add-props h nil 'face
10770 (nth (% (1- n) org-n-level-faces)
10771 org-level-faces))
10773 path "/")))))
10775 (defun org-display-outline-path (&optional file current)
10776 "Display the current outline path in the echo area."
10777 (interactive "P")
10778 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10779 (case-fold-search nil)
10780 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10781 (if current (setq path (append path
10782 (save-excursion
10783 (org-back-to-heading t)
10784 (if (looking-at org-complex-heading-regexp)
10785 (list (match-string 4)))))))
10786 (message "%s"
10787 (org-format-outline-path
10788 path
10789 (1- (frame-width))
10790 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10792 (defvar org-refile-history nil
10793 "History for refiling operations.")
10795 (defvar org-after-refile-insert-hook nil
10796 "Hook run after `org-refile' has inserted its stuff at the new location.
10797 Note that this is still *before* the stuff will be removed from
10798 the *old* location.")
10800 (defvar org-capture-last-stored-marker)
10801 (defun org-refile (&optional goto default-buffer rfloc)
10802 "Move the entry or entries at point to another heading.
10803 The list of target headings is compiled using the information in
10804 `org-refile-targets', which see.
10806 At the target location, the entry is filed as a subitem of the target
10807 heading. Depending on `org-reverse-note-order', the new subitem will
10808 either be the first or the last subitem.
10810 If there is an active region, all entries in that region will be moved.
10811 However, the region must fulfill the requirement that the first heading
10812 is the first one sets the top-level of the moved text - at most siblings
10813 below it are allowed.
10815 With prefix arg GOTO, the command will only visit the target location
10816 and not actually move anything.
10818 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10819 go to the location where the last refiling operation has put the subtree.
10820 With a prefix argument of `2', refile to the running clock.
10822 RFLOC can be a refile location obtained in a different way.
10824 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10826 If you are using target caching (see `org-refile-use-cache'),
10827 you have to clear the target cache in order to find new targets.
10828 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10829 prefix argument (`C-u C-u C-u C-c C-w')."
10831 (interactive "P")
10832 (if (member goto '(0 (64)))
10833 (org-refile-cache-clear)
10834 (let* ((cbuf (current-buffer))
10835 (regionp (org-region-active-p))
10836 (region-start (and regionp (region-beginning)))
10837 (region-end (and regionp (region-end)))
10838 (region-length (and regionp (- region-end region-start)))
10839 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10840 pos it nbuf file re level reversed)
10841 (setq last-command nil)
10842 (when regionp
10843 (goto-char region-start)
10844 (or (bolp) (goto-char (point-at-bol)))
10845 (setq region-start (point))
10846 (unless (or (org-kill-is-subtree-p
10847 (buffer-substring region-start region-end))
10848 (prog1 org-refile-active-region-within-subtree
10849 (org-toggle-heading)))
10850 (error "The region is not a (sequence of) subtree(s)")))
10851 (if (equal goto '(16))
10852 (org-refile-goto-last-stored)
10853 (when (or
10854 (and (equal goto 2)
10855 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10856 (prog1
10857 (setq it (list (or org-clock-heading "running clock")
10858 (buffer-file-name
10859 (marker-buffer org-clock-hd-marker))
10861 (marker-position org-clock-hd-marker)))
10862 (setq goto nil)))
10863 (setq it (or rfloc
10864 (let (heading-text)
10865 (save-excursion
10866 (unless goto
10867 (org-back-to-heading t)
10868 (setq heading-text
10869 (nth 4 (org-heading-components))))
10870 (org-refile-get-location
10871 (cond (goto "Goto")
10872 (regionp "Refile region to")
10873 (t (concat "Refile subtree \""
10874 heading-text "\" to")))
10875 default-buffer
10876 (and (not (equal '(4) goto))
10877 org-refile-allow-creating-parent-nodes)
10878 goto))))))
10879 (setq file (nth 1 it)
10880 re (nth 2 it)
10881 pos (nth 3 it))
10882 (if (and (not goto)
10884 (equal (buffer-file-name) file)
10885 (if regionp
10886 (and (>= pos region-start)
10887 (<= pos region-end))
10888 (and (>= pos (point))
10889 (< pos (save-excursion
10890 (org-end-of-subtree t t))))))
10891 (error "Cannot refile to position inside the tree or region"))
10893 (setq nbuf (or (find-buffer-visiting file)
10894 (find-file-noselect file)))
10895 (if goto
10896 (progn
10897 (org-pop-to-buffer-same-window nbuf)
10898 (goto-char pos)
10899 (org-show-context 'org-goto))
10900 (if regionp
10901 (progn
10902 (org-kill-new (buffer-substring region-start region-end))
10903 (org-save-markers-in-region region-start region-end))
10904 (org-copy-subtree 1 nil t))
10905 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10906 (find-file-noselect file)))
10907 (setq reversed (org-notes-order-reversed-p))
10908 (save-excursion
10909 (save-restriction
10910 (widen)
10911 (if pos
10912 (progn
10913 (goto-char pos)
10914 (looking-at org-outline-regexp)
10915 (setq level (org-get-valid-level (funcall outline-level) 1))
10916 (goto-char
10917 (if reversed
10918 (or (outline-next-heading) (point-max))
10919 (or (save-excursion (org-get-next-sibling))
10920 (org-end-of-subtree t t)
10921 (point-max)))))
10922 (setq level 1)
10923 (if (not reversed)
10924 (goto-char (point-max))
10925 (goto-char (point-min))
10926 (or (outline-next-heading) (goto-char (point-max)))))
10927 (if (not (bolp)) (newline))
10928 (org-paste-subtree level)
10929 (when org-log-refile
10930 (org-add-log-setup 'refile nil nil 'findpos
10931 org-log-refile)
10932 (unless (eq org-log-refile 'note)
10933 (save-excursion (org-add-log-note))))
10934 (and org-auto-align-tags
10935 (let ((org-loop-over-headlines-in-active-region nil))
10936 (org-set-tags nil t)))
10937 (with-demoted-errors
10938 (bookmark-set "org-refile-last-stored"))
10939 ;; If we are refiling for capture, make sure that the
10940 ;; last-capture pointers point here
10941 (when (org-bound-and-true-p org-refile-for-capture)
10942 (with-demoted-errors
10943 (bookmark-set "org-capture-last-stored-marker"))
10944 (move-marker org-capture-last-stored-marker (point)))
10945 (if (fboundp 'deactivate-mark) (deactivate-mark))
10946 (run-hooks 'org-after-refile-insert-hook))))
10947 (if regionp
10948 (delete-region (point) (+ (point) region-length))
10949 (org-cut-subtree))
10950 (when (featurep 'org-inlinetask)
10951 (org-inlinetask-remove-END-maybe))
10952 (setq org-markers-to-move nil)
10953 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10955 (defun org-refile-goto-last-stored ()
10956 "Go to the location where the last refile was stored."
10957 (interactive)
10958 (bookmark-jump "org-refile-last-stored")
10959 (message "This is the location of the last refile"))
10961 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10962 no-exclude)
10963 "Prompt the user for a refile location, using PROMPT.
10964 PROMPT should not be suffixed with a colon and a space, because
10965 this function appends the default value from
10966 `org-refile-history' automatically, if that is not empty.
10967 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10968 this is used for the GOTO interface."
10969 (let ((org-refile-targets org-refile-targets)
10970 (org-refile-use-outline-path org-refile-use-outline-path)
10971 excluded-entries)
10972 (when (and (derived-mode-p 'org-mode)
10973 (not org-refile-use-cache)
10974 (not no-exclude))
10975 (org-map-tree
10976 (lambda()
10977 (setq excluded-entries
10978 (append excluded-entries (list (org-get-heading t t)))))))
10979 (setq org-refile-target-table
10980 (org-refile-get-targets default-buffer excluded-entries)))
10981 (unless org-refile-target-table
10982 (error "No refile targets"))
10983 (let* ((prompt (concat prompt
10984 (and (car org-refile-history)
10985 (concat " (default " (car org-refile-history) ")"))
10986 ": "))
10987 (cbuf (current-buffer))
10988 (partial-completion-mode nil)
10989 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10990 (cfunc (if (and org-refile-use-outline-path
10991 org-outline-path-complete-in-steps)
10992 'org-olpath-completing-read
10993 'org-icompleting-read))
10994 (extra (if org-refile-use-outline-path "/" ""))
10995 (filename (and cfn (expand-file-name cfn)))
10996 (tbl (mapcar
10997 (lambda (x)
10998 (if (and (not (member org-refile-use-outline-path
10999 '(file full-file-path)))
11000 (not (equal filename (nth 1 x))))
11001 (cons (concat (car x) extra " ("
11002 (file-name-nondirectory (nth 1 x)) ")")
11003 (cdr x))
11004 (cons (concat (car x) extra) (cdr x))))
11005 org-refile-target-table))
11006 (completion-ignore-case t)
11007 pa answ parent-target child parent old-hist)
11008 (setq old-hist org-refile-history)
11009 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11010 nil 'org-refile-history (car org-refile-history)))
11011 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11012 (org-refile-check-position pa)
11013 (if pa
11014 (progn
11015 (when (or (not org-refile-history)
11016 (not (eq old-hist org-refile-history))
11017 (not (equal (car pa) (car org-refile-history))))
11018 (setq org-refile-history
11019 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11020 org-refile-history
11021 (cdr org-refile-history))))
11022 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11023 (pop org-refile-history)))
11025 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11026 (progn
11027 (setq parent (match-string 1 answ)
11028 child (match-string 2 answ))
11029 (setq parent-target (or (assoc parent tbl)
11030 (assoc (concat parent "/") tbl)))
11031 (when (and parent-target
11032 (or (eq new-nodes t)
11033 (and (eq new-nodes 'confirm)
11034 (y-or-n-p (format "Create new node \"%s\"? "
11035 child)))))
11036 (org-refile-new-child parent-target child)))
11037 (error "Invalid target location")))))
11039 (declare-function org-string-nw-p "org-macs" (s))
11040 (defun org-refile-check-position (refile-pointer)
11041 "Check if the refile pointer matches the headline to which it points."
11042 (let* ((file (nth 1 refile-pointer))
11043 (re (nth 2 refile-pointer))
11044 (pos (nth 3 refile-pointer))
11045 buffer)
11046 (if (and (not (markerp pos)) (not file))
11047 (error "Please save the buffer to a file before refiling")
11048 (when (org-string-nw-p re)
11049 (setq buffer (if (markerp pos)
11050 (marker-buffer pos)
11051 (or (find-buffer-visiting file)
11052 (find-file-noselect file))))
11053 (with-current-buffer buffer
11054 (save-excursion
11055 (save-restriction
11056 (widen)
11057 (goto-char pos)
11058 (beginning-of-line 1)
11059 (unless (org-looking-at-p re)
11060 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11062 (defun org-refile-new-child (parent-target child)
11063 "Use refile target PARENT-TARGET to add new CHILD below it."
11064 (unless parent-target
11065 (error "Cannot find parent for new node"))
11066 (let ((file (nth 1 parent-target))
11067 (pos (nth 3 parent-target))
11068 level)
11069 (with-current-buffer (or (find-buffer-visiting file)
11070 (find-file-noselect file))
11071 (save-excursion
11072 (save-restriction
11073 (widen)
11074 (if pos
11075 (goto-char pos)
11076 (goto-char (point-max))
11077 (if (not (bolp)) (newline)))
11078 (when (looking-at org-outline-regexp)
11079 (setq level (funcall outline-level))
11080 (org-end-of-subtree t t))
11081 (org-back-over-empty-lines)
11082 (insert "\n" (make-string
11083 (if pos (org-get-valid-level level 1) 1) ?*)
11084 " " child "\n")
11085 (beginning-of-line 0)
11086 (list (concat (car parent-target) "/" child) file "" (point)))))))
11088 (defun org-olpath-completing-read (prompt collection &rest args)
11089 "Read an outline path like a file name."
11090 (let ((thetable collection)
11091 (org-completion-use-ido nil) ; does not work with ido.
11092 (org-completion-use-iswitchb nil)) ; or iswitchb
11093 (apply
11094 'org-icompleting-read prompt
11095 (lambda (string predicate &optional flag)
11096 (let (rtn r f (l (length string)))
11097 (cond
11098 ((eq flag nil)
11099 ;; try completion
11100 (try-completion string thetable))
11101 ((eq flag t)
11102 ;; all-completions
11103 (setq rtn (all-completions string thetable predicate))
11104 (mapcar
11105 (lambda (x)
11106 (setq r (substring x l))
11107 (if (string-match " ([^)]*)$" x)
11108 (setq f (match-string 0 x))
11109 (setq f ""))
11110 (if (string-match "/" r)
11111 (concat string (substring r 0 (match-end 0)) f)
11113 rtn))
11114 ((eq flag 'lambda)
11115 ;; exact match?
11116 (assoc string thetable)))))
11117 args)))
11119 ;;;; Dynamic blocks
11121 (defun org-find-dblock (name)
11122 "Find the first dynamic block with name NAME in the buffer.
11123 If not found, stay at current position and return nil."
11124 (let ((case-fold-search t) pos)
11125 (save-excursion
11126 (goto-char (point-min))
11127 (setq pos (and (re-search-forward
11128 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11129 (match-beginning 0))))
11130 (if pos (goto-char pos))
11131 pos))
11133 (defconst org-dblock-start-re
11134 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11135 "Matches the start line of a dynamic block, with parameters.")
11137 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11138 "Matches the end of a dynamic block.")
11140 (defun org-create-dblock (plist)
11141 "Create a dynamic block section, with parameters taken from PLIST.
11142 PLIST must contain a :name entry which is used as name of the block."
11143 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11144 (end-of-line 1)
11145 (newline))
11146 (let ((col (current-column))
11147 (name (plist-get plist :name)))
11148 (insert "#+BEGIN: " name)
11149 (while plist
11150 (if (eq (car plist) :name)
11151 (setq plist (cddr plist))
11152 (insert " " (prin1-to-string (pop plist)))))
11153 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11154 (beginning-of-line -2)))
11156 (defun org-prepare-dblock ()
11157 "Prepare dynamic block for refresh.
11158 This empties the block, puts the cursor at the insert position and returns
11159 the property list including an extra property :name with the block name."
11160 (unless (looking-at org-dblock-start-re)
11161 (error "Not at a dynamic block"))
11162 (let* ((begdel (1+ (match-end 0)))
11163 (name (org-no-properties (match-string 1)))
11164 (params (append (list :name name)
11165 (read (concat "(" (match-string 3) ")")))))
11166 (save-excursion
11167 (beginning-of-line 1)
11168 (skip-chars-forward " \t")
11169 (setq params (plist-put params :indentation-column (current-column))))
11170 (unless (re-search-forward org-dblock-end-re nil t)
11171 (error "Dynamic block not terminated"))
11172 (setq params
11173 (append params
11174 (list :content (buffer-substring
11175 begdel (match-beginning 0)))))
11176 (delete-region begdel (match-beginning 0))
11177 (goto-char begdel)
11178 (open-line 1)
11179 params))
11181 (defun org-map-dblocks (&optional command)
11182 "Apply COMMAND to all dynamic blocks in the current buffer.
11183 If COMMAND is not given, use `org-update-dblock'."
11184 (let ((cmd (or command 'org-update-dblock)))
11185 (save-excursion
11186 (goto-char (point-min))
11187 (while (re-search-forward org-dblock-start-re nil t)
11188 (goto-char (match-beginning 0))
11189 (save-excursion
11190 (condition-case nil
11191 (funcall cmd)
11192 (error (message "Error during update of dynamic block"))))
11193 (unless (re-search-forward org-dblock-end-re nil t)
11194 (error "Dynamic block not terminated"))))))
11196 (defun org-dblock-update (&optional arg)
11197 "User command for updating dynamic blocks.
11198 Update the dynamic block at point. With prefix ARG, update all dynamic
11199 blocks in the buffer."
11200 (interactive "P")
11201 (if arg
11202 (org-update-all-dblocks)
11203 (or (looking-at org-dblock-start-re)
11204 (org-beginning-of-dblock))
11205 (org-update-dblock)))
11207 (defun org-update-dblock ()
11208 "Update the dynamic block at point.
11209 This means to empty the block, parse for parameters and then call
11210 the correct writing function."
11211 (interactive)
11212 (save-window-excursion
11213 (let* ((pos (point))
11214 (line (org-current-line))
11215 (params (org-prepare-dblock))
11216 (name (plist-get params :name))
11217 (indent (plist-get params :indentation-column))
11218 (cmd (intern (concat "org-dblock-write:" name))))
11219 (message "Updating dynamic block `%s' at line %d..." name line)
11220 (funcall cmd params)
11221 (message "Updating dynamic block `%s' at line %d...done" name line)
11222 (goto-char pos)
11223 (when (and indent (> indent 0))
11224 (setq indent (make-string indent ?\ ))
11225 (save-excursion
11226 (org-beginning-of-dblock)
11227 (forward-line 1)
11228 (while (not (looking-at org-dblock-end-re))
11229 (insert indent)
11230 (beginning-of-line 2))
11231 (when (looking-at org-dblock-end-re)
11232 (and (looking-at "[ \t]+")
11233 (replace-match ""))
11234 (insert indent)))))))
11236 (defun org-beginning-of-dblock ()
11237 "Find the beginning of the dynamic block at point.
11238 Error if there is no such block at point."
11239 (let ((pos (point))
11240 beg)
11241 (end-of-line 1)
11242 (if (and (re-search-backward org-dblock-start-re nil t)
11243 (setq beg (match-beginning 0))
11244 (re-search-forward org-dblock-end-re nil t)
11245 (> (match-end 0) pos))
11246 (goto-char beg)
11247 (goto-char pos)
11248 (error "Not in a dynamic block"))))
11250 (defun org-update-all-dblocks ()
11251 "Update all dynamic blocks in the buffer.
11252 This function can be used in a hook."
11253 (interactive)
11254 (when (derived-mode-p 'org-mode)
11255 (org-map-dblocks 'org-update-dblock)))
11258 ;;;; Completion
11260 (defconst org-additional-option-like-keywords
11261 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11262 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11263 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11264 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11265 "BEGIN:" "END:"
11266 "ORGTBL" "TBLFM:" "TBLNAME:"
11267 "BEGIN_EXAMPLE" "END_EXAMPLE"
11268 "BEGIN_VERBATIM" "END_VERBATIM"
11269 "BEGIN_QUOTE" "END_QUOTE"
11270 "BEGIN_VERSE" "END_VERSE"
11271 "BEGIN_CENTER" "END_CENTER"
11272 "BEGIN_SRC" "END_SRC"
11273 "BEGIN_RESULT" "END_RESULT"
11274 "BEGIN_lstlisting" "END_lstlisting"
11275 "NAME:" "RESULTS:"
11276 "HEADER:" "HEADERS:"
11277 "COLUMNS:" "PROPERTY:"
11278 "CAPTION:" "LABEL:"
11279 "SETUPFILE:"
11280 "INCLUDE:" "INDEX:"
11281 "BIND:"
11282 "MACRO:"))
11284 (defconst org-options-keywords
11285 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11286 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11287 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11288 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11289 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11290 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11291 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11293 (defconst org-additional-option-like-keywords-for-flyspell
11294 (delete-dups
11295 (split-string
11296 (mapconcat (lambda(k)
11297 (replace-regexp-in-string
11298 "_\\|:" " "
11299 (concat k " " (downcase k) " " (upcase k))))
11300 (append org-options-keywords org-additional-option-like-keywords)
11301 " ")
11302 " +" t)))
11304 (defcustom org-structure-template-alist
11305 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11306 "<src lang=\"?\">\n\n</src>")
11307 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11308 "<example>\n?\n</example>")
11309 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11310 "<quote>\n?\n</quote>")
11311 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11312 "<verse>\n?\n</verse>")
11313 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11314 "<verbatim>\n?\n</verbatim>")
11315 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11316 "<center>\n?\n</center>")
11317 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11318 "<literal style=\"latex\">\n?\n</literal>")
11319 ("L" "#+LaTeX: "
11320 "<literal style=\"latex\">?</literal>")
11321 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11322 "<literal style=\"html\">\n?\n</literal>")
11323 ("H" "#+HTML: "
11324 "<literal style=\"html\">?</literal>")
11325 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11326 ("A" "#+ASCII: ")
11327 ("i" "#+INDEX: ?"
11328 "#+INDEX: ?")
11329 ("I" "#+INCLUDE: %file ?"
11330 "<include file=%file markup=\"?\">"))
11331 "Structure completion elements.
11332 This is a list of abbreviation keys and values. The value gets inserted
11333 if you type `<' followed by the key and then press the completion key,
11334 usually `M-TAB'. %file will be replaced by a file name after prompting
11335 for the file using completion. The cursor will be placed at the position
11336 of the `?` in the template.
11337 There are two templates for each key, the first uses the original Org syntax,
11338 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11339 the default when the /org-mtags.el/ module has been loaded. See also the
11340 variable `org-mtags-prefer-muse-templates'."
11341 :group 'org-completion
11342 :type '(repeat
11343 (string :tag "Key")
11344 (string :tag "Template")
11345 (string :tag "Muse Template")))
11347 (defun org-try-structure-completion ()
11348 "Try to complete a structure template before point.
11349 This looks for strings like \"<e\" on an otherwise empty line and
11350 expands them."
11351 (let ((l (buffer-substring (point-at-bol) (point)))
11353 (when (and (looking-at "[ \t]*$")
11354 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11355 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11356 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11357 (match-beginning 1)) a)
11358 t)))
11360 (defun org-complete-expand-structure-template (start cell)
11361 "Expand a structure template."
11362 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11363 (rpl (nth (if musep 2 1) cell))
11364 (ind ""))
11365 (delete-region start (point))
11366 (when (string-match "\\`#\\+" rpl)
11367 (cond
11368 ((bolp))
11369 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11370 (setq ind (buffer-substring (point-at-bol) (point))))
11371 (t (newline))))
11372 (setq start (point))
11373 (if (string-match "%file" rpl)
11374 (setq rpl (replace-match
11375 (concat
11376 "\""
11377 (save-match-data
11378 (abbreviate-file-name (read-file-name "Include file: ")))
11379 "\"")
11380 t t rpl)))
11381 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11382 (concat "\n" ind)))
11383 (insert rpl)
11384 (if (re-search-backward "\\?" start t) (delete-char 1))))
11386 ;;;; TODO, DEADLINE, Comments
11388 (defun org-toggle-comment ()
11389 "Change the COMMENT state of an entry."
11390 (interactive)
11391 (save-excursion
11392 (org-back-to-heading)
11393 (let (case-fold-search)
11394 (cond
11395 ((looking-at (format org-heading-keyword-regexp-format
11396 org-comment-string))
11397 (goto-char (match-end 1))
11398 (looking-at (concat " +" org-comment-string))
11399 (replace-match "" t t)
11400 (when (eolp) (insert " ")))
11401 ((looking-at org-outline-regexp)
11402 (goto-char (match-end 0))
11403 (insert org-comment-string " "))))))
11405 (defvar org-last-todo-state-is-todo nil
11406 "This is non-nil when the last TODO state change led to a TODO state.
11407 If the last change removed the TODO tag or switched to DONE, then
11408 this is nil.")
11410 (defvar org-setting-tags nil) ; dynamically skipped
11412 (defvar org-todo-setup-filter-hook nil
11413 "Hook for functions that pre-filter todo specs.
11414 Each function takes a todo spec and returns either nil or the spec
11415 transformed into canonical form." )
11417 (defvar org-todo-get-default-hook nil
11418 "Hook for functions that get a default item for todo.
11419 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11420 nil or a string to be used for the todo mark." )
11422 (defvar org-agenda-headline-snapshot-before-repeat)
11424 (defun org-current-effective-time ()
11425 "Return current time adjusted for `org-extend-today-until' variable."
11426 (let* ((ct (org-current-time))
11427 (dct (decode-time ct))
11428 (ct1
11429 (if (and org-use-effective-time
11430 (< (nth 2 dct) org-extend-today-until))
11431 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11432 ct)))
11433 ct1))
11435 (defun org-todo-yesterday (&optional arg)
11436 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11437 (interactive "P")
11438 (if (eq major-mode 'org-agenda-mode)
11439 (apply 'org-agenda-todo-yesterday arg)
11440 (let* ((hour (third (decode-time
11441 (org-current-time))))
11442 (org-extend-today-until (1+ hour)))
11443 (org-todo arg))))
11445 (defun org-todo (&optional arg)
11446 "Change the TODO state of an item.
11447 The state of an item is given by a keyword at the start of the heading,
11448 like
11449 *** TODO Write paper
11450 *** DONE Call mom
11452 The different keywords are specified in the variable `org-todo-keywords'.
11453 By default the available states are \"TODO\" and \"DONE\".
11454 So for this example: when the item starts with TODO, it is changed to DONE.
11455 When it starts with DONE, the DONE is removed. And when neither TODO nor
11456 DONE are present, add TODO at the beginning of the heading.
11458 With \\[universal-argument] prefix arg, use completion to determine the new \
11459 state.
11460 With numeric prefix arg, switch to that state.
11461 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11462 keywords (nextset).
11463 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11464 With a numeric prefix arg of 0, inhibit note taking for the change.
11466 For calling through lisp, arg is also interpreted in the following way:
11467 'none -> empty state
11468 \"\"(empty string) -> switch to empty state
11469 'done -> switch to DONE
11470 'nextset -> switch to the next set of keywords
11471 'previousset -> switch to the previous set of keywords
11472 \"WAITING\" -> switch to the specified keyword, but only if it
11473 really is a member of `org-todo-keywords'."
11474 (interactive "P")
11475 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11476 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11477 'region-start-level 'region))
11478 org-loop-over-headlines-in-active-region)
11479 (org-map-entries
11480 `(org-todo ,arg)
11481 org-loop-over-headlines-in-active-region
11482 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11483 (if (equal arg '(16)) (setq arg 'nextset))
11484 (let ((org-blocker-hook org-blocker-hook)
11485 commentp
11486 case-fold-search)
11487 (when (equal arg '(64))
11488 (setq arg nil org-blocker-hook nil))
11489 (when (and org-blocker-hook
11490 (or org-inhibit-blocking
11491 (org-entry-get nil "NOBLOCKING")))
11492 (setq org-blocker-hook nil))
11493 (save-excursion
11494 (catch 'exit
11495 (org-back-to-heading t)
11496 (when (looking-at (concat "^\\*+ " org-comment-string))
11497 (org-toggle-comment)
11498 (setq commentp t))
11499 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11500 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11501 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11502 (let* ((match-data (match-data))
11503 (startpos (point-at-bol))
11504 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11505 (org-log-done org-log-done)
11506 (org-log-repeat org-log-repeat)
11507 (org-todo-log-states org-todo-log-states)
11508 (org-inhibit-logging
11509 (if (equal arg 0)
11510 (progn (setq arg nil) 'note) org-inhibit-logging))
11511 (this (match-string 1))
11512 (hl-pos (match-beginning 0))
11513 (head (org-get-todo-sequence-head this))
11514 (ass (assoc head org-todo-kwd-alist))
11515 (interpret (nth 1 ass))
11516 (done-word (nth 3 ass))
11517 (final-done-word (nth 4 ass))
11518 (org-last-state (or this ""))
11519 (completion-ignore-case t)
11520 (member (member this org-todo-keywords-1))
11521 (tail (cdr member))
11522 (org-state (cond
11523 ((and org-todo-key-trigger
11524 (or (and (equal arg '(4))
11525 (eq org-use-fast-todo-selection 'prefix))
11526 (and (not arg) org-use-fast-todo-selection
11527 (not (eq org-use-fast-todo-selection
11528 'prefix)))))
11529 ;; Use fast selection
11530 (org-fast-todo-selection))
11531 ((and (equal arg '(4))
11532 (or (not org-use-fast-todo-selection)
11533 (not org-todo-key-trigger)))
11534 ;; Read a state with completion
11535 (org-icompleting-read
11536 "State: " (mapcar (lambda(x) (list x))
11537 org-todo-keywords-1)
11538 nil t))
11539 ((eq arg 'right)
11540 (if this
11541 (if tail (car tail) nil)
11542 (car org-todo-keywords-1)))
11543 ((eq arg 'left)
11544 (if (equal member org-todo-keywords-1)
11546 (if this
11547 (nth (- (length org-todo-keywords-1)
11548 (length tail) 2)
11549 org-todo-keywords-1)
11550 (org-last org-todo-keywords-1))))
11551 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11552 (setq arg nil))) ; hack to fall back to cycling
11553 (arg
11554 ;; user or caller requests a specific state
11555 (cond
11556 ((equal arg "") nil)
11557 ((eq arg 'none) nil)
11558 ((eq arg 'done) (or done-word (car org-done-keywords)))
11559 ((eq arg 'nextset)
11560 (or (car (cdr (member head org-todo-heads)))
11561 (car org-todo-heads)))
11562 ((eq arg 'previousset)
11563 (let ((org-todo-heads (reverse org-todo-heads)))
11564 (or (car (cdr (member head org-todo-heads)))
11565 (car org-todo-heads))))
11566 ((car (member arg org-todo-keywords-1)))
11567 ((stringp arg)
11568 (error "State `%s' not valid in this file" arg))
11569 ((nth (1- (prefix-numeric-value arg))
11570 org-todo-keywords-1))))
11571 ((null member) (or head (car org-todo-keywords-1)))
11572 ((equal this final-done-word) nil) ;; -> make empty
11573 ((null tail) nil) ;; -> first entry
11574 ((memq interpret '(type priority))
11575 (if (eq this-command last-command)
11576 (car tail)
11577 (if (> (length tail) 0)
11578 (or done-word (car org-done-keywords))
11579 nil)))
11581 (car tail))))
11582 (org-state (or
11583 (run-hook-with-args-until-success
11584 'org-todo-get-default-hook org-state org-last-state)
11585 org-state))
11586 (next (if org-state (concat " " org-state " ") " "))
11587 (change-plist (list :type 'todo-state-change :from this :to org-state
11588 :position startpos))
11589 dolog now-done-p)
11590 (when org-blocker-hook
11591 (setq org-last-todo-state-is-todo
11592 (not (member this org-done-keywords)))
11593 (unless (save-excursion
11594 (save-match-data
11595 (org-with-wide-buffer
11596 (run-hook-with-args-until-failure
11597 'org-blocker-hook change-plist))))
11598 (if (org-called-interactively-p 'interactive)
11599 (error "TODO state change from %s to %s blocked" this org-state)
11600 ;; fail silently
11601 (message "TODO state change from %s to %s blocked" this org-state)
11602 (throw 'exit nil))))
11603 (store-match-data match-data)
11604 (replace-match next t t)
11605 (unless (pos-visible-in-window-p hl-pos)
11606 (message "TODO state changed to %s" (org-trim next)))
11607 (unless head
11608 (setq head (org-get-todo-sequence-head org-state)
11609 ass (assoc head org-todo-kwd-alist)
11610 interpret (nth 1 ass)
11611 done-word (nth 3 ass)
11612 final-done-word (nth 4 ass)))
11613 (when (memq arg '(nextset previousset))
11614 (message "Keyword-Set %d/%d: %s"
11615 (- (length org-todo-sets) -1
11616 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11617 (length org-todo-sets)
11618 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11619 (setq org-last-todo-state-is-todo
11620 (not (member org-state org-done-keywords)))
11621 (setq now-done-p (and (member org-state org-done-keywords)
11622 (not (member this org-done-keywords))))
11623 (and logging (org-local-logging logging))
11624 (when (and (or org-todo-log-states org-log-done)
11625 (not (eq org-inhibit-logging t))
11626 (not (memq arg '(nextset previousset))))
11627 ;; we need to look at recording a time and note
11628 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11629 (nth 2 (assoc this org-todo-log-states))))
11630 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11631 (setq dolog 'time))
11632 (when (and org-state
11633 (member org-state org-not-done-keywords)
11634 (not (member this org-not-done-keywords)))
11635 ;; This is now a todo state and was not one before
11636 ;; If there was a CLOSED time stamp, get rid of it.
11637 (org-add-planning-info nil nil 'closed))
11638 (when (and now-done-p org-log-done)
11639 ;; It is now done, and it was not done before
11640 (org-add-planning-info 'closed (org-current-effective-time))
11641 (if (and (not dolog) (eq 'note org-log-done))
11642 (org-add-log-setup 'done org-state this 'findpos 'note)))
11643 (when (and org-state dolog)
11644 ;; This is a non-nil state, and we need to log it
11645 (org-add-log-setup 'state org-state this 'findpos dolog)))
11646 ;; Fixup tag positioning
11647 (org-todo-trigger-tag-changes org-state)
11648 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11649 (when org-provide-todo-statistics
11650 (org-update-parent-todo-statistics))
11651 (run-hooks 'org-after-todo-state-change-hook)
11652 (if (and arg (not (member org-state org-done-keywords)))
11653 (setq head (org-get-todo-sequence-head org-state)))
11654 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11655 ;; Do we need to trigger a repeat?
11656 (when now-done-p
11657 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11658 ;; This is for the agenda, take a snapshot of the headline.
11659 (save-match-data
11660 (setq org-agenda-headline-snapshot-before-repeat
11661 (org-get-heading))))
11662 (org-auto-repeat-maybe org-state))
11663 ;; Fixup cursor location if close to the keyword
11664 (if (and (outline-on-heading-p)
11665 (not (bolp))
11666 (save-excursion (beginning-of-line 1)
11667 (looking-at org-todo-line-regexp))
11668 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11669 (progn
11670 (goto-char (or (match-end 2) (match-end 1)))
11671 (and (looking-at " ") (just-one-space))))
11672 (when org-trigger-hook
11673 (save-excursion
11674 (run-hook-with-args 'org-trigger-hook change-plist)))
11675 (when commentp (org-toggle-comment))))))))
11677 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11678 "Block turning an entry into a TODO, using the hierarchy.
11679 This checks whether the current task should be blocked from state
11680 changes. Such blocking occurs when:
11682 1. The task has children which are not all in a completed state.
11684 2. A task has a parent with the property :ORDERED:, and there
11685 are siblings prior to the current task with incomplete
11686 status.
11688 3. The parent of the task is blocked because it has siblings that should
11689 be done first, or is child of a block grandparent TODO entry."
11691 (if (not org-enforce-todo-dependencies)
11692 t ; if locally turned off don't block
11693 (catch 'dont-block
11694 ;; If this is not a todo state change, or if this entry is already DONE,
11695 ;; do not block
11696 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11697 (member (plist-get change-plist :from)
11698 (cons 'done org-done-keywords))
11699 (member (plist-get change-plist :to)
11700 (cons 'todo org-not-done-keywords))
11701 (not (plist-get change-plist :to)))
11702 (throw 'dont-block t))
11703 ;; If this task has children, and any are undone, it's blocked
11704 (save-excursion
11705 (org-back-to-heading t)
11706 (let ((this-level (funcall outline-level)))
11707 (outline-next-heading)
11708 (let ((child-level (funcall outline-level)))
11709 (while (and (not (eobp))
11710 (> child-level this-level))
11711 ;; this todo has children, check whether they are all
11712 ;; completed
11713 (if (and (not (org-entry-is-done-p))
11714 (org-entry-is-todo-p))
11715 (throw 'dont-block nil))
11716 (outline-next-heading)
11717 (setq child-level (funcall outline-level))))))
11718 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11719 ;; any previous siblings are undone, it's blocked
11720 (save-excursion
11721 (org-back-to-heading t)
11722 (let* ((pos (point))
11723 (parent-pos (and (org-up-heading-safe) (point))))
11724 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11725 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11726 (forward-line 1)
11727 (re-search-forward org-not-done-heading-regexp pos t))
11728 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11729 ;; Search further up the hierarchy, to see if an ancestor is blocked
11730 (while t
11731 (goto-char parent-pos)
11732 (if (not (looking-at org-not-done-heading-regexp))
11733 (throw 'dont-block t)) ; do not block, parent is not a TODO
11734 (setq pos (point))
11735 (setq parent-pos (and (org-up-heading-safe) (point)))
11736 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11737 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11738 (forward-line 1)
11739 (re-search-forward org-not-done-heading-regexp pos t))
11740 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11742 (defcustom org-track-ordered-property-with-tag nil
11743 "Should the ORDERED property also be shown as a tag?
11744 The ORDERED property decides if an entry should require subtasks to be
11745 completed in sequence. Since a property is not very visible, setting
11746 this option means that toggling the ORDERED property with the command
11747 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11748 not relevant for the behavior, but it makes things more visible.
11750 Note that toggling the tag with tags commands will not change the property
11751 and therefore not influence behavior!
11753 This can be t, meaning the tag ORDERED should be used, It can also be a
11754 string to select a different tag for this task."
11755 :group 'org-todo
11756 :type '(choice
11757 (const :tag "No tracking" nil)
11758 (const :tag "Track with ORDERED tag" t)
11759 (string :tag "Use other tag")))
11761 (defun org-toggle-ordered-property ()
11762 "Toggle the ORDERED property of the current entry.
11763 For better visibility, you can track the value of this property with a tag.
11764 See variable `org-track-ordered-property-with-tag'."
11765 (interactive)
11766 (let* ((t1 org-track-ordered-property-with-tag)
11767 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11768 (save-excursion
11769 (org-back-to-heading)
11770 (if (org-entry-get nil "ORDERED")
11771 (progn
11772 (org-delete-property "ORDERED")
11773 (and tag (org-toggle-tag tag 'off))
11774 (message "Subtasks can be completed in arbitrary order"))
11775 (org-entry-put nil "ORDERED" "t")
11776 (and tag (org-toggle-tag tag 'on))
11777 (message "Subtasks must be completed in sequence")))))
11779 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11780 (defun org-block-todo-from-checkboxes (change-plist)
11781 "Block turning an entry into a TODO, using checkboxes.
11782 This checks whether the current task should be blocked from state
11783 changes because there are unchecked boxes in this entry."
11784 (if (not org-enforce-todo-checkbox-dependencies)
11785 t ; if locally turned off don't block
11786 (catch 'dont-block
11787 ;; If this is not a todo state change, or if this entry is already DONE,
11788 ;; do not block
11789 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11790 (member (plist-get change-plist :from)
11791 (cons 'done org-done-keywords))
11792 (member (plist-get change-plist :to)
11793 (cons 'todo org-not-done-keywords))
11794 (not (plist-get change-plist :to)))
11795 (throw 'dont-block t))
11796 ;; If this task has checkboxes that are not checked, it's blocked
11797 (save-excursion
11798 (org-back-to-heading t)
11799 (let ((beg (point)) end)
11800 (outline-next-heading)
11801 (setq end (point))
11802 (goto-char beg)
11803 (if (org-list-search-forward
11804 (concat (org-item-beginning-re)
11805 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11806 "\\[[- ]\\]")
11807 end t)
11808 (progn
11809 (if (boundp 'org-blocked-by-checkboxes)
11810 (setq org-blocked-by-checkboxes t))
11811 (throw 'dont-block nil)))))
11812 t))) ; do not block
11814 (defun org-entry-blocked-p ()
11815 "Is the current entry blocked?"
11816 (org-with-buffer-modified-unmodified
11817 (if (org-entry-get nil "NOBLOCKING")
11818 nil ;; Never block this entry
11819 (not
11820 (run-hook-with-args-until-failure
11821 'org-blocker-hook
11822 (list :type 'todo-state-change
11823 :position (point)
11824 :from 'todo
11825 :to 'done))))))
11827 (defun org-update-statistics-cookies (all)
11828 "Update the statistics cookie, either from TODO or from checkboxes.
11829 This should be called with the cursor in a line with a statistics cookie."
11830 (interactive "P")
11831 (if all
11832 (progn
11833 (org-update-checkbox-count 'all)
11834 (org-map-entries 'org-update-parent-todo-statistics))
11835 (if (not (org-at-heading-p))
11836 (org-update-checkbox-count)
11837 (let ((pos (point-marker))
11838 end l1 l2)
11839 (ignore-errors (org-back-to-heading t))
11840 (if (not (org-at-heading-p))
11841 (org-update-checkbox-count)
11842 (setq l1 (org-outline-level))
11843 (setq end (save-excursion
11844 (outline-next-heading)
11845 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11846 (point)))
11847 (if (and (save-excursion
11848 (re-search-forward
11849 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11850 (not (save-excursion (re-search-forward
11851 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11852 (org-update-checkbox-count)
11853 (if (and l2 (> l2 l1))
11854 (progn
11855 (goto-char end)
11856 (org-update-parent-todo-statistics))
11857 (goto-char pos)
11858 (beginning-of-line 1)
11859 (while (re-search-forward
11860 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11861 (point-at-eol) t)
11862 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11863 (goto-char pos)
11864 (move-marker pos nil)))))
11866 (defvar org-entry-property-inherited-from) ;; defined below
11867 (defun org-update-parent-todo-statistics ()
11868 "Update any statistics cookie in the parent of the current headline.
11869 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11870 the entire subtree and this will travel up the hierarchy and update
11871 statistics everywhere."
11872 (let* ((prop (save-excursion (org-up-heading-safe)
11873 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11874 (recursive (or (not org-hierarchical-todo-statistics)
11875 (and prop (string-match "\\<recursive\\>" prop))))
11876 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11878 (first t)
11879 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11880 level ltoggle l1 new ndel
11881 (cnt-all 0) (cnt-done 0) is-percent kwd
11882 checkbox-beg ov ovs ove cookie-present)
11883 (catch 'exit
11884 (save-excursion
11885 (beginning-of-line 1)
11886 (setq ltoggle (funcall outline-level))
11887 ;; Three situations are to consider:
11889 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11890 ;; to the top-level ancestor on the headline;
11892 ;; 2. If parent has "recursive" property, repeat up to the
11893 ;; headline setting that property, taking inheritance into
11894 ;; account;
11896 ;; 3. Else, move up to direct parent and proceed only once.
11897 (while (and (setq level (org-up-heading-safe))
11898 (or recursive first)
11899 (>= (point) lim))
11900 (setq first nil cookie-present nil)
11901 (unless (and level
11902 (not (string-match
11903 "\\<checkbox\\>"
11904 (downcase (or (org-entry-get nil "COOKIE_DATA")
11905 "")))))
11906 (throw 'exit nil))
11907 (while (re-search-forward box-re (point-at-eol) t)
11908 (setq cnt-all 0 cnt-done 0 cookie-present t)
11909 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11910 (save-match-data
11911 (unless (outline-next-heading) (throw 'exit nil))
11912 (while (and (looking-at org-complex-heading-regexp)
11913 (> (setq l1 (length (match-string 1))) level))
11914 (setq kwd (and (or recursive (= l1 ltoggle))
11915 (match-string 2)))
11916 (if (or (eq org-provide-todo-statistics 'all-headlines)
11917 (and (listp org-provide-todo-statistics)
11918 (or (member kwd org-provide-todo-statistics)
11919 (member kwd org-done-keywords))))
11920 (setq cnt-all (1+ cnt-all))
11921 (if (eq org-provide-todo-statistics t)
11922 (and kwd (setq cnt-all (1+ cnt-all)))))
11923 (and (member kwd org-done-keywords)
11924 (setq cnt-done (1+ cnt-done)))
11925 (outline-next-heading)))
11926 (setq new
11927 (if is-percent
11928 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11929 (format "[%d/%d]" cnt-done cnt-all))
11930 ndel (- (match-end 0) checkbox-beg))
11931 ;; handle overlays when updating cookie from column view
11932 (when (setq ov (car (overlays-at checkbox-beg)))
11933 (setq ovs (overlay-start ov) ove (overlay-end ov))
11934 (delete-overlay ov))
11935 (goto-char checkbox-beg)
11936 (insert new)
11937 (delete-region (point) (+ (point) ndel))
11938 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11939 (when ov (move-overlay ov ovs ove)))
11940 (when cookie-present
11941 (run-hook-with-args 'org-after-todo-statistics-hook
11942 cnt-done (- cnt-all cnt-done))))))
11943 (run-hooks 'org-todo-statistics-hook)))
11945 (defvar org-after-todo-statistics-hook nil
11946 "Hook that is called after a TODO statistics cookie has been updated.
11947 Each function is called with two arguments: the number of not-done entries
11948 and the number of done entries.
11950 For example, the following function, when added to this hook, will switch
11951 an entry to DONE when all children are done, and back to TODO when new
11952 entries are set to a TODO status. Note that this hook is only called
11953 when there is a statistics cookie in the headline!
11955 (defun org-summary-todo (n-done n-not-done)
11956 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11957 (let (org-log-done org-log-states) ; turn off logging
11958 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11961 (defvar org-todo-statistics-hook nil
11962 "Hook that is run whenever Org thinks TODO statistics should be updated.
11963 This hook runs even if there is no statistics cookie present, in which case
11964 `org-after-todo-statistics-hook' would not run.")
11966 (defun org-todo-trigger-tag-changes (state)
11967 "Apply the changes defined in `org-todo-state-tags-triggers'."
11968 (let ((l org-todo-state-tags-triggers)
11969 changes)
11970 (when (or (not state) (equal state ""))
11971 (setq changes (append changes (cdr (assoc "" l)))))
11972 (when (and (stringp state) (> (length state) 0))
11973 (setq changes (append changes (cdr (assoc state l)))))
11974 (when (member state org-not-done-keywords)
11975 (setq changes (append changes (cdr (assoc 'todo l)))))
11976 (when (member state org-done-keywords)
11977 (setq changes (append changes (cdr (assoc 'done l)))))
11978 (dolist (c changes)
11979 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11981 (defun org-local-logging (value)
11982 "Get logging settings from a property VALUE."
11983 (let* (words w a)
11984 ;; directly set the variables, they are already local.
11985 (setq org-log-done nil
11986 org-log-repeat nil
11987 org-todo-log-states nil)
11988 (setq words (org-split-string value))
11989 (while (setq w (pop words))
11990 (cond
11991 ((setq a (assoc w org-startup-options))
11992 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11993 (set (nth 1 a) (nth 2 a))))
11994 ((setq a (org-extract-log-state-settings w))
11995 (and (member (car a) org-todo-keywords-1)
11996 (push a org-todo-log-states)))))))
11998 (defun org-get-todo-sequence-head (kwd)
11999 "Return the head of the TODO sequence to which KWD belongs.
12000 If KWD is not set, check if there is a text property remembering the
12001 right sequence."
12002 (let (p)
12003 (cond
12004 ((not kwd)
12005 (or (get-text-property (point-at-bol) 'org-todo-head)
12006 (progn
12007 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12008 nil (point-at-eol)))
12009 (get-text-property p 'org-todo-head))))
12010 ((not (member kwd org-todo-keywords-1))
12011 (car org-todo-keywords-1))
12012 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12014 (defun org-fast-todo-selection ()
12015 "Fast TODO keyword selection with single keys.
12016 Returns the new TODO keyword, or nil if no state change should occur."
12017 (let* ((fulltable org-todo-key-alist)
12018 (done-keywords org-done-keywords) ;; needed for the faces.
12019 (maxlen (apply 'max (mapcar
12020 (lambda (x)
12021 (if (stringp (car x)) (string-width (car x)) 0))
12022 fulltable)))
12023 (expert nil)
12024 (fwidth (+ maxlen 3 1 3))
12025 (ncol (/ (- (window-width) 4) fwidth))
12026 tg cnt e c tbl
12027 groups ingroup)
12028 (save-excursion
12029 (save-window-excursion
12030 (if expert
12031 (set-buffer (get-buffer-create " *Org todo*"))
12032 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12033 (erase-buffer)
12034 (org-set-local 'org-done-keywords done-keywords)
12035 (setq tbl fulltable cnt 0)
12036 (while (setq e (pop tbl))
12037 (cond
12038 ((equal e '(:startgroup))
12039 (push '() groups) (setq ingroup t)
12040 (when (not (= cnt 0))
12041 (setq cnt 0)
12042 (insert "\n"))
12043 (insert "{ "))
12044 ((equal e '(:endgroup))
12045 (setq ingroup nil cnt 0)
12046 (insert "}\n"))
12047 ((equal e '(:newline))
12048 (when (not (= cnt 0))
12049 (setq cnt 0)
12050 (insert "\n")
12051 (setq e (car tbl))
12052 (while (equal (car tbl) '(:newline))
12053 (insert "\n")
12054 (setq tbl (cdr tbl)))))
12056 (setq tg (car e) c (cdr e))
12057 (if ingroup (push tg (car groups)))
12058 (setq tg (org-add-props tg nil 'face
12059 (org-get-todo-face tg)))
12060 (if (and (= cnt 0) (not ingroup)) (insert " "))
12061 (insert "[" c "] " tg (make-string
12062 (- fwidth 4 (length tg)) ?\ ))
12063 (when (= (setq cnt (1+ cnt)) ncol)
12064 (insert "\n")
12065 (if ingroup (insert " "))
12066 (setq cnt 0)))))
12067 (insert "\n")
12068 (goto-char (point-min))
12069 (if (not expert) (org-fit-window-to-buffer))
12070 (message "[a-z..]:Set [SPC]:clear")
12071 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12072 (cond
12073 ((or (= c ?\C-g)
12074 (and (= c ?q) (not (rassoc c fulltable))))
12075 (setq quit-flag t))
12076 ((= c ?\ ) nil)
12077 ((setq e (rassoc c fulltable) tg (car e))
12079 (t (setq quit-flag t)))))))
12081 (defun org-entry-is-todo-p ()
12082 (member (org-get-todo-state) org-not-done-keywords))
12084 (defun org-entry-is-done-p ()
12085 (member (org-get-todo-state) org-done-keywords))
12087 (defun org-get-todo-state ()
12088 (save-excursion
12089 (org-back-to-heading t)
12090 (and (looking-at org-todo-line-regexp)
12091 (match-end 2)
12092 (match-string 2))))
12094 (defun org-at-date-range-p (&optional inactive-ok)
12095 "Is the cursor inside a date range?"
12096 (interactive)
12097 (save-excursion
12098 (catch 'exit
12099 (let ((pos (point)))
12100 (skip-chars-backward "^[<\r\n")
12101 (skip-chars-backward "<[")
12102 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12103 (>= (match-end 0) pos)
12104 (throw 'exit t))
12105 (skip-chars-backward "^<[\r\n")
12106 (skip-chars-backward "<[")
12107 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12108 (>= (match-end 0) pos)
12109 (throw 'exit t)))
12110 nil)))
12112 (defun org-get-repeat (&optional tagline)
12113 "Check if there is a deadline/schedule with repeater in this entry."
12114 (save-match-data
12115 (save-excursion
12116 (org-back-to-heading t)
12117 (and (re-search-forward (if tagline
12118 (concat tagline "\\s-*" org-repeat-re)
12119 org-repeat-re)
12120 (org-entry-end-position) t)
12121 (match-string-no-properties 1)))))
12123 (defvar org-last-changed-timestamp)
12124 (defvar org-last-inserted-timestamp)
12125 (defvar org-log-post-message)
12126 (defvar org-log-note-purpose)
12127 (defvar org-log-note-how)
12128 (defvar org-log-note-extra)
12129 (defun org-auto-repeat-maybe (done-word)
12130 "Check if the current headline contains a repeated deadline/schedule.
12131 If yes, set TODO state back to what it was and change the base date
12132 of repeating deadline/scheduled time stamps to new date.
12133 This function is run automatically after each state change to a DONE state."
12134 ;; last-state is dynamically scoped into this function
12135 (let* ((repeat (org-get-repeat))
12136 (aa (assoc org-last-state org-todo-kwd-alist))
12137 (interpret (nth 1 aa))
12138 (head (nth 2 aa))
12139 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12140 (msg "Entry repeats: ")
12141 (org-log-done nil)
12142 (org-todo-log-states nil)
12143 re type n what ts time to-state)
12144 (when repeat
12145 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12146 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12147 org-todo-repeat-to-state))
12148 (unless (and to-state (member to-state org-todo-keywords-1))
12149 (setq to-state (if (eq interpret 'type) org-last-state head)))
12150 (org-todo to-state)
12151 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12152 (org-entry-put nil "LAST_REPEAT" (format-time-string
12153 (org-time-stamp-format t t))))
12154 (when org-log-repeat
12155 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12156 (memq 'org-add-log-note post-command-hook))
12157 ;; OK, we are already setup for some record
12158 (if (eq org-log-repeat 'note)
12159 ;; make sure we take a note, not only a time stamp
12160 (setq org-log-note-how 'note))
12161 ;; Set up for taking a record
12162 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12163 org-last-state
12164 'findpos org-log-repeat)))
12165 (org-back-to-heading t)
12166 (org-add-planning-info nil nil 'closed)
12167 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12168 org-deadline-time-regexp "\\)\\|\\("
12169 org-ts-regexp "\\)"))
12170 (while (re-search-forward
12171 re (save-excursion (outline-next-heading) (point)) t)
12172 (setq type (if (match-end 1) org-scheduled-string
12173 (if (match-end 3) org-deadline-string "Plain:"))
12174 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12175 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12176 (setq n (string-to-number (match-string 2 ts))
12177 what (match-string 3 ts))
12178 (if (equal what "w") (setq n (* n 7) what "d"))
12179 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12180 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12181 ;; Preparation, see if we need to modify the start date for the change
12182 (when (match-end 1)
12183 (setq time (save-match-data (org-time-string-to-time ts)))
12184 (cond
12185 ((equal (match-string 1 ts) ".")
12186 ;; Shift starting date to today
12187 (org-timestamp-change
12188 (- (org-today) (time-to-days time))
12189 'day))
12190 ((equal (match-string 1 ts) "+")
12191 (let ((nshiftmax 10) (nshift 0))
12192 (while (or (= nshift 0)
12193 (<= (time-to-days time)
12194 (time-to-days (current-time))))
12195 (when (= (incf nshift) nshiftmax)
12196 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12197 (error "Abort")))
12198 (org-timestamp-change n (cdr (assoc what whata)))
12199 (org-at-timestamp-p t)
12200 (setq ts (match-string 1))
12201 (setq time (save-match-data (org-time-string-to-time ts)))))
12202 (org-timestamp-change (- n) (cdr (assoc what whata)))
12203 ;; rematch, so that we have everything in place for the real shift
12204 (org-at-timestamp-p t)
12205 (setq ts (match-string 1))
12206 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12207 (org-timestamp-change n (cdr (assoc what whata)))
12208 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12209 (setq org-log-post-message msg)
12210 (message "%s" msg))))
12212 (defun org-show-todo-tree (arg)
12213 "Make a compact tree which shows all headlines marked with TODO.
12214 The tree will show the lines where the regexp matches, and all higher
12215 headlines above the match.
12216 With a \\[universal-argument] prefix, prompt for a regexp to match.
12217 With a numeric prefix N, construct a sparse tree for the Nth element
12218 of `org-todo-keywords-1'."
12219 (interactive "P")
12220 (let ((case-fold-search nil)
12221 (kwd-re
12222 (cond ((null arg) org-not-done-regexp)
12223 ((equal arg '(4))
12224 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12225 (mapcar 'list org-todo-keywords-1))))
12226 (concat "\\("
12227 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12228 "\\)\\>")))
12229 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12230 (regexp-quote (nth (1- (prefix-numeric-value arg))
12231 org-todo-keywords-1)))
12232 (t (error "Invalid prefix argument: %s" arg)))))
12233 (message "%d TODO entries found"
12234 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12236 (defun org-deadline (&optional remove time)
12237 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12238 With argument REMOVE, remove any deadline from the item.
12239 With argument TIME, set the deadline at the corresponding date. TIME
12240 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12241 (interactive "P")
12242 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12243 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12244 'region-start-level 'region))
12245 org-loop-over-headlines-in-active-region)
12246 (org-map-entries
12247 `(org-deadline ',remove ,time)
12248 org-loop-over-headlines-in-active-region
12249 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12250 (let* ((old-date (org-entry-get nil "DEADLINE"))
12251 (repeater (and old-date
12252 (string-match
12253 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12254 old-date)
12255 (match-string 1 old-date))))
12256 (if remove
12257 (progn
12258 (when (and old-date org-log-redeadline)
12259 (org-add-log-setup 'deldeadline nil old-date 'findpos
12260 org-log-redeadline))
12261 (org-remove-timestamp-with-keyword org-deadline-string)
12262 (message "Item no longer has a deadline."))
12263 (org-add-planning-info 'deadline time 'closed)
12264 (when (and old-date org-log-redeadline
12265 (not (equal old-date
12266 (substring org-last-inserted-timestamp 1 -1))))
12267 (org-add-log-setup 'redeadline nil old-date 'findpos
12268 org-log-redeadline))
12269 (when repeater
12270 (save-excursion
12271 (org-back-to-heading t)
12272 (when (re-search-forward (concat org-deadline-string " "
12273 org-last-inserted-timestamp)
12274 (save-excursion
12275 (outline-next-heading) (point)) t)
12276 (goto-char (1- (match-end 0)))
12277 (insert " " repeater)
12278 (setq org-last-inserted-timestamp
12279 (concat (substring org-last-inserted-timestamp 0 -1)
12280 " " repeater
12281 (substring org-last-inserted-timestamp -1))))))
12282 (message "Deadline on %s" org-last-inserted-timestamp)))))
12284 (defun org-schedule (&optional remove time)
12285 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12286 With argument REMOVE, remove any scheduling date from the item.
12287 With argument TIME, scheduled at the corresponding date. TIME can
12288 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12289 (interactive "P")
12290 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12291 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12292 'region-start-level 'region))
12293 org-loop-over-headlines-in-active-region)
12294 (org-map-entries
12295 `(org-schedule ',remove ,time)
12296 org-loop-over-headlines-in-active-region
12297 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12298 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12299 (repeater (and old-date
12300 (string-match
12301 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12302 old-date)
12303 (match-string 1 old-date))))
12304 (if remove
12305 (progn
12306 (when (and old-date org-log-reschedule)
12307 (org-add-log-setup 'delschedule nil old-date 'findpos
12308 org-log-reschedule))
12309 (org-remove-timestamp-with-keyword org-scheduled-string)
12310 (message "Item is no longer scheduled."))
12311 (org-add-planning-info 'scheduled time 'closed)
12312 (when (and old-date org-log-reschedule
12313 (not (equal old-date
12314 (substring org-last-inserted-timestamp 1 -1))))
12315 (org-add-log-setup 'reschedule nil old-date 'findpos
12316 org-log-reschedule))
12317 (when repeater
12318 (save-excursion
12319 (org-back-to-heading t)
12320 (when (re-search-forward (concat org-scheduled-string " "
12321 org-last-inserted-timestamp)
12322 (save-excursion
12323 (outline-next-heading) (point)) t)
12324 (goto-char (1- (match-end 0)))
12325 (insert " " repeater)
12326 (setq org-last-inserted-timestamp
12327 (concat (substring org-last-inserted-timestamp 0 -1)
12328 " " repeater
12329 (substring org-last-inserted-timestamp -1))))))
12330 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12332 (defun org-get-scheduled-time (pom &optional inherit)
12333 "Get the scheduled time as a time tuple, of a format suitable
12334 for calling org-schedule with, or if there is no scheduling,
12335 returns nil."
12336 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12337 (when time
12338 (apply 'encode-time (org-parse-time-string time)))))
12340 (defun org-get-deadline-time (pom &optional inherit)
12341 "Get the deadline as a time tuple, of a format suitable for
12342 calling org-deadline with, or if there is no scheduling, returns
12343 nil."
12344 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12345 (when time
12346 (apply 'encode-time (org-parse-time-string time)))))
12348 (defun org-remove-timestamp-with-keyword (keyword)
12349 "Remove all time stamps with KEYWORD in the current entry."
12350 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12351 beg)
12352 (save-excursion
12353 (org-back-to-heading t)
12354 (setq beg (point))
12355 (outline-next-heading)
12356 (while (re-search-backward re beg t)
12357 (replace-match "")
12358 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12359 (equal (char-before) ?\ ))
12360 (backward-delete-char 1)
12361 (if (string-match "^[ \t]*$" (buffer-substring
12362 (point-at-bol) (point-at-eol)))
12363 (delete-region (point-at-bol)
12364 (min (point-max) (1+ (point-at-eol))))))))))
12366 (defun org-add-planning-info (what &optional time &rest remove)
12367 "Insert new timestamp with keyword in the line directly after the headline.
12368 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12369 If non is given, the user is prompted for a date.
12370 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12371 be removed."
12372 (interactive)
12373 (let (org-time-was-given org-end-time-was-given ts
12374 end default-time default-input)
12376 (catch 'exit
12377 (when (and (memq what '(scheduled deadline))
12378 (or (not time)
12379 (and (stringp time)
12380 (string-match "^[-+]+[0-9]" time))))
12381 ;; Try to get a default date/time from existing timestamp
12382 (save-excursion
12383 (org-back-to-heading t)
12384 (setq end (save-excursion (outline-next-heading) (point)))
12385 (when (re-search-forward (if (eq what 'scheduled)
12386 org-scheduled-time-regexp
12387 org-deadline-time-regexp)
12388 end t)
12389 (setq ts (match-string 1)
12390 default-time
12391 (apply 'encode-time (org-parse-time-string ts))
12392 default-input (and ts (org-get-compact-tod ts))))))
12393 (when what
12394 (setq time
12395 (if (stringp time)
12396 ;; This is a string (relative or absolute), set proper date
12397 (apply 'encode-time
12398 (org-read-date-analyze
12399 time default-time (decode-time default-time)))
12400 ;; If necessary, get the time from the user
12401 (or time (org-read-date nil 'to-time nil nil
12402 default-time default-input)))))
12404 (when (and org-insert-labeled-timestamps-at-point
12405 (member what '(scheduled deadline)))
12406 (insert
12407 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12408 (org-insert-time-stamp time org-time-was-given
12409 nil nil nil (list org-end-time-was-given))
12410 (setq what nil))
12411 (save-excursion
12412 (save-restriction
12413 (let (col list elt ts buffer-invisibility-spec)
12414 (org-back-to-heading t)
12415 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12416 (goto-char (match-end 1))
12417 (setq col (current-column))
12418 (goto-char (match-end 0))
12419 (if (eobp) (insert "\n") (forward-char 1))
12420 (when (and (not what)
12421 (not (looking-at
12422 (concat "[ \t]*"
12423 org-keyword-time-not-clock-regexp))))
12424 ;; Nothing to add, nothing to remove...... :-)
12425 (throw 'exit nil))
12426 (if (and (not (looking-at org-outline-regexp))
12427 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12428 "[^\r\n]*"))
12429 (not (equal (match-string 1) org-clock-string)))
12430 (narrow-to-region (match-beginning 0) (match-end 0))
12431 (insert-before-markers "\n")
12432 (backward-char 1)
12433 (narrow-to-region (point) (point))
12434 (and org-adapt-indentation (org-indent-to-column col)))
12435 ;; Check if we have to remove something.
12436 (setq list (cons what remove))
12437 (while list
12438 (setq elt (pop list))
12439 (when (or (and (eq elt 'scheduled)
12440 (re-search-forward org-scheduled-time-regexp nil t))
12441 (and (eq elt 'deadline)
12442 (re-search-forward org-deadline-time-regexp nil t))
12443 (and (eq elt 'closed)
12444 (re-search-forward org-closed-time-regexp nil t)))
12445 (replace-match "")
12446 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12447 (and (looking-at "[ \t]+") (replace-match ""))
12448 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12449 (when what
12450 (insert
12451 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12452 (cond ((eq what 'scheduled) org-scheduled-string)
12453 ((eq what 'deadline) org-deadline-string)
12454 ((eq what 'closed) org-closed-string))
12455 " ")
12456 (setq ts (org-insert-time-stamp
12457 time
12458 (or org-time-was-given
12459 (and (eq what 'closed) org-log-done-with-time))
12460 (eq what 'closed)
12461 nil nil (list org-end-time-was-given)))
12462 (insert
12463 (if (not (or (bolp) (eq (char-before) ?\ )
12464 (memq (char-after) '(32 10))
12465 (eobp))) " " ""))
12466 (end-of-line 1))
12467 (goto-char (point-min))
12468 (widen)
12469 (if (and (looking-at "[ \t]*\n")
12470 (equal (char-before) ?\n))
12471 (delete-region (1- (point)) (point-at-eol)))
12472 ts))))))
12474 (defvar org-log-note-marker (make-marker))
12475 (defvar org-log-note-purpose nil)
12476 (defvar org-log-note-state nil)
12477 (defvar org-log-note-previous-state nil)
12478 (defvar org-log-note-how nil)
12479 (defvar org-log-note-extra nil)
12480 (defvar org-log-note-window-configuration nil)
12481 (defvar org-log-note-return-to (make-marker))
12482 (defvar org-log-note-effective-time nil
12483 "Remembered current time so that dynamically scoped
12484 `org-extend-today-until' affects tha timestamps in state change
12485 log")
12487 (defvar org-log-post-message nil
12488 "Message to be displayed after a log note has been stored.
12489 The auto-repeater uses this.")
12491 (defun org-add-note ()
12492 "Add a note to the current entry.
12493 This is done in the same way as adding a state change note."
12494 (interactive)
12495 (org-add-log-setup 'note nil nil 'findpos nil))
12497 (defvar org-property-end-re)
12498 (defun org-add-log-setup (&optional purpose state prev-state
12499 findpos how extra)
12500 "Set up the post command hook to take a note.
12501 If this is about to TODO state change, the new state is expected in STATE.
12502 When FINDPOS is non-nil, find the correct position for the note in
12503 the current entry. If not, assume that it can be inserted at point.
12504 HOW is an indicator what kind of note should be created.
12505 EXTRA is additional text that will be inserted into the notes buffer."
12506 (let* ((org-log-into-drawer (org-log-into-drawer))
12507 (drawer (cond ((stringp org-log-into-drawer)
12508 org-log-into-drawer)
12509 (org-log-into-drawer "LOGBOOK"))))
12510 (save-restriction
12511 (save-excursion
12512 (when findpos
12513 (org-back-to-heading t)
12514 (narrow-to-region (point) (save-excursion
12515 (outline-next-heading) (point)))
12516 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12517 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12518 "[^\r\n]*\\)?"))
12519 (goto-char (match-end 0))
12520 (cond
12521 (drawer
12522 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12523 nil t)
12524 (progn
12525 (goto-char (match-end 0))
12526 (or org-log-states-order-reversed
12527 (and (re-search-forward org-property-end-re nil t)
12528 (goto-char (1- (match-beginning 0))))))
12529 (insert "\n:" drawer ":\n:END:")
12530 (beginning-of-line 0)
12531 (org-indent-line)
12532 (beginning-of-line 2)
12533 (org-indent-line)
12534 (end-of-line 0)))
12535 ((and org-log-state-notes-insert-after-drawers
12536 (save-excursion
12537 (forward-line) (looking-at org-drawer-regexp)))
12538 (forward-line)
12539 (while (looking-at org-drawer-regexp)
12540 (goto-char (match-end 0))
12541 (re-search-forward org-property-end-re (point-max) t)
12542 (forward-line))
12543 (forward-line -1)))
12544 (unless org-log-states-order-reversed
12545 (and (= (char-after) ?\n) (forward-char 1))
12546 (org-skip-over-state-notes)
12547 (skip-chars-backward " \t\n\r")))
12548 (move-marker org-log-note-marker (point))
12549 (setq org-log-note-purpose purpose
12550 org-log-note-state state
12551 org-log-note-previous-state prev-state
12552 org-log-note-how how
12553 org-log-note-extra extra
12554 org-log-note-effective-time (org-current-effective-time))
12555 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12557 (defun org-skip-over-state-notes ()
12558 "Skip past the list of State notes in an entry."
12559 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12560 (when (ignore-errors (goto-char (org-in-item-p)))
12561 (let* ((struct (org-list-struct))
12562 (prevs (org-list-prevs-alist struct)))
12563 (while (looking-at "[ \t]*- State")
12564 (goto-char (or (org-list-get-next-item (point) struct prevs)
12565 (org-list-get-item-end (point) struct)))))))
12567 (defun org-add-log-note (&optional purpose)
12568 "Pop up a window for taking a note, and add this note later at point."
12569 (remove-hook 'post-command-hook 'org-add-log-note)
12570 (setq org-log-note-window-configuration (current-window-configuration))
12571 (delete-other-windows)
12572 (move-marker org-log-note-return-to (point))
12573 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12574 (goto-char org-log-note-marker)
12575 (org-switch-to-buffer-other-window "*Org Note*")
12576 (erase-buffer)
12577 (if (memq org-log-note-how '(time state))
12578 (let (current-prefix-arg) (org-store-log-note))
12579 (let ((org-inhibit-startup t)) (org-mode))
12580 (insert (format "# Insert note for %s.
12581 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12582 (cond
12583 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12584 ((eq org-log-note-purpose 'done) "closed todo item")
12585 ((eq org-log-note-purpose 'state)
12586 (format "state change from \"%s\" to \"%s\""
12587 (or org-log-note-previous-state "")
12588 (or org-log-note-state "")))
12589 ((eq org-log-note-purpose 'reschedule)
12590 "rescheduling")
12591 ((eq org-log-note-purpose 'delschedule)
12592 "no longer scheduled")
12593 ((eq org-log-note-purpose 'redeadline)
12594 "changing deadline")
12595 ((eq org-log-note-purpose 'deldeadline)
12596 "removing deadline")
12597 ((eq org-log-note-purpose 'refile)
12598 "refiling")
12599 ((eq org-log-note-purpose 'note)
12600 "this entry")
12601 (t (error "This should not happen")))))
12602 (if org-log-note-extra (insert org-log-note-extra))
12603 (org-set-local 'org-finish-function 'org-store-log-note)
12604 (run-hooks 'org-log-buffer-setup-hook)))
12606 (defvar org-note-abort nil) ; dynamically scoped
12607 (defun org-store-log-note ()
12608 "Finish taking a log note, and insert it to where it belongs."
12609 (let ((txt (buffer-string))
12610 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12611 lines ind bul)
12612 (kill-buffer (current-buffer))
12613 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12614 (setq txt (replace-match "" t t txt)))
12615 (if (string-match "\\s-+\\'" txt)
12616 (setq txt (replace-match "" t t txt)))
12617 (setq lines (org-split-string txt "\n"))
12618 (when (and note (string-match "\\S-" note))
12619 (setq note
12620 (org-replace-escapes
12621 note
12622 (list (cons "%u" (user-login-name))
12623 (cons "%U" user-full-name)
12624 (cons "%t" (format-time-string
12625 (org-time-stamp-format 'long 'inactive)
12626 org-log-note-effective-time))
12627 (cons "%T" (format-time-string
12628 (org-time-stamp-format 'long nil)
12629 org-log-note-effective-time))
12630 (cons "%d" (format-time-string
12631 (org-time-stamp-format nil 'inactive)
12632 org-log-note-effective-time))
12633 (cons "%D" (format-time-string
12634 (org-time-stamp-format nil nil)
12635 org-log-note-effective-time))
12636 (cons "%s" (if org-log-note-state
12637 (concat "\"" org-log-note-state "\"")
12638 ""))
12639 (cons "%S" (if org-log-note-previous-state
12640 (concat "\"" org-log-note-previous-state "\"")
12641 "\"\"")))))
12642 (if lines (setq note (concat note " \\\\")))
12643 (push note lines))
12644 (when (or current-prefix-arg org-note-abort)
12645 (when org-log-into-drawer
12646 (org-remove-empty-drawer-at
12647 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12648 org-log-note-marker))
12649 (setq lines nil))
12650 (when lines
12651 (with-current-buffer (marker-buffer org-log-note-marker)
12652 (save-excursion
12653 (goto-char org-log-note-marker)
12654 (move-marker org-log-note-marker nil)
12655 (end-of-line 1)
12656 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12657 (setq ind (save-excursion
12658 (if (ignore-errors (goto-char (org-in-item-p)))
12659 (let ((struct (org-list-struct)))
12660 (org-list-get-ind
12661 (org-list-get-top-point struct) struct))
12662 (skip-chars-backward " \r\t\n")
12663 (cond
12664 ((and (org-at-heading-p)
12665 org-adapt-indentation)
12666 (1+ (org-current-level)))
12667 ((org-at-heading-p) 0)
12668 (t (org-get-indentation))))))
12669 (setq bul (org-list-bullet-string "-"))
12670 (org-indent-line-to ind)
12671 (insert bul (pop lines))
12672 (let ((ind-body (+ (length bul) ind)))
12673 (while lines
12674 (insert "\n")
12675 (org-indent-line-to ind-body)
12676 (insert (pop lines))))
12677 (message "Note stored")
12678 (org-back-to-heading t)
12679 (org-cycle-hide-drawers 'children)))))
12680 (set-window-configuration org-log-note-window-configuration)
12681 (with-current-buffer (marker-buffer org-log-note-return-to)
12682 (goto-char org-log-note-return-to))
12683 (move-marker org-log-note-return-to nil)
12684 (and org-log-post-message (message "%s" org-log-post-message)))
12686 (defun org-remove-empty-drawer-at (drawer pos)
12687 "Remove an empty drawer DRAWER at position POS.
12688 POS may also be a marker."
12689 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12690 (save-excursion
12691 (save-restriction
12692 (widen)
12693 (goto-char pos)
12694 (if (org-in-regexp
12695 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12696 (replace-match ""))))))
12698 (defvar org-ts-type nil)
12699 (defun org-sparse-tree (&optional arg type)
12700 "Create a sparse tree, prompt for the details.
12701 This command can create sparse trees. You first need to select the type
12702 of match used to create the tree:
12704 t Show all TODO entries.
12705 T Show entries with a specific TODO keyword.
12706 m Show entries selected by a tags/property match.
12707 p Enter a property name and its value (both with completion on existing
12708 names/values) and show entries with that property.
12709 r Show entries matching a regular expression (`/' can be used as well).
12710 b Show deadlines and scheduled items before a date.
12711 a Show deadlines and scheduled items after a date.
12712 d Show deadlines due within `org-deadline-warning-days'.
12713 D Show deadlines and scheduled items between a date range."
12714 (interactive "P")
12715 (let (ans kwd value ts-type)
12716 (setq type (or type org-sparse-tree-default-date-type))
12717 (setq org-ts-type type)
12718 (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"
12719 (cond ((eq type 'all) "all timestamps")
12720 ((eq type 'scheduled) "only scheduled")
12721 ((eq type 'deadline) "only deadline")
12722 ((eq type 'active) "only active timestamps")
12723 ((eq type 'inactive) "only inactive timestamps")
12724 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12725 (t "scheduled/deadline")))
12726 (setq ans (read-char-exclusive))
12727 (cond
12728 ((equal ans ?c)
12729 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12730 ((equal ans ?d)
12731 (call-interactively 'org-check-deadlines))
12732 ((equal ans ?b)
12733 (call-interactively 'org-check-before-date))
12734 ((equal ans ?a)
12735 (call-interactively 'org-check-after-date))
12736 ((equal ans ?D)
12737 (call-interactively 'org-check-dates-range))
12738 ((equal ans ?t)
12739 (call-interactively 'org-show-todo-tree))
12740 ((equal ans ?T)
12741 (org-show-todo-tree '(4)))
12742 ((member ans '(?T ?m))
12743 (call-interactively 'org-match-sparse-tree))
12744 ((member ans '(?p ?P))
12745 (setq kwd (org-icompleting-read "Property: "
12746 (mapcar 'list (org-buffer-property-keys))))
12747 (setq value (org-icompleting-read "Value: "
12748 (mapcar 'list (org-property-values kwd))))
12749 (unless (string-match "\\`{.*}\\'" value)
12750 (setq value (concat "\"" value "\"")))
12751 (org-match-sparse-tree arg (concat kwd "=" value)))
12752 ((member ans '(?r ?R ?/))
12753 (call-interactively 'org-occur))
12754 (t (error "No such sparse tree command \"%c\"" ans)))))
12756 (defvar org-occur-highlights nil
12757 "List of overlays used for occur matches.")
12758 (make-variable-buffer-local 'org-occur-highlights)
12759 (defvar org-occur-parameters nil
12760 "Parameters of the active org-occur calls.
12761 This is a list, each call to org-occur pushes as cons cell,
12762 containing the regular expression and the callback, onto the list.
12763 The list can contain several entries if `org-occur' has been called
12764 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12765 will only contain one set of parameters. When the highlights are
12766 removed (for example with `C-c C-c', or with the next edit (depending
12767 on `org-remove-highlights-with-change'), this variable is emptied
12768 as well.")
12769 (make-variable-buffer-local 'org-occur-parameters)
12771 (defun org-occur (regexp &optional keep-previous callback)
12772 "Make a compact tree which shows all matches of REGEXP.
12773 The tree will show the lines where the regexp matches, and all higher
12774 headlines above the match. It will also show the heading after the match,
12775 to make sure editing the matching entry is easy.
12776 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12777 call to `org-occur' will be kept, to allow stacking of calls to this
12778 command.
12779 If CALLBACK is non-nil, it is a function which is called to confirm
12780 that the match should indeed be shown."
12781 (interactive "sRegexp: \nP")
12782 (when (equal regexp "")
12783 (error "Regexp cannot be empty"))
12784 (unless keep-previous
12785 (org-remove-occur-highlights nil nil t))
12786 (push (cons regexp callback) org-occur-parameters)
12787 (let ((cnt 0))
12788 (save-excursion
12789 (goto-char (point-min))
12790 (if (or (not keep-previous) ; do not want to keep
12791 (not org-occur-highlights)) ; no previous matches
12792 ;; hide everything
12793 (org-overview))
12794 (while (re-search-forward regexp nil t)
12795 (when (or (not callback)
12796 (save-match-data (funcall callback)))
12797 (setq cnt (1+ cnt))
12798 (when org-highlight-sparse-tree-matches
12799 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12800 (org-show-context 'occur-tree))))
12801 (when org-remove-highlights-with-change
12802 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12803 nil 'local))
12804 (unless org-sparse-tree-open-archived-trees
12805 (org-hide-archived-subtrees (point-min) (point-max)))
12806 (run-hooks 'org-occur-hook)
12807 (if (org-called-interactively-p 'interactive)
12808 (message "%d match(es) for regexp %s" cnt regexp))
12809 cnt))
12811 (defun org-occur-next-match (&optional n reset)
12812 "Function for `next-error-function' to find sparse tree matches.
12813 N is the number of matches to move, when negative move backwards.
12814 RESET is entirely ignored - this function always goes back to the
12815 starting point when no match is found."
12816 (let* ((limit (if (< n 0) (point-min) (point-max)))
12817 (search-func (if (< n 0)
12818 'previous-single-char-property-change
12819 'next-single-char-property-change))
12820 (n (abs n))
12821 (pos (point))
12823 (catch 'exit
12824 (while (setq p1 (funcall search-func (point) 'org-type))
12825 (when (equal p1 limit)
12826 (goto-char pos)
12827 (error "No more matches"))
12828 (when (equal (get-char-property p1 'org-type) 'org-occur)
12829 (setq n (1- n))
12830 (when (= n 0)
12831 (goto-char p1)
12832 (throw 'exit (point))))
12833 (goto-char p1))
12834 (goto-char p1)
12835 (error "No more matches"))))
12837 (defun org-show-context (&optional key)
12838 "Make sure point and context are visible.
12839 How much context is shown depends upon the variables
12840 `org-show-hierarchy-above', `org-show-following-heading',
12841 `org-show-entry-below' and `org-show-siblings'."
12842 (let ((heading-p (org-at-heading-p t))
12843 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12844 (following-p (org-get-alist-option org-show-following-heading key))
12845 (entry-p (org-get-alist-option org-show-entry-below key))
12846 (siblings-p (org-get-alist-option org-show-siblings key)))
12847 ;; Show heading or entry text
12848 (if (and heading-p (not entry-p))
12849 (org-flag-heading nil) ; only show the heading
12850 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12851 (org-show-hidden-entry))) ; show entire entry
12852 (when following-p
12853 ;; Show next sibling, or heading below text
12854 (save-excursion
12855 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12856 (org-flag-heading nil))))
12857 (when siblings-p (org-show-siblings))
12858 (when hierarchy-p
12859 ;; show all higher headings, possibly with siblings
12860 (save-excursion
12861 (while (and (condition-case nil
12862 (progn (org-up-heading-all 1) t)
12863 (error nil))
12864 (not (bobp)))
12865 (org-flag-heading nil)
12866 (when siblings-p (org-show-siblings)))))
12867 (save-excursion (goto-char (window-start)) (recenter 0))))
12869 (defvar org-reveal-start-hook nil
12870 "Hook run before revealing a location.")
12872 (defun org-reveal (&optional siblings)
12873 "Show current entry, hierarchy above it, and the following headline.
12874 This can be used to show a consistent set of context around locations
12875 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12876 not t for the search context.
12878 With optional argument SIBLINGS, on each level of the hierarchy all
12879 siblings are shown. This repairs the tree structure to what it would
12880 look like when opened with hierarchical calls to `org-cycle'.
12881 With double optional argument \\[universal-argument] \\[universal-argument], \
12882 go to the parent and show the
12883 entire tree."
12884 (interactive "P")
12885 (run-hooks 'org-reveal-start-hook)
12886 (let ((org-show-hierarchy-above t)
12887 (org-show-following-heading t)
12888 (org-show-siblings (if siblings t org-show-siblings)))
12889 (org-show-context nil))
12890 (when (equal siblings '(16))
12891 (save-excursion
12892 (when (org-up-heading-safe)
12893 (org-show-subtree)
12894 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12896 (defun org-highlight-new-match (beg end)
12897 "Highlight from BEG to END and mark the highlight is an occur headline."
12898 (let ((ov (make-overlay beg end)))
12899 (overlay-put ov 'face 'secondary-selection)
12900 (overlay-put ov 'org-type 'org-occur)
12901 (push ov org-occur-highlights)))
12903 (defun org-remove-occur-highlights (&optional beg end noremove)
12904 "Remove the occur highlights from the buffer.
12905 BEG and END are ignored. If NOREMOVE is nil, remove this function
12906 from the `before-change-functions' in the current buffer."
12907 (interactive)
12908 (unless org-inhibit-highlight-removal
12909 (mapc 'delete-overlay org-occur-highlights)
12910 (setq org-occur-highlights nil)
12911 (setq org-occur-parameters nil)
12912 (unless noremove
12913 (remove-hook 'before-change-functions
12914 'org-remove-occur-highlights 'local))))
12916 ;;;; Priorities
12918 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12919 "Regular expression matching the priority indicator.")
12921 (defvar org-remove-priority-next-time nil)
12923 (defun org-priority-up ()
12924 "Increase the priority of the current item."
12925 (interactive)
12926 (org-priority 'up))
12928 (defun org-priority-down ()
12929 "Decrease the priority of the current item."
12930 (interactive)
12931 (org-priority 'down))
12933 (defun org-priority (&optional action show)
12934 "Change the priority of an item.
12935 ACTION can be `set', `up', `down', or a character."
12936 (interactive "P")
12937 (if (equal action '(4))
12938 (org-show-priority)
12939 (unless org-enable-priority-commands
12940 (error "Priority commands are disabled"))
12941 (setq action (or action 'set))
12942 (let (current new news have remove)
12943 (save-excursion
12944 (org-back-to-heading t)
12945 (if (looking-at org-priority-regexp)
12946 (setq current (string-to-char (match-string 2))
12947 have t))
12948 (cond
12949 ((eq action 'remove)
12950 (setq remove t new ?\ ))
12951 ((or (eq action 'set)
12952 (if (featurep 'xemacs) (characterp action) (integerp action)))
12953 (if (not (eq action 'set))
12954 (setq new action)
12955 (message "Priority %c-%c, SPC to remove: "
12956 org-highest-priority org-lowest-priority)
12957 (save-match-data
12958 (setq new (read-char-exclusive))))
12959 (if (and (= (upcase org-highest-priority) org-highest-priority)
12960 (= (upcase org-lowest-priority) org-lowest-priority))
12961 (setq new (upcase new)))
12962 (cond ((equal new ?\ ) (setq remove t))
12963 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12964 (error "Priority must be between `%c' and `%c'"
12965 org-highest-priority org-lowest-priority))))
12966 ((eq action 'up)
12967 (setq new (if have
12968 (1- current) ; normal cycling
12969 ;; last priority was empty
12970 (if (eq last-command this-command)
12971 org-lowest-priority ; wrap around empty to lowest
12972 ;; default
12973 (if org-priority-start-cycle-with-default
12974 org-default-priority
12975 (1- org-default-priority))))))
12976 ((eq action 'down)
12977 (setq new (if have
12978 (1+ current) ; normal cycling
12979 ;; last priority was empty
12980 (if (eq last-command this-command)
12981 org-highest-priority ; wrap around empty to highest
12982 ;; default
12983 (if org-priority-start-cycle-with-default
12984 org-default-priority
12985 (1+ org-default-priority))))))
12986 (t (error "Invalid action")))
12987 (if (or (< (upcase new) org-highest-priority)
12988 (> (upcase new) org-lowest-priority))
12989 (if (and (memq action '(up down))
12990 (not have) (not (eq last-command this-command)))
12991 ;; `new' is from default priority
12992 (error
12993 "The default can not be set, see `org-default-priority' why")
12994 ;; normal cycling: `new' is beyond highest/lowest priority
12995 ;; and is wrapped around to the empty priority
12996 (setq remove t)))
12997 (setq news (format "%c" new))
12998 (if have
12999 (if remove
13000 (replace-match "" t t nil 1)
13001 (replace-match news t t nil 2))
13002 (if remove
13003 (error "No priority cookie found in line")
13004 (let ((case-fold-search nil))
13005 (looking-at org-todo-line-regexp))
13006 (if (match-end 2)
13007 (progn
13008 (goto-char (match-end 2))
13009 (insert " [#" news "]"))
13010 (goto-char (match-beginning 3))
13011 (insert "[#" news "] "))))
13012 (org-preserve-lc (org-set-tags nil 'align)))
13013 (if remove
13014 (message "Priority removed")
13015 (message "Priority of current item set to %s" news)))))
13017 (defun org-show-priority ()
13018 "Show the priority of the current item.
13019 This priority is composed of the main priority given with the [#A] cookies,
13020 and by additional input from the age of a schedules or deadline entry."
13021 (interactive)
13022 (let ((pri (if (eq major-mode 'org-agenda-mode)
13023 (org-get-at-bol 'priority)
13024 (save-excursion
13025 (save-match-data
13026 (beginning-of-line)
13027 (and (looking-at org-heading-regexp)
13028 (org-get-priority (match-string 0))))))))
13029 (message "Priority is %d" (if pri pri -1000))))
13031 (defun org-get-priority (s)
13032 "Find priority cookie and return priority."
13033 (save-match-data
13034 (if (functionp org-get-priority-function)
13035 (funcall org-get-priority-function)
13036 (if (not (string-match org-priority-regexp s))
13037 (* 1000 (- org-lowest-priority org-default-priority))
13038 (* 1000 (- org-lowest-priority
13039 (string-to-char (match-string 2 s))))))))
13041 ;;;; Tags
13043 (defvar org-agenda-archives-mode)
13044 (defvar org-map-continue-from nil
13045 "Position from where mapping should continue.
13046 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13048 (defvar org-scanner-tags nil
13049 "The current tag list while the tags scanner is running.")
13050 (defvar org-trust-scanner-tags nil
13051 "Should `org-get-tags-at' use the tags for the scanner.
13052 This is for internal dynamical scoping only.
13053 When this is non-nil, the function `org-get-tags-at' will return the value
13054 of `org-scanner-tags' instead of building the list by itself. This
13055 can lead to large speed-ups when the tags scanner is used in a file with
13056 many entries, and when the list of tags is retrieved, for example to
13057 obtain a list of properties. Building the tags list for each entry in such
13058 a file becomes an N^2 operation - but with this variable set, it scales
13059 as N.")
13061 (defun org-scan-tags (action matcher todo-only &optional start-level)
13062 "Scan headline tags with inheritance and produce output ACTION.
13064 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13065 or `agenda' to produce an entry list for an agenda view. It can also be
13066 a Lisp form or a function that should be called at each matched headline, in
13067 this case the return value is a list of all return values from these calls.
13069 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13070 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13071 only lines with a not-done TODO keyword are included in the output.
13072 This should be the same variable that was scoped into
13073 and set by `org-make-tags-matcher' when it constructed MATCHER.
13075 START-LEVEL can be a string with asterisks, reducing the scope to
13076 headlines matching this string."
13077 (require 'org-agenda)
13078 (let* ((re (concat "^"
13079 (if start-level
13080 ;; Get the correct level to match
13081 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13082 org-outline-regexp)
13083 " *\\(\\<\\("
13084 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13085 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13086 (props (list 'face 'default
13087 'done-face 'org-agenda-done
13088 'undone-face 'default
13089 'mouse-face 'highlight
13090 'org-not-done-regexp org-not-done-regexp
13091 'org-todo-regexp org-todo-regexp
13092 'org-complex-heading-regexp org-complex-heading-regexp
13093 'help-echo
13094 (format "mouse-2 or RET jump to org file %s"
13095 (abbreviate-file-name
13096 (or (buffer-file-name (buffer-base-buffer))
13097 (buffer-name (buffer-base-buffer)))))))
13098 (case-fold-search nil)
13099 (org-map-continue-from nil)
13100 lspos tags tags-list
13101 (tags-alist (list (cons 0 org-file-tags)))
13102 (llast 0) rtn rtn1 level category i txt
13103 todo marker entry priority)
13104 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13105 (setq action (list 'lambda nil action)))
13106 (save-excursion
13107 (goto-char (point-min))
13108 (when (eq action 'sparse-tree)
13109 (org-overview)
13110 (org-remove-occur-highlights))
13111 (while (re-search-forward re nil t)
13112 (setq org-map-continue-from nil)
13113 (catch :skip
13114 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13115 tags (if (match-end 4) (org-match-string-no-properties 4)))
13116 (goto-char (setq lspos (match-beginning 0)))
13117 (setq level (org-reduced-level (funcall outline-level))
13118 category (org-get-category))
13119 (setq i llast llast level)
13120 ;; remove tag lists from same and sublevels
13121 (while (>= i level)
13122 (when (setq entry (assoc i tags-alist))
13123 (setq tags-alist (delete entry tags-alist)))
13124 (setq i (1- i)))
13125 ;; add the next tags
13126 (when tags
13127 (setq tags (org-split-string tags ":")
13128 tags-alist
13129 (cons (cons level tags) tags-alist)))
13130 ;; compile tags for current headline
13131 (setq tags-list
13132 (if org-use-tag-inheritance
13133 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13134 tags)
13135 org-scanner-tags tags-list)
13136 (when org-use-tag-inheritance
13137 (setcdr (car tags-alist)
13138 (mapcar (lambda (x)
13139 (setq x (copy-sequence x))
13140 (org-add-prop-inherited x))
13141 (cdar tags-alist))))
13142 (when (and tags org-use-tag-inheritance
13143 (or (not (eq t org-use-tag-inheritance))
13144 org-tags-exclude-from-inheritance))
13145 ;; selective inheritance, remove uninherited ones
13146 (setcdr (car tags-alist)
13147 (org-remove-uninherited-tags (cdar tags-alist))))
13148 (when (and
13150 ;; eval matcher only when the todo condition is OK
13151 (and (or (not todo-only) (member todo org-not-done-keywords))
13152 (let ((case-fold-search t) (org-trust-scanner-tags t))
13153 (eval matcher)))
13155 ;; Call the skipper, but return t if it does not skip,
13156 ;; so that the `and' form continues evaluating
13157 (progn
13158 (unless (eq action 'sparse-tree) (org-agenda-skip))
13161 ;; Check if timestamps are deselecting this entry
13162 (or (not todo-only)
13163 (and (member todo org-not-done-keywords)
13164 (or (not org-agenda-tags-todo-honor-ignore-options)
13165 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13167 ;; select this headline
13168 (cond
13169 ((eq action 'sparse-tree)
13170 (and org-highlight-sparse-tree-matches
13171 (org-get-heading) (match-end 0)
13172 (org-highlight-new-match
13173 (match-beginning 1) (match-end 1)))
13174 (org-show-context 'tags-tree))
13175 ((eq action 'agenda)
13176 (setq txt (org-agenda-format-item
13178 (concat
13179 (if (eq org-tags-match-list-sublevels 'indented)
13180 (make-string (1- level) ?.) "")
13181 (org-get-heading))
13182 category
13183 tags-list)
13184 priority (org-get-priority txt))
13185 (goto-char lspos)
13186 (setq marker (org-agenda-new-marker))
13187 (org-add-props txt props
13188 'org-marker marker 'org-hd-marker marker 'org-category category
13189 'todo-state todo
13190 'priority priority 'type "tagsmatch")
13191 (push txt rtn))
13192 ((functionp action)
13193 (setq org-map-continue-from nil)
13194 (save-excursion
13195 (setq rtn1 (funcall action))
13196 (push rtn1 rtn)))
13197 (t (error "Invalid action")))
13199 ;; if we are to skip sublevels, jump to end of subtree
13200 (unless org-tags-match-list-sublevels
13201 (org-end-of-subtree t)
13202 (backward-char 1))))
13203 ;; Get the correct position from where to continue
13204 (if org-map-continue-from
13205 (goto-char org-map-continue-from)
13206 (and (= (point) lspos) (end-of-line 1)))))
13207 (when (and (eq action 'sparse-tree)
13208 (not org-sparse-tree-open-archived-trees))
13209 (org-hide-archived-subtrees (point-min) (point-max)))
13210 (nreverse rtn)))
13212 (defun org-remove-uninherited-tags (tags)
13213 "Remove all tags that are not inherited from the list TAGS."
13214 (cond
13215 ((eq org-use-tag-inheritance t)
13216 (if org-tags-exclude-from-inheritance
13217 (org-delete-all org-tags-exclude-from-inheritance tags)
13218 tags))
13219 ((not org-use-tag-inheritance) nil)
13220 ((stringp org-use-tag-inheritance)
13221 (delq nil (mapcar
13222 (lambda (x)
13223 (if (and (string-match org-use-tag-inheritance x)
13224 (not (member x org-tags-exclude-from-inheritance)))
13225 x nil))
13226 tags)))
13227 ((listp org-use-tag-inheritance)
13228 (delq nil (mapcar
13229 (lambda (x)
13230 (if (member x org-use-tag-inheritance) x nil))
13231 tags)))))
13233 (defun org-match-sparse-tree (&optional todo-only match)
13234 "Create a sparse tree according to tags string MATCH.
13235 MATCH can contain positive and negative selection of tags, like
13236 \"+WORK+URGENT-WITHBOSS\".
13237 If optional argument TODO-ONLY is non-nil, only select lines that are
13238 also TODO lines."
13239 (interactive "P")
13240 (org-agenda-prepare-buffers (list (current-buffer)))
13241 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13243 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13245 (defvar org-cached-props nil)
13246 (defun org-cached-entry-get (pom property)
13247 (if (or (eq t org-use-property-inheritance)
13248 (and (stringp org-use-property-inheritance)
13249 (string-match org-use-property-inheritance property))
13250 (and (listp org-use-property-inheritance)
13251 (member property org-use-property-inheritance)))
13252 ;; Caching is not possible, check it directly
13253 (org-entry-get pom property 'inherit)
13254 ;; Get all properties, so that we can do complicated checks easily
13255 (cdr (assoc property (or org-cached-props
13256 (setq org-cached-props
13257 (org-entry-properties pom)))))))
13259 (defun org-global-tags-completion-table (&optional files)
13260 "Return the list of all tags in all agenda buffer/files.
13261 Optional FILES argument is a list of files which can be used
13262 instead of the agenda files."
13263 (save-excursion
13264 (org-uniquify
13265 (delq nil
13266 (apply 'append
13267 (mapcar
13268 (lambda (file)
13269 (set-buffer (find-file-noselect file))
13270 (append (org-get-buffer-tags)
13271 (mapcar (lambda (x) (if (stringp (car-safe x))
13272 (list (car-safe x)) nil))
13273 org-tag-alist)))
13274 (if (and files (car files))
13275 files
13276 (org-agenda-files))))))))
13278 (defun org-make-tags-matcher (match)
13279 "Create the TAGS/TODO matcher form for the selection string MATCH.
13281 The variable `todo-only' is scoped dynamically into this function.
13282 It will be set to t if the matcher restricts matching to TODO entries,
13283 otherwise will not be touched.
13285 Returns a cons of the selection string MATCH and the constructed
13286 lisp form implementing the matcher. The matcher is to be evaluated
13287 at an Org entry, with point on the headline, and returns t if the
13288 entry matches the selection string MATCH. The returned lisp form
13289 references two variables with information about the entry, which
13290 must be bound around the form's evaluation: todo, the TODO keyword
13291 at the entry (or nil of none); and tags-list, the list of all tags
13292 at the entry including inherited ones. Additionally, the category
13293 of the entry (if any) must be specified as the text property
13294 'org-category on the headline.
13296 See also `org-scan-tags'.
13298 (declare (special todo-only))
13299 (unless (boundp 'todo-only)
13300 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13301 (unless match
13302 ;; Get a new match request, with completion
13303 (let ((org-last-tags-completion-table
13304 (org-global-tags-completion-table)))
13305 (setq match (org-completing-read-no-i
13306 "Match: " 'org-tags-completion-function nil nil nil
13307 'org-tags-history))))
13309 ;; Parse the string and create a lisp form
13310 (let ((match0 match)
13311 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13312 minus tag mm
13313 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13314 orterms term orlist re-p str-p level-p level-op time-p
13315 prop-p pn pv po gv rest)
13316 (if (string-match "/+" match)
13317 ;; match contains also a todo-matching request
13318 (progn
13319 (setq tagsmatch (substring match 0 (match-beginning 0))
13320 todomatch (substring match (match-end 0)))
13321 (if (string-match "^!" todomatch)
13322 (setq todo-only t todomatch (substring todomatch 1)))
13323 (if (string-match "^\\s-*$" todomatch)
13324 (setq todomatch nil)))
13325 ;; only matching tags
13326 (setq tagsmatch match todomatch nil))
13328 ;; Make the tags matcher
13329 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13330 (setq tagsmatcher t)
13331 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13332 (while (setq term (pop orterms))
13333 (while (and (equal (substring term -1) "\\") orterms)
13334 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13335 (while (string-match re term)
13336 (setq rest (substring term (match-end 0))
13337 minus (and (match-end 1)
13338 (equal (match-string 1 term) "-"))
13339 tag (save-match-data (replace-regexp-in-string
13340 "\\\\-" "-"
13341 (match-string 2 term)))
13342 re-p (equal (string-to-char tag) ?{)
13343 level-p (match-end 4)
13344 prop-p (match-end 5)
13345 mm (cond
13346 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13347 (level-p
13348 (setq level-op (org-op-to-function (match-string 3 term)))
13349 `(,level-op level ,(string-to-number
13350 (match-string 4 term))))
13351 (prop-p
13352 (setq pn (match-string 5 term)
13353 po (match-string 6 term)
13354 pv (match-string 7 term)
13355 re-p (equal (string-to-char pv) ?{)
13356 str-p (equal (string-to-char pv) ?\")
13357 time-p (save-match-data
13358 (string-match "^\"[[<].*[]>]\"$" pv))
13359 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13360 (if time-p (setq pv (org-matcher-time pv)))
13361 (setq po (org-op-to-function po (if time-p 'time str-p)))
13362 (cond
13363 ((equal pn "CATEGORY")
13364 (setq gv '(get-text-property (point) 'org-category)))
13365 ((equal pn "TODO")
13366 (setq gv 'todo))
13368 (setq gv `(org-cached-entry-get nil ,pn))))
13369 (if re-p
13370 (if (eq po 'org<>)
13371 `(not (string-match ,pv (or ,gv "")))
13372 `(string-match ,pv (or ,gv "")))
13373 (if str-p
13374 `(,po (or ,gv "") ,pv)
13375 `(,po (string-to-number (or ,gv ""))
13376 ,(string-to-number pv) ))))
13377 (t `(member ,tag tags-list)))
13378 mm (if minus (list 'not mm) mm)
13379 term rest)
13380 (push mm tagsmatcher))
13381 (push (if (> (length tagsmatcher) 1)
13382 (cons 'and tagsmatcher)
13383 (car tagsmatcher))
13384 orlist)
13385 (setq tagsmatcher nil))
13386 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13387 (setq tagsmatcher
13388 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13389 ;; Make the todo matcher
13390 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13391 (setq todomatcher t)
13392 (setq orterms (org-split-string todomatch "|") orlist nil)
13393 (while (setq term (pop orterms))
13394 (while (string-match re term)
13395 (setq minus (and (match-end 1)
13396 (equal (match-string 1 term) "-"))
13397 kwd (match-string 2 term)
13398 re-p (equal (string-to-char kwd) ?{)
13399 term (substring term (match-end 0))
13400 mm (if re-p
13401 `(string-match ,(substring kwd 1 -1) todo)
13402 (list 'equal 'todo kwd))
13403 mm (if minus (list 'not mm) mm))
13404 (push mm todomatcher))
13405 (push (if (> (length todomatcher) 1)
13406 (cons 'and todomatcher)
13407 (car todomatcher))
13408 orlist)
13409 (setq todomatcher nil))
13410 (setq todomatcher (if (> (length orlist) 1)
13411 (cons 'or orlist) (car orlist))))
13413 ;; Return the string and lisp forms of the matcher
13414 (setq matcher (if todomatcher
13415 (list 'and tagsmatcher todomatcher)
13416 tagsmatcher))
13417 (when todo-only
13418 (setq matcher (list 'and '(member todo org-not-done-keywords)
13419 matcher)))
13420 (cons match0 matcher)))
13422 (defun org-op-to-function (op &optional stringp)
13423 "Turn an operator into the appropriate function."
13424 (setq op
13425 (cond
13426 ((equal op "<" ) '(< string< org-time<))
13427 ((equal op ">" ) '(> org-string> org-time>))
13428 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13429 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13430 ((member op '("=" "==")) '(= string= org-time=))
13431 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13432 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13434 (defun org<> (a b) (not (= a b)))
13435 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13436 (defun org-string>= (a b) (not (string< a b)))
13437 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13438 (defun org-string<> (a b) (not (string= a b)))
13439 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13440 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13441 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13442 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13443 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13444 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13445 (defun org-2ft (s)
13446 "Convert S to a floating point time.
13447 If S is already a number, just return it. If it is a string, parse
13448 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13449 (cond
13450 ((numberp s) s)
13451 ((stringp s)
13452 (condition-case nil
13453 (float-time (apply 'encode-time (org-parse-time-string s)))
13454 (error 0.)))
13455 (t 0.)))
13457 (defun org-time-today ()
13458 "Time in seconds today at 0:00.
13459 Returns the float number of seconds since the beginning of the
13460 epoch to the beginning of today (00:00)."
13461 (float-time (apply 'encode-time
13462 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13464 (defun org-matcher-time (s)
13465 "Interpret a time comparison value."
13466 (save-match-data
13467 (cond
13468 ((string= s "<now>") (float-time))
13469 ((string= s "<today>") (org-time-today))
13470 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13471 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13472 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13473 (+ (org-time-today)
13474 (* (string-to-number (match-string 1 s))
13475 (cdr (assoc (match-string 2 s)
13476 '(("d" . 86400.0) ("w" . 604800.0)
13477 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13478 (t (org-2ft s)))))
13480 (defun org-match-any-p (re list)
13481 "Does re match any element of list?"
13482 (setq list (mapcar (lambda (x) (string-match re x)) list))
13483 (delq nil list))
13485 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13486 (defvar org-tags-overlay (make-overlay 1 1))
13487 (org-detach-overlay org-tags-overlay)
13489 (defun org-get-local-tags-at (&optional pos)
13490 "Get a list of tags defined in the current headline."
13491 (org-get-tags-at pos 'local))
13493 (defun org-get-local-tags ()
13494 "Get a list of tags defined in the current headline."
13495 (org-get-tags-at nil 'local))
13497 (defun org-get-tags-at (&optional pos local)
13498 "Get a list of all headline tags applicable at POS.
13499 POS defaults to point. If tags are inherited, the list contains
13500 the targets in the same sequence as the headlines appear, i.e.
13501 the tags of the current headline come last.
13502 When LOCAL is non-nil, only return tags from the current headline,
13503 ignore inherited ones."
13504 (interactive)
13505 (if (and org-trust-scanner-tags
13506 (or (not pos) (equal pos (point)))
13507 (not local))
13508 org-scanner-tags
13509 (let (tags ltags lastpos parent)
13510 (save-excursion
13511 (save-restriction
13512 (widen)
13513 (goto-char (or pos (point)))
13514 (save-match-data
13515 (catch 'done
13516 (condition-case nil
13517 (progn
13518 (org-back-to-heading t)
13519 (while (not (equal lastpos (point)))
13520 (setq lastpos (point))
13521 (when (looking-at
13522 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13523 (setq ltags (org-split-string
13524 (org-match-string-no-properties 1) ":"))
13525 (when parent
13526 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13527 (setq tags (append
13528 (if parent
13529 (org-remove-uninherited-tags ltags)
13530 ltags)
13531 tags)))
13532 (or org-use-tag-inheritance (throw 'done t))
13533 (if local (throw 'done t))
13534 (or (org-up-heading-safe) (error nil))
13535 (setq parent t)))
13536 (error nil)))))
13537 (if local
13538 tags
13539 (reverse (delete-dups
13540 (reverse (append
13541 (org-remove-uninherited-tags
13542 org-file-tags) tags)))))))))
13544 (defun org-add-prop-inherited (s)
13545 (add-text-properties 0 (length s) '(inherited t) s)
13548 (defun org-toggle-tag (tag &optional onoff)
13549 "Toggle the tag TAG for the current line.
13550 If ONOFF is `on' or `off', don't toggle but set to this state."
13551 (let (res current)
13552 (save-excursion
13553 (org-back-to-heading t)
13554 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13555 (point-at-eol) t)
13556 (progn
13557 (setq current (match-string 1))
13558 (replace-match ""))
13559 (setq current ""))
13560 (setq current (nreverse (org-split-string current ":")))
13561 (cond
13562 ((eq onoff 'on)
13563 (setq res t)
13564 (or (member tag current) (push tag current)))
13565 ((eq onoff 'off)
13566 (or (not (member tag current)) (setq current (delete tag current))))
13567 (t (if (member tag current)
13568 (setq current (delete tag current))
13569 (setq res t)
13570 (push tag current))))
13571 (end-of-line 1)
13572 (if current
13573 (progn
13574 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13575 (org-set-tags nil t))
13576 (delete-horizontal-space))
13577 (run-hooks 'org-after-tags-change-hook))
13578 res))
13580 (defun org-align-tags-here (to-col)
13581 ;; Assumes that this is a headline
13582 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13583 (beginning-of-line 1)
13584 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13585 (< pos (match-beginning 2)))
13586 (progn
13587 (setq tags-l (- (match-end 2) (match-beginning 2)))
13588 (goto-char (match-beginning 1))
13589 (insert " ")
13590 (delete-region (point) (1+ (match-beginning 2)))
13591 (setq ncol (max (current-column)
13592 (1+ col)
13593 (if (> to-col 0)
13594 to-col
13595 (- (abs to-col) tags-l))))
13596 (setq p (point))
13597 (insert (make-string (- ncol (current-column)) ?\ ))
13598 (setq ncol (current-column))
13599 (when indent-tabs-mode (tabify p (point-at-eol)))
13600 (org-move-to-column (min ncol col) t))
13601 (goto-char pos))))
13603 (defun org-set-tags-command (&optional arg just-align)
13604 "Call the set-tags command for the current entry."
13605 (interactive "P")
13606 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13607 (org-set-tags arg just-align)
13608 (save-excursion
13609 (unless (and (org-region-active-p)
13610 org-loop-over-headlines-in-active-region)
13611 (org-back-to-heading t))
13612 (org-set-tags arg just-align))))
13614 (defun org-set-tags-to (data)
13615 "Set the tags of the current entry to DATA, replacing the current tags.
13616 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13617 If DATA is nil or the empty string, any tags will be removed."
13618 (interactive "sTags: ")
13619 (setq data
13620 (cond
13621 ((eq data nil) "")
13622 ((equal data "") "")
13623 ((stringp data)
13624 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13625 ":"))
13626 ((listp data)
13627 (concat ":" (mapconcat 'identity data ":") ":"))))
13628 (when data
13629 (save-excursion
13630 (org-back-to-heading t)
13631 (when (looking-at org-complex-heading-regexp)
13632 (if (match-end 5)
13633 (progn
13634 (goto-char (match-beginning 5))
13635 (insert data)
13636 (delete-region (point) (point-at-eol))
13637 (org-set-tags nil 'align))
13638 (goto-char (point-at-eol))
13639 (insert " " data)
13640 (org-set-tags nil 'align)))
13641 (beginning-of-line 1)
13642 (if (looking-at ".*?\\([ \t]+\\)$")
13643 (delete-region (match-beginning 1) (match-end 1))))))
13645 (defun org-align-all-tags ()
13646 "Align the tags i all headings."
13647 (interactive)
13648 (save-excursion
13649 (or (ignore-errors (org-back-to-heading t))
13650 (outline-next-heading))
13651 (if (org-at-heading-p)
13652 (org-set-tags t)
13653 (message "No headings"))))
13655 (defvar org-indent-indentation-per-level)
13656 (defun org-set-tags (&optional arg just-align)
13657 "Set the tags for the current headline.
13658 With prefix ARG, realign all tags in headings in the current buffer."
13659 (interactive "P")
13660 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13661 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13662 'region-start-level 'region))
13663 org-loop-over-headlines-in-active-region)
13664 (org-map-entries
13665 ;; We don't use ARG and JUST-ALIGN here these args are not
13666 ;; useful when looping over headlines
13667 `(org-set-tags)
13668 org-loop-over-headlines-in-active-region
13669 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13670 (let* ((re org-outline-regexp-bol)
13671 (current (unless arg (org-get-tags-string)))
13672 (col (current-column))
13673 (org-setting-tags t)
13674 table current-tags inherited-tags ; computed below when needed
13675 tags p0 c0 c1 rpl di tc level)
13676 (if arg
13677 (save-excursion
13678 (goto-char (point-min))
13679 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13680 (while (re-search-forward re nil t)
13681 (org-set-tags nil t)
13682 (end-of-line 1)))
13683 (message "All tags realigned to column %d" org-tags-column))
13684 (if just-align
13685 (setq tags current)
13686 ;; Get a new set of tags from the user
13687 (save-excursion
13688 (setq table (append org-tag-persistent-alist
13689 (or org-tag-alist (org-get-buffer-tags))
13690 (and
13691 org-complete-tags-always-offer-all-agenda-tags
13692 (org-global-tags-completion-table
13693 (org-agenda-files))))
13694 org-last-tags-completion-table table
13695 current-tags (org-split-string current ":")
13696 inherited-tags (nreverse
13697 (nthcdr (length current-tags)
13698 (nreverse (org-get-tags-at))))
13699 tags
13700 (if (or (eq t org-use-fast-tag-selection)
13701 (and org-use-fast-tag-selection
13702 (delq nil (mapcar 'cdr table))))
13703 (org-fast-tag-selection
13704 current-tags inherited-tags table
13705 (if org-fast-tag-selection-include-todo
13706 org-todo-key-alist))
13707 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13708 (org-trim
13709 (org-icompleting-read "Tags: "
13710 'org-tags-completion-function
13711 nil nil current 'org-tags-history))))))
13712 (while (string-match "[-+&]+" tags)
13713 ;; No boolean logic, just a list
13714 (setq tags (replace-match ":" t t tags))))
13716 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13718 (if org-tags-sort-function
13719 (setq tags (mapconcat 'identity
13720 (sort (org-split-string
13721 tags (org-re "[^[:alnum:]_@#%]+"))
13722 org-tags-sort-function) ":")))
13724 (if (string-match "\\`[\t ]*\\'" tags)
13725 (setq tags "")
13726 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13727 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13729 ;; Insert new tags at the correct column
13730 (beginning-of-line 1)
13731 (setq level (or (and (looking-at org-outline-regexp)
13732 (- (match-end 0) (point) 1))
13734 (cond
13735 ((and (equal current "") (equal tags "")))
13736 ((re-search-forward
13737 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13738 (point-at-eol) t)
13739 (if (equal tags "")
13740 (setq rpl "")
13741 (goto-char (match-beginning 0))
13742 (setq c0 (current-column)
13743 ;; compute offset for the case of org-indent-mode active
13744 di (if org-indent-mode
13745 (* (1- org-indent-indentation-per-level) (1- level))
13747 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13748 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13749 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13750 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13751 (replace-match rpl t t)
13752 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13753 tags)
13754 (t (error "Tags alignment failed")))
13755 (org-move-to-column col)
13756 (unless just-align
13757 (run-hooks 'org-after-tags-change-hook))))))
13759 (defun org-change-tag-in-region (beg end tag off)
13760 "Add or remove TAG for each entry in the region.
13761 This works in the agenda, and also in an org-mode buffer."
13762 (interactive
13763 (list (region-beginning) (region-end)
13764 (let ((org-last-tags-completion-table
13765 (if (derived-mode-p 'org-mode)
13766 (org-get-buffer-tags)
13767 (org-global-tags-completion-table))))
13768 (org-icompleting-read
13769 "Tag: " 'org-tags-completion-function nil nil nil
13770 'org-tags-history))
13771 (progn
13772 (message "[s]et or [r]emove? ")
13773 (equal (read-char-exclusive) ?r))))
13774 (if (fboundp 'deactivate-mark) (deactivate-mark))
13775 (let ((agendap (equal major-mode 'org-agenda-mode))
13776 l1 l2 m buf pos newhead (cnt 0))
13777 (goto-char end)
13778 (setq l2 (1- (org-current-line)))
13779 (goto-char beg)
13780 (setq l1 (org-current-line))
13781 (loop for l from l1 to l2 do
13782 (org-goto-line l)
13783 (setq m (get-text-property (point) 'org-hd-marker))
13784 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13785 (and agendap m))
13786 (setq buf (if agendap (marker-buffer m) (current-buffer))
13787 pos (if agendap m (point)))
13788 (with-current-buffer buf
13789 (save-excursion
13790 (save-restriction
13791 (goto-char pos)
13792 (setq cnt (1+ cnt))
13793 (org-toggle-tag tag (if off 'off 'on))
13794 (setq newhead (org-get-heading)))))
13795 (and agendap (org-agenda-change-all-lines newhead m))))
13796 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13798 (defun org-tags-completion-function (string predicate &optional flag)
13799 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13800 (confirm (lambda (x) (stringp (car x)))))
13801 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13802 (setq s1 (match-string 1 string)
13803 s2 (match-string 2 string))
13804 (setq s1 "" s2 string))
13805 (cond
13806 ((eq flag nil)
13807 ;; try completion
13808 (setq rtn (try-completion s2 ctable confirm))
13809 (if (stringp rtn)
13810 (setq rtn
13811 (concat s1 s2 (substring rtn (length s2))
13812 (if (and org-add-colon-after-tag-completion
13813 (assoc rtn ctable))
13814 ":" ""))))
13815 rtn)
13816 ((eq flag t)
13817 ;; all-completions
13818 (all-completions s2 ctable confirm)
13820 ((eq flag 'lambda)
13821 ;; exact match?
13822 (assoc s2 ctable)))
13825 (defun org-fast-tag-insert (kwd tags face &optional end)
13826 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13827 (insert (format "%-12s" (concat kwd ":"))
13828 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13829 (or end "")))
13831 (defun org-fast-tag-show-exit (flag)
13832 (save-excursion
13833 (org-goto-line 3)
13834 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13835 (replace-match ""))
13836 (when flag
13837 (end-of-line 1)
13838 (org-move-to-column (- (window-width) 19) t)
13839 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13841 (defun org-set-current-tags-overlay (current prefix)
13842 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13843 (if (featurep 'xemacs)
13844 (org-overlay-display org-tags-overlay (concat prefix s)
13845 'secondary-selection)
13846 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13847 (org-overlay-display org-tags-overlay (concat prefix s)))))
13849 (defvar org-last-tag-selection-key nil)
13850 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13851 "Fast tag selection with single keys.
13852 CURRENT is the current list of tags in the headline, INHERITED is the
13853 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13854 possibly with grouping information. TODO-TABLE is a similar table with
13855 TODO keywords, should these have keys assigned to them.
13856 If the keys are nil, a-z are automatically assigned.
13857 Returns the new tags string, or nil to not change the current settings."
13858 (let* ((fulltable (append table todo-table))
13859 (maxlen (apply 'max (mapcar
13860 (lambda (x)
13861 (if (stringp (car x)) (string-width (car x)) 0))
13862 fulltable)))
13863 (buf (current-buffer))
13864 (expert (eq org-fast-tag-selection-single-key 'expert))
13865 (buffer-tags nil)
13866 (fwidth (+ maxlen 3 1 3))
13867 (ncol (/ (- (window-width) 4) fwidth))
13868 (i-face 'org-done)
13869 (c-face 'org-todo)
13870 tg cnt e c char c1 c2 ntable tbl rtn
13871 ov-start ov-end ov-prefix
13872 (exit-after-next org-fast-tag-selection-single-key)
13873 (done-keywords org-done-keywords)
13874 groups ingroup)
13875 (save-excursion
13876 (beginning-of-line 1)
13877 (if (looking-at
13878 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13879 (setq ov-start (match-beginning 1)
13880 ov-end (match-end 1)
13881 ov-prefix "")
13882 (setq ov-start (1- (point-at-eol))
13883 ov-end (1+ ov-start))
13884 (skip-chars-forward "^\n\r")
13885 (setq ov-prefix
13886 (concat
13887 (buffer-substring (1- (point)) (point))
13888 (if (> (current-column) org-tags-column)
13890 (make-string (- org-tags-column (current-column)) ?\ ))))))
13891 (move-overlay org-tags-overlay ov-start ov-end)
13892 (save-window-excursion
13893 (if expert
13894 (set-buffer (get-buffer-create " *Org tags*"))
13895 (delete-other-windows)
13896 (split-window-vertically)
13897 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13898 (erase-buffer)
13899 (org-set-local 'org-done-keywords done-keywords)
13900 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13901 (org-fast-tag-insert "Current" current c-face "\n\n")
13902 (org-fast-tag-show-exit exit-after-next)
13903 (org-set-current-tags-overlay current ov-prefix)
13904 (setq tbl fulltable char ?a cnt 0)
13905 (while (setq e (pop tbl))
13906 (cond
13907 ((equal (car e) :startgroup)
13908 (push '() groups) (setq ingroup t)
13909 (when (not (= cnt 0))
13910 (setq cnt 0)
13911 (insert "\n"))
13912 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13913 ((equal (car e) :endgroup)
13914 (setq ingroup nil cnt 0)
13915 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13916 ((equal e '(:newline))
13917 (when (not (= cnt 0))
13918 (setq cnt 0)
13919 (insert "\n")
13920 (setq e (car tbl))
13921 (while (equal (car tbl) '(:newline))
13922 (insert "\n")
13923 (setq tbl (cdr tbl)))))
13925 (setq tg (copy-sequence (car e)) c2 nil)
13926 (if (cdr e)
13927 (setq c (cdr e))
13928 ;; automatically assign a character.
13929 (setq c1 (string-to-char
13930 (downcase (substring
13931 tg (if (= (string-to-char tg) ?@) 1 0)))))
13932 (if (or (rassoc c1 ntable) (rassoc c1 table))
13933 (while (or (rassoc char ntable) (rassoc char table))
13934 (setq char (1+ char)))
13935 (setq c2 c1))
13936 (setq c (or c2 char)))
13937 (if ingroup (push tg (car groups)))
13938 (setq tg (org-add-props tg nil 'face
13939 (cond
13940 ((not (assoc tg table))
13941 (org-get-todo-face tg))
13942 ((member tg current) c-face)
13943 ((member tg inherited) i-face))))
13944 (if (and (= cnt 0) (not ingroup)) (insert " "))
13945 (insert "[" c "] " tg (make-string
13946 (- fwidth 4 (length tg)) ?\ ))
13947 (push (cons tg c) ntable)
13948 (when (= (setq cnt (1+ cnt)) ncol)
13949 (insert "\n")
13950 (if ingroup (insert " "))
13951 (setq cnt 0)))))
13952 (setq ntable (nreverse ntable))
13953 (insert "\n")
13954 (goto-char (point-min))
13955 (if (not expert) (org-fit-window-to-buffer))
13956 (setq rtn
13957 (catch 'exit
13958 (while t
13959 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13960 (if (not groups) "no " "")
13961 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13962 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13963 (setq org-last-tag-selection-key c)
13964 (cond
13965 ((= c ?\r) (throw 'exit t))
13966 ((= c ?!)
13967 (setq groups (not groups))
13968 (goto-char (point-min))
13969 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13970 ((= c ?\C-c)
13971 (if (not expert)
13972 (org-fast-tag-show-exit
13973 (setq exit-after-next (not exit-after-next)))
13974 (setq expert nil)
13975 (delete-other-windows)
13976 (set-window-buffer (split-window-vertically) " *Org tags*")
13977 (org-switch-to-buffer-other-window " *Org tags*")
13978 (org-fit-window-to-buffer)))
13979 ((or (= c ?\C-g)
13980 (and (= c ?q) (not (rassoc c ntable))))
13981 (org-detach-overlay org-tags-overlay)
13982 (setq quit-flag t))
13983 ((= c ?\ )
13984 (setq current nil)
13985 (if exit-after-next (setq exit-after-next 'now)))
13986 ((= c ?\t)
13987 (condition-case nil
13988 (setq tg (org-icompleting-read
13989 "Tag: "
13990 (or buffer-tags
13991 (with-current-buffer buf
13992 (org-get-buffer-tags)))))
13993 (quit (setq tg "")))
13994 (when (string-match "\\S-" tg)
13995 (add-to-list 'buffer-tags (list tg))
13996 (if (member tg current)
13997 (setq current (delete tg current))
13998 (push tg current)))
13999 (if exit-after-next (setq exit-after-next 'now)))
14000 ((setq e (rassoc c todo-table) tg (car e))
14001 (with-current-buffer buf
14002 (save-excursion (org-todo tg)))
14003 (if exit-after-next (setq exit-after-next 'now)))
14004 ((setq e (rassoc c ntable) tg (car e))
14005 (if (member tg current)
14006 (setq current (delete tg current))
14007 (loop for g in groups do
14008 (if (member tg g)
14009 (mapc (lambda (x)
14010 (setq current (delete x current)))
14011 g)))
14012 (push tg current))
14013 (if exit-after-next (setq exit-after-next 'now))))
14015 ;; Create a sorted list
14016 (setq current
14017 (sort current
14018 (lambda (a b)
14019 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14020 (if (eq exit-after-next 'now) (throw 'exit t))
14021 (goto-char (point-min))
14022 (beginning-of-line 2)
14023 (delete-region (point) (point-at-eol))
14024 (org-fast-tag-insert "Current" current c-face)
14025 (org-set-current-tags-overlay current ov-prefix)
14026 (while (re-search-forward
14027 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14028 (setq tg (match-string 1))
14029 (add-text-properties
14030 (match-beginning 1) (match-end 1)
14031 (list 'face
14032 (cond
14033 ((member tg current) c-face)
14034 ((member tg inherited) i-face)
14035 (t (get-text-property (match-beginning 1) 'face))))))
14036 (goto-char (point-min)))))
14037 (org-detach-overlay org-tags-overlay)
14038 (if rtn
14039 (mapconcat 'identity current ":")
14040 nil))))
14042 (defun org-get-tags-string ()
14043 "Get the TAGS string in the current headline."
14044 (unless (org-at-heading-p t)
14045 (error "Not on a heading"))
14046 (save-excursion
14047 (beginning-of-line 1)
14048 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14049 (org-match-string-no-properties 1)
14050 "")))
14052 (defun org-get-tags ()
14053 "Get the list of tags specified in the current headline."
14054 (org-split-string (org-get-tags-string) ":"))
14056 (defun org-get-buffer-tags ()
14057 "Get a table of all tags used in the buffer, for completion."
14058 (let (tags)
14059 (save-excursion
14060 (goto-char (point-min))
14061 (while (re-search-forward
14062 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14063 (when (equal (char-after (point-at-bol 0)) ?*)
14064 (mapc (lambda (x) (add-to-list 'tags x))
14065 (org-split-string (org-match-string-no-properties 1) ":")))))
14066 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14067 (mapcar 'list tags)))
14069 ;;;; The mapping API
14071 (defun org-map-entries (func &optional match scope &rest skip)
14072 "Call FUNC at each headline selected by MATCH in SCOPE.
14074 FUNC is a function or a lisp form. The function will be called without
14075 arguments, with the cursor positioned at the beginning of the headline.
14076 The return values of all calls to the function will be collected and
14077 returned as a list.
14079 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14080 does not need to preserve point. After evaluation, the cursor will be
14081 moved to the end of the line (presumably of the headline of the
14082 processed entry) and search continues from there. Under some
14083 circumstances, this may not produce the wanted results. For example,
14084 if you have removed (e.g. archived) the current (sub)tree it could
14085 mean that the next entry will be skipped entirely. In such cases, you
14086 can specify the position from where search should continue by making
14087 FUNC set the variable `org-map-continue-from' to the desired buffer
14088 position.
14090 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14091 Only headlines that are matched by this query will be considered during
14092 the iteration. When MATCH is nil or t, all headlines will be
14093 visited by the iteration.
14095 SCOPE determines the scope of this command. It can be any of:
14097 nil The current buffer, respecting the restriction if any
14098 tree The subtree started with the entry at point
14099 region The entries within the active region, if any
14100 region-start-level
14101 The entries within the active region, but only those at
14102 the same level than the first one.
14103 file The current buffer, without restriction
14104 file-with-archives
14105 The current buffer, and any archives associated with it
14106 agenda All agenda files
14107 agenda-with-archives
14108 All agenda files with any archive files associated with them
14109 \(file1 file2 ...)
14110 If this is a list, all files in the list will be scanned
14112 The remaining args are treated as settings for the skipping facilities of
14113 the scanner. The following items can be given here:
14115 archive skip trees with the archive tag
14116 comment skip trees with the COMMENT keyword
14117 function or Emacs Lisp form:
14118 will be used as value for `org-agenda-skip-function', so
14119 whenever the function returns a position, FUNC will not be
14120 called for that entry and search will continue from the
14121 position returned
14123 If your function needs to retrieve the tags including inherited tags
14124 at the *current* entry, you can use the value of the variable
14125 `org-scanner-tags' which will be much faster than getting the value
14126 with `org-get-tags-at'. If your function gets properties with
14127 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14128 to t around the call to `org-entry-properties' to get the same speedup.
14129 Note that if your function moves around to retrieve tags and properties at
14130 a *different* entry, you cannot use these techniques."
14131 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14132 (not (org-region-active-p)))
14133 (let* ((org-agenda-archives-mode nil) ; just to make sure
14134 (org-agenda-skip-archived-trees (memq 'archive skip))
14135 (org-agenda-skip-comment-trees (memq 'comment skip))
14136 (org-agenda-skip-function
14137 (car (org-delete-all '(comment archive) skip)))
14138 (org-tags-match-list-sublevels t)
14139 (start-level (eq scope 'region-start-level))
14140 matcher file res
14141 org-todo-keywords-for-agenda
14142 org-done-keywords-for-agenda
14143 org-todo-keyword-alist-for-agenda
14144 org-drawers-for-agenda
14145 org-tag-alist-for-agenda
14146 todo-only)
14148 (cond
14149 ((eq match t) (setq matcher t))
14150 ((eq match nil) (setq matcher t))
14151 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14153 (save-excursion
14154 (save-restriction
14155 (cond ((eq scope 'tree)
14156 (org-back-to-heading t)
14157 (org-narrow-to-subtree)
14158 (setq scope nil))
14159 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14160 (org-region-active-p))
14161 ;; If needed, set start-level to a string like "2"
14162 (when start-level
14163 (save-excursion
14164 (goto-char (region-beginning))
14165 (unless (org-at-heading-p) (outline-next-heading))
14166 (setq start-level (org-current-level))))
14167 (narrow-to-region (region-beginning)
14168 (save-excursion
14169 (goto-char (region-end))
14170 (unless (and (bolp) (org-at-heading-p))
14171 (outline-next-heading))
14172 (point)))
14173 (setq scope nil)))
14175 (if (not scope)
14176 (progn
14177 (org-agenda-prepare-buffers
14178 (list (buffer-file-name (current-buffer))))
14179 (setq res (org-scan-tags func matcher todo-only start-level)))
14180 ;; Get the right scope
14181 (cond
14182 ((and scope (listp scope) (symbolp (car scope)))
14183 (setq scope (eval scope)))
14184 ((eq scope 'agenda)
14185 (setq scope (org-agenda-files t)))
14186 ((eq scope 'agenda-with-archives)
14187 (setq scope (org-agenda-files t))
14188 (setq scope (org-add-archive-files scope)))
14189 ((eq scope 'file)
14190 (setq scope (list (buffer-file-name))))
14191 ((eq scope 'file-with-archives)
14192 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14193 (org-agenda-prepare-buffers scope)
14194 (while (setq file (pop scope))
14195 (with-current-buffer (org-find-base-buffer-visiting file)
14196 (save-excursion
14197 (save-restriction
14198 (widen)
14199 (goto-char (point-min))
14200 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14201 res)))
14203 ;;;; Properties
14205 ;;; Setting and retrieving properties
14207 (defconst org-special-properties
14208 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14209 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14210 "The special properties valid in Org-mode.
14212 These are properties that are not defined in the property drawer,
14213 but in some other way.")
14215 (defconst org-default-properties
14216 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14217 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14218 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14219 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14220 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14221 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14222 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14223 "Some properties that are used by Org-mode for various purposes.
14224 Being in this list makes sure that they are offered for completion.")
14226 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14227 "Regular expression matching the first line of a property drawer.")
14229 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14230 "Regular expression matching the last line of a property drawer.")
14232 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14233 "Regular expression matching the first line of a property drawer.")
14235 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14236 "Regular expression matching the first line of a property drawer.")
14238 (defconst org-property-drawer-re
14239 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14240 org-property-end-re "\\)\n?")
14241 "Matches an entire property drawer.")
14243 (defconst org-clock-drawer-re
14244 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14245 org-property-end-re "\\)\n?")
14246 "Matches an entire clock drawer.")
14248 (defsubst org-re-property (property)
14249 "Return a regexp matching a PROPERTY line.
14250 Match group 1 will be set to the value."
14251 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14253 (defsubst org-re-property-keyword (property)
14254 "Return a regexp matching a PROPERTY line, possibly with no
14255 value for the property."
14256 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14258 (defun org-property-action ()
14259 "Do an action on properties."
14260 (interactive)
14261 (let (c)
14262 (org-at-property-p)
14263 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14264 (setq c (read-char-exclusive))
14265 (cond
14266 ((equal c ?s)
14267 (call-interactively 'org-set-property))
14268 ((equal c ?d)
14269 (call-interactively 'org-delete-property))
14270 ((equal c ?D)
14271 (call-interactively 'org-delete-property-globally))
14272 ((equal c ?c)
14273 (call-interactively 'org-compute-property-at-point))
14274 (t (error "No such property action %c" c)))))
14276 (defun org-inc-effort ()
14277 "Increment the value of the effort property in the current entry."
14278 (interactive)
14279 (org-set-effort nil t))
14281 (defun org-set-effort (&optional value increment)
14282 "Set the effort property of the current entry.
14283 With numerical prefix arg, use the nth allowed value, 0 stands for the
14284 10th allowed value.
14286 When INCREMENT is non-nil, set the property to the next allowed value."
14287 (interactive "P")
14288 (if (equal value 0) (setq value 10))
14289 (let* ((completion-ignore-case t)
14290 (prop org-effort-property)
14291 (cur (org-entry-get nil prop))
14292 (allowed (org-property-get-allowed-values nil prop 'table))
14293 (existing (mapcar 'list (org-property-values prop)))
14295 (val (cond
14296 ((stringp value) value)
14297 ((and allowed (integerp value))
14298 (or (car (nth (1- value) allowed))
14299 (car (org-last allowed))))
14300 ((and allowed increment)
14301 (or (caadr (member (list cur) allowed))
14302 (error "Allowed effort values are not set")))
14303 (allowed
14304 (message "Select 1-9,0, [RET%s]: %s"
14305 (if cur (concat "=" cur) "")
14306 (mapconcat 'car allowed " "))
14307 (setq rpl (read-char-exclusive))
14308 (if (equal rpl ?\r)
14310 (setq rpl (- rpl ?0))
14311 (if (equal rpl 0) (setq rpl 10))
14312 (if (and (> rpl 0) (<= rpl (length allowed)))
14313 (car (nth (1- rpl) allowed))
14314 (org-completing-read "Effort: " allowed nil))))
14316 (let (org-completion-use-ido org-completion-use-iswitchb)
14317 (org-completing-read
14318 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14319 (concat "[" cur "]") "")
14320 ": ")
14321 existing nil nil "" nil cur))))))
14322 (unless (equal (org-entry-get nil prop) val)
14323 (org-entry-put nil prop val))
14324 (save-excursion
14325 (org-back-to-heading t)
14326 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14327 (message "%s is now %s" prop val)))
14329 (defun org-at-property-p ()
14330 "Is cursor inside a property drawer?"
14331 (save-excursion
14332 (beginning-of-line 1)
14333 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14334 (save-match-data ;; Used by calling procedures
14335 (let ((p (point))
14336 (range (unless (org-before-first-heading-p)
14337 (org-get-property-block))))
14338 (and range (<= (car range) p) (< p (cdr range))))))))
14340 (defun org-get-property-block (&optional beg end force)
14341 "Return the (beg . end) range of the body of the property drawer.
14342 BEG and END are the beginning and end of the current subtree, or of
14343 the part before the first headline. If they are not given, they will
14344 be found. If the drawer does not exist and FORCE is non-nil, create
14345 the drawer."
14346 (catch 'exit
14347 (save-excursion
14348 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14349 (progn (org-back-to-heading t) (point))))
14350 (end (or end (and (not (outline-next-heading)) (point-max))
14351 (point))))
14352 (goto-char beg)
14353 (if (re-search-forward org-property-start-re end t)
14354 (setq beg (1+ (match-end 0)))
14355 (if force
14356 (save-excursion
14357 (org-insert-property-drawer)
14358 (setq end (progn (outline-next-heading) (point))))
14359 (throw 'exit nil))
14360 (goto-char beg)
14361 (if (re-search-forward org-property-start-re end t)
14362 (setq beg (1+ (match-end 0)))))
14363 (if (re-search-forward org-property-end-re end t)
14364 (setq end (match-beginning 0))
14365 (or force (throw 'exit nil))
14366 (goto-char beg)
14367 (setq end beg)
14368 (org-indent-line)
14369 (insert ":END:\n"))
14370 (cons beg end)))))
14372 (defun org-entry-properties (&optional pom which specific)
14373 "Get all properties of the entry at point-or-marker POM.
14374 This includes the TODO keyword, the tags, time strings for deadline,
14375 scheduled, and clocking, and any additional properties defined in the
14376 entry. The return value is an alist, keys may occur multiple times
14377 if the property key was used several times.
14378 POM may also be nil, in which case the current entry is used.
14379 If WHICH is nil or `all', get all properties. If WHICH is
14380 `special' or `standard', only get that subclass. If WHICH
14381 is a string only get exactly this property. SPECIFIC can be a string, the
14382 specific property we are interested in. Specifying it can speed
14383 things up because then unnecessary parsing is avoided."
14384 (setq which (or which 'all))
14385 (org-with-point-at pom
14386 (let ((clockstr (substring org-clock-string 0 -1))
14387 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14388 (case-fold-search nil)
14389 beg end range props sum-props key key1 value string clocksum clocksumt)
14390 (save-excursion
14391 (when (condition-case nil
14392 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14393 (error nil))
14394 (setq beg (point))
14395 (setq sum-props (get-text-property (point) 'org-summaries))
14396 (setq clocksum (get-text-property (point) :org-clock-minutes)
14397 clocksumt (get-text-property (point) :org-clock-minutes-today))
14398 (outline-next-heading)
14399 (setq end (point))
14400 (when (memq which '(all special))
14401 ;; Get the special properties, like TODO and tags
14402 (goto-char beg)
14403 (when (and (or (not specific) (string= specific "TODO"))
14404 (looking-at org-todo-line-regexp) (match-end 2))
14405 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14406 (when (and (or (not specific) (string= specific "PRIORITY"))
14407 (looking-at org-priority-regexp))
14408 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14409 (when (or (not specific) (string= specific "FILE"))
14410 (push (cons "FILE" buffer-file-name) props))
14411 (when (and (or (not specific) (string= specific "TAGS"))
14412 (setq value (org-get-tags-string))
14413 (string-match "\\S-" value))
14414 (push (cons "TAGS" value) props))
14415 (when (and (or (not specific) (string= specific "ALLTAGS"))
14416 (setq value (org-get-tags-at)))
14417 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14418 ":"))
14419 props))
14420 (when (or (not specific) (string= specific "BLOCKED"))
14421 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14422 (when (or (not specific)
14423 (member specific
14424 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14425 "TIMESTAMP" "TIMESTAMP_IA")))
14426 (catch 'match
14427 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14428 (setq key (if (match-end 1)
14429 (substring (org-match-string-no-properties 1)
14430 0 -1))
14431 string (if (equal key clockstr)
14432 (org-trim
14433 (buffer-substring-no-properties
14434 (match-beginning 3) (goto-char
14435 (point-at-eol))))
14436 (substring (org-match-string-no-properties 3)
14437 1 -1)))
14438 ;; Get the correct property name from the key. This is
14439 ;; necessary if the user has configured time keywords.
14440 (setq key1 (concat key ":"))
14441 (cond
14442 ((not key)
14443 (setq key
14444 (if (= (char-after (match-beginning 3)) ?\[)
14445 "TIMESTAMP_IA" "TIMESTAMP")))
14446 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14447 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14448 ((equal key1 org-closed-string) (setq key "CLOSED"))
14449 ((equal key1 org-clock-string) (setq key "CLOCK")))
14450 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14451 (progn
14452 (push (cons key string) props)
14453 ;; no need to search further if match is found
14454 (throw 'match t))
14455 (when (or (equal key "CLOCK") (not (assoc key props)))
14456 (push (cons key string) props)))))))
14458 (when (memq which '(all standard))
14459 ;; Get the standard properties, like :PROP: ...
14460 (setq range (org-get-property-block beg end))
14461 (when range
14462 (goto-char (car range))
14463 (while (re-search-forward
14464 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14465 (cdr range) t)
14466 (setq key (org-match-string-no-properties 1)
14467 value (org-trim (or (org-match-string-no-properties 2) "")))
14468 (unless (member key excluded)
14469 (push (cons key (or value "")) props)))))
14470 (if clocksum
14471 (push (cons "CLOCKSUM"
14472 (org-columns-number-to-string (/ (float clocksum) 60.)
14473 'add_times))
14474 props))
14475 (if clocksumt
14476 (push (cons "CLOCKSUM_T"
14477 (org-columns-number-to-string (/ (float clocksumt) 60.)
14478 'add_times))
14479 props))
14480 (unless (assoc "CATEGORY" props)
14481 (push (cons "CATEGORY" (org-get-category)) props))
14482 (append sum-props (nreverse props)))))))
14484 (defun org-entry-get (pom property &optional inherit literal-nil)
14485 "Get value of PROPERTY for entry or content at point-or-marker POM.
14486 If INHERIT is non-nil and the entry does not have the property,
14487 then also check higher levels of the hierarchy.
14488 If INHERIT is the symbol `selective', use inheritance only if the setting
14489 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14490 If the property is present but empty, the return value is the empty string.
14491 If the property is not present at all, nil is returned.
14493 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14494 do not interpret it as the list atom nil. This is used for inheritance
14495 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14496 (org-with-point-at pom
14497 (if (and inherit (if (eq inherit 'selective)
14498 (org-property-inherit-p property)
14500 (org-entry-get-with-inheritance property literal-nil)
14501 (if (member property org-special-properties)
14502 ;; We need a special property. Use `org-entry-properties' to
14503 ;; retrieve it, but specify the wanted property
14504 (cdr (assoc property (org-entry-properties nil 'special property)))
14505 (let ((range (org-get-property-block)))
14506 (when (and range (not (eq (car range) (cdr range))))
14507 (let* ((props (list (or (assoc property org-file-properties)
14508 (assoc property org-global-properties)
14509 (assoc property org-global-properties-fixed))))
14510 (ap (lambda (key)
14511 (when (re-search-forward
14512 (org-re-property key) (cdr range) t)
14513 (setq props
14514 (org-update-property-plist
14516 (if (match-end 1)
14517 (org-match-string-no-properties 1) "")
14518 props)))))
14519 val)
14520 (goto-char (car range))
14521 (funcall ap property)
14522 (goto-char (car range))
14523 (while (funcall ap (concat property "+")))
14524 (setq val (cdr (assoc property props)))
14525 (when val (if literal-nil val (org-not-nil val))))))))))
14527 (defun org-property-or-variable-value (var &optional inherit)
14528 "Check if there is a property fixing the value of VAR.
14529 If yes, return this value. If not, return the current value of the variable."
14530 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14531 (if (and prop (stringp prop) (string-match "\\S-" prop))
14532 (read prop)
14533 (symbol-value var))))
14535 (defun org-entry-delete (pom property)
14536 "Delete the property PROPERTY from entry at point-or-marker POM."
14537 (org-with-point-at pom
14538 (if (member property org-special-properties)
14539 nil ; cannot delete these properties.
14540 (let ((range (org-get-property-block)))
14541 (if (and range
14542 (goto-char (car range))
14543 (re-search-forward
14544 (org-re-property property)
14545 (cdr range) t))
14546 (progn
14547 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14549 nil)))))
14551 ;; Multi-values properties are properties that contain multiple values
14552 ;; These values are assumed to be single words, separated by whitespace.
14553 (defun org-entry-add-to-multivalued-property (pom property value)
14554 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14555 (let* ((old (org-entry-get pom property))
14556 (values (and old (org-split-string old "[ \t]"))))
14557 (setq value (org-entry-protect-space value))
14558 (unless (member value values)
14559 (setq values (cons value values))
14560 (org-entry-put pom property
14561 (mapconcat 'identity values " ")))))
14563 (defun org-entry-remove-from-multivalued-property (pom property value)
14564 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14565 (let* ((old (org-entry-get pom property))
14566 (values (and old (org-split-string old "[ \t]"))))
14567 (setq value (org-entry-protect-space value))
14568 (when (member value values)
14569 (setq values (delete value values))
14570 (org-entry-put pom property
14571 (mapconcat 'identity values " ")))))
14573 (defun org-entry-member-in-multivalued-property (pom property value)
14574 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14575 (let* ((old (org-entry-get pom property))
14576 (values (and old (org-split-string old "[ \t]"))))
14577 (setq value (org-entry-protect-space value))
14578 (member value values)))
14580 (defun org-entry-get-multivalued-property (pom property)
14581 "Return a list of values in a multivalued property."
14582 (let* ((value (org-entry-get pom property))
14583 (values (and value (org-split-string value "[ \t]"))))
14584 (mapcar 'org-entry-restore-space values)))
14586 (defun org-entry-put-multivalued-property (pom property &rest values)
14587 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14588 VALUES should be a list of strings. Spaces will be protected."
14589 (org-entry-put pom property
14590 (mapconcat 'org-entry-protect-space values " "))
14591 (let* ((value (org-entry-get pom property))
14592 (values (and value (org-split-string value "[ \t]"))))
14593 (mapcar 'org-entry-restore-space values)))
14595 (defun org-entry-protect-space (s)
14596 "Protect spaces and newline in string S."
14597 (while (string-match " " s)
14598 (setq s (replace-match "%20" t t s)))
14599 (while (string-match "\n" s)
14600 (setq s (replace-match "%0A" t t s)))
14603 (defun org-entry-restore-space (s)
14604 "Restore spaces and newline in string S."
14605 (while (string-match "%20" s)
14606 (setq s (replace-match " " t t s)))
14607 (while (string-match "%0A" s)
14608 (setq s (replace-match "\n" t t s)))
14611 (defvar org-entry-property-inherited-from (make-marker)
14612 "Marker pointing to the entry from where a property was inherited.
14613 Each call to `org-entry-get-with-inheritance' will set this marker to the
14614 location of the entry where the inheritance search matched. If there was
14615 no match, the marker will point nowhere.
14616 Note that also `org-entry-get' calls this function, if the INHERIT flag
14617 is set.")
14619 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14620 "Get PROPERTY of entry or content at point, search higher levels if needed.
14621 The search will stop at the first ancestor which has the property defined.
14622 If the value found is \"nil\", return nil to show that the property
14623 should be considered as undefined (this is the meaning of nil here).
14624 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14625 (move-marker org-entry-property-inherited-from nil)
14626 (let (tmp)
14627 (save-excursion
14628 (save-restriction
14629 (widen)
14630 (catch 'ex
14631 (while t
14632 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14633 (or (ignore-errors (org-back-to-heading t))
14634 (goto-char (point-min)))
14635 (move-marker org-entry-property-inherited-from (point))
14636 (throw 'ex tmp))
14637 (or (ignore-errors (org-up-heading-safe))
14638 (throw 'ex nil))))))
14639 (setq tmp (or tmp
14640 (cdr (assoc property org-file-properties))
14641 (cdr (assoc property org-global-properties))
14642 (cdr (assoc property org-global-properties-fixed))))
14643 (if literal-nil tmp (org-not-nil tmp))))
14645 (defvar org-property-changed-functions nil
14646 "Hook called when the value of a property has changed.
14647 Each hook function should accept two arguments, the name of the property
14648 and the new value.")
14650 (defun org-entry-put (pom property value)
14651 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14652 (org-with-point-at pom
14653 (org-back-to-heading t)
14654 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14655 range)
14656 (cond
14657 ((equal property "TODO")
14658 (when (and (stringp value) (string-match "\\S-" value)
14659 (not (member value org-todo-keywords-1)))
14660 (error "\"%s\" is not a valid TODO state" value))
14661 (if (or (not value)
14662 (not (string-match "\\S-" value)))
14663 (setq value 'none))
14664 (org-todo value)
14665 (org-set-tags nil 'align))
14666 ((equal property "PRIORITY")
14667 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14668 (string-to-char value) ?\ ))
14669 (org-set-tags nil 'align))
14670 ((equal property "SCHEDULED")
14671 (if (re-search-forward org-scheduled-time-regexp end t)
14672 (cond
14673 ((eq value 'earlier) (org-timestamp-change -1 'day))
14674 ((eq value 'later) (org-timestamp-change 1 'day))
14675 (t (call-interactively 'org-schedule)))
14676 (call-interactively 'org-schedule)))
14677 ((equal property "DEADLINE")
14678 (if (re-search-forward org-deadline-time-regexp end t)
14679 (cond
14680 ((eq value 'earlier) (org-timestamp-change -1 'day))
14681 ((eq value 'later) (org-timestamp-change 1 'day))
14682 (t (call-interactively 'org-deadline)))
14683 (call-interactively 'org-deadline)))
14684 ((member property org-special-properties)
14685 (error "The %s property can not yet be set with `org-entry-put'"
14686 property))
14687 (t ; a non-special property
14688 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14689 (setq range (org-get-property-block beg end 'force))
14690 (goto-char (car range))
14691 (if (re-search-forward
14692 (org-re-property-keyword property) (cdr range) t)
14693 (progn
14694 (delete-region (match-beginning 0) (match-end 0))
14695 (goto-char (match-beginning 0)))
14696 (goto-char (cdr range))
14697 (insert "\n")
14698 (backward-char 1)
14699 (org-indent-line))
14700 (insert ":" property ":")
14701 (and value (insert " " value))
14702 (org-indent-line)))))
14703 (run-hook-with-args 'org-property-changed-functions property value)))
14705 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14706 "Get all property keys in the current buffer.
14707 With INCLUDE-SPECIALS, also list the special properties that reflect things
14708 like tags and TODO state.
14709 With INCLUDE-DEFAULTS, also include properties that has special meaning
14710 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14711 and others.
14712 With INCLUDE-COLUMNS, also include property names given in COLUMN
14713 formats in the current buffer."
14714 (let (rtn range cfmt s p)
14715 (save-excursion
14716 (save-restriction
14717 (widen)
14718 (goto-char (point-min))
14719 (while (re-search-forward org-property-start-re nil t)
14720 (setq range (org-get-property-block))
14721 (goto-char (car range))
14722 (while (re-search-forward
14723 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14724 (cdr range) t)
14725 (add-to-list 'rtn (org-match-string-no-properties 1)))
14726 (outline-next-heading))))
14728 (when include-specials
14729 (setq rtn (append org-special-properties rtn)))
14731 (when include-defaults
14732 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14733 (add-to-list 'rtn org-effort-property))
14735 (when include-columns
14736 (save-excursion
14737 (save-restriction
14738 (widen)
14739 (goto-char (point-min))
14740 (while (re-search-forward
14741 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14742 nil t)
14743 (setq cfmt (match-string 2) s 0)
14744 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14745 cfmt s)
14746 (setq s (match-end 0)
14747 p (match-string 1 cfmt))
14748 (unless (or (equal p "ITEM")
14749 (member p org-special-properties))
14750 (add-to-list 'rtn (match-string 1 cfmt))))))))
14752 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14754 (defun org-property-values (key)
14755 "Return a list of all values of property KEY in the current buffer."
14756 (save-excursion
14757 (save-restriction
14758 (widen)
14759 (goto-char (point-min))
14760 (let ((re (org-re-property key))
14761 values)
14762 (while (re-search-forward re nil t)
14763 (add-to-list 'values (org-trim (match-string 1))))
14764 (delete "" values)))))
14766 (defun org-insert-property-drawer ()
14767 "Insert a property drawer into the current entry."
14768 (org-back-to-heading t)
14769 (looking-at org-outline-regexp)
14770 (let ((indent (if org-adapt-indentation
14771 (- (match-end 0) (match-beginning 0))
14773 (beg (point))
14774 (re (concat "^[ \t]*" org-keyword-time-regexp))
14775 end hiddenp)
14776 (outline-next-heading)
14777 (setq end (point))
14778 (goto-char beg)
14779 (while (re-search-forward re end t))
14780 (setq hiddenp (outline-invisible-p))
14781 (end-of-line 1)
14782 (and (equal (char-after) ?\n) (forward-char 1))
14783 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14784 (if (member (match-string 1) '("CLOCK:" ":END:"))
14785 ;; just skip this line
14786 (beginning-of-line 2)
14787 ;; Drawer start, find the end
14788 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14789 (beginning-of-line 1)))
14790 (org-skip-over-state-notes)
14791 (skip-chars-backward " \t\n\r")
14792 (if (eq (char-before) ?*) (forward-char 1))
14793 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14794 (beginning-of-line 0)
14795 (org-indent-to-column indent)
14796 (beginning-of-line 2)
14797 (org-indent-to-column indent)
14798 (beginning-of-line 0)
14799 (if hiddenp
14800 (save-excursion
14801 (org-back-to-heading t)
14802 (hide-entry))
14803 (org-flag-drawer t))))
14805 (defun org-insert-drawer (&optional arg drawer)
14806 "Insert a drawer at point.
14808 Optional argument DRAWER, when non-nil, is a string representing
14809 drawer's name. Otherwise, the user is prompted for a name.
14811 If a region is active, insert the drawer around that region
14812 instead.
14814 Point is left between drawer's boundaries."
14815 (interactive "P")
14816 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14817 "LOGBOOK"))
14818 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14819 ;; internally by Org. They are meant to be inserted
14820 ;; automatically.
14821 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14822 ;; Remove system drawers from list. Note: For some reason,
14823 ;; `org-completing-read' ignores the predicate while
14824 ;; `completing-read' handles it fine.
14825 (drawer (if arg "PROPERTIES"
14826 (or drawer
14827 (completing-read
14828 "Drawer: " org-drawers
14829 (lambda (d) (not (member d system-drawers))))))))
14830 (cond
14831 ;; With C-u, fall back on `org-insert-property-drawer'
14832 (arg (org-insert-property-drawer))
14833 ;; With an active region, insert a drawer at point.
14834 ((not (org-region-active-p))
14835 (progn
14836 (unless (bolp) (insert "\n"))
14837 (insert (format ":%s:\n\n:END:\n" drawer))
14838 (forward-line -2)))
14839 ;; Otherwise, insert the drawer at point
14841 (let ((rbeg (region-beginning))
14842 (rend (copy-marker (region-end))))
14843 (unwind-protect
14844 (progn
14845 (goto-char rbeg)
14846 (beginning-of-line)
14847 (when (save-excursion
14848 (re-search-forward org-outline-regexp-bol rend t))
14849 (error "Drawers cannot contain headlines"))
14850 ;; Position point at the beginning of the first
14851 ;; non-blank line in region. Insert drawer's opening
14852 ;; there, then indent it.
14853 (org-skip-whitespace)
14854 (beginning-of-line)
14855 (insert ":" drawer ":\n")
14856 (forward-line -1)
14857 (indent-for-tab-command)
14858 ;; Move point to the beginning of the first blank line
14859 ;; after the last non-blank line in region. Insert
14860 ;; drawer's closing, then indent it.
14861 (goto-char rend)
14862 (skip-chars-backward " \r\t\n")
14863 (insert "\n:END:")
14864 (deactivate-mark t)
14865 (indent-for-tab-command)
14866 (unless (eolp) (insert "\n")))
14867 ;; Clear marker, whatever the outcome of insertion is.
14868 (set-marker rend nil)))))))
14870 (defvar org-property-set-functions-alist nil
14871 "Property set function alist.
14872 Each entry should have the following format:
14874 (PROPERTY . READ-FUNCTION)
14876 The read function will be called with the same argument as
14877 `org-completing-read'.")
14879 (defun org-set-property-function (property)
14880 "Get the function that should be used to set PROPERTY.
14881 This is computed according to `org-property-set-functions-alist'."
14882 (or (cdr (assoc property org-property-set-functions-alist))
14883 'org-completing-read))
14885 (defun org-read-property-value (property)
14886 "Read PROPERTY value from user."
14887 (let* ((completion-ignore-case t)
14888 (allowed (org-property-get-allowed-values nil property 'table))
14889 (cur (org-entry-get nil property))
14890 (prompt (concat property " value"
14891 (if (and cur (string-match "\\S-" cur))
14892 (concat " [" cur "]") "") ": "))
14893 (set-function (org-set-property-function property))
14894 (val (if allowed
14895 (funcall set-function prompt allowed nil
14896 (not (get-text-property 0 'org-unrestricted
14897 (caar allowed))))
14898 (let (org-completion-use-ido org-completion-use-iswitchb)
14899 (funcall set-function prompt
14900 (mapcar 'list (org-property-values property))
14901 nil nil "" nil cur)))))
14902 (if (equal val "")
14904 val)))
14906 (defvar org-last-set-property nil)
14907 (defun org-read-property-name ()
14908 "Read a property name."
14909 (let* ((completion-ignore-case t)
14910 (keys (org-buffer-property-keys nil t t))
14911 (default-prop (or (save-excursion
14912 (save-match-data
14913 (beginning-of-line)
14914 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14915 (null (string= (match-string 1) "END"))
14916 (match-string 1))))
14917 org-last-set-property))
14918 (property (org-icompleting-read
14919 (concat "Property"
14920 (if default-prop (concat " [" default-prop "]") "")
14921 ": ")
14922 (mapcar 'list keys)
14923 nil nil nil nil
14924 default-prop
14926 (if (member property keys)
14927 property
14928 (or (cdr (assoc (downcase property)
14929 (mapcar (lambda (x) (cons (downcase x) x))
14930 keys)))
14931 property))))
14933 (defun org-set-property (property value)
14934 "In the current entry, set PROPERTY to VALUE.
14935 When called interactively, this will prompt for a property name, offering
14936 completion on existing and default properties. And then it will prompt
14937 for a value, offering completion either on allowed values (via an inherited
14938 xxx_ALL property) or on existing values in other instances of this property
14939 in the current file."
14940 (interactive (list nil nil))
14941 (let* ((property (or property (org-read-property-name)))
14942 (value (or value (org-read-property-value property)))
14943 (fn (cdr (assoc property org-properties-postprocess-alist))))
14944 (setq org-last-set-property property)
14945 ;; Possibly postprocess the inserted value:
14946 (when fn (setq value (funcall fn value)))
14947 (unless (equal (org-entry-get nil property) value)
14948 (org-entry-put nil property value))))
14950 (defun org-delete-property (property)
14951 "In the current entry, delete PROPERTY."
14952 (interactive
14953 (let* ((completion-ignore-case t)
14954 (prop (org-icompleting-read "Property: "
14955 (org-entry-properties nil 'standard))))
14956 (list prop)))
14957 (message "Property %s %s" property
14958 (if (org-entry-delete nil property)
14959 "deleted"
14960 "was not present in the entry")))
14962 (defun org-delete-property-globally (property)
14963 "Remove PROPERTY globally, from all entries."
14964 (interactive
14965 (let* ((completion-ignore-case t)
14966 (prop (org-icompleting-read
14967 "Globally remove property: "
14968 (mapcar 'list (org-buffer-property-keys)))))
14969 (list prop)))
14970 (save-excursion
14971 (save-restriction
14972 (widen)
14973 (goto-char (point-min))
14974 (let ((cnt 0))
14975 (while (re-search-forward
14976 (org-re-property property)
14977 nil t)
14978 (setq cnt (1+ cnt))
14979 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14980 (message "Property \"%s\" removed from %d entries" property cnt)))))
14982 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14984 (defun org-compute-property-at-point ()
14985 "Compute the property at point.
14986 This looks for an enclosing column format, extracts the operator and
14987 then applies it to the property in the column format's scope."
14988 (interactive)
14989 (unless (org-at-property-p)
14990 (error "Not at a property"))
14991 (let ((prop (org-match-string-no-properties 2)))
14992 (org-columns-get-format-and-top-level)
14993 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14994 (error "No operator defined for property %s" prop))
14995 (org-columns-compute prop)))
14997 (defvar org-property-allowed-value-functions nil
14998 "Hook for functions supplying allowed values for a specific property.
14999 The functions must take a single argument, the name of the property, and
15000 return a flat list of allowed values. If \":ETC\" is one of
15001 the values, this means that these values are intended as defaults for
15002 completion, but that other values should be allowed too.
15003 The functions must return nil if they are not responsible for this
15004 property.")
15006 (defun org-property-get-allowed-values (pom property &optional table)
15007 "Get allowed values for the property PROPERTY.
15008 When TABLE is non-nil, return an alist that can directly be used for
15009 completion."
15010 (let (vals)
15011 (cond
15012 ((equal property "TODO")
15013 (setq vals (org-with-point-at pom
15014 (append org-todo-keywords-1 '("")))))
15015 ((equal property "PRIORITY")
15016 (let ((n org-lowest-priority))
15017 (while (>= n org-highest-priority)
15018 (push (char-to-string n) vals)
15019 (setq n (1- n)))))
15020 ((member property org-special-properties))
15021 ((setq vals (run-hook-with-args-until-success
15022 'org-property-allowed-value-functions property)))
15024 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15025 (when (and vals (string-match "\\S-" vals))
15026 (setq vals (car (read-from-string (concat "(" vals ")"))))
15027 (setq vals (mapcar (lambda (x)
15028 (cond ((stringp x) x)
15029 ((numberp x) (number-to-string x))
15030 ((symbolp x) (symbol-name x))
15031 (t "???")))
15032 vals)))))
15033 (when (member ":ETC" vals)
15034 (setq vals (remove ":ETC" vals))
15035 (org-add-props (car vals) '(org-unrestricted t)))
15036 (if table (mapcar 'list vals) vals)))
15038 (defun org-property-previous-allowed-value (&optional previous)
15039 "Switch to the next allowed value for this property."
15040 (interactive)
15041 (org-property-next-allowed-value t))
15043 (defun org-property-next-allowed-value (&optional previous)
15044 "Switch to the next allowed value for this property."
15045 (interactive)
15046 (unless (org-at-property-p)
15047 (error "Not at a property"))
15048 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15049 (key (match-string 2))
15050 (value (match-string 3))
15051 (allowed (or (org-property-get-allowed-values (point) key)
15052 (and (member value '("[ ]" "[-]" "[X]"))
15053 '("[ ]" "[X]"))))
15054 nval)
15055 (unless allowed
15056 (error "Allowed values for this property have not been defined"))
15057 (if previous (setq allowed (reverse allowed)))
15058 (if (member value allowed)
15059 (setq nval (car (cdr (member value allowed)))))
15060 (setq nval (or nval (car allowed)))
15061 (if (equal nval value)
15062 (error "Only one allowed value for this property"))
15063 (org-at-property-p)
15064 (replace-match (concat " :" key ": " nval) t t)
15065 (org-indent-line)
15066 (beginning-of-line 1)
15067 (skip-chars-forward " \t")
15068 (when (equal prop org-effort-property)
15069 (save-excursion
15070 (org-back-to-heading t)
15071 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15072 (run-hook-with-args 'org-property-changed-functions key nval)))
15074 (defun org-find-olp (path &optional this-buffer)
15075 "Return a marker pointing to the entry at outline path OLP.
15076 If anything goes wrong, throw an error.
15077 You can wrap this call to catch the error like this:
15079 (condition-case msg
15080 (org-mobile-locate-entry (match-string 4))
15081 (error (nth 1 msg)))
15083 The return value will then be either a string with the error message,
15084 or a marker if everything is OK.
15086 If THIS-BUFFER is set, the outline path does not contain a file,
15087 only headings."
15088 (let* ((file (if this-buffer buffer-file-name (pop path)))
15089 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15090 (level 1)
15091 (lmin 1)
15092 (lmax 1)
15093 limit re end found pos heading cnt flevel)
15094 (unless buffer (error "File not found :%s" file))
15095 (with-current-buffer buffer
15096 (save-excursion
15097 (save-restriction
15098 (widen)
15099 (setq limit (point-max))
15100 (goto-char (point-min))
15101 (while (setq heading (pop path))
15102 (setq re (format org-complex-heading-regexp-format
15103 (regexp-quote heading)))
15104 (setq cnt 0 pos (point))
15105 (while (re-search-forward re end t)
15106 (setq level (- (match-end 1) (match-beginning 1)))
15107 (if (and (>= level lmin) (<= level lmax))
15108 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15109 (when (= cnt 0) (error "Heading not found on level %d: %s"
15110 lmax heading))
15111 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15112 lmax heading))
15113 (goto-char found)
15114 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15115 (setq end (save-excursion (org-end-of-subtree t t))))
15116 (when (org-at-heading-p)
15117 (point-marker)))))))
15119 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15120 "Find node HEADING in BUFFER.
15121 Return a marker to the heading if it was found, or nil if not.
15122 If POS-ONLY is set, return just the position instead of a marker.
15124 The heading text must match exact, but it may have a TODO keyword,
15125 a priority cookie and tags in the standard locations."
15126 (with-current-buffer (or buffer (current-buffer))
15127 (save-excursion
15128 (save-restriction
15129 (widen)
15130 (goto-char (point-min))
15131 (let (case-fold-search)
15132 (if (re-search-forward
15133 (format org-complex-heading-regexp-format
15134 (regexp-quote heading)) nil t)
15135 (if pos-only
15136 (match-beginning 0)
15137 (move-marker (make-marker) (match-beginning 0)))))))))
15139 (defun org-find-exact-heading-in-directory (heading &optional dir)
15140 "Find Org node headline HEADING in all .org files in directory DIR.
15141 When the target headline is found, return a marker to this location."
15142 (let ((files (directory-files (or dir default-directory)
15143 nil "\\`[^.#].*\\.org\\'"))
15144 file visiting m buffer)
15145 (catch 'found
15146 (while (setq file (pop files))
15147 (message "trying %s" file)
15148 (setq visiting (org-find-base-buffer-visiting file))
15149 (setq buffer (or visiting (find-file-noselect file)))
15150 (setq m (org-find-exact-headline-in-buffer
15151 heading buffer))
15152 (when (and (not m) (not visiting)) (kill-buffer buffer))
15153 (and m (throw 'found m))))))
15155 (defun org-find-entry-with-id (ident)
15156 "Locate the entry that contains the ID property with exact value IDENT.
15157 IDENT can be a string, a symbol or a number, this function will search for
15158 the string representation of it.
15159 Return the position where this entry starts, or nil if there is no such entry."
15160 (interactive "sID: ")
15161 (let ((id (cond
15162 ((stringp ident) ident)
15163 ((symbol-name ident) (symbol-name ident))
15164 ((numberp ident) (number-to-string ident))
15165 (t (error "IDENT %s must be a string, symbol or number" ident))))
15166 (case-fold-search nil))
15167 (save-excursion
15168 (save-restriction
15169 (widen)
15170 (goto-char (point-min))
15171 (when (re-search-forward
15172 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15173 nil t)
15174 (org-back-to-heading t)
15175 (point))))))
15177 ;;;; Timestamps
15179 (defvar org-last-changed-timestamp nil)
15180 (defvar org-last-inserted-timestamp nil
15181 "The last time stamp inserted with `org-insert-time-stamp'.")
15182 (defvar org-time-was-given) ; dynamically scoped parameter
15183 (defvar org-end-time-was-given) ; dynamically scoped parameter
15184 (defvar org-ts-what) ; dynamically scoped parameter
15186 (defun org-time-stamp (arg &optional inactive)
15187 "Prompt for a date/time and insert a time stamp.
15188 If the user specifies a time like HH:MM or if this command is
15189 called with at least one prefix argument, the time stamp contains
15190 the date and the time. Otherwise, only the date is be included.
15192 All parts of a date not specified by the user is filled in from
15193 the current date/time. So if you just press return without
15194 typing anything, the time stamp will represent the current
15195 date/time.
15197 If there is already a timestamp at the cursor, it will be
15198 modified.
15200 With two universal prefix arguments, insert an active timestamp
15201 with the current time without prompting the user."
15202 (interactive "P")
15203 (let* ((ts nil)
15204 (default-time
15205 ;; Default time is either today, or, when entering a range,
15206 ;; the range start.
15207 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15208 (save-excursion
15209 (re-search-backward
15210 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15211 (- (point) 20) t)))
15212 (apply 'encode-time (org-parse-time-string (match-string 1)))
15213 (current-time)))
15214 (default-input (and ts (org-get-compact-tod ts)))
15215 (repeater (save-excursion
15216 (save-match-data
15217 (beginning-of-line)
15218 (when (re-search-forward
15219 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15220 (save-excursion (progn (end-of-line) (point))) t)
15221 (match-string 0)))))
15222 org-time-was-given org-end-time-was-given time)
15223 (cond
15224 ((and (org-at-timestamp-p t)
15225 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15226 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15227 (insert "--")
15228 (setq time (let ((this-command this-command))
15229 (org-read-date arg 'totime nil nil
15230 default-time default-input inactive)))
15231 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15232 ((org-at-timestamp-p t)
15233 (setq time (let ((this-command this-command))
15234 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15235 (when (org-at-timestamp-p t) ; just to get the match data
15236 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15237 (replace-match "")
15238 (setq org-last-changed-timestamp
15239 (org-insert-time-stamp
15240 time (or org-time-was-given arg)
15241 inactive nil nil (list org-end-time-was-given)))
15242 (when repeater (goto-char (1- (point))) (insert " " repeater)
15243 (setq org-last-changed-timestamp
15244 (concat (substring org-last-inserted-timestamp 0 -1)
15245 " " repeater ">"))))
15246 (message "Timestamp updated"))
15247 ((equal arg '(16))
15248 (org-insert-time-stamp (current-time) t))
15250 (setq time (let ((this-command this-command))
15251 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15252 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15253 nil nil (list org-end-time-was-given))))))
15255 ;; FIXME: can we use this for something else, like computing time differences?
15256 (defun org-get-compact-tod (s)
15257 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15258 (let* ((t1 (match-string 1 s))
15259 (h1 (string-to-number (match-string 2 s)))
15260 (m1 (string-to-number (match-string 3 s)))
15261 (t2 (and (match-end 4) (match-string 5 s)))
15262 (h2 (and t2 (string-to-number (match-string 6 s))))
15263 (m2 (and t2 (string-to-number (match-string 7 s))))
15264 dh dm)
15265 (if (not t2)
15267 (setq dh (- h2 h1) dm (- m2 m1))
15268 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15269 (concat t1 "+" (number-to-string dh)
15270 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15272 (defun org-time-stamp-inactive (&optional arg)
15273 "Insert an inactive time stamp.
15274 An inactive time stamp is enclosed in square brackets instead of angle
15275 brackets. It is inactive in the sense that it does not trigger agenda entries,
15276 does not link to the calendar and cannot be changed with the S-cursor keys.
15277 So these are more for recording a certain time/date."
15278 (interactive "P")
15279 (org-time-stamp arg 'inactive))
15281 (defvar org-date-ovl (make-overlay 1 1))
15282 (overlay-put org-date-ovl 'face 'org-date-selected)
15283 (org-detach-overlay org-date-ovl)
15285 (defvar org-ans1) ; dynamically scoped parameter
15286 (defvar org-ans2) ; dynamically scoped parameter
15288 (defvar org-plain-time-of-day-regexp) ; defined below
15290 (defvar org-overriding-default-time nil) ; dynamically scoped
15291 (defvar org-read-date-overlay nil)
15292 (defvar org-dcst nil) ; dynamically scoped
15293 (defvar org-read-date-history nil)
15294 (defvar org-read-date-final-answer nil)
15295 (defvar org-read-date-analyze-futurep nil)
15296 (defvar org-read-date-analyze-forced-year nil)
15297 (defvar org-read-date-inactive)
15299 (defun org-read-date (&optional org-with-time to-time from-string prompt
15300 default-time default-input inactive)
15301 "Read a date, possibly a time, and make things smooth for the user.
15302 The prompt will suggest to enter an ISO date, but you can also enter anything
15303 which will at least partially be understood by `parse-time-string'.
15304 Unrecognized parts of the date will default to the current day, month, year,
15305 hour and minute. If this command is called to replace a timestamp at point,
15306 or to enter the second timestamp of a range, the default time is taken
15307 from the existing stamp. Furthermore, the command prefers the future,
15308 so if you are giving a date where the year is not given, and the day-month
15309 combination is already past in the current year, it will assume you
15310 mean next year. For details, see the manual. A few examples:
15312 3-2-5 --> 2003-02-05
15313 feb 15 --> currentyear-02-15
15314 2/15 --> currentyear-02-15
15315 sep 12 9 --> 2009-09-12
15316 12:45 --> today 12:45
15317 22 sept 0:34 --> currentyear-09-22 0:34
15318 12 --> currentyear-currentmonth-12
15319 Fri --> nearest Friday (today or later)
15320 etc.
15322 Furthermore you can specify a relative date by giving, as the *first* thing
15323 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15324 change in days weeks, months, years.
15325 With a single plus or minus, the date is relative to today. With a double
15326 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15327 +4d --> four days from today
15328 +4 --> same as above
15329 +2w --> two weeks from today
15330 ++5 --> five days from default date
15332 The function understands only English month and weekday abbreviations.
15334 While prompting, a calendar is popped up - you can also select the
15335 date with the mouse (button 1). The calendar shows a period of three
15336 months. To scroll it to other months, use the keys `>' and `<'.
15337 If you don't like the calendar, turn it off with
15338 \(setq org-read-date-popup-calendar nil)
15340 With optional argument TO-TIME, the date will immediately be converted
15341 to an internal time.
15342 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15343 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15344 still enter a time, and this function will inform the calling routine
15345 about this change. The calling routine may then choose to change the
15346 format used to insert the time stamp into the buffer to include the time.
15347 With optional argument FROM-STRING, read from this string instead from
15348 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15349 the time/date that is used for everything that is not specified by the
15350 user."
15351 (require 'parse-time)
15352 (let* ((org-time-stamp-rounding-minutes
15353 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15354 (org-dcst org-display-custom-times)
15355 (ct (org-current-time))
15356 (org-def (or org-overriding-default-time default-time ct))
15357 (org-defdecode (decode-time org-def))
15358 (dummy (progn
15359 (when (< (nth 2 org-defdecode) org-extend-today-until)
15360 (setcar (nthcdr 2 org-defdecode) -1)
15361 (setcar (nthcdr 1 org-defdecode) 59)
15362 (setq org-def (apply 'encode-time org-defdecode)
15363 org-defdecode (decode-time org-def)))))
15364 (mouse-autoselect-window nil) ; Don't let the mouse jump
15365 (calendar-frame-setup nil)
15366 (calendar-setup nil)
15367 (calendar-move-hook nil)
15368 (calendar-view-diary-initially-flag nil)
15369 (calendar-view-holidays-initially-flag nil)
15370 (timestr (format-time-string
15371 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15372 (prompt (concat (if prompt (concat prompt " ") "")
15373 (format "Date+time [%s]: " timestr)))
15374 ans (org-ans0 "") org-ans1 org-ans2 final)
15376 (cond
15377 (from-string (setq ans from-string))
15378 (org-read-date-popup-calendar
15379 (save-excursion
15380 (save-window-excursion
15381 (calendar)
15382 (org-eval-in-calendar '(setq cursor-type nil) t)
15383 (unwind-protect
15384 (progn
15385 (calendar-forward-day (- (time-to-days org-def)
15386 (calendar-absolute-from-gregorian
15387 (calendar-current-date))))
15388 (org-eval-in-calendar nil t)
15389 (let* ((old-map (current-local-map))
15390 (map (copy-keymap calendar-mode-map))
15391 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15392 (org-defkey map (kbd "RET") 'org-calendar-select)
15393 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15394 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15395 (org-defkey minibuffer-local-map [(meta shift left)]
15396 (lambda () (interactive)
15397 (org-eval-in-calendar '(calendar-backward-month 1))))
15398 (org-defkey minibuffer-local-map [(meta shift right)]
15399 (lambda () (interactive)
15400 (org-eval-in-calendar '(calendar-forward-month 1))))
15401 (org-defkey minibuffer-local-map [(meta shift up)]
15402 (lambda () (interactive)
15403 (org-eval-in-calendar '(calendar-backward-year 1))))
15404 (org-defkey minibuffer-local-map [(meta shift down)]
15405 (lambda () (interactive)
15406 (org-eval-in-calendar '(calendar-forward-year 1))))
15407 (org-defkey minibuffer-local-map [?\e (shift left)]
15408 (lambda () (interactive)
15409 (org-eval-in-calendar '(calendar-backward-month 1))))
15410 (org-defkey minibuffer-local-map [?\e (shift right)]
15411 (lambda () (interactive)
15412 (org-eval-in-calendar '(calendar-forward-month 1))))
15413 (org-defkey minibuffer-local-map [?\e (shift up)]
15414 (lambda () (interactive)
15415 (org-eval-in-calendar '(calendar-backward-year 1))))
15416 (org-defkey minibuffer-local-map [?\e (shift down)]
15417 (lambda () (interactive)
15418 (org-eval-in-calendar '(calendar-forward-year 1))))
15419 (org-defkey minibuffer-local-map [(shift up)]
15420 (lambda () (interactive)
15421 (org-eval-in-calendar '(calendar-backward-week 1))))
15422 (org-defkey minibuffer-local-map [(shift down)]
15423 (lambda () (interactive)
15424 (org-eval-in-calendar '(calendar-forward-week 1))))
15425 (org-defkey minibuffer-local-map [(shift left)]
15426 (lambda () (interactive)
15427 (org-eval-in-calendar '(calendar-backward-day 1))))
15428 (org-defkey minibuffer-local-map [(shift right)]
15429 (lambda () (interactive)
15430 (org-eval-in-calendar '(calendar-forward-day 1))))
15431 (org-defkey minibuffer-local-map ">"
15432 (lambda () (interactive)
15433 (org-eval-in-calendar '(scroll-calendar-left 1))))
15434 (org-defkey minibuffer-local-map "<"
15435 (lambda () (interactive)
15436 (org-eval-in-calendar '(scroll-calendar-right 1))))
15437 (org-defkey minibuffer-local-map "\C-v"
15438 (lambda () (interactive)
15439 (org-eval-in-calendar
15440 '(calendar-scroll-left-three-months 1))))
15441 (org-defkey minibuffer-local-map "\M-v"
15442 (lambda () (interactive)
15443 (org-eval-in-calendar
15444 '(calendar-scroll-right-three-months 1))))
15445 (run-hooks 'org-read-date-minibuffer-setup-hook)
15446 (unwind-protect
15447 (progn
15448 (use-local-map map)
15449 (setq org-read-date-inactive inactive)
15450 (add-hook 'post-command-hook 'org-read-date-display)
15451 (setq org-ans0 (read-string prompt default-input
15452 'org-read-date-history nil))
15453 ;; org-ans0: from prompt
15454 ;; org-ans1: from mouse click
15455 ;; org-ans2: from calendar motion
15456 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15457 (remove-hook 'post-command-hook 'org-read-date-display)
15458 (use-local-map old-map)
15459 (when org-read-date-overlay
15460 (delete-overlay org-read-date-overlay)
15461 (setq org-read-date-overlay nil)))))
15462 (bury-buffer "*Calendar*")))))
15464 (t ; Naked prompt only
15465 (unwind-protect
15466 (setq ans (read-string prompt default-input
15467 'org-read-date-history timestr))
15468 (when org-read-date-overlay
15469 (delete-overlay org-read-date-overlay)
15470 (setq org-read-date-overlay nil)))))
15472 (setq final (org-read-date-analyze ans org-def org-defdecode))
15474 (when org-read-date-analyze-forced-year
15475 (message "Year was forced into %s"
15476 (if org-read-date-force-compatible-dates
15477 "compatible range (1970-2037)"
15478 "range representable on this machine"))
15479 (ding))
15481 ;; One round trip to get rid of 34th of August and stuff like that....
15482 (setq final (decode-time (apply 'encode-time final)))
15484 (setq org-read-date-final-answer ans)
15486 (if to-time
15487 (apply 'encode-time final)
15488 (if (and (boundp 'org-time-was-given) org-time-was-given)
15489 (format "%04d-%02d-%02d %02d:%02d"
15490 (nth 5 final) (nth 4 final) (nth 3 final)
15491 (nth 2 final) (nth 1 final))
15492 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15494 (defvar org-def)
15495 (defvar org-defdecode)
15496 (defvar org-with-time)
15497 (defun org-read-date-display ()
15498 "Display the current date prompt interpretation in the minibuffer."
15499 (when org-read-date-display-live
15500 (when org-read-date-overlay
15501 (delete-overlay org-read-date-overlay))
15502 (when (minibufferp (current-buffer))
15503 (save-excursion
15504 (end-of-line 1)
15505 (while (not (equal (buffer-substring
15506 (max (point-min) (- (point) 4)) (point))
15507 " "))
15508 (insert " ")))
15509 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15510 " " (or org-ans1 org-ans2)))
15511 (org-end-time-was-given nil)
15512 (f (org-read-date-analyze ans org-def org-defdecode))
15513 (fmts (if org-dcst
15514 org-time-stamp-custom-formats
15515 org-time-stamp-formats))
15516 (fmt (if (or org-with-time
15517 (and (boundp 'org-time-was-given) org-time-was-given))
15518 (cdr fmts)
15519 (car fmts)))
15520 (txt (format-time-string fmt (apply 'encode-time f)))
15521 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15522 (txt (concat "=> " txt)))
15523 (when (and org-end-time-was-given
15524 (string-match org-plain-time-of-day-regexp txt))
15525 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15526 org-end-time-was-given
15527 (substring txt (match-end 0)))))
15528 (when org-read-date-analyze-futurep
15529 (setq txt (concat txt " (=>F)")))
15530 (setq org-read-date-overlay
15531 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15532 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15534 (defun org-read-date-analyze (ans org-def org-defdecode)
15535 "Analyze the combined answer of the date prompt."
15536 ;; FIXME: cleanup and comment
15537 (let ((nowdecode (decode-time (current-time)))
15538 delta deltan deltaw deltadef year month day
15539 hour minute second wday pm h2 m2 tl wday1
15540 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15541 (setq org-read-date-analyze-futurep nil
15542 org-read-date-analyze-forced-year nil)
15543 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15544 (setq ans "+0"))
15546 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15547 (setq ans (replace-match "" t t ans)
15548 deltan (car delta)
15549 deltaw (nth 1 delta)
15550 deltadef (nth 2 delta)))
15552 ;; Check if there is an iso week date in there. If yes, store the
15553 ;; info and postpone interpreting it until the rest of the parsing
15554 ;; is done.
15555 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15556 (setq iso-year (if (match-end 1)
15557 (org-small-year-to-year
15558 (string-to-number (match-string 1 ans))))
15559 iso-weekday (if (match-end 3)
15560 (string-to-number (match-string 3 ans)))
15561 iso-week (string-to-number (match-string 2 ans)))
15562 (setq ans (replace-match "" t t ans)))
15564 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15565 (when (string-match
15566 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15567 (setq year (if (match-end 2)
15568 (string-to-number (match-string 2 ans))
15569 (progn (setq kill-year t)
15570 (string-to-number (format-time-string "%Y"))))
15571 month (string-to-number (match-string 3 ans))
15572 day (string-to-number (match-string 4 ans)))
15573 (if (< year 100) (setq year (+ 2000 year)))
15574 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15575 t nil ans)))
15577 ;; Help matching dotted european dates
15578 (when (string-match
15579 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15580 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15581 (setq kill-year t)
15582 (string-to-number (format-time-string "%Y")))
15583 day (string-to-number (match-string 1 ans))
15584 month (string-to-number (match-string 2 ans))
15585 ans (replace-match (format "%04d-%02d-%02d" year month day)
15586 t nil ans)))
15588 ;; Help matching american dates, like 5/30 or 5/30/7
15589 (when (string-match
15590 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15591 (setq year (if (match-end 4)
15592 (string-to-number (match-string 4 ans))
15593 (progn (setq kill-year t)
15594 (string-to-number (format-time-string "%Y"))))
15595 month (string-to-number (match-string 1 ans))
15596 day (string-to-number (match-string 2 ans)))
15597 (if (< year 100) (setq year (+ 2000 year)))
15598 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15599 t nil ans)))
15600 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15601 ;; If there is a time with am/pm, and *no* time without it, we convert
15602 ;; so that matching will be successful.
15603 (loop for i from 1 to 2 do ; twice, for end time as well
15604 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15605 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15606 (setq hour (string-to-number (match-string 1 ans))
15607 minute (if (match-end 3)
15608 (string-to-number (match-string 3 ans))
15610 pm (equal ?p
15611 (string-to-char (downcase (match-string 4 ans)))))
15612 (if (and (= hour 12) (not pm))
15613 (setq hour 0)
15614 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15615 (setq ans (replace-match (format "%02d:%02d" hour minute)
15616 t t ans))))
15618 ;; Check if a time range is given as a duration
15619 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15620 (setq hour (string-to-number (match-string 1 ans))
15621 h2 (+ hour (string-to-number (match-string 3 ans)))
15622 minute (string-to-number (match-string 2 ans))
15623 m2 (+ minute (if (match-end 5) (string-to-number
15624 (match-string 5 ans))0)))
15625 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15626 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15627 t t ans)))
15629 ;; Check if there is a time range
15630 (when (boundp 'org-end-time-was-given)
15631 (setq org-time-was-given nil)
15632 (when (and (string-match org-plain-time-of-day-regexp ans)
15633 (match-end 8))
15634 (setq org-end-time-was-given (match-string 8 ans))
15635 (setq ans (concat (substring ans 0 (match-beginning 7))
15636 (substring ans (match-end 7))))))
15638 (setq tl (parse-time-string ans)
15639 day (or (nth 3 tl) (nth 3 org-defdecode))
15640 month (or (nth 4 tl)
15641 (if (and org-read-date-prefer-future
15642 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15643 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15644 (nth 4 org-defdecode)))
15645 year (or (and (not kill-year) (nth 5 tl))
15646 (if (and org-read-date-prefer-future
15647 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15648 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15649 (nth 5 org-defdecode)))
15650 hour (or (nth 2 tl) (nth 2 org-defdecode))
15651 minute (or (nth 1 tl) (nth 1 org-defdecode))
15652 second (or (nth 0 tl) 0)
15653 wday (nth 6 tl))
15655 (when (and (eq org-read-date-prefer-future 'time)
15656 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15657 (equal day (nth 3 nowdecode))
15658 (equal month (nth 4 nowdecode))
15659 (equal year (nth 5 nowdecode))
15660 (nth 2 tl)
15661 (or (< (nth 2 tl) (nth 2 nowdecode))
15662 (and (= (nth 2 tl) (nth 2 nowdecode))
15663 (nth 1 tl)
15664 (< (nth 1 tl) (nth 1 nowdecode)))))
15665 (setq day (1+ day)
15666 futurep t))
15668 ;; Special date definitions below
15669 (cond
15670 (iso-week
15671 ;; There was an iso week
15672 (require 'cal-iso)
15673 (setq futurep nil)
15674 (setq year (or iso-year year)
15675 day (or iso-weekday wday 1)
15676 wday nil ; to make sure that the trigger below does not match
15677 iso-date (calendar-gregorian-from-absolute
15678 (calendar-absolute-from-iso
15679 (list iso-week day year))))
15680 ; FIXME: Should we also push ISO weeks into the future?
15681 ; (when (and org-read-date-prefer-future
15682 ; (not iso-year)
15683 ; (< (calendar-absolute-from-gregorian iso-date)
15684 ; (time-to-days (current-time))))
15685 ; (setq year (1+ year)
15686 ; iso-date (calendar-gregorian-from-absolute
15687 ; (calendar-absolute-from-iso
15688 ; (list iso-week day year)))))
15689 (setq month (car iso-date)
15690 year (nth 2 iso-date)
15691 day (nth 1 iso-date)))
15692 (deltan
15693 (setq futurep nil)
15694 (unless deltadef
15695 (let ((now (decode-time (current-time))))
15696 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15697 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15698 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15699 ((equal deltaw "m") (setq month (+ month deltan)))
15700 ((equal deltaw "y") (setq year (+ year deltan)))))
15701 ((and wday (not (nth 3 tl)))
15702 ;; Weekday was given, but no day, so pick that day in the week
15703 ;; on or after the derived date.
15704 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15705 (unless (equal wday wday1)
15706 (setq day (+ day (% (- wday wday1 -7) 7))))))
15707 (if (and (boundp 'org-time-was-given)
15708 (nth 2 tl))
15709 (setq org-time-was-given t))
15710 (if (< year 100) (setq year (+ 2000 year)))
15711 ;; Check of the date is representable
15712 (if org-read-date-force-compatible-dates
15713 (progn
15714 (if (< year 1970)
15715 (setq year 1970 org-read-date-analyze-forced-year t))
15716 (if (> year 2037)
15717 (setq year 2037 org-read-date-analyze-forced-year t)))
15718 (condition-case nil
15719 (ignore (encode-time second minute hour day month year))
15720 (error
15721 (setq year (nth 5 org-defdecode))
15722 (setq org-read-date-analyze-forced-year t))))
15723 (setq org-read-date-analyze-futurep futurep)
15724 (list second minute hour day month year)))
15726 (defvar parse-time-weekdays)
15727 (defun org-read-date-get-relative (s today default)
15728 "Check string S for special relative date string.
15729 TODAY and DEFAULT are internal times, for today and for a default.
15730 Return shift list (N what def-flag)
15731 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15732 N is the number of WHATs to shift.
15733 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15734 the DEFAULT date rather than TODAY."
15735 (require 'parse-time)
15736 (when (and
15737 (string-match
15738 (concat
15739 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15740 "\\([0-9]+\\)?"
15741 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15742 "\\([ \t]\\|$\\)") s)
15743 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15744 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15745 (string-to-char (substring (match-string 1 s) -1))
15746 ?+))
15747 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15748 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15749 (what (if (match-end 3) (match-string 3 s) "d"))
15750 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15751 (date (if rel default today))
15752 (wday (nth 6 (decode-time date)))
15753 delta)
15754 (if wday1
15755 (progn
15756 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15757 (if (= dir ?-) (setq delta (- delta 7)))
15758 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15759 (list delta "d" rel))
15760 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15762 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15763 "Turn a user-specified date into the internal representation.
15764 The internal representation needed by the calendar is (month day year).
15765 This is a wrapper to handle the brain-dead convention in calendar that
15766 user function argument order change dependent on argument order."
15767 (if (boundp 'calendar-date-style)
15768 (cond
15769 ((eq calendar-date-style 'american)
15770 (list arg1 arg2 arg3))
15771 ((eq calendar-date-style 'european)
15772 (list arg2 arg1 arg3))
15773 ((eq calendar-date-style 'iso)
15774 (list arg2 arg3 arg1)))
15775 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15776 (if (org-bound-and-true-p european-calendar-style)
15777 (list arg2 arg1 arg3)
15778 (list arg1 arg2 arg3)))))
15780 (defun org-eval-in-calendar (form &optional keepdate)
15781 "Eval FORM in the calendar window and return to current window.
15782 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15783 otherwise stick to the current value of `org-ans2'."
15784 (let ((sf (selected-frame))
15785 (sw (selected-window)))
15786 (select-window (get-buffer-window "*Calendar*" t))
15787 (eval form)
15788 (when (and (not keepdate) (calendar-cursor-to-date))
15789 (let* ((date (calendar-cursor-to-date))
15790 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15791 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15792 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15793 (select-window sw)
15794 (org-select-frame-set-input-focus sf)))
15796 (defun org-calendar-select ()
15797 "Return to `org-read-date' with the date currently selected.
15798 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15799 (interactive)
15800 (when (calendar-cursor-to-date)
15801 (let* ((date (calendar-cursor-to-date))
15802 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15803 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15804 (if (active-minibuffer-window) (exit-minibuffer))))
15806 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15807 "Insert a date stamp for the date given by the internal TIME.
15808 WITH-HM means use the stamp format that includes the time of the day.
15809 INACTIVE means use square brackets instead of angular ones, so that the
15810 stamp will not contribute to the agenda.
15811 PRE and POST are optional strings to be inserted before and after the
15812 stamp.
15813 The command returns the inserted time stamp."
15814 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15815 stamp)
15816 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15817 (insert-before-markers (or pre ""))
15818 (when (listp extra)
15819 (setq extra (car extra))
15820 (if (and (stringp extra)
15821 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15822 (setq extra (format "-%02d:%02d"
15823 (string-to-number (match-string 1 extra))
15824 (string-to-number (match-string 2 extra))))
15825 (setq extra nil)))
15826 (when extra
15827 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15828 (insert-before-markers (setq stamp (format-time-string fmt time)))
15829 (insert-before-markers (or post ""))
15830 (setq org-last-inserted-timestamp stamp)))
15832 (defun org-toggle-time-stamp-overlays ()
15833 "Toggle the use of custom time stamp formats."
15834 (interactive)
15835 (setq org-display-custom-times (not org-display-custom-times))
15836 (unless org-display-custom-times
15837 (let ((p (point-min)) (bmp (buffer-modified-p)))
15838 (while (setq p (next-single-property-change p 'display))
15839 (if (and (get-text-property p 'display)
15840 (eq (get-text-property p 'face) 'org-date))
15841 (remove-text-properties
15842 p (setq p (next-single-property-change p 'display))
15843 '(display t))))
15844 (set-buffer-modified-p bmp)))
15845 (if (featurep 'xemacs)
15846 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15847 (org-restart-font-lock)
15848 (setq org-table-may-need-update t)
15849 (if org-display-custom-times
15850 (message "Time stamps are overlaid with custom format")
15851 (message "Time stamp overlays removed")))
15853 (defun org-display-custom-time (beg end)
15854 "Overlay modified time stamp format over timestamp between BEG and END."
15855 (let* ((ts (buffer-substring beg end))
15856 t1 w1 with-hm tf time str w2 (off 0))
15857 (save-match-data
15858 (setq t1 (org-parse-time-string ts t))
15859 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15860 (setq off (- (match-end 0) (match-beginning 0)))))
15861 (setq end (- end off))
15862 (setq w1 (- end beg)
15863 with-hm (and (nth 1 t1) (nth 2 t1))
15864 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15865 time (org-fix-decoded-time t1)
15866 str (org-add-props
15867 (format-time-string
15868 (substring tf 1 -1) (apply 'encode-time time))
15869 nil 'mouse-face 'highlight)
15870 w2 (length str))
15871 (if (not (= w2 w1))
15872 (add-text-properties (1+ beg) (+ 2 beg)
15873 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15874 (if (featurep 'xemacs)
15875 (progn
15876 (put-text-property beg end 'invisible t)
15877 (put-text-property beg end 'end-glyph (make-glyph str)))
15878 (put-text-property beg end 'display str))))
15880 (defun org-translate-time (string)
15881 "Translate all timestamps in STRING to custom format.
15882 But do this only if the variable `org-display-custom-times' is set."
15883 (when org-display-custom-times
15884 (save-match-data
15885 (let* ((start 0)
15886 (re org-ts-regexp-both)
15887 t1 with-hm inactive tf time str beg end)
15888 (while (setq start (string-match re string start))
15889 (setq beg (match-beginning 0)
15890 end (match-end 0)
15891 t1 (save-match-data
15892 (org-parse-time-string (substring string beg end) t))
15893 with-hm (and (nth 1 t1) (nth 2 t1))
15894 inactive (equal (substring string beg (1+ beg)) "[")
15895 tf (funcall (if with-hm 'cdr 'car)
15896 org-time-stamp-custom-formats)
15897 time (org-fix-decoded-time t1)
15898 str (format-time-string
15899 (concat
15900 (if inactive "[" "<") (substring tf 1 -1)
15901 (if inactive "]" ">"))
15902 (apply 'encode-time time))
15903 string (replace-match str t t string)
15904 start (+ start (length str)))))))
15905 string)
15907 (defun org-fix-decoded-time (time)
15908 "Set 0 instead of nil for the first 6 elements of time.
15909 Don't touch the rest."
15910 (let ((n 0))
15911 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15913 (defun org-days-to-time (timestamp-string)
15914 "Difference between TIMESTAMP-STRING and now in days."
15915 (- (time-to-days (org-time-string-to-time timestamp-string))
15916 (time-to-days (current-time))))
15918 (defun org-deadline-close (timestamp-string &optional ndays)
15919 "Is the time in TIMESTAMP-STRING close to the current date?"
15920 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15921 (and (< (org-days-to-time timestamp-string) ndays)
15922 (not (org-entry-is-done-p))))
15924 (defun org-get-wdays (ts)
15925 "Get the deadline lead time appropriate for timestring TS."
15926 (cond
15927 ((<= org-deadline-warning-days 0)
15928 ;; 0 or negative, enforce this value no matter what
15929 (- org-deadline-warning-days))
15930 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15931 ;; lead time is specified.
15932 (floor (* (string-to-number (match-string 1 ts))
15933 (cdr (assoc (match-string 2 ts)
15934 '(("d" . 1) ("w" . 7)
15935 ("m" . 30.4) ("y" . 365.25)
15936 ("h" . 0.041667)))))))
15937 ;; go for the default.
15938 (t org-deadline-warning-days)))
15940 (defun org-calendar-select-mouse (ev)
15941 "Return to `org-read-date' with the date currently selected.
15942 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15943 (interactive "e")
15944 (mouse-set-point ev)
15945 (when (calendar-cursor-to-date)
15946 (let* ((date (calendar-cursor-to-date))
15947 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15948 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15949 (if (active-minibuffer-window) (exit-minibuffer))))
15951 (defun org-check-deadlines (ndays)
15952 "Check if there are any deadlines due or past due.
15953 A deadline is considered due if it happens within `org-deadline-warning-days'
15954 days from today's date. If the deadline appears in an entry marked DONE,
15955 it is not shown. The prefix arg NDAYS can be used to test that many
15956 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15957 (interactive "P")
15958 (let* ((org-warn-days
15959 (cond
15960 ((equal ndays '(4)) 100000)
15961 (ndays (prefix-numeric-value ndays))
15962 (t (abs org-deadline-warning-days))))
15963 (case-fold-search nil)
15964 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15965 (callback
15966 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15968 (message "%d deadlines past-due or due within %d days"
15969 (org-occur regexp nil callback)
15970 org-warn-days)))
15972 (defsubst org-re-timestamp (type)
15973 "Return a regexp for timestamp TYPE.
15974 Allowed values for TYPE are:
15976 all: all timestamps
15977 active: only active timestamps (<...>)
15978 inactive: only inactive timestamps ([...])
15979 scheduled: only scheduled timestamps
15980 deadline: only deadline timestamps
15982 When TYPE is nil, fall back on returning a regexp that matches
15983 both scheduled and deadline timestamps."
15984 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15985 ((eq type 'active) org-ts-regexp)
15986 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15987 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15988 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15989 ((eq type 'scheduled-or-deadline)
15990 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15992 (defun org-check-before-date (date)
15993 "Check if there are deadlines or scheduled entries before 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 () (time-less-p
15999 (org-time-string-to-time (match-string 1))
16000 (org-time-string-to-time date)))))
16001 (message "%d entries before %s"
16002 (org-occur regexp nil callback) date)))
16004 (defun org-check-after-date (date)
16005 "Check if there are deadlines or scheduled entries after DATE."
16006 (interactive (list (org-read-date)))
16007 (let ((case-fold-search nil)
16008 (regexp (org-re-timestamp org-ts-type))
16009 (callback
16010 (lambda () (not
16011 (time-less-p
16012 (org-time-string-to-time (match-string 1))
16013 (org-time-string-to-time date))))))
16014 (message "%d entries after %s"
16015 (org-occur regexp nil callback) date)))
16017 (defun org-check-dates-range (start-date end-date)
16018 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16019 (interactive (list (org-read-date nil nil nil "Range starts")
16020 (org-read-date nil nil nil "Range end")))
16021 (let ((case-fold-search nil)
16022 (regexp (org-re-timestamp org-ts-type))
16023 (callback
16024 (lambda ()
16025 (let ((match (match-string 1)))
16026 (and
16027 (not (time-less-p
16028 (org-time-string-to-time match)
16029 (org-time-string-to-time start-date)))
16030 (time-less-p
16031 (org-time-string-to-time match)
16032 (org-time-string-to-time end-date)))))))
16033 (message "%d entries between %s and %s"
16034 (org-occur regexp nil callback) start-date end-date)))
16036 (defun org-evaluate-time-range (&optional to-buffer)
16037 "Evaluate a time range by computing the difference between start and end.
16038 Normally the result is just printed in the echo area, but with prefix arg
16039 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16040 If the time range is actually in a table, the result is inserted into the
16041 next column.
16042 For time difference computation, a year is assumed to be exactly 365
16043 days in order to avoid rounding problems."
16044 (interactive "P")
16046 (org-clock-update-time-maybe)
16047 (save-excursion
16048 (unless (org-at-date-range-p t)
16049 (goto-char (point-at-bol))
16050 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16051 (if (not (org-at-date-range-p t))
16052 (error "Not at a time-stamp range, and none found in current line")))
16053 (let* ((ts1 (match-string 1))
16054 (ts2 (match-string 2))
16055 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16056 (match-end (match-end 0))
16057 (time1 (org-time-string-to-time ts1))
16058 (time2 (org-time-string-to-time ts2))
16059 (t1 (org-float-time time1))
16060 (t2 (org-float-time time2))
16061 (diff (abs (- t2 t1)))
16062 (negative (< (- t2 t1) 0))
16063 ;; (ys (floor (* 365 24 60 60)))
16064 (ds (* 24 60 60))
16065 (hs (* 60 60))
16066 (fy "%dy %dd %02d:%02d")
16067 (fy1 "%dy %dd")
16068 (fd "%dd %02d:%02d")
16069 (fd1 "%dd")
16070 (fh "%02d:%02d")
16071 y d h m align)
16072 (if havetime
16073 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16075 d (floor (/ diff ds)) diff (mod diff ds)
16076 h (floor (/ diff hs)) diff (mod diff hs)
16077 m (floor (/ diff 60)))
16078 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16080 d (floor (+ (/ diff ds) 0.5))
16081 h 0 m 0))
16082 (if (not to-buffer)
16083 (message "%s" (org-make-tdiff-string y d h m))
16084 (if (org-at-table-p)
16085 (progn
16086 (goto-char match-end)
16087 (setq align t)
16088 (and (looking-at " *|") (goto-char (match-end 0))))
16089 (goto-char match-end))
16090 (if (looking-at
16091 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16092 (replace-match ""))
16093 (if negative (insert " -"))
16094 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16095 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16096 (insert " " (format fh h m))))
16097 (if align (org-table-align))
16098 (message "Time difference inserted")))))
16100 (defun org-make-tdiff-string (y d h m)
16101 (let ((fmt "")
16102 (l nil))
16103 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16104 l (push y l)))
16105 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16106 l (push d l)))
16107 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16108 l (push h l)))
16109 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16110 l (push m l)))
16111 (apply 'format fmt (nreverse l))))
16113 (defun org-time-string-to-time (s &optional buffer pos)
16114 "Convert a timestamp string into internal time."
16115 (condition-case errdata
16116 (apply 'encode-time (org-parse-time-string s))
16117 (error (error "Bad timestamp `%s'%s\nError was: %s"
16118 s (if (not (and buffer pos))
16120 (format " at %d in buffer `%s'" pos buffer))
16121 (cdr errdata)))))
16123 (defun org-time-string-to-seconds (s)
16124 "Convert a timestamp string to a number of seconds."
16125 (org-float-time (org-time-string-to-time s)))
16127 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16128 "Convert a time stamp to an absolute day number.
16129 If there is a specifier for a cyclic time stamp, get the closest date to
16130 DAYNR.
16131 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16132 The variable date is bound by the calendar when this is called."
16133 (cond
16134 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16135 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16136 daynr
16137 (+ daynr 1000)))
16138 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16139 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16140 (time-to-days (current-time))) (match-string 0 s)
16141 prefer show-all))
16142 (t (time-to-days
16143 (condition-case errdata
16144 (apply 'encode-time (org-parse-time-string s))
16145 (error (error "Bad timestamp `%s'%s\nError was: %s"
16146 s (if (not (and buffer pos))
16148 (format " at %d in buffer `%s'" pos buffer))
16149 (cdr errdata))))))))
16151 (defun org-days-to-iso-week (days)
16152 "Return the iso week number."
16153 (require 'cal-iso)
16154 (car (calendar-iso-from-absolute days)))
16156 (defun org-small-year-to-year (year)
16157 "Convert 2-digit years into 4-digit years.
16158 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16159 The year 2000 cannot be abbreviated. Any year larger than 99
16160 is returned unchanged."
16161 (if (< year 38)
16162 (setq year (+ 2000 year))
16163 (if (< year 100)
16164 (setq year (+ 1900 year))))
16165 year)
16167 (defun org-time-from-absolute (d)
16168 "Return the time corresponding to date D.
16169 D may be an absolute day number, or a calendar-type list (month day year)."
16170 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16171 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16173 (defun org-calendar-holiday ()
16174 "List of holidays, for Diary display in Org-mode."
16175 (require 'holidays)
16176 (let ((hl (funcall
16177 (if (fboundp 'calendar-check-holidays)
16178 'calendar-check-holidays 'check-calendar-holidays) date)))
16179 (if hl (mapconcat 'identity hl "; "))))
16181 (defun org-diary-sexp-entry (sexp entry date)
16182 "Process a SEXP diary ENTRY for DATE."
16183 (require 'diary-lib)
16184 (let ((result (if calendar-debug-sexp
16185 (let ((stack-trace-on-error t))
16186 (eval (car (read-from-string sexp))))
16187 (condition-case nil
16188 (eval (car (read-from-string sexp)))
16189 (error
16190 (beep)
16191 (message "Bad sexp at line %d in %s: %s"
16192 (org-current-line)
16193 (buffer-file-name) sexp)
16194 (sleep-for 2))))))
16195 (cond ((stringp result) (split-string result "; "))
16196 ((and (consp result)
16197 (not (consp (cdr result)))
16198 (stringp (cdr result))) (cdr result))
16199 ((and (consp result)
16200 (stringp (car result))) result)
16201 (result entry))))
16203 (defun org-diary-to-ical-string (frombuf)
16204 "Get iCalendar entries from diary entries in buffer FROMBUF.
16205 This uses the icalendar.el library."
16206 (let* ((tmpdir (if (featurep 'xemacs)
16207 (temp-directory)
16208 temporary-file-directory))
16209 (tmpfile (make-temp-name
16210 (expand-file-name "orgics" tmpdir)))
16211 buf rtn b e)
16212 (with-current-buffer frombuf
16213 (icalendar-export-region (point-min) (point-max) tmpfile)
16214 (setq buf (find-buffer-visiting tmpfile))
16215 (set-buffer buf)
16216 (goto-char (point-min))
16217 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16218 (setq b (match-beginning 0)))
16219 (goto-char (point-max))
16220 (if (re-search-backward "^END:VEVENT" nil t)
16221 (setq e (match-end 0)))
16222 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16223 (kill-buffer buf)
16224 (delete-file tmpfile)
16225 rtn))
16227 (defun org-closest-date (start current change prefer show-all)
16228 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16229 When PREFER is `past', return a date that is either CURRENT or past.
16230 When PREFER is `future', return a date that is either CURRENT or future.
16231 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16232 ;; Make the proper lists from the dates
16233 (catch 'exit
16234 (let ((a1 '(("h" . hour)
16235 ("d" . day)
16236 ("w" . week)
16237 ("m" . month)
16238 ("y" . year)))
16239 (shour (nth 2 (org-parse-time-string start)))
16240 dn dw sday cday n1 n2 n0
16241 d m y y1 y2 date1 date2 nmonths nm ny m2)
16243 (setq start (org-date-to-gregorian start)
16244 current (org-date-to-gregorian
16245 (if show-all
16246 current
16247 (time-to-days (current-time))))
16248 sday (calendar-absolute-from-gregorian start)
16249 cday (calendar-absolute-from-gregorian current))
16251 (if (<= cday sday) (throw 'exit sday))
16253 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16254 (setq dn (string-to-number (match-string 1 change))
16255 dw (cdr (assoc (match-string 2 change) a1)))
16256 (error "Invalid change specifier: %s" change))
16257 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16258 (cond
16259 ((eq dw 'hour)
16260 (let ((missing-hours
16261 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16262 dn)))
16263 (setq n1 (if (zerop missing-hours) cday
16264 (- cday (1+ (floor (/ missing-hours 24)))))
16265 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16266 ((eq dw 'day)
16267 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16268 n2 (+ n1 dn)))
16269 ((eq dw 'year)
16270 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16271 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16272 (setq date1 (list m d y1)
16273 n1 (calendar-absolute-from-gregorian date1)
16274 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16275 n2 (calendar-absolute-from-gregorian date2)))
16276 ((eq dw 'month)
16277 ;; approx number of month between the two dates
16278 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16279 ;; How often does dn fit in there?
16280 (setq d (nth 1 start) m (car start) y (nth 2 start)
16281 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16282 m (+ m nm)
16283 ny (floor (/ m 12))
16284 y (+ y ny)
16285 m (- m (* ny 12)))
16286 (while (> m 12) (setq m (- m 12) y (1+ y)))
16287 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16288 (setq m2 (+ m dn) y2 y)
16289 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16290 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16291 (while (<= n2 cday)
16292 (setq n1 n2 m m2 y y2)
16293 (setq m2 (+ m dn) y2 y)
16294 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16295 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16296 ;; Make sure n1 is the earlier date
16297 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16298 (if show-all
16299 (cond
16300 ((eq prefer 'past) (if (= cday n2) n2 n1))
16301 ((eq prefer 'future) (if (= cday n1) n1 n2))
16302 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16303 (cond
16304 ((eq prefer 'past) (if (= cday n2) n2 n1))
16305 ((eq prefer 'future) (if (= cday n1) n1 n2))
16306 (t (if (= cday n1) n1 n2)))))))
16308 (defun org-date-to-gregorian (date)
16309 "Turn any specification of DATE into a Gregorian date for the calendar."
16310 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16311 ((and (listp date) (= (length date) 3)) date)
16312 ((stringp date)
16313 (setq date (org-parse-time-string date))
16314 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16315 ((listp date)
16316 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16318 (defun org-parse-time-string (s &optional nodefault)
16319 "Parse the standard Org-mode time string.
16320 This should be a lot faster than the normal `parse-time-string'.
16321 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16322 hour and minute fields will be nil if not given."
16323 (if (string-match org-ts-regexp0 s)
16324 (list 0
16325 (if (or (match-beginning 8) (not nodefault))
16326 (string-to-number (or (match-string 8 s) "0")))
16327 (if (or (match-beginning 7) (not nodefault))
16328 (string-to-number (or (match-string 7 s) "0")))
16329 (string-to-number (match-string 4 s))
16330 (string-to-number (match-string 3 s))
16331 (string-to-number (match-string 2 s))
16332 nil nil nil)
16333 (error "Not a standard Org-mode time string: %s" s)))
16335 (defun org-timestamp-up (&optional arg)
16336 "Increase the date item at the cursor by one.
16337 If the cursor is on the year, change the year. If it is on the month,
16338 the day or the time, change that.
16339 With prefix ARG, change by that many units."
16340 (interactive "p")
16341 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16343 (defun org-timestamp-down (&optional arg)
16344 "Decrease the date item at the cursor by one.
16345 If the cursor is on the year, change the year. If it is on the month,
16346 the day or the time, change that.
16347 With prefix ARG, change by that many units."
16348 (interactive "p")
16349 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16351 (defun org-timestamp-up-day (&optional arg)
16352 "Increase the date in the time stamp by one day.
16353 With prefix ARG, change that many days."
16354 (interactive "p")
16355 (if (and (not (org-at-timestamp-p t))
16356 (org-at-heading-p))
16357 (org-todo 'up)
16358 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16360 (defun org-timestamp-down-day (&optional arg)
16361 "Decrease the date in the time stamp by one day.
16362 With prefix ARG, change that many days."
16363 (interactive "p")
16364 (if (and (not (org-at-timestamp-p t))
16365 (org-at-heading-p))
16366 (org-todo 'down)
16367 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16369 (defun org-at-timestamp-p (&optional inactive-ok)
16370 "Determine if the cursor is in or at a timestamp."
16371 (interactive)
16372 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16373 (pos (point))
16374 (ans (or (looking-at tsr)
16375 (save-excursion
16376 (skip-chars-backward "^[<\n\r\t")
16377 (if (> (point) (point-min)) (backward-char 1))
16378 (and (looking-at tsr)
16379 (> (- (match-end 0) pos) -1))))))
16380 (and ans
16381 (boundp 'org-ts-what)
16382 (setq org-ts-what
16383 (cond
16384 ((= pos (match-beginning 0)) 'bracket)
16385 ;; Point is considered to be "on the bracket" whether
16386 ;; it's really on it or right after it.
16387 ((= pos (1- (match-end 0))) 'bracket)
16388 ((= pos (match-end 0)) 'after)
16389 ((org-pos-in-match-range pos 2) 'year)
16390 ((org-pos-in-match-range pos 3) 'month)
16391 ((org-pos-in-match-range pos 7) 'hour)
16392 ((org-pos-in-match-range pos 8) 'minute)
16393 ((or (org-pos-in-match-range pos 4)
16394 (org-pos-in-match-range pos 5)) 'day)
16395 ((and (> pos (or (match-end 8) (match-end 5)))
16396 (< pos (match-end 0)))
16397 (- pos (or (match-end 8) (match-end 5))))
16398 (t 'day))))
16399 ans))
16401 (defun org-toggle-timestamp-type ()
16402 "Toggle the type (<active> or [inactive]) of a time stamp."
16403 (interactive)
16404 (when (org-at-timestamp-p t)
16405 (let ((beg (match-beginning 0)) (end (match-end 0))
16406 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16407 (save-excursion
16408 (goto-char beg)
16409 (while (re-search-forward "[][<>]" end t)
16410 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16411 t t)))
16412 (message "Timestamp is now %sactive"
16413 (if (equal (char-after beg) ?<) "" "in")))))
16415 (defun org-at-clock-log-p nil
16416 "Is the cursor on the clock log line?"
16417 (save-excursion
16418 (move-beginning-of-line 1)
16419 (looking-at "^[ \t]*CLOCK:")))
16421 (defvar org-clock-history) ; defined in org-clock.el
16422 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16423 (defun org-timestamp-change (n &optional what updown)
16424 "Change the date in the time stamp at point.
16425 The date will be changed by N times WHAT. WHAT can be `day', `month',
16426 `year', `minute', `second'. If WHAT is not given, the cursor position
16427 in the timestamp determines what will be changed."
16428 (let ((origin (point)) origin-cat
16429 with-hm inactive
16430 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16431 org-ts-what
16432 extra rem
16433 ts time time0 fixnext clrgx)
16434 (if (not (org-at-timestamp-p t))
16435 (error "Not at a timestamp"))
16436 (if (and (not what) (eq org-ts-what 'bracket))
16437 (org-toggle-timestamp-type)
16438 ;; Point isn't on brackets. Remember the part of the time-stamp
16439 ;; the point was in. Indeed, size of time-stamps may change,
16440 ;; but point must be kept in the same category nonetheless.
16441 (setq origin-cat org-ts-what)
16442 (if (and (not what) (not (eq org-ts-what 'day))
16443 org-display-custom-times
16444 (get-text-property (point) 'display)
16445 (not (get-text-property (1- (point)) 'display)))
16446 (setq org-ts-what 'day))
16447 (setq org-ts-what (or what org-ts-what)
16448 inactive (= (char-after (match-beginning 0)) ?\[)
16449 ts (match-string 0))
16450 (replace-match "")
16451 (if (string-match
16452 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16454 (setq extra (match-string 1 ts)))
16455 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16456 (setq with-hm t))
16457 (setq time0 (org-parse-time-string ts))
16458 (when (and updown
16459 (eq org-ts-what 'minute)
16460 (not current-prefix-arg))
16461 ;; This looks like s-up and s-down. Change by one rounding step.
16462 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16463 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16464 (setcar (cdr time0) (+ (nth 1 time0)
16465 (if (> n 0) (- rem) (- dm rem))))))
16466 (setq time
16467 (encode-time (or (car time0) 0)
16468 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16469 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16470 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16471 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16472 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16473 (nthcdr 6 time0)))
16474 (when (and (member org-ts-what '(hour minute))
16475 extra
16476 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16477 (setq extra (org-modify-ts-extra
16478 extra
16479 (if (eq org-ts-what 'hour) 2 5)
16480 n dm)))
16481 (when (integerp org-ts-what)
16482 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16483 (if (eq what 'calendar)
16484 (let ((cal-date (org-get-date-from-calendar)))
16485 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16486 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16487 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16488 (setcar time0 (or (car time0) 0))
16489 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16490 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16491 (setq time (apply 'encode-time time0))))
16492 ;; Insert the new time-stamp, and ensure point stays in the same
16493 ;; category as before (i.e. not after the last position in that
16494 ;; category).
16495 (let ((pos (point)))
16496 ;; Stay before inserted string. `save-excursion' is of no use.
16497 (setq org-last-changed-timestamp
16498 (org-insert-time-stamp time with-hm inactive nil nil extra))
16499 (goto-char pos))
16500 (save-match-data
16501 (looking-at org-ts-regexp3)
16502 (goto-char (cond
16503 ;; `day' category ends before `hour' if any, or at
16504 ;; the end of the day name.
16505 ((eq origin-cat 'day)
16506 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16507 ((eq origin-cat 'hour) (min (match-end 7) origin))
16508 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16509 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16510 ;; `year' and `month' have both fixed size: point
16511 ;; couldn't have moved into another part.
16512 (t origin))))
16513 ;; Update clock if on a CLOCK line.
16514 (org-clock-update-time-maybe)
16515 ;; Maybe adjust the closest clock in `org-clock-history'
16516 (when org-clock-adjust-closest
16517 (if (not (and (org-at-clock-log-p)
16518 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16519 org-clock-history))))))
16520 (message "No clock to adjust")
16521 (cond ((save-excursion ; fix previous clock?
16522 (re-search-backward org-ts-regexp0 nil t)
16523 (org-looking-back (concat org-clock-string " \\[")))
16524 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16525 ((save-excursion ; fix next clock?
16526 (re-search-backward org-ts-regexp0 nil t)
16527 (looking-at (concat org-ts-regexp0 "\\] =>")))
16528 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16529 (save-window-excursion
16530 ;; Find closest clock to point, adjust the previous/next one in history
16531 (let* ((p (save-excursion (org-back-to-heading t)))
16532 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16533 (clfixnth
16534 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16535 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16536 (if (not clfixpos)
16537 (message "No clock to adjust")
16538 (save-excursion
16539 (org-goto-marker-or-bmk clfixpos)
16540 (org-show-subtree)
16541 (when (re-search-forward clrgx nil t)
16542 (goto-char (match-beginning 1))
16543 (let (org-clock-adjust-closest)
16544 (org-timestamp-change n org-ts-what updown))
16545 (message "Clock adjusted in %s for heading: %s"
16546 (file-name-nondirectory (buffer-file-name))
16547 (org-get-heading t t)))))))))
16548 ;; Try to recenter the calendar window, if any.
16549 (if (and org-calendar-follow-timestamp-change
16550 (get-buffer-window "*Calendar*" t)
16551 (memq org-ts-what '(day month year)))
16552 (org-recenter-calendar (time-to-days time))))))
16554 (defun org-modify-ts-extra (s pos n dm)
16555 "Change the different parts of the lead-time and repeat fields in timestamp."
16556 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16557 ng h m new rem)
16558 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16559 (cond
16560 ((or (org-pos-in-match-range pos 2)
16561 (org-pos-in-match-range pos 3))
16562 (setq m (string-to-number (match-string 3 s))
16563 h (string-to-number (match-string 2 s)))
16564 (if (org-pos-in-match-range pos 2)
16565 (setq h (+ h n))
16566 (setq n (* dm (org-no-warnings (signum n))))
16567 (when (not (= 0 (setq rem (% m dm))))
16568 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16569 (setq m (+ m n)))
16570 (if (< m 0) (setq m (+ m 60) h (1- h)))
16571 (if (> m 59) (setq m (- m 60) h (1+ h)))
16572 (setq h (min 24 (max 0 h)))
16573 (setq ng 1 new (format "-%02d:%02d" h m)))
16574 ((org-pos-in-match-range pos 6)
16575 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16576 ((org-pos-in-match-range pos 5)
16577 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16579 ((org-pos-in-match-range pos 9)
16580 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16581 ((org-pos-in-match-range pos 8)
16582 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16584 (when ng
16585 (setq s (concat
16586 (substring s 0 (match-beginning ng))
16588 (substring s (match-end ng))))))
16591 (defun org-recenter-calendar (date)
16592 "If the calendar is visible, recenter it to DATE."
16593 (let ((cwin (get-buffer-window "*Calendar*" t)))
16594 (when cwin
16595 (let ((calendar-move-hook nil))
16596 (with-selected-window cwin
16597 (calendar-goto-date (if (listp date) date
16598 (calendar-gregorian-from-absolute date))))))))
16600 (defun org-goto-calendar (&optional arg)
16601 "Go to the Emacs calendar at the current date.
16602 If there is a time stamp in the current line, go to that date.
16603 A prefix ARG can be used to force the current date."
16604 (interactive "P")
16605 (let ((tsr org-ts-regexp) diff
16606 (calendar-move-hook nil)
16607 (calendar-view-holidays-initially-flag nil)
16608 (calendar-view-diary-initially-flag nil))
16609 (if (or (org-at-timestamp-p)
16610 (save-excursion
16611 (beginning-of-line 1)
16612 (looking-at (concat ".*" tsr))))
16613 (let ((d1 (time-to-days (current-time)))
16614 (d2 (time-to-days
16615 (org-time-string-to-time (match-string 1)))))
16616 (setq diff (- d2 d1))))
16617 (calendar)
16618 (calendar-goto-today)
16619 (if (and diff (not arg)) (calendar-forward-day diff))))
16621 (defun org-get-date-from-calendar ()
16622 "Return a list (month day year) of date at point in calendar."
16623 (with-current-buffer "*Calendar*"
16624 (save-match-data
16625 (calendar-cursor-to-date))))
16627 (defun org-date-from-calendar ()
16628 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16629 If there is already a time stamp at the cursor position, update it."
16630 (interactive)
16631 (if (org-at-timestamp-p t)
16632 (org-timestamp-change 0 'calendar)
16633 (let ((cal-date (org-get-date-from-calendar)))
16634 (org-insert-time-stamp
16635 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16637 (defun org-minutes-to-hh:mm-string (m)
16638 "Compute H:MM from a number of minutes."
16639 (let ((h (/ m 60)))
16640 (setq m (- m (* 60 h)))
16641 (format org-time-clocksum-format h m)))
16643 (defun org-hh:mm-string-to-minutes (s)
16644 "Convert a string H:MM to a number of minutes.
16645 If the string is just a number, interpret it as minutes.
16646 In fact, the first hh:mm or number in the string will be taken,
16647 there can be extra stuff in the string.
16648 If no number is found, the return value is 0."
16649 (cond
16650 ((integerp s) s)
16651 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16652 (+ (* (string-to-number (match-string 1 s)) 60)
16653 (string-to-number (match-string 2 s))))
16654 ((string-match "\\([0-9]+\\)" s)
16655 (string-to-number (match-string 1 s)))
16656 (t 0)))
16658 (defcustom org-effort-durations
16659 `(("h" . 60)
16660 ("d" . ,(* 60 8))
16661 ("w" . ,(* 60 8 5))
16662 ("m" . ,(* 60 8 5 4))
16663 ("y" . ,(* 60 8 5 40)))
16664 "Conversion factor to minutes for an effort modifier.
16666 Each entry has the form (MODIFIER . MINUTES).
16668 In an effort string, a number followed by MODIFIER is multiplied
16669 by the specified number of MINUTES to obtain an effort in
16670 minutes.
16672 For example, if the value of this variable is ((\"hours\" . 60)), then an
16673 effort string \"2hours\" is equivalent to 120 minutes."
16674 :group 'org-agenda
16675 :version "24.1"
16676 :type '(alist :key-type (string :tag "Modifier")
16677 :value-type (number :tag "Minutes")))
16679 (defcustom org-agenda-inhibit-startup t
16680 "Inhibit startup when preparing agenda buffers.
16681 When this variable is `t' (the default), the initialization of
16682 the Org agenda buffers is inhibited: e.g. the visibility state
16683 is not set, the tables are not re-aligned, etc."
16684 :type 'boolean
16685 :version "24.3"
16686 :group 'org-agenda)
16688 (defun org-duration-string-to-minutes (s &optional output-to-string)
16689 "Convert a duration string S to minutes.
16691 A bare number is interpreted as minutes, modifiers can be set by
16692 customizing `org-effort-durations' (which see).
16694 Entries containing a colon are interpreted as H:MM by
16695 `org-hh:mm-string-to-minutes'."
16696 (let ((result 0)
16697 (re (concat "\\([0-9.]+\\) *\\("
16698 (regexp-opt (mapcar 'car org-effort-durations))
16699 "\\)")))
16700 (while (string-match re s)
16701 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16702 (string-to-number (match-string 1 s))))
16703 (setq s (replace-match "" nil t s)))
16704 (setq result (floor result))
16705 (incf result (org-hh:mm-string-to-minutes s))
16706 (if output-to-string (number-to-string result) result)))
16708 ;;;; Files
16710 (defun org-save-all-org-buffers ()
16711 "Save all Org-mode buffers without user confirmation."
16712 (interactive)
16713 (message "Saving all Org-mode buffers...")
16714 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16715 (when (featurep 'org-id) (org-id-locations-save))
16716 (message "Saving all Org-mode buffers... done"))
16718 (defun org-revert-all-org-buffers ()
16719 "Revert all Org-mode buffers.
16720 Prompt for confirmation when there are unsaved changes.
16721 Be sure you know what you are doing before letting this function
16722 overwrite your changes.
16724 This function is useful in a setup where one tracks org files
16725 with a version control system, to revert on one machine after pulling
16726 changes from another. I believe the procedure must be like this:
16728 1. M-x org-save-all-org-buffers
16729 2. Pull changes from the other machine, resolve conflicts
16730 3. M-x org-revert-all-org-buffers"
16731 (interactive)
16732 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16733 (error "Abort"))
16734 (save-excursion
16735 (save-window-excursion
16736 (mapc
16737 (lambda (b)
16738 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16739 (with-current-buffer b buffer-file-name))
16740 (org-pop-to-buffer-same-window b)
16741 (revert-buffer t 'no-confirm)))
16742 (buffer-list))
16743 (when (and (featurep 'org-id) org-id-track-globally)
16744 (org-id-locations-load)))))
16746 ;;;; Agenda files
16748 ;;;###autoload
16749 (defun org-switchb (&optional arg)
16750 "Switch between Org buffers.
16751 With one prefix argument, restrict available buffers to files.
16752 With two prefix arguments, restrict available buffers to agenda files.
16754 Defaults to `iswitchb' for buffer name completion.
16755 Set `org-completion-use-ido' to make it use ido instead."
16756 (interactive "P")
16757 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16758 ((equal arg '(16)) (org-buffer-list 'agenda))
16759 (t (org-buffer-list))))
16760 (org-completion-use-iswitchb org-completion-use-iswitchb)
16761 (org-completion-use-ido org-completion-use-ido))
16762 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16763 (setq org-completion-use-iswitchb t))
16764 (org-pop-to-buffer-same-window
16765 (org-icompleting-read "Org buffer: "
16766 (mapcar 'list (mapcar 'buffer-name blist))
16767 nil t))))
16769 ;;; Define some older names previously used for this functionality
16770 ;;;###autoload
16771 (defalias 'org-ido-switchb 'org-switchb)
16772 ;;;###autoload
16773 (defalias 'org-iswitchb 'org-switchb)
16775 (defun org-buffer-list (&optional predicate exclude-tmp)
16776 "Return a list of Org buffers.
16777 PREDICATE can be `export', `files' or `agenda'.
16779 export restrict the list to Export buffers.
16780 files restrict the list to buffers visiting Org files.
16781 agenda restrict the list to buffers visiting agenda files.
16783 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16784 (let* ((bfn nil)
16785 (agenda-files (and (eq predicate 'agenda)
16786 (mapcar 'file-truename (org-agenda-files t))))
16787 (filter
16788 (cond
16789 ((eq predicate 'files)
16790 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16791 ((eq predicate 'export)
16792 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16793 ((eq predicate 'agenda)
16794 (lambda (b)
16795 (with-current-buffer b
16796 (and (derived-mode-p 'org-mode)
16797 (setq bfn (buffer-file-name b))
16798 (member (file-truename bfn) agenda-files)))))
16799 (t (lambda (b) (with-current-buffer b
16800 (or (derived-mode-p 'org-mode)
16801 (string-match "\*Org .*Export"
16802 (buffer-name b)))))))))
16803 (delq nil
16804 (mapcar
16805 (lambda(b)
16806 (if (and (funcall filter b)
16807 (or (not exclude-tmp)
16808 (not (string-match "tmp" (buffer-name b)))))
16810 nil))
16811 (buffer-list)))))
16813 (defun org-agenda-files (&optional unrestricted archives)
16814 "Get the list of agenda files.
16815 Optional UNRESTRICTED means return the full list even if a restriction
16816 is currently in place.
16817 When ARCHIVES is t, include all archive files that are really being
16818 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16819 `org-agenda-archives-mode' is t."
16820 (let ((files
16821 (cond
16822 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16823 ((stringp org-agenda-files) (org-read-agenda-file-list))
16824 ((listp org-agenda-files) org-agenda-files)
16825 (t (error "Invalid value of `org-agenda-files'")))))
16826 (setq files (apply 'append
16827 (mapcar (lambda (f)
16828 (if (file-directory-p f)
16829 (directory-files
16830 f t org-agenda-file-regexp)
16831 (list f)))
16832 files)))
16833 (when org-agenda-skip-unavailable-files
16834 (setq files (delq nil
16835 (mapcar (function
16836 (lambda (file)
16837 (and (file-readable-p file) file)))
16838 files))))
16839 (when (or (eq archives t)
16840 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16841 (setq files (org-add-archive-files files)))
16842 files))
16844 (defun org-agenda-file-p (&optional file)
16845 "Return non-nil, if FILE is an agenda file.
16846 If FILE is omitted, use the file associated with the current
16847 buffer."
16848 (member (or file (buffer-file-name))
16849 (org-agenda-files t)))
16851 (defun org-edit-agenda-file-list ()
16852 "Edit the list of agenda files.
16853 Depending on setup, this either uses customize to edit the variable
16854 `org-agenda-files', or it visits the file that is holding the list. In the
16855 latter case, the buffer is set up in a way that saving it automatically kills
16856 the buffer and restores the previous window configuration."
16857 (interactive)
16858 (if (stringp org-agenda-files)
16859 (let ((cw (current-window-configuration)))
16860 (find-file org-agenda-files)
16861 (org-set-local 'org-window-configuration cw)
16862 (org-add-hook 'after-save-hook
16863 (lambda ()
16864 (set-window-configuration
16865 (prog1 org-window-configuration
16866 (kill-buffer (current-buffer))))
16867 (org-install-agenda-files-menu)
16868 (message "New agenda file list installed"))
16869 nil 'local)
16870 (message "%s" (substitute-command-keys
16871 "Edit list and finish with \\[save-buffer]")))
16872 (customize-variable 'org-agenda-files)))
16874 (defun org-store-new-agenda-file-list (list)
16875 "Set new value for the agenda file list and save it correctly."
16876 (if (stringp org-agenda-files)
16877 (let ((fe (org-read-agenda-file-list t)) b u)
16878 (while (setq b (find-buffer-visiting org-agenda-files))
16879 (kill-buffer b))
16880 (with-temp-file org-agenda-files
16881 (insert
16882 (mapconcat
16883 (lambda (f) ;; Keep un-expanded entries.
16884 (if (setq u (assoc f fe))
16885 (cdr u)
16887 list "\n")
16888 "\n")))
16889 (let ((org-mode-hook nil) (org-inhibit-startup t)
16890 (org-insert-mode-line-in-empty-file nil))
16891 (setq org-agenda-files list)
16892 (customize-save-variable 'org-agenda-files org-agenda-files))))
16894 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16895 "Read the list of agenda files from a file.
16896 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16897 filenames, used by `org-store-new-agenda-file-list' to write back
16898 un-expanded file names."
16899 (when (file-directory-p org-agenda-files)
16900 (error "`org-agenda-files' cannot be a single directory"))
16901 (when (stringp org-agenda-files)
16902 (with-temp-buffer
16903 (insert-file-contents org-agenda-files)
16904 (mapcar
16905 (lambda (f)
16906 (let ((e (expand-file-name (substitute-in-file-name f)
16907 org-directory)))
16908 (if pair-with-expansion
16909 (cons e f)
16910 e)))
16911 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16913 ;;;###autoload
16914 (defun org-cycle-agenda-files ()
16915 "Cycle through the files in `org-agenda-files'.
16916 If the current buffer visits an agenda file, find the next one in the list.
16917 If the current buffer does not, find the first agenda file."
16918 (interactive)
16919 (let* ((fs (org-agenda-files t))
16920 (files (append fs (list (car fs))))
16921 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16922 file)
16923 (unless files (error "No agenda files"))
16924 (catch 'exit
16925 (while (setq file (pop files))
16926 (if (equal (file-truename file) tcf)
16927 (when (car files)
16928 (find-file (car files))
16929 (throw 'exit t))))
16930 (find-file (car fs)))
16931 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16933 (defun org-agenda-file-to-front (&optional to-end)
16934 "Move/add the current file to the top of the agenda file list.
16935 If the file is not present in the list, it is added to the front. If it is
16936 present, it is moved there. With optional argument TO-END, add/move to the
16937 end of the list."
16938 (interactive "P")
16939 (let ((org-agenda-skip-unavailable-files nil)
16940 (file-alist (mapcar (lambda (x)
16941 (cons (file-truename x) x))
16942 (org-agenda-files t)))
16943 (ctf (file-truename
16944 (or buffer-file-name
16945 (error "Please save the current buffer to a file"))))
16946 x had)
16947 (setq x (assoc ctf file-alist) had x)
16949 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16950 (if to-end
16951 (setq file-alist (append (delq x file-alist) (list x)))
16952 (setq file-alist (cons x (delq x file-alist))))
16953 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16954 (org-install-agenda-files-menu)
16955 (message "File %s to %s of agenda file list"
16956 (if had "moved" "added") (if to-end "end" "front"))))
16958 (defun org-remove-file (&optional file)
16959 "Remove current file from the list of files in variable `org-agenda-files'.
16960 These are the files which are being checked for agenda entries.
16961 Optional argument FILE means use this file instead of the current."
16962 (interactive)
16963 (let* ((org-agenda-skip-unavailable-files nil)
16964 (file (or file buffer-file-name
16965 (error "Current buffer does not visit a file")))
16966 (true-file (file-truename file))
16967 (afile (abbreviate-file-name file))
16968 (files (delq nil (mapcar
16969 (lambda (x)
16970 (if (equal true-file
16971 (file-truename x))
16972 nil x))
16973 (org-agenda-files t)))))
16974 (if (not (= (length files) (length (org-agenda-files t))))
16975 (progn
16976 (org-store-new-agenda-file-list files)
16977 (org-install-agenda-files-menu)
16978 (message "Removed file: %s" afile))
16979 (message "File was not in list: %s (not removed)" afile))))
16981 (defun org-file-menu-entry (file)
16982 (vector file (list 'find-file file) t))
16984 (defun org-check-agenda-file (file)
16985 "Make sure FILE exists. If not, ask user what to do."
16986 (when (not (file-exists-p file))
16987 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16988 (abbreviate-file-name file))
16989 (let ((r (downcase (read-char-exclusive))))
16990 (cond
16991 ((equal r ?r)
16992 (org-remove-file file)
16993 (throw 'nextfile t))
16994 (t (error "Abort"))))))
16996 (defun org-get-agenda-file-buffer (file)
16997 "Get a buffer visiting FILE. If the buffer needs to be created, add
16998 it to the list of buffers which might be released later."
16999 (let ((buf (org-find-base-buffer-visiting file)))
17000 (if buf
17001 buf ; just return it
17002 ;; Make a new buffer and remember it
17003 (setq buf (find-file-noselect file))
17004 (if buf (push buf org-agenda-new-buffers))
17005 buf)))
17007 (defun org-release-buffers (blist)
17008 "Release all buffers in list, asking the user for confirmation when needed.
17009 When a buffer is unmodified, it is just killed. When modified, it is saved
17010 \(if the user agrees) and then killed."
17011 (let (buf file)
17012 (while (setq buf (pop blist))
17013 (setq file (buffer-file-name buf))
17014 (when (and (buffer-modified-p buf)
17015 file
17016 (y-or-n-p (format "Save file %s? " file)))
17017 (with-current-buffer buf (save-buffer)))
17018 (kill-buffer buf))))
17020 (defun org-agenda-prepare-buffers (files)
17021 "Create buffers for all agenda files, protect archived trees and comments."
17022 (interactive)
17023 (let ((pa '(:org-archived t))
17024 (pc '(:org-comment t))
17025 (pall '(:org-archived t :org-comment t))
17026 (inhibit-read-only t)
17027 (org-inhibit-startup org-agenda-inhibit-startup)
17028 (rea (concat ":" org-archive-tag ":"))
17029 bmp file re)
17030 (save-excursion
17031 (save-restriction
17032 (while (setq file (pop files))
17033 (catch 'nextfile
17034 (if (bufferp file)
17035 (set-buffer file)
17036 (org-check-agenda-file file)
17037 (set-buffer (org-get-agenda-file-buffer file)))
17038 (widen)
17039 (setq bmp (buffer-modified-p))
17040 (org-refresh-category-properties)
17041 (org-refresh-properties org-effort-property 'org-effort)
17042 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17043 (setq org-todo-keywords-for-agenda
17044 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17045 (setq org-done-keywords-for-agenda
17046 (append org-done-keywords-for-agenda org-done-keywords))
17047 (setq org-todo-keyword-alist-for-agenda
17048 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17049 (setq org-drawers-for-agenda
17050 (append org-drawers-for-agenda org-drawers))
17051 (setq org-tag-alist-for-agenda
17052 (append org-tag-alist-for-agenda org-tag-alist))
17054 (save-excursion
17055 (remove-text-properties (point-min) (point-max) pall)
17056 (when org-agenda-skip-archived-trees
17057 (goto-char (point-min))
17058 (while (re-search-forward rea nil t)
17059 (if (org-at-heading-p t)
17060 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17061 (goto-char (point-min))
17062 (setq re (format org-heading-keyword-regexp-format
17063 org-comment-string))
17064 (while (re-search-forward re nil t)
17065 (add-text-properties
17066 (match-beginning 0) (org-end-of-subtree t) pc)))
17067 (set-buffer-modified-p bmp)))))
17068 (setq org-todo-keywords-for-agenda
17069 (org-uniquify org-todo-keywords-for-agenda))
17070 (setq org-todo-keyword-alist-for-agenda
17071 (org-uniquify org-todo-keyword-alist-for-agenda)
17072 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17074 ;;;; Embedded LaTeX
17076 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17077 "Keymap for the minor `org-cdlatex-mode'.")
17079 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17080 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17081 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17082 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17083 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17085 (defvar org-cdlatex-texmathp-advice-is-done nil
17086 "Flag remembering if we have applied the advice to texmathp already.")
17088 (define-minor-mode org-cdlatex-mode
17089 "Toggle the minor `org-cdlatex-mode'.
17090 This mode supports entering LaTeX environment and math in LaTeX fragments
17091 in Org-mode.
17092 \\{org-cdlatex-mode-map}"
17093 nil " OCDL" nil
17094 (when org-cdlatex-mode
17095 (require 'cdlatex)
17096 (run-hooks 'cdlatex-mode-hook)
17097 (cdlatex-compute-tables))
17098 (unless org-cdlatex-texmathp-advice-is-done
17099 (setq org-cdlatex-texmathp-advice-is-done t)
17100 (defadvice texmathp (around org-math-always-on activate)
17101 "Always return t in org-mode buffers.
17102 This is because we want to insert math symbols without dollars even outside
17103 the LaTeX math segments. If Orgmode thinks that point is actually inside
17104 an embedded LaTeX fragment, let texmathp do its job.
17105 \\[org-cdlatex-mode-map]"
17106 (interactive)
17107 (let (p)
17108 (cond
17109 ((not (derived-mode-p 'org-mode)) ad-do-it)
17110 ((eq this-command 'cdlatex-math-symbol)
17111 (setq ad-return-value t
17112 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17114 (let ((p (org-inside-LaTeX-fragment-p)))
17115 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17116 (setq ad-return-value t
17117 texmathp-why '("Org-mode embedded math" . 0))
17118 (if p ad-do-it)))))))))
17120 (defun turn-on-org-cdlatex ()
17121 "Unconditionally turn on `org-cdlatex-mode'."
17122 (org-cdlatex-mode 1))
17124 (defun org-inside-LaTeX-fragment-p ()
17125 "Test if point is inside a LaTeX fragment.
17126 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17127 sequence appearing also before point.
17128 Even though the matchers for math are configurable, this function assumes
17129 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17130 delimiters are skipped when they have been removed by customization.
17131 The return value is nil, or a cons cell with the delimiter and the
17132 position of this delimiter.
17134 This function does a reasonably good job, but can locally be fooled by
17135 for example currency specifications. For example it will assume being in
17136 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17137 fragments that are properly closed, but during editing, we have to live
17138 with the uncertainty caused by missing closing delimiters. This function
17139 looks only before point, not after."
17140 (catch 'exit
17141 (let ((pos (point))
17142 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17143 (lim (progn
17144 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17145 (point)))
17146 dd-on str (start 0) m re)
17147 (goto-char pos)
17148 (when dodollar
17149 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17150 re (nth 1 (assoc "$" org-latex-regexps)))
17151 (while (string-match re str start)
17152 (cond
17153 ((= (match-end 0) (length str))
17154 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17155 ((= (match-end 0) (- (length str) 5))
17156 (throw 'exit nil))
17157 (t (setq start (match-end 0))))))
17158 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17159 (goto-char pos)
17160 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17161 (and (match-beginning 2) (throw 'exit nil))
17162 ;; count $$
17163 (while (re-search-backward "\\$\\$" lim t)
17164 (setq dd-on (not dd-on)))
17165 (goto-char pos)
17166 (if dd-on (cons "$$" m))))))
17168 (defun org-inside-latex-macro-p ()
17169 "Is point inside a LaTeX macro or its arguments?"
17170 (save-match-data
17171 (org-in-regexp
17172 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17174 (defun org-try-cdlatex-tab ()
17175 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17176 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17177 - inside a LaTeX fragment, or
17178 - after the first word in a line, where an abbreviation expansion could
17179 insert a LaTeX environment."
17180 (when org-cdlatex-mode
17181 (cond
17182 ;; Before any word on the line: No expansion possible.
17183 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17184 ;; Just after first word on the line: Expand it. Make sure it
17185 ;; cannot happen on headlines, though.
17186 ((save-excursion
17187 (skip-chars-backward "a-zA-Z0-9*")
17188 (skip-chars-backward " \t")
17189 (and (bolp) (not (org-at-heading-p))))
17190 (cdlatex-tab) t)
17191 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17193 (defun org-cdlatex-underscore-caret (&optional arg)
17194 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17195 Revert to the normal definition outside of these fragments."
17196 (interactive "P")
17197 (if (org-inside-LaTeX-fragment-p)
17198 (call-interactively 'cdlatex-sub-superscript)
17199 (let (org-cdlatex-mode)
17200 (call-interactively (key-binding (vector last-input-event))))))
17202 (defun org-cdlatex-math-modify (&optional arg)
17203 "Execute `cdlatex-math-modify' in LaTeX fragments.
17204 Revert to the normal definition outside of these fragments."
17205 (interactive "P")
17206 (if (org-inside-LaTeX-fragment-p)
17207 (call-interactively 'cdlatex-math-modify)
17208 (let (org-cdlatex-mode)
17209 (call-interactively (key-binding (vector last-input-event))))))
17211 (defvar org-latex-fragment-image-overlays nil
17212 "List of overlays carrying the images of latex fragments.")
17213 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17215 (defun org-remove-latex-fragment-image-overlays ()
17216 "Remove all overlays with LaTeX fragment images in current buffer."
17217 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17218 (setq org-latex-fragment-image-overlays nil))
17220 (defun org-preview-latex-fragment (&optional subtree)
17221 "Preview the LaTeX fragment at point, or all locally or globally.
17222 If the cursor is in a LaTeX fragment, create the image and overlay
17223 it over the source code. If there is no fragment at point, display
17224 all fragments in the current text, from one headline to the next. With
17225 prefix SUBTREE, display all fragments in the current subtree. With a
17226 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17227 the cursor is before the first headline,
17228 display all fragments in the buffer.
17229 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17230 (interactive "P")
17231 (unless buffer-file-name
17232 (error "Can't preview LaTeX fragment in a non-file buffer"))
17233 (org-remove-latex-fragment-image-overlays)
17234 (save-excursion
17235 (save-restriction
17236 (let (beg end at msg)
17237 (cond
17238 ((or (equal subtree '(16))
17239 (not (save-excursion
17240 (re-search-backward org-outline-regexp-bol nil t))))
17241 (setq beg (point-min) end (point-max)
17242 msg "Creating images for buffer...%s"))
17243 ((equal subtree '(4))
17244 (org-back-to-heading)
17245 (setq beg (point) end (org-end-of-subtree t)
17246 msg "Creating images for subtree...%s"))
17248 (if (setq at (org-inside-LaTeX-fragment-p))
17249 (goto-char (max (point-min) (- (cdr at) 2)))
17250 (org-back-to-heading))
17251 (setq beg (point) end (progn (outline-next-heading) (point))
17252 msg (if at "Creating image...%s"
17253 "Creating images for entry...%s"))))
17254 (message msg "")
17255 (narrow-to-region beg end)
17256 (goto-char beg)
17257 (org-format-latex
17258 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17259 (file-name-nondirectory
17260 buffer-file-name)))
17261 default-directory 'overlays msg at 'forbuffer
17262 org-latex-create-formula-image-program)
17263 (message msg "done. Use `C-c C-c' to remove images.")))))
17265 (defvar org-latex-regexps
17266 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17267 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17268 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17269 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17270 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17271 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17272 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17273 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17274 "Regular expressions for matching embedded LaTeX.")
17276 (defvar org-export-have-math nil) ;; dynamic scoping
17277 (defun org-format-latex (prefix &optional dir overlays msg at
17278 forbuffer processing-type)
17279 "Replace LaTeX fragments with links to an image, and produce images.
17280 Some of the options can be changed using the variable
17281 `org-format-latex-options'."
17282 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17283 (let* ((prefixnodir (file-name-nondirectory prefix))
17284 (absprefix (expand-file-name prefix dir))
17285 (todir (file-name-directory absprefix))
17286 (opt org-format-latex-options)
17287 (matchers (plist-get opt :matchers))
17288 (re-list org-latex-regexps)
17289 (org-format-latex-header-extra
17290 (plist-get (org-infile-export-plist) :latex-header-extra))
17291 (cnt 0) txt hash link beg end re e checkdir
17292 executables-checked string
17293 m n block-type block linkfile movefile ov)
17294 ;; Check the different regular expressions
17295 (while (setq e (pop re-list))
17296 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17297 block (if block-type "\n\n" ""))
17298 (when (member m matchers)
17299 (goto-char (point-min))
17300 (while (re-search-forward re nil t)
17301 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17302 (not (get-text-property (match-beginning n)
17303 'org-protected))
17304 (or (not overlays)
17305 (not (eq (get-char-property (match-beginning n)
17306 'org-overlay-type)
17307 'org-latex-overlay))))
17308 (setq org-export-have-math t)
17309 (cond
17310 ((eq processing-type 'verbatim)
17311 ;; Leave the text verbatim, just protect it
17312 (add-text-properties (match-beginning n) (match-end n)
17313 '(org-protected t)))
17314 ((eq processing-type 'mathjax)
17315 ;; Prepare for MathJax processing
17316 (setq string (match-string n))
17317 (if (member m '("$" "$1"))
17318 (save-excursion
17319 (delete-region (match-beginning n) (match-end n))
17320 (goto-char (match-beginning n))
17321 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17322 "\\)")
17323 '(org-protected t))))
17324 (add-text-properties (match-beginning n) (match-end n)
17325 '(org-protected t))))
17326 ((or (eq processing-type 'dvipng)
17327 (eq processing-type 'imagemagick))
17328 ;; Process to an image
17329 (setq txt (match-string n)
17330 beg (match-beginning n) end (match-end n)
17331 cnt (1+ cnt))
17332 (let (print-length print-level) ; make sure full list is printed
17333 (setq hash (sha1 (prin1-to-string
17334 (list org-format-latex-header
17335 org-format-latex-header-extra
17336 org-export-latex-default-packages-alist
17337 org-export-latex-packages-alist
17338 org-format-latex-options
17339 forbuffer txt)))
17340 linkfile (format "%s_%s.png" prefix hash)
17341 movefile (format "%s_%s.png" absprefix hash)))
17342 (setq link (concat block "[[file:" linkfile "]]" block))
17343 (if msg (message msg cnt))
17344 (goto-char beg)
17345 (unless checkdir ; make sure the directory exists
17346 (setq checkdir t)
17347 (or (file-directory-p todir) (make-directory todir t)))
17348 (cond
17349 ((eq processing-type 'dvipng)
17350 (unless executables-checked
17351 (org-check-external-command
17352 "latex" "needed to convert LaTeX fragments to images")
17353 (org-check-external-command
17354 "dvipng" "needed to convert LaTeX fragments to images")
17355 (setq executables-checked t))
17356 (unless (file-exists-p movefile)
17357 (org-create-formula-image-with-dvipng
17358 txt movefile opt forbuffer)))
17359 ((eq processing-type 'imagemagick)
17360 (unless executables-checked
17361 (org-check-external-command
17362 "convert" "you need to install imagemagick")
17363 (setq executables-checked t))
17364 (unless (file-exists-p movefile)
17365 (org-create-formula-image-with-imagemagick
17366 txt movefile opt forbuffer))))
17367 (if overlays
17368 (progn
17369 (mapc (lambda (o)
17370 (if (eq (overlay-get o 'org-overlay-type)
17371 'org-latex-overlay)
17372 (delete-overlay o)))
17373 (overlays-in beg end))
17374 (setq ov (make-overlay beg end))
17375 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17376 (if (featurep 'xemacs)
17377 (progn
17378 (overlay-put ov 'invisible t)
17379 (overlay-put
17380 ov 'end-glyph
17381 (make-glyph (vector 'png :file movefile))))
17382 (overlay-put
17383 ov 'display
17384 (list 'image :type 'png :file movefile :ascent 'center)))
17385 (push ov org-latex-fragment-image-overlays)
17386 (goto-char end))
17387 (delete-region beg end)
17388 (insert (org-add-props link
17389 (list 'org-latex-src
17390 (replace-regexp-in-string
17391 "\"" "" txt)
17392 'org-latex-src-embed-type
17393 (if block-type 'paragraph 'character))))))
17394 ((eq processing-type 'mathml)
17395 ;; Process to MathML
17396 (unless executables-checked
17397 (unless (save-match-data (org-format-latex-mathml-available-p))
17398 (error "LaTeX to MathML converter not configured"))
17399 (setq executables-checked t))
17400 (setq txt (match-string n)
17401 beg (match-beginning n) end (match-end n)
17402 cnt (1+ cnt))
17403 (if msg (message msg cnt))
17404 (goto-char beg)
17405 (delete-region beg end)
17406 (insert (org-format-latex-as-mathml
17407 txt block-type prefix dir)))
17409 (error "Unknown conversion type %s for latex fragments"
17410 processing-type)))))))))
17412 (defun org-create-math-formula (latex-frag &optional mathml-file)
17413 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17414 Use `org-latex-to-mathml-convert-command'. If the conversion is
17415 sucessful, return the portion between \"<math...> </math>\"
17416 elements otherwise return nil. When MATHML-FILE is specified,
17417 write the results in to that file. When invoked as an
17418 interactive command, prompt for LATEX-FRAG, with initial value
17419 set to the current active region and echo the results for user
17420 inspection."
17421 (interactive (list (let ((frag (when (org-region-active-p)
17422 (buffer-substring-no-properties
17423 (region-beginning) (region-end)))))
17424 (read-string "LaTeX Fragment: " frag nil frag))))
17425 (unless latex-frag (error "Invalid latex-frag"))
17426 (let* ((tmp-in-file (file-relative-name
17427 (make-temp-name (expand-file-name "ltxmathml-in"))))
17428 (ignore (write-region latex-frag nil tmp-in-file))
17429 (tmp-out-file (file-relative-name
17430 (make-temp-name (expand-file-name "ltxmathml-out"))))
17431 (cmd (format-spec
17432 org-latex-to-mathml-convert-command
17433 `((?j . ,(shell-quote-argument
17434 (expand-file-name org-latex-to-mathml-jar-file)))
17435 (?I . ,(shell-quote-argument tmp-in-file))
17436 (?o . ,(shell-quote-argument tmp-out-file)))))
17437 mathml shell-command-output)
17438 (when (org-called-interactively-p 'any)
17439 (unless (org-format-latex-mathml-available-p)
17440 (error "LaTeX to MathML converter not configured")))
17441 (message "Running %s" cmd)
17442 (setq shell-command-output (shell-command-to-string cmd))
17443 (setq mathml
17444 (when (file-readable-p tmp-out-file)
17445 (with-current-buffer (find-file-noselect tmp-out-file t)
17446 (goto-char (point-min))
17447 (when (re-search-forward
17448 (concat
17449 (regexp-quote
17450 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17451 "\\(.\\|\n\\)*"
17452 (regexp-quote "</math>")) nil t)
17453 (prog1 (match-string 0) (kill-buffer))))))
17454 (cond
17455 (mathml
17456 (setq mathml
17457 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17458 (when mathml-file
17459 (write-region mathml nil mathml-file))
17460 (when (org-called-interactively-p 'any)
17461 (message mathml)))
17462 ((message "LaTeX to MathML conversion failed")
17463 (message shell-command-output)))
17464 (delete-file tmp-in-file)
17465 (when (file-exists-p tmp-out-file)
17466 (delete-file tmp-out-file))
17467 mathml))
17469 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17470 prefix &optional dir)
17471 "Use `org-create-math-formula' but check local cache first."
17472 (let* ((absprefix (expand-file-name prefix dir))
17473 (print-length nil) (print-level nil)
17474 (formula-id (concat
17475 "formula-"
17476 (sha1
17477 (prin1-to-string
17478 (list latex-frag
17479 org-latex-to-mathml-convert-command)))))
17480 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17481 (formula-cache-dir (file-name-directory formula-cache)))
17483 (unless (file-directory-p formula-cache-dir)
17484 (make-directory formula-cache-dir t))
17486 (unless (file-exists-p formula-cache)
17487 (org-create-math-formula latex-frag formula-cache))
17489 (if (file-exists-p formula-cache)
17490 ;; Successful conversion. Return the link to MathML file.
17491 (org-add-props
17492 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17493 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17494 'org-latex-src-embed-type (if latex-frag-type
17495 'paragraph 'character)))
17496 ;; Failed conversion. Return the LaTeX fragment verbatim
17497 (add-text-properties
17498 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17499 latex-frag)))
17501 ;; This function borrows from Ganesh Swami's latex2png.el
17502 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17503 "This calls dvipng."
17504 (require 'org-latex)
17505 (let* ((tmpdir (if (featurep 'xemacs)
17506 (temp-directory)
17507 temporary-file-directory))
17508 (texfilebase (make-temp-name
17509 (expand-file-name "orgtex" tmpdir)))
17510 (texfile (concat texfilebase ".tex"))
17511 (dvifile (concat texfilebase ".dvi"))
17512 (pngfile (concat texfilebase ".png"))
17513 (fnh (if (featurep 'xemacs)
17514 (font-height (face-font 'default))
17515 (face-attribute 'default :height nil)))
17516 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17517 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17518 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17519 "Black"))
17520 (bg (or (plist-get options (if buffer :background :html-background))
17521 "Transparent")))
17522 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17523 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17524 (with-temp-file texfile
17525 (insert (org-splice-latex-header
17526 org-format-latex-header
17527 org-export-latex-default-packages-alist
17528 org-export-latex-packages-alist t
17529 org-format-latex-header-extra))
17530 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17531 (require 'org-latex)
17532 (org-export-latex-fix-inputenc))
17533 (let ((dir default-directory))
17534 (condition-case nil
17535 (progn
17536 (cd tmpdir)
17537 (call-process "latex" nil nil nil texfile))
17538 (error nil))
17539 (cd dir))
17540 (if (not (file-exists-p dvifile))
17541 (progn (message "Failed to create dvi file from %s" texfile) nil)
17542 (condition-case nil
17543 (if (featurep 'xemacs)
17544 (call-process "dvipng" nil nil nil
17545 "-fg" fg "-bg" bg
17546 "-T" "tight"
17547 "-o" pngfile
17548 dvifile)
17549 (call-process "dvipng" nil nil nil
17550 "-fg" fg "-bg" bg
17551 "-D" dpi
17552 ;;"-x" scale "-y" scale
17553 "-T" "tight"
17554 "-o" pngfile
17555 dvifile))
17556 (error nil))
17557 (if (not (file-exists-p pngfile))
17558 (if org-format-latex-signal-error
17559 (error "Failed to create png file from %s" texfile)
17560 (message "Failed to create png file from %s" texfile)
17561 nil)
17562 ;; Use the requested file name and clean up
17563 (copy-file pngfile tofile 'replace)
17564 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17565 (if (file-exists-p (concat texfilebase e))
17566 (delete-file (concat texfilebase e))))
17567 pngfile))))
17569 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17570 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17571 "This calls convert, which is included into imagemagick."
17572 (require 'org-latex)
17573 (let* ((tmpdir (if (featurep 'xemacs)
17574 (temp-directory)
17575 temporary-file-directory))
17576 (texfilebase (make-temp-name
17577 (expand-file-name "orgtex" tmpdir)))
17578 (texfile (concat texfilebase ".tex"))
17579 (pdffile (concat texfilebase ".pdf"))
17580 (pngfile (concat texfilebase ".png"))
17581 (fnh (if (featurep 'xemacs)
17582 (font-height (face-font 'default))
17583 (face-attribute 'default :height nil)))
17584 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17585 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17586 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17587 "black"))
17588 (bg (or (plist-get options (if buffer :background :html-background))
17589 "white")))
17590 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17591 (setq fg (org-latex-color-format fg)))
17592 (if (eq bg 'default) (setq bg (org-latex-color :background))
17593 (setq bg (org-latex-color-format
17594 (if (string= bg "Transparent")(setq bg "white")))))
17595 (with-temp-file texfile
17596 (insert (org-splice-latex-header
17597 org-format-latex-header
17598 org-export-latex-default-packages-alist
17599 org-export-latex-packages-alist t
17600 org-format-latex-header-extra))
17601 (insert "\n\\begin{document}\n"
17602 "\\definecolor{fg}{rgb}{" fg "}\n"
17603 "\\definecolor{bg}{rgb}{" bg "}\n"
17604 "\n\\pagecolor{bg}\n"
17605 "\n{\\color{fg}\n"
17606 string
17607 "\n}\n"
17608 "\n\\end{document}\n" )
17609 (require 'org-latex)
17610 (org-export-latex-fix-inputenc))
17611 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17612 (condition-case nil
17613 (progn
17614 (cd tmpdir)
17615 (setq cmds org-latex-to-pdf-process)
17616 (while cmds
17617 (setq latex-frags-cmds (pop cmds))
17618 (if (listp latex-frags-cmds)
17619 (setq cmds nil)
17620 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17621 (while latex-frags-cmds
17622 (setq cmd (pop latex-frags-cmds))
17623 (while (string-match "%b" cmd)
17624 (setq cmd (replace-match
17625 (save-match-data
17626 (shell-quote-argument texfile))
17627 t t cmd)))
17628 (while (string-match "%f" cmd)
17629 (setq cmd (replace-match
17630 (save-match-data
17631 (shell-quote-argument (file-name-nondirectory texfile)))
17632 t t cmd)))
17633 (while (string-match "%o" cmd)
17634 (setq cmd (replace-match
17635 (save-match-data
17636 (shell-quote-argument (file-name-directory texfile)))
17637 t t cmd)))
17638 (setq cmd (split-string cmd))
17639 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17640 (error nil))
17641 (cd dir))
17642 (if (not (file-exists-p pdffile))
17643 (progn (message "Failed to create pdf file from %s" texfile) nil)
17644 (condition-case nil
17645 (if (featurep 'xemacs)
17646 (call-process "convert" nil nil nil
17647 "-density" "96"
17648 "-trim"
17649 "-antialias"
17650 pdffile
17651 "-quality" "100"
17652 ;; "-sharpen" "0x1.0"
17653 pngfile)
17654 (call-process "convert" nil nil nil
17655 "-density" dpi
17656 "-trim"
17657 "-antialias"
17658 pdffile
17659 "-quality" "100"
17660 ; "-sharpen" "0x1.0"
17661 pngfile))
17662 (error nil))
17663 (if (not (file-exists-p pngfile))
17664 (if org-format-latex-signal-error
17665 (error "Failed to create png file from %s" texfile)
17666 (message "Failed to create png file from %s" texfile)
17667 nil)
17668 ;; Use the requested file name and clean up
17669 (copy-file pngfile tofile 'replace)
17670 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17671 (if (file-exists-p (concat texfilebase e))
17672 (delete-file (concat texfilebase e))))
17673 pngfile))))
17675 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17676 "Fill a LaTeX header template TPL.
17677 In the template, the following place holders will be recognized:
17679 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17680 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17681 [PACKAGES] \\usepackage statements for PKG
17682 [NO-PACKAGES] do not include PKG
17683 [EXTRA] the string EXTRA
17684 [NO-EXTRA] do not include EXTRA
17686 For backward compatibility, if both the positive and the negative place
17687 holder is missing, the positive one (without the \"NO-\") will be
17688 assumed to be present at the end of the template.
17689 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17690 EXTRA is a string.
17691 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17692 (let (rpl (end ""))
17693 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17694 (setq rpl (if (or (match-end 1) (not def-pkg))
17695 "" (org-latex-packages-to-string def-pkg snippets-p t))
17696 tpl (replace-match rpl t t tpl))
17697 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17699 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17700 (setq rpl (if (or (match-end 1) (not pkg))
17701 "" (org-latex-packages-to-string pkg snippets-p t))
17702 tpl (replace-match rpl t t tpl))
17703 (if pkg (setq end
17704 (concat end "\n"
17705 (org-latex-packages-to-string pkg snippets-p)))))
17707 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17708 (setq rpl (if (or (match-end 1) (not extra))
17709 "" (concat extra "\n"))
17710 tpl (replace-match rpl t t tpl))
17711 (if (and extra (string-match "\\S-" extra))
17712 (setq end (concat end "\n" extra))))
17714 (if (string-match "\\S-" end)
17715 (concat tpl "\n" end)
17716 tpl)))
17718 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17719 "Turn an alist of packages into a string with the \\usepackage macros."
17720 (setq pkg (mapconcat (lambda(p)
17721 (cond
17722 ((stringp p) p)
17723 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17724 (format "%% Package %s omitted" (cadr p)))
17725 ((equal "" (car p))
17726 (format "\\usepackage{%s}" (cadr p)))
17728 (format "\\usepackage[%s]{%s}"
17729 (car p) (cadr p)))))
17731 "\n"))
17732 (if newline (concat pkg "\n") pkg))
17734 (defun org-dvipng-color (attr)
17735 "Return a RGB color specification for dvipng."
17736 (apply 'format "rgb %s %s %s"
17737 (mapcar 'org-normalize-color
17738 (if (featurep 'xemacs)
17739 (color-rgb-components
17740 (face-property 'default
17741 (cond ((eq attr :foreground) 'foreground)
17742 ((eq attr :background) 'background))))
17743 (color-values (face-attribute 'default attr nil))))))
17745 (defun org-latex-color (attr)
17746 "Return a RGB color for the LaTeX color package."
17747 (apply 'format "%s,%s,%s"
17748 (mapcar 'org-normalize-color
17749 (if (featurep 'xemacs)
17750 (color-rgb-components
17751 (face-property 'default
17752 (cond ((eq attr :foreground) 'foreground)
17753 ((eq attr :background) 'background))))
17754 (color-values (face-attribute 'default attr nil))))))
17756 (defun org-latex-color-format (color-name)
17757 "Convert COLOR-NAME to a RGB color value."
17758 (apply 'format "%s,%s,%s"
17759 (mapcar 'org-normalize-color
17760 (color-values color-name))))
17762 (defun org-normalize-color (value)
17763 "Return string to be used as color value for an RGB component."
17764 (format "%g" (/ value 65535.0)))
17766 ;; Image display
17769 (defvar org-inline-image-overlays nil)
17770 (make-variable-buffer-local 'org-inline-image-overlays)
17772 (defun org-toggle-inline-images (&optional include-linked)
17773 "Toggle the display of inline images.
17774 INCLUDE-LINKED is passed to `org-display-inline-images'."
17775 (interactive "P")
17776 (if org-inline-image-overlays
17777 (progn
17778 (org-remove-inline-images)
17779 (message "Inline image display turned off"))
17780 (org-display-inline-images include-linked)
17781 (if org-inline-image-overlays
17782 (message "%d images displayed inline"
17783 (length org-inline-image-overlays))
17784 (message "No images to display inline"))))
17786 (defun org-redisplay-inline-images ()
17787 "Refresh the display of inline images."
17788 (interactive)
17789 (if (not org-inline-image-overlays)
17790 (org-toggle-inline-images)
17791 (org-toggle-inline-images)
17792 (org-toggle-inline-images)))
17794 (defun org-display-inline-images (&optional include-linked refresh beg end)
17795 "Display inline images.
17796 Normally only links without a description part are inlined, because this
17797 is how it will work for export. When INCLUDE-LINKED is set, also links
17798 with a description part will be inlined. This can be nice for a quick
17799 look at those images, but it does not reflect what exported files will look
17800 like.
17801 When REFRESH is set, refresh existing images between BEG and END.
17802 This will create new image displays only if necessary.
17803 BEG and END default to the buffer boundaries."
17804 (interactive "P")
17805 (unless refresh
17806 (org-remove-inline-images)
17807 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17808 (save-excursion
17809 (save-restriction
17810 (widen)
17811 (setq beg (or beg (point-min)) end (or end (point-max)))
17812 (goto-char beg)
17813 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17814 (substring (org-image-file-name-regexp) 0 -2)
17815 "\\)\\]" (if include-linked "" "\\]")))
17816 old file ov img)
17817 (while (re-search-forward re end t)
17818 (setq old (get-char-property-and-overlay (match-beginning 1)
17819 'org-image-overlay))
17820 (setq file (expand-file-name
17821 (concat (or (match-string 3) "") (match-string 4))))
17822 (when (file-exists-p file)
17823 (if (and (car-safe old) refresh)
17824 (image-refresh (overlay-get (cdr old) 'display))
17825 (setq img (save-match-data (create-image file)))
17826 (when img
17827 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17828 (overlay-put ov 'display img)
17829 (overlay-put ov 'face 'default)
17830 (overlay-put ov 'org-image-overlay t)
17831 (overlay-put ov 'modification-hooks
17832 (list 'org-display-inline-remove-overlay))
17833 (push ov org-inline-image-overlays)))))))))
17835 (define-obsolete-function-alias
17836 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17838 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17839 "Remove inline-display overlay if a corresponding region is modified."
17840 (let ((inhibit-modification-hooks t))
17841 (when (and ov after)
17842 (delete ov org-inline-image-overlays)
17843 (delete-overlay ov))))
17845 (defun org-remove-inline-images ()
17846 "Remove inline display of images."
17847 (interactive)
17848 (mapc 'delete-overlay org-inline-image-overlays)
17849 (setq org-inline-image-overlays nil))
17851 ;;;; Key bindings
17853 ;; Outline functions from `outline-mode-prefix-map'
17854 ;; that can be remapped in Org:
17855 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17856 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17857 (define-key org-mode-map [remap outline-forward-same-level]
17858 'org-forward-heading-same-level)
17859 (define-key org-mode-map [remap outline-backward-same-level]
17860 'org-backward-heading-same-level)
17861 (define-key org-mode-map [remap show-branches]
17862 'org-kill-note-or-show-branches)
17863 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17864 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17865 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17867 ;; Outline functions from `outline-mode-prefix-map' that can not
17868 ;; be remapped in Org:
17870 ;; - the column "key binding" shows whether the Outline function is still
17871 ;; available in Org mode on the same key that it has been bound to in
17872 ;; Outline mode:
17873 ;; - "overridden": key used for a different functionality in Org mode
17874 ;; - else: key still bound to the same Outline function in Org mode
17876 ;; | Outline function | key binding | Org replacement |
17877 ;; |------------------------------------+-------------+-----------------------|
17878 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17879 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17880 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17881 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17882 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17883 ;; | `show-entry' | overridden | no replacement |
17884 ;; | `show-children' | `C-c C-i' | visibility cycling |
17885 ;; | `show-branches' | `C-c C-k' | still same function |
17886 ;; | `show-subtree' | overridden | visibility cycling |
17887 ;; | `show-all' | overridden | no replacement |
17888 ;; | `hide-subtree' | overridden | visibility cycling |
17889 ;; | `hide-body' | overridden | no replacement |
17890 ;; | `hide-entry' | overridden | visibility cycling |
17891 ;; | `hide-leaves' | overridden | no replacement |
17892 ;; | `hide-sublevels' | overridden | no replacement |
17893 ;; | `hide-other' | overridden | no replacement |
17895 ;; Make `C-c C-x' a prefix key
17896 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17898 ;; TAB key with modifiers
17899 (org-defkey org-mode-map "\C-i" 'org-cycle)
17900 (org-defkey org-mode-map [(tab)] 'org-cycle)
17901 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17902 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17903 ;; The following line is necessary under Suse GNU/Linux
17904 (unless (featurep 'xemacs)
17905 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17906 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17907 (define-key org-mode-map [backtab] 'org-shifttab)
17909 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17910 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17911 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17913 ;; Cursor keys with modifiers
17914 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17915 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17916 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17917 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17919 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17920 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17921 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17922 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17924 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17925 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17926 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17927 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17929 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17930 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17931 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17932 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17934 ;; Babel keys
17935 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17936 (mapc (lambda (pair)
17937 (define-key org-babel-map (car pair) (cdr pair)))
17938 org-babel-key-bindings)
17940 ;;; Extra keys for tty access.
17941 ;; We only set them when really needed because otherwise the
17942 ;; menus don't show the simple keys
17944 (when (or org-use-extra-keys
17945 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17946 (not window-system))
17947 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17948 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17949 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17950 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17951 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17952 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17953 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17954 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17955 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17956 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17957 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17958 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17959 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17960 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17961 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17962 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17963 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17964 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17965 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17966 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17967 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17968 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17969 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17970 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17971 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17972 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17973 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17974 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17976 ;; All the other keys
17978 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17979 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17980 (if (boundp 'narrow-map)
17981 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17982 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17983 (if (boundp 'narrow-map)
17984 (org-defkey narrow-map "b" 'org-narrow-to-block)
17985 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17986 (if (boundp 'narrow-map)
17987 (org-defkey narrow-map "e" 'org-narrow-to-element)
17988 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17989 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17990 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17991 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17992 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17993 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17994 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17995 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17996 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17997 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17998 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17999 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18000 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18001 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18002 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18003 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18004 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18005 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18006 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18007 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18008 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18009 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18010 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18011 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18012 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18013 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18014 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18015 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18016 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18017 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18018 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18019 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18020 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18021 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18022 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18023 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18024 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18025 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18026 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18027 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18028 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18029 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18030 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18031 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18032 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18033 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18034 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18035 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18036 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18037 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18038 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18039 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18040 (org-defkey org-mode-map "\C-c^" 'org-sort)
18041 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18042 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18043 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18044 (org-defkey org-mode-map "\C-m" 'org-return)
18045 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18046 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18047 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18048 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18049 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18050 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18051 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18052 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18053 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18054 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18055 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18056 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18057 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18058 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18059 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18060 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18061 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18062 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18063 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18064 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18065 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18066 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18067 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18069 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18070 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18071 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18073 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18074 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18075 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18076 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18077 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18078 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18079 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18080 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18081 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18082 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18083 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18084 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18085 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18086 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18087 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18088 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18089 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18090 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18091 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18092 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18093 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18094 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18096 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18097 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18098 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18099 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18100 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18102 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18104 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18106 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18107 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18109 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18112 (when (featurep 'xemacs)
18113 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18116 (defconst org-speed-commands-default
18118 ("Outline Navigation")
18119 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18120 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18121 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18122 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18123 ("u" . (org-speed-move-safe 'outline-up-heading))
18124 ("j" . org-goto)
18125 ("g" . (org-refile t))
18126 ("Outline Visibility")
18127 ("c" . org-cycle)
18128 ("C" . org-shifttab)
18129 (" " . org-display-outline-path)
18130 ("=" . org-columns)
18131 ("Outline Structure Editing")
18132 ("U" . org-shiftmetaup)
18133 ("D" . org-shiftmetadown)
18134 ("r" . org-metaright)
18135 ("l" . org-metaleft)
18136 ("R" . org-shiftmetaright)
18137 ("L" . org-shiftmetaleft)
18138 ("i" . (progn (forward-char 1) (call-interactively
18139 'org-insert-heading-respect-content)))
18140 ("^" . org-sort)
18141 ("w" . org-refile)
18142 ("a" . org-archive-subtree-default-with-confirmation)
18143 ("." . org-mark-subtree)
18144 ("#" . org-toggle-comment)
18145 ("Clock Commands")
18146 ("I" . org-clock-in)
18147 ("O" . org-clock-out)
18148 ("Meta Data Editing")
18149 ("t" . org-todo)
18150 ("," . (org-priority))
18151 ("0" . (org-priority ?\ ))
18152 ("1" . (org-priority ?A))
18153 ("2" . (org-priority ?B))
18154 ("3" . (org-priority ?C))
18155 (":" . org-set-tags-command)
18156 ("e" . org-set-effort)
18157 ("E" . org-inc-effort)
18158 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18159 (org-entry-put (point) "APPT_WARNTIME" m)))
18160 ("Agenda Views etc")
18161 ("v" . org-agenda)
18162 ("/" . org-sparse-tree)
18163 ("Misc")
18164 ("o" . org-open-at-point)
18165 ("?" . org-speed-command-help)
18166 ("<" . (org-agenda-set-restriction-lock 'subtree))
18167 (">" . (org-agenda-remove-restriction-lock))
18169 "The default speed commands.")
18171 (defun org-print-speed-command (e)
18172 (if (> (length (car e)) 1)
18173 (progn
18174 (princ "\n")
18175 (princ (car e))
18176 (princ "\n")
18177 (princ (make-string (length (car e)) ?-))
18178 (princ "\n"))
18179 (princ (car e))
18180 (princ " ")
18181 (if (symbolp (cdr e))
18182 (princ (symbol-name (cdr e)))
18183 (prin1 (cdr e)))
18184 (princ "\n")))
18186 (defun org-speed-command-help ()
18187 "Show the available speed commands."
18188 (interactive)
18189 (if (not org-use-speed-commands)
18190 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18191 (with-output-to-temp-buffer "*Help*"
18192 (princ "User-defined Speed commands\n===========================\n")
18193 (mapc 'org-print-speed-command org-speed-commands-user)
18194 (princ "\n")
18195 (princ "Built-in Speed commands\n=======================\n")
18196 (mapc 'org-print-speed-command org-speed-commands-default))
18197 (with-current-buffer "*Help*"
18198 (setq truncate-lines t))))
18200 (defun org-speed-move-safe (cmd)
18201 "Execute CMD, but make sure that the cursor always ends up in a headline.
18202 If not, return to the original position and throw an error."
18203 (interactive)
18204 (let ((pos (point)))
18205 (call-interactively cmd)
18206 (unless (and (bolp) (org-at-heading-p))
18207 (goto-char pos)
18208 (error "Boundary reached while executing %s" cmd))))
18210 (defvar org-self-insert-command-undo-counter 0)
18212 (defvar org-table-auto-blank-field) ; defined in org-table.el
18213 (defvar org-speed-command nil)
18215 (define-obsolete-function-alias
18216 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18218 (defun org-speed-command-activate (keys)
18219 "Hook for activating single-letter speed commands.
18220 `org-speed-commands-default' specifies a minimal command set.
18221 Use `org-speed-commands-user' for further customization."
18222 (when (or (and (bolp) (looking-at org-outline-regexp))
18223 (and (functionp org-use-speed-commands)
18224 (funcall org-use-speed-commands)))
18225 (cdr (assoc keys (append org-speed-commands-user
18226 org-speed-commands-default)))))
18228 (define-obsolete-function-alias
18229 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18231 (defun org-babel-speed-command-activate (keys)
18232 "Hook for activating single-letter code block commands."
18233 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18234 (cdr (assoc keys org-babel-key-bindings))))
18236 (defcustom org-speed-command-hook
18237 '(org-speed-command-default-hook org-babel-speed-command-hook)
18238 "Hook for activating speed commands at strategic locations.
18239 Hook functions are called in sequence until a valid handler is
18240 found.
18242 Each hook takes a single argument, a user-pressed command key
18243 which is also a `self-insert-command' from the global map.
18245 Within the hook, examine the cursor position and the command key
18246 and return nil or a valid handler as appropriate. Handler could
18247 be one of an interactive command, a function, or a form.
18249 Set `org-use-speed-commands' to non-nil value to enable this
18250 hook. The default setting is `org-speed-command-activate'."
18251 :group 'org-structure
18252 :version "24.1"
18253 :type 'hook)
18255 (defun org-self-insert-command (N)
18256 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18257 If the cursor is in a table looking at whitespace, the whitespace is
18258 overwritten, and the table is not marked as requiring realignment."
18259 (interactive "p")
18260 (org-check-before-invisible-edit 'insert)
18261 (cond
18262 ((and org-use-speed-commands
18263 (setq org-speed-command
18264 (run-hook-with-args-until-success
18265 'org-speed-command-hook (this-command-keys))))
18266 (cond
18267 ((commandp org-speed-command)
18268 (setq this-command org-speed-command)
18269 (call-interactively org-speed-command))
18270 ((functionp org-speed-command)
18271 (funcall org-speed-command))
18272 ((and org-speed-command (listp org-speed-command))
18273 (eval org-speed-command))
18274 (t (let (org-use-speed-commands)
18275 (call-interactively 'org-self-insert-command)))))
18276 ((and
18277 (org-table-p)
18278 (progn
18279 ;; check if we blank the field, and if that triggers align
18280 (and (featurep 'org-table) org-table-auto-blank-field
18281 (member last-command
18282 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18283 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18284 ;; got extra space, this field does not determine column width
18285 (let (org-table-may-need-update) (org-table-blank-field))
18286 ;; no extra space, this field may determine column width
18287 (org-table-blank-field)))
18289 (eq N 1)
18290 (looking-at "[^|\n]* |"))
18291 (let (org-table-may-need-update)
18292 (goto-char (1- (match-end 0)))
18293 (backward-delete-char 1)
18294 (goto-char (match-beginning 0))
18295 (self-insert-command N)))
18297 (setq org-table-may-need-update t)
18298 (self-insert-command N)
18299 (org-fix-tags-on-the-fly)
18300 (if org-self-insert-cluster-for-undo
18301 (if (not (eq last-command 'org-self-insert-command))
18302 (setq org-self-insert-command-undo-counter 1)
18303 (if (>= org-self-insert-command-undo-counter 20)
18304 (setq org-self-insert-command-undo-counter 1)
18305 (and (> org-self-insert-command-undo-counter 0)
18306 buffer-undo-list (listp buffer-undo-list)
18307 (not (cadr buffer-undo-list)) ; remove nil entry
18308 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18309 (setq org-self-insert-command-undo-counter
18310 (1+ org-self-insert-command-undo-counter))))))))
18312 (defun org-check-before-invisible-edit (kind)
18313 "Check is editing if kind KIND would be dangerous with invisible text around.
18314 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18315 ;; First, try to get out of here as quickly as possible, to reduce overhead
18316 (if (and org-catch-invisible-edits
18317 (or (not (boundp 'visible-mode)) (not visible-mode))
18318 (or (get-char-property (point) 'invisible)
18319 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18320 ;; OK, we need to take a closer look
18321 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18322 (invisible-before-point (if (bobp) nil (get-char-property
18323 (1- (point)) 'invisible)))
18324 (border-and-ok-direction
18326 ;; Check if we are acting predictably before invisible text
18327 (and invisible-at-point (not invisible-before-point)
18328 (memq kind '(insert delete-backward)))
18329 ;; Check if we are acting predictably after invisible text
18330 ;; This works not well, and I have turned it off. It seems
18331 ;; better to always show and stop after invisible text.
18332 ;; (and (not invisible-at-point) invisible-before-point
18333 ;; (memq kind '(insert delete)))
18335 (when (or (memq invisible-at-point '(outline org-hide-block t))
18336 (memq invisible-before-point '(outline org-hide-block t)))
18337 (if (eq org-catch-invisible-edits 'error)
18338 (error "Editing in invisible areas is prohibited - make visible first"))
18339 (if (and org-custom-properties-overlays
18340 (y-or-n-p "Display invisible properties in this buffer? "))
18341 (org-toggle-custom-properties-visibility)
18342 ;; Make the area visible
18343 (save-excursion
18344 (if invisible-before-point
18345 (goto-char (previous-single-char-property-change
18346 (point) 'invisible)))
18347 (org-cycle))
18348 (cond
18349 ((eq org-catch-invisible-edits 'show)
18350 ;; That's it, we do the edit after showing
18351 (message
18352 "Unfolding invisible region around point before editing")
18353 (sit-for 1))
18354 ((and (eq org-catch-invisible-edits 'smart)
18355 border-and-ok-direction)
18356 (message "Unfolding invisible region around point before editing"))
18358 ;; Don't do the edit, make the user repeat it in full visibility
18359 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18361 (defun org-fix-tags-on-the-fly ()
18362 (when (and (equal (char-after (point-at-bol)) ?*)
18363 (org-at-heading-p))
18364 (org-align-tags-here org-tags-column)))
18366 (defun org-delete-backward-char (N)
18367 "Like `delete-backward-char', insert whitespace at field end in tables.
18368 When deleting backwards, in tables this function will insert whitespace in
18369 front of the next \"|\" separator, to keep the table aligned. The table will
18370 still be marked for re-alignment if the field did fill the entire column,
18371 because, in this case the deletion might narrow the column."
18372 (interactive "p")
18373 (save-match-data
18374 (org-check-before-invisible-edit 'delete-backward)
18375 (if (and (org-table-p)
18376 (eq N 1)
18377 (string-match "|" (buffer-substring (point-at-bol) (point)))
18378 (looking-at ".*?|"))
18379 (let ((pos (point))
18380 (noalign (looking-at "[^|\n\r]* |"))
18381 (c org-table-may-need-update))
18382 (backward-delete-char N)
18383 (if (not overwrite-mode)
18384 (progn
18385 (skip-chars-forward "^|")
18386 (insert " ")
18387 (goto-char (1- pos))))
18388 ;; noalign: if there were two spaces at the end, this field
18389 ;; does not determine the width of the column.
18390 (if noalign (setq org-table-may-need-update c)))
18391 (backward-delete-char N)
18392 (org-fix-tags-on-the-fly))))
18394 (defun org-delete-char (N)
18395 "Like `delete-char', but insert whitespace at field end in tables.
18396 When deleting characters, in tables this function will insert whitespace in
18397 front of the next \"|\" separator, to keep the table aligned. The table will
18398 still be marked for re-alignment if the field did fill the entire column,
18399 because, in this case the deletion might narrow the column."
18400 (interactive "p")
18401 (save-match-data
18402 (org-check-before-invisible-edit 'delete)
18403 (if (and (org-table-p)
18404 (not (bolp))
18405 (not (= (char-after) ?|))
18406 (eq N 1))
18407 (if (looking-at ".*?|")
18408 (let ((pos (point))
18409 (noalign (looking-at "[^|\n\r]* |"))
18410 (c org-table-may-need-update))
18411 (replace-match (concat
18412 (substring (match-string 0) 1 -1)
18413 " |"))
18414 (goto-char pos)
18415 ;; noalign: if there were two spaces at the end, this field
18416 ;; does not determine the width of the column.
18417 (if noalign (setq org-table-may-need-update c)))
18418 (delete-char N))
18419 (delete-char N)
18420 (org-fix-tags-on-the-fly))))
18422 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18423 (put 'org-self-insert-command 'delete-selection t)
18424 (put 'orgtbl-self-insert-command 'delete-selection t)
18425 (put 'org-delete-char 'delete-selection 'supersede)
18426 (put 'org-delete-backward-char 'delete-selection 'supersede)
18427 (put 'org-yank 'delete-selection 'yank)
18429 ;; Make `flyspell-mode' delay after some commands
18430 (put 'org-self-insert-command 'flyspell-delayed t)
18431 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18432 (put 'org-delete-char 'flyspell-delayed t)
18433 (put 'org-delete-backward-char 'flyspell-delayed t)
18435 ;; Make pabbrev-mode expand after org-mode commands
18436 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18437 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18439 ;; How to do this: Measure non-white length of current string
18440 ;; If equal to column width, we should realign.
18442 (defun org-remap (map &rest commands)
18443 "In MAP, remap the functions given in COMMANDS.
18444 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18445 (let (new old)
18446 (while commands
18447 (setq old (pop commands) new (pop commands))
18448 (if (fboundp 'command-remapping)
18449 (org-defkey map (vector 'remap old) new)
18450 (substitute-key-definition old new map global-map)))))
18452 (when (eq org-enable-table-editor 'optimized)
18453 ;; If the user wants maximum table support, we need to hijack
18454 ;; some standard editing functions
18455 (org-remap org-mode-map
18456 'self-insert-command 'org-self-insert-command
18457 'delete-char 'org-delete-char
18458 'delete-backward-char 'org-delete-backward-char)
18459 (org-defkey org-mode-map "|" 'org-force-self-insert))
18461 (defvar org-ctrl-c-ctrl-c-hook nil
18462 "Hook for functions attaching themselves to `C-c C-c'.
18464 This can be used to add additional functionality to the C-c C-c
18465 key which executes context-dependent commands. This hook is run
18466 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18467 run after the last test.
18469 Each function will be called with no arguments. The function
18470 must check if the context is appropriate for it to act. If yes,
18471 it should do its thing and then return a non-nil value. If the
18472 context is wrong, just do nothing and return nil.")
18474 (defvar org-ctrl-c-ctrl-c-final-hook nil
18475 "Hook for functions attaching themselves to `C-c C-c'.
18477 This can be used to add additional functionality to the C-c C-c
18478 key which executes context-dependent commands. This hook is run
18479 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18480 before the first test.
18482 Each function will be called with no arguments. The function
18483 must check if the context is appropriate for it to act. If yes,
18484 it should do its thing and then return a non-nil value. If the
18485 context is wrong, just do nothing and return nil.")
18487 (defvar org-tab-first-hook nil
18488 "Hook for functions to attach themselves to TAB.
18489 See `org-ctrl-c-ctrl-c-hook' for more information.
18490 This hook runs as the first action when TAB is pressed, even before
18491 `org-cycle' messes around with the `outline-regexp' to cater for
18492 inline tasks and plain list item folding.
18493 If any function in this hook returns t, any other actions that
18494 would have been caused by TAB (such as table field motion or visibility
18495 cycling) will not occur.")
18497 (defvar org-tab-after-check-for-table-hook nil
18498 "Hook for functions to attach themselves to TAB.
18499 See `org-ctrl-c-ctrl-c-hook' for more information.
18500 This hook runs after it has been established that the cursor is not in a
18501 table, but before checking if the cursor is in a headline or if global cycling
18502 should be done.
18503 If any function in this hook returns t, not other actions like visibility
18504 cycling will be done.")
18506 (defvar org-tab-after-check-for-cycling-hook nil
18507 "Hook for functions to attach themselves to TAB.
18508 See `org-ctrl-c-ctrl-c-hook' for more information.
18509 This hook runs after it has been established that not table field motion and
18510 not visibility should be done because of current context. This is probably
18511 the place where a package like yasnippets can hook in.")
18513 (defvar org-tab-before-tab-emulation-hook nil
18514 "Hook for functions to attach themselves to TAB.
18515 See `org-ctrl-c-ctrl-c-hook' for more information.
18516 This hook runs after every other options for TAB have been exhausted, but
18517 before indentation and \t insertion takes place.")
18519 (defvar org-metaleft-hook nil
18520 "Hook for functions attaching themselves to `M-left'.
18521 See `org-ctrl-c-ctrl-c-hook' for more information.")
18522 (defvar org-metaright-hook nil
18523 "Hook for functions attaching themselves to `M-right'.
18524 See `org-ctrl-c-ctrl-c-hook' for more information.")
18525 (defvar org-metaup-hook nil
18526 "Hook for functions attaching themselves to `M-up'.
18527 See `org-ctrl-c-ctrl-c-hook' for more information.")
18528 (defvar org-metadown-hook nil
18529 "Hook for functions attaching themselves to `M-down'.
18530 See `org-ctrl-c-ctrl-c-hook' for more information.")
18531 (defvar org-shiftmetaleft-hook nil
18532 "Hook for functions attaching themselves to `M-S-left'.
18533 See `org-ctrl-c-ctrl-c-hook' for more information.")
18534 (defvar org-shiftmetaright-hook nil
18535 "Hook for functions attaching themselves to `M-S-right'.
18536 See `org-ctrl-c-ctrl-c-hook' for more information.")
18537 (defvar org-shiftmetaup-hook nil
18538 "Hook for functions attaching themselves to `M-S-up'.
18539 See `org-ctrl-c-ctrl-c-hook' for more information.")
18540 (defvar org-shiftmetadown-hook nil
18541 "Hook for functions attaching themselves to `M-S-down'.
18542 See `org-ctrl-c-ctrl-c-hook' for more information.")
18543 (defvar org-metareturn-hook nil
18544 "Hook for functions attaching themselves to `M-RET'.
18545 See `org-ctrl-c-ctrl-c-hook' for more information.")
18546 (defvar org-shiftup-hook nil
18547 "Hook for functions attaching themselves to `S-up'.
18548 See `org-ctrl-c-ctrl-c-hook' for more information.")
18549 (defvar org-shiftup-final-hook nil
18550 "Hook for functions attaching themselves to `S-up'.
18551 This one runs after all other options except shift-select have been excluded.
18552 See `org-ctrl-c-ctrl-c-hook' for more information.")
18553 (defvar org-shiftdown-hook nil
18554 "Hook for functions attaching themselves to `S-down'.
18555 See `org-ctrl-c-ctrl-c-hook' for more information.")
18556 (defvar org-shiftdown-final-hook nil
18557 "Hook for functions attaching themselves to `S-down'.
18558 This one runs after all other options except shift-select have been excluded.
18559 See `org-ctrl-c-ctrl-c-hook' for more information.")
18560 (defvar org-shiftleft-hook nil
18561 "Hook for functions attaching themselves to `S-left'.
18562 See `org-ctrl-c-ctrl-c-hook' for more information.")
18563 (defvar org-shiftleft-final-hook nil
18564 "Hook for functions attaching themselves to `S-left'.
18565 This one runs after all other options except shift-select have been excluded.
18566 See `org-ctrl-c-ctrl-c-hook' for more information.")
18567 (defvar org-shiftright-hook nil
18568 "Hook for functions attaching themselves to `S-right'.
18569 See `org-ctrl-c-ctrl-c-hook' for more information.")
18570 (defvar org-shiftright-final-hook nil
18571 "Hook for functions attaching themselves to `S-right'.
18572 This one runs after all other options except shift-select have been excluded.
18573 See `org-ctrl-c-ctrl-c-hook' for more information.")
18575 (defun org-modifier-cursor-error ()
18576 "Throw an error, a modified cursor command was applied in wrong context."
18577 (error "This command is active in special context like tables, headlines or items"))
18579 (defun org-shiftselect-error ()
18580 "Throw an error because Shift-Cursor command was applied in wrong context."
18581 (if (and (boundp 'shift-select-mode) shift-select-mode)
18582 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18583 (error "This command works only in special context like headlines or timestamps")))
18585 (defun org-call-for-shift-select (cmd)
18586 (let ((this-command-keys-shift-translated t))
18587 (call-interactively cmd)))
18589 (defun org-shifttab (&optional arg)
18590 "Global visibility cycling or move to previous table field.
18591 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18592 on context.
18593 See the individual commands for more information."
18594 (interactive "P")
18595 (cond
18596 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18597 ((integerp arg)
18598 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18599 (message "Content view to level: %d" arg)
18600 (org-content (prefix-numeric-value arg2))
18601 (setq org-cycle-global-status 'overview)))
18602 (t (call-interactively 'org-global-cycle))))
18604 (defun org-shiftmetaleft ()
18605 "Promote subtree or delete table column.
18606 Calls `org-promote-subtree', `org-outdent-item-tree', or
18607 `org-table-delete-column', depending on context. See the
18608 individual commands for more information."
18609 (interactive)
18610 (cond
18611 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18612 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18613 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18614 ((if (not (org-region-active-p)) (org-at-item-p)
18615 (save-excursion (goto-char (region-beginning))
18616 (org-at-item-p)))
18617 (call-interactively 'org-outdent-item-tree))
18618 (t (org-modifier-cursor-error))))
18620 (defun org-shiftmetaright ()
18621 "Demote subtree or insert table column.
18622 Calls `org-demote-subtree', `org-indent-item-tree', or
18623 `org-table-insert-column', depending on context. See the
18624 individual commands for more information."
18625 (interactive)
18626 (cond
18627 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18628 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18629 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18630 ((if (not (org-region-active-p)) (org-at-item-p)
18631 (save-excursion (goto-char (region-beginning))
18632 (org-at-item-p)))
18633 (call-interactively 'org-indent-item-tree))
18634 (t (org-modifier-cursor-error))))
18636 (defun org-shiftmetaup (&optional arg)
18637 "Move subtree up or kill table row.
18638 Calls `org-move-subtree-up' or `org-table-kill-row' or
18639 `org-move-item-up' or `org-timestamp-up', depending on context.
18640 See the individual commands for more information."
18641 (interactive "P")
18642 (cond
18643 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18644 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18645 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18646 ((org-at-item-p) (call-interactively 'org-move-item-up))
18647 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18648 (call-interactively 'org-timestamp-up)))
18649 (t (org-modifier-cursor-error))))
18651 (defun org-shiftmetadown (&optional arg)
18652 "Move subtree down or insert table row.
18653 Calls `org-move-subtree-down' or `org-table-insert-row' or
18654 `org-move-item-down' or `org-timestamp-up', depending on context.
18655 See the individual commands for more information."
18656 (interactive "P")
18657 (cond
18658 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18659 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18660 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18661 ((org-at-item-p) (call-interactively 'org-move-item-down))
18662 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18663 (call-interactively 'org-timestamp-down)))
18664 (t (org-modifier-cursor-error))))
18666 (defsubst org-hidden-tree-error ()
18667 (error
18668 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18670 (defun org-metaleft (&optional arg)
18671 "Promote heading or move table column to left.
18672 Calls `org-do-promote' or `org-table-move-column', depending on context.
18673 With no specific context, calls the Emacs default `backward-word'.
18674 See the individual commands for more information."
18675 (interactive "P")
18676 (cond
18677 ((run-hook-with-args-until-success 'org-metaleft-hook))
18678 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18679 ((org-with-limited-levels
18680 (or (org-at-heading-p)
18681 (and (org-region-active-p)
18682 (save-excursion
18683 (goto-char (region-beginning))
18684 (org-at-heading-p)))))
18685 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18686 (call-interactively 'org-do-promote))
18687 ;; At an inline task.
18688 ((org-at-heading-p)
18689 (call-interactively 'org-inlinetask-promote))
18690 ((or (org-at-item-p)
18691 (and (org-region-active-p)
18692 (save-excursion
18693 (goto-char (region-beginning))
18694 (org-at-item-p))))
18695 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18696 (call-interactively 'org-outdent-item))
18697 (t (call-interactively 'backward-word))))
18699 (defun org-metaright (&optional arg)
18700 "Demote a subtree, a list item or move table column to right.
18701 In front of a drawer or a block keyword, indent it correctly.
18702 With no specific context, calls the Emacs default `forward-word'.
18703 See the individual commands for more information."
18704 (interactive "P")
18705 (cond
18706 ((run-hook-with-args-until-success 'org-metaright-hook))
18707 ((org-at-table-p) (call-interactively 'org-table-move-column))
18708 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18709 ((org-at-block-p) (call-interactively 'org-indent-block))
18710 ((org-with-limited-levels
18711 (or (org-at-heading-p)
18712 (and (org-region-active-p)
18713 (save-excursion
18714 (goto-char (region-beginning))
18715 (org-at-heading-p)))))
18716 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18717 (call-interactively 'org-do-demote))
18718 ;; At an inline task.
18719 ((org-at-heading-p)
18720 (call-interactively 'org-inlinetask-demote))
18721 ((or (org-at-item-p)
18722 (and (org-region-active-p)
18723 (save-excursion
18724 (goto-char (region-beginning))
18725 (org-at-item-p))))
18726 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18727 (call-interactively 'org-indent-item))
18728 (t (call-interactively 'forward-word))))
18730 (defun org-check-for-hidden (what)
18731 "Check if there are hidden headlines/items in the current visual line.
18732 WHAT can be either `headlines' or `items'. If the current line is
18733 an outline or item heading and it has a folded subtree below it,
18734 this function returns t, nil otherwise."
18735 (let ((re (cond
18736 ((eq what 'headlines) org-outline-regexp-bol)
18737 ((eq what 'items) (org-item-beginning-re))
18738 (t (error "This should not happen"))))
18739 beg end)
18740 (save-excursion
18741 (catch 'exit
18742 (unless (org-region-active-p)
18743 (setq beg (point-at-bol))
18744 (beginning-of-line 2)
18745 (while (and (not (eobp)) ;; this is like `next-line'
18746 (get-char-property (1- (point)) 'invisible))
18747 (beginning-of-line 2))
18748 (setq end (point))
18749 (goto-char beg)
18750 (goto-char (point-at-eol))
18751 (setq end (max end (point)))
18752 (while (re-search-forward re end t)
18753 (if (get-char-property (match-beginning 0) 'invisible)
18754 (throw 'exit t))))
18755 nil))))
18757 (org-autoload "org-element" '(org-element-at-point org-element-type))
18759 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18760 (declare-function org-element-type "org-element" (element))
18761 (declare-function org-element-contents "org-element" (element))
18762 (declare-function org-element-property "org-element" (property element))
18763 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18764 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18765 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18766 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18767 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18769 (defun org-metaup (&optional arg)
18770 "Move subtree up or move table row up.
18771 Calls `org-move-subtree-up' or `org-table-move-row' or
18772 `org-move-item-up', depending on context. See the individual commands
18773 for more information."
18774 (interactive "P")
18775 (cond
18776 ((run-hook-with-args-until-success 'org-metaup-hook))
18777 ((org-region-active-p)
18778 (let* ((a (min (region-beginning) (region-end)))
18779 (b (1- (max (region-beginning) (region-end))))
18780 (c (save-excursion (goto-char a)
18781 (move-beginning-of-line 0)))
18782 (d (save-excursion (goto-char a)
18783 (move-end-of-line 0) (point))))
18784 (transpose-regions a b c d)
18785 (goto-char c)))
18786 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18787 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18788 ((org-at-item-p) (call-interactively 'org-move-item-up))
18789 (t (org-drag-element-backward))))
18791 (defun org-metadown (&optional arg)
18792 "Move subtree down or move table row down.
18793 Calls `org-move-subtree-down' or `org-table-move-row' or
18794 `org-move-item-down', depending on context. See the individual
18795 commands for more information."
18796 (interactive "P")
18797 (cond
18798 ((run-hook-with-args-until-success 'org-metadown-hook))
18799 ((org-region-active-p)
18800 (let* ((a (min (region-beginning) (region-end)))
18801 (b (max (region-beginning) (region-end)))
18802 (c (save-excursion (goto-char b)
18803 (move-beginning-of-line 1)))
18804 (d (save-excursion (goto-char b)
18805 (move-end-of-line 1) (1+ (point)))))
18806 (transpose-regions a b c d)
18807 (goto-char d)))
18808 ((org-at-table-p) (call-interactively 'org-table-move-row))
18809 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18810 ((org-at-item-p) (call-interactively 'org-move-item-down))
18811 (t (org-drag-element-forward))))
18813 (defun org-shiftup (&optional arg)
18814 "Increase item in timestamp or increase priority of current headline.
18815 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18816 depending on context. See the individual commands for more information."
18817 (interactive "P")
18818 (cond
18819 ((run-hook-with-args-until-success 'org-shiftup-hook))
18820 ((and org-support-shift-select (org-region-active-p))
18821 (org-call-for-shift-select 'previous-line))
18822 ((org-at-timestamp-p t)
18823 (call-interactively (if org-edit-timestamp-down-means-later
18824 'org-timestamp-down 'org-timestamp-up)))
18825 ((and (not (eq org-support-shift-select 'always))
18826 org-enable-priority-commands
18827 (org-at-heading-p))
18828 (call-interactively 'org-priority-up))
18829 ((and (not org-support-shift-select) (org-at-item-p))
18830 (call-interactively 'org-previous-item))
18831 ((org-clocktable-try-shift 'up arg))
18832 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18833 (org-support-shift-select
18834 (org-call-for-shift-select 'previous-line))
18835 (t (org-shiftselect-error))))
18837 (defun org-shiftdown (&optional arg)
18838 "Decrease item in timestamp or decrease priority of current headline.
18839 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18840 depending on context. See the individual commands for more information."
18841 (interactive "P")
18842 (cond
18843 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18844 ((and org-support-shift-select (org-region-active-p))
18845 (org-call-for-shift-select 'next-line))
18846 ((org-at-timestamp-p t)
18847 (call-interactively (if org-edit-timestamp-down-means-later
18848 'org-timestamp-up 'org-timestamp-down)))
18849 ((and (not (eq org-support-shift-select 'always))
18850 org-enable-priority-commands
18851 (org-at-heading-p))
18852 (call-interactively 'org-priority-down))
18853 ((and (not org-support-shift-select) (org-at-item-p))
18854 (call-interactively 'org-next-item))
18855 ((org-clocktable-try-shift 'down arg))
18856 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18857 (org-support-shift-select
18858 (org-call-for-shift-select 'next-line))
18859 (t (org-shiftselect-error))))
18861 (defun org-shiftright (&optional arg)
18862 "Cycle the thing at point or in the current line, depending on context.
18863 Depending on context, this does one of the following:
18865 - switch a timestamp at point one day into the future
18866 - on a headline, switch to the next TODO keyword.
18867 - on an item, switch entire list to the next bullet type
18868 - on a property line, switch to the next allowed value
18869 - on a clocktable definition line, move time block into the future"
18870 (interactive "P")
18871 (cond
18872 ((run-hook-with-args-until-success 'org-shiftright-hook))
18873 ((and org-support-shift-select (org-region-active-p))
18874 (org-call-for-shift-select 'forward-char))
18875 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18876 ((and (not (eq org-support-shift-select 'always))
18877 (org-at-heading-p))
18878 (let ((org-inhibit-logging
18879 (not org-treat-S-cursor-todo-selection-as-state-change))
18880 (org-inhibit-blocking
18881 (not org-treat-S-cursor-todo-selection-as-state-change)))
18882 (org-call-with-arg 'org-todo 'right)))
18883 ((or (and org-support-shift-select
18884 (not (eq org-support-shift-select 'always))
18885 (org-at-item-bullet-p))
18886 (and (not org-support-shift-select) (org-at-item-p)))
18887 (org-call-with-arg 'org-cycle-list-bullet nil))
18888 ((and (not (eq org-support-shift-select 'always))
18889 (org-at-property-p))
18890 (call-interactively 'org-property-next-allowed-value))
18891 ((org-clocktable-try-shift 'right arg))
18892 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18893 (org-support-shift-select
18894 (org-call-for-shift-select 'forward-char))
18895 (t (org-shiftselect-error))))
18897 (defun org-shiftleft (&optional arg)
18898 "Cycle the thing at point or in the current line, depending on context.
18899 Depending on context, this does one of the following:
18901 - switch a timestamp at point one day into the past
18902 - on a headline, switch to the previous TODO keyword.
18903 - on an item, switch entire list to the previous bullet type
18904 - on a property line, switch to the previous allowed value
18905 - on a clocktable definition line, move time block into the past"
18906 (interactive "P")
18907 (cond
18908 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18909 ((and org-support-shift-select (org-region-active-p))
18910 (org-call-for-shift-select 'backward-char))
18911 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18912 ((and (not (eq org-support-shift-select 'always))
18913 (org-at-heading-p))
18914 (let ((org-inhibit-logging
18915 (not org-treat-S-cursor-todo-selection-as-state-change))
18916 (org-inhibit-blocking
18917 (not org-treat-S-cursor-todo-selection-as-state-change)))
18918 (org-call-with-arg 'org-todo 'left)))
18919 ((or (and org-support-shift-select
18920 (not (eq org-support-shift-select 'always))
18921 (org-at-item-bullet-p))
18922 (and (not org-support-shift-select) (org-at-item-p)))
18923 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18924 ((and (not (eq org-support-shift-select 'always))
18925 (org-at-property-p))
18926 (call-interactively 'org-property-previous-allowed-value))
18927 ((org-clocktable-try-shift 'left arg))
18928 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18929 (org-support-shift-select
18930 (org-call-for-shift-select 'backward-char))
18931 (t (org-shiftselect-error))))
18933 (defun org-shiftcontrolright ()
18934 "Switch to next TODO set."
18935 (interactive)
18936 (cond
18937 ((and org-support-shift-select (org-region-active-p))
18938 (org-call-for-shift-select 'forward-word))
18939 ((and (not (eq org-support-shift-select 'always))
18940 (org-at-heading-p))
18941 (org-call-with-arg 'org-todo 'nextset))
18942 (org-support-shift-select
18943 (org-call-for-shift-select 'forward-word))
18944 (t (org-shiftselect-error))))
18946 (defun org-shiftcontrolleft ()
18947 "Switch to previous TODO set."
18948 (interactive)
18949 (cond
18950 ((and org-support-shift-select (org-region-active-p))
18951 (org-call-for-shift-select 'backward-word))
18952 ((and (not (eq org-support-shift-select 'always))
18953 (org-at-heading-p))
18954 (org-call-with-arg 'org-todo 'previousset))
18955 (org-support-shift-select
18956 (org-call-for-shift-select 'backward-word))
18957 (t (org-shiftselect-error))))
18959 (defun org-shiftcontrolup ()
18960 "Change timestamps synchronously up in CLOCK log lines."
18961 (interactive)
18962 (cond ((and (not org-support-shift-select)
18963 (org-at-clock-log-p)
18964 (org-at-timestamp-p t))
18965 (org-clock-timestamps-up))
18966 (t (org-shiftselect-error))))
18968 (defun org-shiftcontroldown ()
18969 "Change timestamps synchronously down in CLOCK log lines."
18970 (interactive)
18971 (cond ((and (not org-support-shift-select)
18972 (org-at-clock-log-p)
18973 (org-at-timestamp-p t))
18974 (org-clock-timestamps-down))
18975 (t (org-shiftselect-error))))
18977 (defun org-ctrl-c-ret ()
18978 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18979 (interactive)
18980 (cond
18981 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18982 (t (call-interactively 'org-insert-heading))))
18984 (defun org-find-visible ()
18985 (let ((s (point)))
18986 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18987 (get-char-property s 'invisible)))
18989 (defun org-find-invisible ()
18990 (let ((s (point)))
18991 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18992 (not (get-char-property s 'invisible))))
18995 (defun org-copy-visible (beg end)
18996 "Copy the visible parts of the region."
18997 (interactive "r")
18998 (let (snippets s)
18999 (save-excursion
19000 (save-restriction
19001 (narrow-to-region beg end)
19002 (setq s (goto-char (point-min)))
19003 (while (not (= (point) (point-max)))
19004 (goto-char (org-find-invisible))
19005 (push (buffer-substring s (point)) snippets)
19006 (setq s (goto-char (org-find-visible))))))
19007 (kill-new (apply 'concat (nreverse snippets)))))
19009 (defun org-copy-special ()
19010 "Copy region in table or copy current subtree.
19011 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19012 See the individual commands for more information."
19013 (interactive)
19014 (call-interactively
19015 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19017 (defun org-cut-special ()
19018 "Cut region in table or cut current subtree.
19019 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19020 See the individual commands for more information."
19021 (interactive)
19022 (call-interactively
19023 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19025 (defun org-paste-special (arg)
19026 "Paste rectangular region into table, or past subtree relative to level.
19027 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19028 See the individual commands for more information."
19029 (interactive "P")
19030 (if (org-at-table-p)
19031 (org-table-paste-rectangle)
19032 (org-paste-subtree arg)))
19034 (defsubst org-in-fixed-width-region-p ()
19035 "Is point in a fixed-width region?"
19036 (save-match-data
19037 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19039 (defun org-edit-special (&optional arg)
19040 "Call a special editor for the stuff at point.
19041 When at a table, call the formula editor with `org-table-edit-formulas'.
19042 When in a source code block, call `org-edit-src-code'.
19043 When in a fixed-width region, call `org-edit-fixed-width-region'.
19044 When in an #+include line, visit the included file.
19045 On a link, call `ffap' to visit the link at point.
19046 Otherwise, return a user error."
19047 (interactive)
19048 ;; possibly prep session before editing source
19049 (when (and (org-in-src-block-p) arg)
19050 (let* ((info (org-babel-get-src-block-info))
19051 (lang (nth 0 info))
19052 (params (nth 2 info))
19053 (session (cdr (assoc :session params))))
19054 (when (and info session) ;; we are in a source-code block with a session
19055 (funcall
19056 (intern (concat "org-babel-prep-session:" lang)) session params))))
19057 (cond ;; proceed with `org-edit-special'
19058 ((save-excursion
19059 (beginning-of-line 1)
19060 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19061 (find-file (org-trim (match-string 1))))
19062 ((org-at-table.el-p) (org-edit-src-code))
19063 ((or (org-at-table-p)
19064 (save-excursion
19065 (beginning-of-line 1)
19066 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19067 (call-interactively 'org-table-edit-formulas))
19068 ((org-in-block-p '("src" "example" "latex" "html")) (org-edit-src-code))
19069 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19070 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19071 (t (user-error "No special environment to edit here"))))
19073 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19074 (defun org-ctrl-c-ctrl-c (&optional arg)
19075 "Set tags in headline, or update according to changed information at point.
19077 This command does many different things, depending on context:
19079 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19080 this is what we do.
19082 - If the cursor is on a statistics cookie, update it.
19084 - If the cursor is in a headline, prompt for tags and insert them
19085 into the current line, aligned to `org-tags-column'. When called
19086 with prefix arg, realign all tags in the current buffer.
19088 - If the cursor is in one of the special #+KEYWORD lines, this
19089 triggers scanning the buffer for these lines and updating the
19090 information.
19092 - If the cursor is inside a table, realign the table. This command
19093 works even if the automatic table editor has been turned off.
19095 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19096 the entire table.
19098 - If the cursor is at a footnote reference or definition, jump to
19099 the corresponding definition or references, respectively.
19101 - If the cursor is a the beginning of a dynamic block, update it.
19103 - If the current buffer is a capture buffer, close note and file it.
19105 - If the cursor is on a <<<target>>>, update radio targets and
19106 corresponding links in this buffer.
19108 - If the cursor is on a numbered item in a plain list, renumber the
19109 ordered list.
19111 - If the cursor is on a checkbox, toggle it.
19113 - If the cursor is on a code block, evaluate it. The variable
19114 `org-confirm-babel-evaluate' can be used to control prompting
19115 before code block evaluation, by default every code block
19116 evaluation requires confirmation. Code block evaluation can be
19117 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19118 (interactive "P")
19119 (let ((org-enable-table-editor t))
19120 (cond
19121 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19122 org-occur-highlights
19123 org-latex-fragment-image-overlays)
19124 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19125 (org-remove-occur-highlights)
19126 (org-remove-latex-fragment-image-overlays)
19127 (message "Temporary highlights/overlays removed from current buffer"))
19128 ((and (local-variable-p 'org-finish-function (current-buffer))
19129 (fboundp org-finish-function))
19130 (funcall org-finish-function))
19131 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19132 ((org-in-regexp org-ts-regexp-both)
19133 (org-timestamp-change 0 'day))
19134 ((or (looking-at org-property-start-re)
19135 (org-at-property-p))
19136 (call-interactively 'org-property-action))
19137 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19138 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19139 (or (org-at-heading-p) (org-at-item-p)))
19140 (call-interactively 'org-update-statistics-cookies))
19141 ((org-at-heading-p) (call-interactively 'org-set-tags))
19142 ((org-at-table.el-p)
19143 (message "Use C-c ' to edit table.el tables"))
19144 ((org-at-table-p)
19145 (org-table-maybe-eval-formula)
19146 (if arg
19147 (call-interactively 'org-table-recalculate)
19148 (org-table-maybe-recalculate-line))
19149 (call-interactively 'org-table-align)
19150 (orgtbl-send-table 'maybe))
19151 ((or (org-footnote-at-reference-p)
19152 (org-footnote-at-definition-p))
19153 (call-interactively 'org-footnote-action))
19154 ((org-at-item-checkbox-p)
19155 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19156 ;; list only if at top item.
19157 (let* ((cbox (match-string 1))
19158 (struct (org-list-struct))
19159 (old-struct (copy-tree struct))
19160 (parents (org-list-parents-alist struct))
19161 (orderedp (org-entry-get nil "ORDERED"))
19162 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19163 block-item)
19164 ;; Use a light version of `org-toggle-checkbox' to avoid
19165 ;; computing list structure twice.
19166 (let ((new-box (cond
19167 ((equal arg '(16)) "[-]")
19168 ((equal arg '(4)) nil)
19169 ((equal "[X]" cbox) "[ ]")
19170 (t "[X]"))))
19171 (if (and firstp arg)
19172 ;; If at first item of sub-list, remove check-box from
19173 ;; every item at the same level.
19174 (mapc
19175 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19176 (org-list-get-all-items
19177 (point-at-bol) struct (org-list-prevs-alist struct)))
19178 (org-list-set-checkbox (point-at-bol) struct new-box)))
19179 ;; Replicate `org-list-write-struct', while grabbing a return
19180 ;; value from `org-list-struct-fix-box'.
19181 (org-list-struct-fix-ind struct parents 2)
19182 (org-list-struct-fix-item-end struct)
19183 (let ((prevs (org-list-prevs-alist struct)))
19184 (org-list-struct-fix-bul struct prevs)
19185 (org-list-struct-fix-ind struct parents)
19186 (setq block-item
19187 (org-list-struct-fix-box struct parents prevs orderedp)))
19188 (if (equal struct old-struct)
19189 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19190 (org-list-struct-apply-struct struct old-struct)
19191 (org-update-checkbox-count-maybe))
19192 (when block-item
19193 (message
19194 "Checkboxes were removed due to unchecked box at line %d"
19195 (org-current-line block-item)))
19196 (when firstp (org-list-send-list 'maybe))))
19197 ((org-at-item-p)
19198 ;; Cursor at an item: repair list. Do checkbox related actions
19199 ;; only if function was called with an argument. Send list only
19200 ;; if at top item.
19201 (let* ((struct (org-list-struct))
19202 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19203 old-struct)
19204 (when arg
19205 (setq old-struct (copy-tree struct))
19206 (if firstp
19207 ;; If at first item of sub-list, add check-box to every
19208 ;; item at the same level.
19209 (mapc
19210 (lambda (pos)
19211 (unless (org-list-get-checkbox pos struct)
19212 (org-list-set-checkbox pos struct "[ ]")))
19213 (org-list-get-all-items
19214 (point-at-bol) struct (org-list-prevs-alist struct)))
19215 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19216 (org-list-write-struct
19217 struct (org-list-parents-alist struct) old-struct)
19218 (when arg (org-update-checkbox-count-maybe))
19219 (when firstp (org-list-send-list 'maybe))))
19220 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19221 ;; Dynamic block
19222 (beginning-of-line 1)
19223 (save-excursion (org-update-dblock)))
19224 ((save-excursion
19225 (let ((case-fold-search t))
19226 (beginning-of-line 1)
19227 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19228 (cond
19229 ((or (equal (match-string 1) "TBLFM")
19230 (equal (match-string 1) "tblfm"))
19231 ;; Recalculate the table before this line
19232 (save-excursion
19233 (beginning-of-line 1)
19234 (skip-chars-backward " \r\n\t")
19235 (if (org-at-table-p)
19236 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19238 (let ((org-inhibit-startup-visibility-stuff t)
19239 (org-startup-align-all-tables nil))
19240 (when (boundp 'org-table-coordinate-overlays)
19241 (mapc 'delete-overlay org-table-coordinate-overlays)
19242 (setq org-table-coordinate-overlays nil))
19243 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19244 (message "Local setup has been refreshed"))))
19245 ((org-clock-update-time-maybe))
19247 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19248 (error "C-c C-c can do nothing useful at this location"))))))
19250 (defun org-mode-restart ()
19251 "Restart Org-mode, to scan again for special lines.
19252 Also updates the keyword regular expressions."
19253 (interactive)
19254 (org-mode)
19255 (message "Org-mode restarted"))
19257 (defun org-kill-note-or-show-branches ()
19258 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19259 (interactive)
19260 (if (not org-finish-function)
19261 (progn
19262 (hide-subtree)
19263 (call-interactively 'show-branches))
19264 (let ((org-note-abort t))
19265 (funcall org-finish-function))))
19267 (defun org-return (&optional indent)
19268 "Goto next table row or insert a newline.
19269 Calls `org-table-next-row' or `newline', depending on context.
19270 See the individual commands for more information."
19271 (interactive)
19272 (let (org-ts-what)
19273 (cond
19274 ((or (bobp) (org-in-src-block-p))
19275 (if indent (newline-and-indent) (newline)))
19276 ((org-at-table-p)
19277 (org-table-justify-field-maybe)
19278 (call-interactively 'org-table-next-row))
19279 ;; when `newline-and-indent' is called within a list, make sure
19280 ;; text moved stays inside the item.
19281 ((and (org-in-item-p) indent)
19282 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19283 (progn
19284 (save-match-data (newline))
19285 (org-indent-line-to (length (match-string 0))))
19286 (let ((ind (org-get-indentation)))
19287 (newline)
19288 (if (org-looking-back org-list-end-re)
19289 (org-indent-line)
19290 (org-indent-line-to ind)))))
19291 ((and org-return-follows-link
19292 (org-at-timestamp-p t)
19293 (not (eq org-ts-what 'after)))
19294 (org-follow-timestamp-link))
19295 ((and org-return-follows-link
19296 (let ((tprop (get-text-property (point) 'face)))
19297 (or (eq tprop 'org-link)
19298 (and (listp tprop) (memq 'org-link tprop)))))
19299 (call-interactively 'org-open-at-point))
19300 ((and (org-at-heading-p)
19301 (looking-at
19302 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19303 (org-show-entry)
19304 (end-of-line 1)
19305 (newline))
19306 (t (if indent (newline-and-indent) (newline))))))
19308 (defun org-return-indent ()
19309 "Goto next table row or insert a newline and indent.
19310 Calls `org-table-next-row' or `newline-and-indent', depending on
19311 context. See the individual commands for more information."
19312 (interactive)
19313 (org-return t))
19315 (defun org-ctrl-c-star ()
19316 "Compute table, or change heading status of lines.
19317 Calls `org-table-recalculate' or `org-toggle-heading',
19318 depending on context."
19319 (interactive)
19320 (cond
19321 ((org-at-table-p)
19322 (call-interactively 'org-table-recalculate))
19324 ;; Convert all lines in region to list items
19325 (call-interactively 'org-toggle-heading))))
19327 (defun org-ctrl-c-minus ()
19328 "Insert separator line in table or modify bullet status of line.
19329 Also turns a plain line or a region of lines into list items.
19330 Calls `org-table-insert-hline', `org-toggle-item', or
19331 `org-cycle-list-bullet', depending on context."
19332 (interactive)
19333 (cond
19334 ((org-at-table-p)
19335 (call-interactively 'org-table-insert-hline))
19336 ((org-region-active-p)
19337 (call-interactively 'org-toggle-item))
19338 ((org-in-item-p)
19339 (call-interactively 'org-cycle-list-bullet))
19341 (call-interactively 'org-toggle-item))))
19343 (defun org-toggle-item (arg)
19344 "Convert headings or normal lines to items, items to normal lines.
19345 If there is no active region, only the current line is considered.
19347 If the first non blank line in the region is an headline, convert
19348 all headlines to items, shifting text accordingly.
19350 If it is an item, convert all items to normal lines.
19352 If it is normal text, change region into an item. With a prefix
19353 argument ARG, change each line in region into an item."
19354 (interactive "P")
19355 (let ((shift-text
19356 (function
19357 ;; Shift text in current section to IND, from point to END.
19358 ;; The function leaves point to END line.
19359 (lambda (ind end)
19360 (let ((min-i 1000) (end (copy-marker end)))
19361 ;; First determine the minimum indentation (MIN-I) of
19362 ;; the text.
19363 (save-excursion
19364 (catch 'exit
19365 (while (< (point) end)
19366 (let ((i (org-get-indentation)))
19367 (cond
19368 ;; Skip blank lines and inline tasks.
19369 ((looking-at "^[ \t]*$"))
19370 ((looking-at org-outline-regexp-bol))
19371 ;; We can't find less than 0 indentation.
19372 ((zerop i) (throw 'exit (setq min-i 0)))
19373 ((< i min-i) (setq min-i i))))
19374 (forward-line))))
19375 ;; Then indent each line so that a line indented to
19376 ;; MIN-I becomes indented to IND. Ignore blank lines
19377 ;; and inline tasks in the process.
19378 (let ((delta (- ind min-i)))
19379 (while (< (point) end)
19380 (unless (or (looking-at "^[ \t]*$")
19381 (looking-at org-outline-regexp-bol))
19382 (org-indent-line-to (+ (org-get-indentation) delta)))
19383 (forward-line)))))))
19384 (skip-blanks
19385 (function
19386 ;; Return beginning of first non-blank line, starting from
19387 ;; line at POS.
19388 (lambda (pos)
19389 (save-excursion
19390 (goto-char pos)
19391 (skip-chars-forward " \r\t\n")
19392 (point-at-bol)))))
19393 beg end)
19394 ;; Determine boundaries of changes.
19395 (if (org-region-active-p)
19396 (setq beg (funcall skip-blanks (region-beginning))
19397 end (copy-marker (region-end)))
19398 (setq beg (funcall skip-blanks (point-at-bol))
19399 end (copy-marker (point-at-eol))))
19400 ;; Depending on the starting line, choose an action on the text
19401 ;; between BEG and END.
19402 (org-with-limited-levels
19403 (save-excursion
19404 (goto-char beg)
19405 (cond
19406 ;; Case 1. Start at an item: de-itemize. Note that it only
19407 ;; happens when a region is active: `org-ctrl-c-minus'
19408 ;; would call `org-cycle-list-bullet' otherwise.
19409 ((org-at-item-p)
19410 (while (< (point) end)
19411 (when (org-at-item-p)
19412 (skip-chars-forward " \t")
19413 (delete-region (point) (match-end 0)))
19414 (forward-line)))
19415 ;; Case 2. Start at an heading: convert to items.
19416 ((org-at-heading-p)
19417 (let* ((bul (org-list-bullet-string "-"))
19418 (bul-len (length bul))
19419 ;; Indentation of the first heading. It should be
19420 ;; relative to the indentation of its parent, if any.
19421 (start-ind (save-excursion
19422 (cond
19423 ((not org-adapt-indentation) 0)
19424 ((not (outline-previous-heading)) 0)
19425 (t (length (match-string 0))))))
19426 ;; Level of first heading. Further headings will be
19427 ;; compared to it to determine hierarchy in the list.
19428 (ref-level (org-reduced-level (org-outline-level))))
19429 (while (< (point) end)
19430 (let* ((level (org-reduced-level (org-outline-level)))
19431 (delta (max 0 (- level ref-level))))
19432 ;; If current headline is less indented than the first
19433 ;; one, set it as reference, in order to preserve
19434 ;; subtrees.
19435 (when (< level ref-level) (setq ref-level level))
19436 (replace-match bul t t)
19437 (org-indent-line-to (+ start-ind (* delta bul-len)))
19438 ;; Ensure all text down to END (or SECTION-END) belongs
19439 ;; to the newly created item.
19440 (let ((section-end (save-excursion
19441 (or (outline-next-heading) (point)))))
19442 (forward-line)
19443 (funcall shift-text
19444 (+ start-ind (* (1+ delta) bul-len))
19445 (min end section-end)))))))
19446 ;; Case 3. Normal line with ARG: turn each non-item line into
19447 ;; an item.
19448 (arg
19449 (while (< (point) end)
19450 (unless (or (org-at-heading-p) (org-at-item-p))
19451 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19452 (replace-match
19453 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19454 (forward-line)))
19455 ;; Case 4. Normal line without ARG: make the first line of
19456 ;; region an item, and shift indentation of others
19457 ;; lines to set them as item's body.
19458 (t (let* ((bul (org-list-bullet-string "-"))
19459 (bul-len (length bul))
19460 (ref-ind (org-get-indentation)))
19461 (skip-chars-forward " \t")
19462 (insert bul)
19463 (forward-line)
19464 (while (< (point) end)
19465 ;; Ensure that lines less indented than first one
19466 ;; still get included in item body.
19467 (funcall shift-text
19468 (+ ref-ind bul-len)
19469 (min end (save-excursion (or (outline-next-heading)
19470 (point)))))
19471 (forward-line)))))))))
19473 (defun org-toggle-heading (&optional nstars)
19474 "Convert headings to normal text, or items or text to headings.
19475 If there is no active region, only the current line is considered.
19477 With a \\[universal-argument] prefix, convert the whole list at
19478 point into heading.
19480 In a region:
19482 - If the first non blank line is an headline, remove the stars
19483 from all headlines in the region.
19485 - If it is a normal line turn each and every normal line (i.e. not an
19486 heading or an item) in the region into a heading.
19488 - If it is a plain list item, turn all plain list items into headings.
19490 When converting a line into a heading, the number of stars is chosen
19491 such that the lines become children of the current entry. However,
19492 when a prefix argument is given, its value determines the number of
19493 stars to add."
19494 (interactive "P")
19495 (let ((skip-blanks
19496 (function
19497 ;; Return beginning of first non-blank line, starting from
19498 ;; line at POS.
19499 (lambda (pos)
19500 (save-excursion
19501 (goto-char pos)
19502 (while (org-at-comment-p) (forward-line))
19503 (skip-chars-forward " \r\t\n")
19504 (point-at-bol)))))
19505 beg end toggled)
19506 ;; Determine boundaries of changes. If a universal prefix has
19507 ;; been given, put the list in a region. If region ends at a bol,
19508 ;; do not consider the last line to be in the region.
19510 (when (and current-prefix-arg (org-at-item-p))
19511 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19512 (org-mark-element))
19514 (if (org-region-active-p)
19515 (setq beg (funcall skip-blanks (region-beginning))
19516 end (copy-marker (save-excursion
19517 (goto-char (region-end))
19518 (if (bolp) (point) (point-at-eol)))))
19519 (setq beg (funcall skip-blanks (point-at-bol))
19520 end (copy-marker (point-at-eol))))
19521 ;; Ensure inline tasks don't count as headings.
19522 (org-with-limited-levels
19523 (save-excursion
19524 (goto-char beg)
19525 (cond
19526 ;; Case 1. Started at an heading: de-star headings.
19527 ((org-at-heading-p)
19528 (while (< (point) end)
19529 (when (org-at-heading-p t)
19530 (looking-at org-outline-regexp) (replace-match "")
19531 (setq toggled t))
19532 (forward-line)))
19533 ;; Case 2. Started at an item: change items into headlines.
19534 ;; One star will be added by `org-list-to-subtree'.
19535 ((org-at-item-p)
19536 (let* ((stars (make-string
19537 (if nstars
19538 ;; subtract the star that will be added again by
19539 ;; `org-list-to-subtree'
19540 (1- (prefix-numeric-value current-prefix-arg))
19541 (or (org-current-level) 0))
19542 ?*))
19543 (add-stars
19544 (cond (nstars "") ; stars from prefix only
19545 ((equal stars "") "") ; before first heading
19546 (org-odd-levels-only "*") ; inside heading, odd
19547 (t "")))) ; inside heading, oddeven
19548 (while (< (point) end)
19549 (when (org-at-item-p)
19550 ;; Pay attention to cases when region ends before list.
19551 (let* ((struct (org-list-struct))
19552 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19553 (save-restriction
19554 (narrow-to-region (point) list-end)
19555 (insert
19556 (org-list-to-subtree
19557 (org-list-parse-list t)
19558 '(:istart (concat stars add-stars (funcall get-stars depth))
19559 :icount (concat stars add-stars (funcall get-stars depth)))))))
19560 (setq toggled t))
19561 (forward-line))))
19562 ;; Case 3. Started at normal text: make every line an heading,
19563 ;; skipping headlines and items.
19564 (t (let* ((stars (make-string
19565 (if nstars
19566 (prefix-numeric-value current-prefix-arg)
19567 (or (org-current-level) 0))
19568 ?*))
19569 (add-stars
19570 (cond (nstars "") ; stars from prefix only
19571 ((equal stars "") "*") ; before first heading
19572 (org-odd-levels-only "**") ; inside heading, odd
19573 (t "*"))) ; inside heading, oddeven
19574 (rpl (concat stars add-stars " ")))
19575 (while (< (point) end)
19576 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19577 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19578 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19579 (forward-line)))))))
19580 (unless toggled (message "Cannot toggle heading from here"))))
19582 (defun org-meta-return (&optional arg)
19583 "Insert a new heading or wrap a region in a table.
19584 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19585 See the individual commands for more information."
19586 (interactive "P")
19587 (cond
19588 ((run-hook-with-args-until-success 'org-metareturn-hook))
19589 ((or (org-at-drawer-p) (org-at-property-p))
19590 (newline-and-indent))
19591 ((org-at-table-p)
19592 (call-interactively 'org-table-wrap-region))
19593 (t (call-interactively 'org-insert-heading))))
19595 ;;; Menu entries
19597 (defsubst org-in-subtree-not-table-p ()
19598 "Are we in a subtree and not in a table?"
19599 (and (not (org-before-first-heading-p))
19600 (not (org-at-table-p))))
19602 ;; Define the Org-mode menus
19603 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19604 '("Tbl"
19605 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19606 ["Next Field" org-cycle (org-at-table-p)]
19607 ["Previous Field" org-shifttab (org-at-table-p)]
19608 ["Next Row" org-return (org-at-table-p)]
19609 "--"
19610 ["Blank Field" org-table-blank-field (org-at-table-p)]
19611 ["Edit Field" org-table-edit-field (org-at-table-p)]
19612 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19613 "--"
19614 ("Column"
19615 ["Move Column Left" org-metaleft (org-at-table-p)]
19616 ["Move Column Right" org-metaright (org-at-table-p)]
19617 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19618 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19619 ("Row"
19620 ["Move Row Up" org-metaup (org-at-table-p)]
19621 ["Move Row Down" org-metadown (org-at-table-p)]
19622 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19623 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19624 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19625 "--"
19626 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19627 ("Rectangle"
19628 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19629 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19630 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19631 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19632 "--"
19633 ("Calculate"
19634 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19635 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19636 ["Edit Formulas" org-edit-special (org-at-table-p)]
19637 "--"
19638 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19639 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19640 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19641 "--"
19642 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19643 "--"
19644 ["Sum Column/Rectangle" org-table-sum
19645 (or (org-at-table-p) (org-region-active-p))]
19646 ["Which Column?" org-table-current-column (org-at-table-p)])
19647 ["Debug Formulas"
19648 org-table-toggle-formula-debugger
19649 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19650 ["Show Col/Row Numbers"
19651 org-table-toggle-coordinate-overlays
19652 :style toggle
19653 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19654 "--"
19655 ["Create" org-table-create (and (not (org-at-table-p))
19656 org-enable-table-editor)]
19657 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19658 ["Import from File" org-table-import (not (org-at-table-p))]
19659 ["Export to File" org-table-export (org-at-table-p)]
19660 "--"
19661 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19663 (easy-menu-define org-org-menu org-mode-map "Org menu"
19664 '("Org"
19665 ("Show/Hide"
19666 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19667 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19668 ["Sparse Tree..." org-sparse-tree t]
19669 ["Reveal Context" org-reveal t]
19670 ["Show All" show-all t]
19671 "--"
19672 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19673 "--"
19674 ["New Heading" org-insert-heading t]
19675 ("Navigate Headings"
19676 ["Up" outline-up-heading t]
19677 ["Next" outline-next-visible-heading t]
19678 ["Previous" outline-previous-visible-heading t]
19679 ["Next Same Level" outline-forward-same-level t]
19680 ["Previous Same Level" outline-backward-same-level t]
19681 "--"
19682 ["Jump" org-goto t])
19683 ("Edit Structure"
19684 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19685 "--"
19686 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19687 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19688 "--"
19689 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19690 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19691 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19692 "--"
19693 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19694 "--"
19695 ["Copy visible text" org-copy-visible t]
19696 "--"
19697 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19698 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19699 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19700 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19701 "--"
19702 ["Sort Region/Children" org-sort t]
19703 "--"
19704 ["Convert to odd levels" org-convert-to-odd-levels t]
19705 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19706 ("Editing"
19707 ["Emphasis..." org-emphasize t]
19708 ["Edit Source Example" org-edit-special t]
19709 "--"
19710 ["Footnote new/jump" org-footnote-action t]
19711 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19712 ("Archive"
19713 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19714 "--"
19715 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19716 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19717 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19719 "--"
19720 ("Hyperlinks"
19721 ["Store Link (Global)" org-store-link t]
19722 ["Find existing link to here" org-occur-link-in-agenda-files t]
19723 ["Insert Link" org-insert-link t]
19724 ["Follow Link" org-open-at-point t]
19725 "--"
19726 ["Next link" org-next-link t]
19727 ["Previous link" org-previous-link t]
19728 "--"
19729 ["Descriptive Links"
19730 org-toggle-link-display
19731 :style radio
19732 :selected org-descriptive-links
19734 ["Literal Links"
19735 org-toggle-link-display
19736 :style radio
19737 :selected (not org-descriptive-links)])
19738 "--"
19739 ("TODO Lists"
19740 ["TODO/DONE/-" org-todo t]
19741 ("Select keyword"
19742 ["Next keyword" org-shiftright (org-at-heading-p)]
19743 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19744 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19745 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19746 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19747 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19748 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19749 "--"
19750 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19751 :selected org-enforce-todo-dependencies :style toggle :active t]
19752 "Settings for tree at point"
19753 ["Do Children sequentially" org-toggle-ordered-property :style radio
19754 :selected (org-entry-get nil "ORDERED")
19755 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19756 ["Do Children parallel" org-toggle-ordered-property :style radio
19757 :selected (not (org-entry-get nil "ORDERED"))
19758 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19759 "--"
19760 ["Set Priority" org-priority t]
19761 ["Priority Up" org-shiftup t]
19762 ["Priority Down" org-shiftdown t]
19763 "--"
19764 ["Get news from all feeds" org-feed-update-all t]
19765 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19766 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19767 ("TAGS and Properties"
19768 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19769 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19770 "--"
19771 ["Set property" org-set-property (not (org-before-first-heading-p))]
19772 ["Column view of properties" org-columns t]
19773 ["Insert Column View DBlock" org-insert-columns-dblock t])
19774 ("Dates and Scheduling"
19775 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19776 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19777 ("Change Date"
19778 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19779 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19780 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19781 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19782 ["Compute Time Range" org-evaluate-time-range t]
19783 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19784 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19785 "--"
19786 ["Custom time format" org-toggle-time-stamp-overlays
19787 :style radio :selected org-display-custom-times]
19788 "--"
19789 ["Goto Calendar" org-goto-calendar t]
19790 ["Date from Calendar" org-date-from-calendar t]
19791 "--"
19792 ["Start/Restart Timer" org-timer-start t]
19793 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19794 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19795 ["Insert Timer String" org-timer t]
19796 ["Insert Timer Item" org-timer-item t])
19797 ("Logging work"
19798 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19799 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19800 ["Clock out" org-clock-out t]
19801 ["Clock cancel" org-clock-cancel t]
19802 "--"
19803 ["Mark as default task" org-clock-mark-default-task t]
19804 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19805 ["Goto running clock" org-clock-goto t]
19806 "--"
19807 ["Display times" org-clock-display t]
19808 ["Create clock table" org-clock-report t]
19809 "--"
19810 ["Record DONE time"
19811 (progn (setq org-log-done (not org-log-done))
19812 (message "Switching to %s will %s record a timestamp"
19813 (car org-done-keywords)
19814 (if org-log-done "automatically" "not")))
19815 :style toggle :selected org-log-done])
19816 "--"
19817 ["Agenda Command..." org-agenda t]
19818 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19819 ("File List for Agenda")
19820 ("Special views current file"
19821 ["TODO Tree" org-show-todo-tree t]
19822 ["Check Deadlines" org-check-deadlines t]
19823 ["Timeline" org-timeline t]
19824 ["Tags/Property tree" org-match-sparse-tree t])
19825 "--"
19826 ["Export/Publish..." org-export t]
19827 ("LaTeX"
19828 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19829 :selected org-cdlatex-mode]
19830 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19831 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19832 ["Modify math symbol" org-cdlatex-math-modify
19833 (org-inside-LaTeX-fragment-p)]
19834 ["Insert citation" org-reftex-citation t]
19835 "--"
19836 ["Template for BEAMER" (progn (require 'org-beamer)
19837 (org-insert-beamer-options-template)) t])
19838 "--"
19839 ("MobileOrg"
19840 ["Push Files and Views" org-mobile-push t]
19841 ["Get Captured and Flagged" org-mobile-pull t]
19842 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19843 "--"
19844 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19845 "--"
19846 ("Documentation"
19847 ["Show Version" org-version t]
19848 ["Info Documentation" org-info t])
19849 ("Customize"
19850 ["Browse Org Group" org-customize t]
19851 "--"
19852 ["Expand This Menu" org-create-customize-menu
19853 (fboundp 'customize-menu-create)])
19854 ["Send bug report" org-submit-bug-report t]
19855 "--"
19856 ("Refresh/Reload"
19857 ["Refresh setup current buffer" org-mode-restart t]
19858 ["Reload Org (after update)" org-reload t]
19859 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
19862 (defun org-info (&optional node)
19863 "Read documentation for Org-mode in the info system.
19864 With optional NODE, go directly to that node."
19865 (interactive)
19866 (info (format "(org)%s" (or node ""))))
19868 ;;;###autoload
19869 (defun org-submit-bug-report ()
19870 "Submit a bug report on Org-mode via mail.
19872 Don't hesitate to report any problems or inaccurate documentation.
19874 If you don't have setup sending mail from (X)Emacs, please copy the
19875 output buffer into your mail program, as it gives us important
19876 information about your Org-mode version and configuration."
19877 (interactive)
19878 (require 'reporter)
19879 (org-load-modules-maybe)
19880 (org-require-autoloaded-modules)
19881 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19882 (reporter-submit-bug-report
19883 "emacs-orgmode@gnu.org"
19884 (org-version nil 'full)
19885 (let (list)
19886 (save-window-excursion
19887 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19888 (delete-other-windows)
19889 (erase-buffer)
19890 (insert "You are about to submit a bug report to the Org-mode mailing list.
19892 We would like to add your full Org-mode and Outline configuration to the
19893 bug report. This greatly simplifies the work of the maintainer and
19894 other experts on the mailing list.
19896 HOWEVER, some variables you have customized may contain private
19897 information. The names of customers, colleagues, or friends, might
19898 appear in the form of file names, tags, todo states, or search strings.
19899 If you answer yes to the prompt, you might want to check and remove
19900 such private information before sending the email.")
19901 (add-text-properties (point-min) (point-max) '(face org-warning))
19902 (when (yes-or-no-p "Include your Org-mode configuration ")
19903 (mapatoms
19904 (lambda (v)
19905 (and (boundp v)
19906 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19907 (or (and (symbol-value v)
19908 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19909 (and
19910 (get v 'custom-type) (get v 'standard-value)
19911 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19912 (push v list)))))
19913 (kill-buffer (get-buffer "*Warn about privacy*"))
19914 list))
19915 nil nil
19916 "Remember to cover the basics, that is, what you expected to happen and
19917 what in fact did happen. You don't know how to make a good report? See
19919 http://orgmode.org/manual/Feedback.html#Feedback
19921 Your bug report will be posted to the Org-mode mailing list.
19922 ------------------------------------------------------------------------")
19923 (save-excursion
19924 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19925 (replace-match "\\1Bug: \\3 [\\2]")))))
19928 (defun org-install-agenda-files-menu ()
19929 (let ((bl (buffer-list)))
19930 (save-excursion
19931 (while bl
19932 (set-buffer (pop bl))
19933 (if (derived-mode-p 'org-mode) (setq bl nil)))
19934 (when (derived-mode-p 'org-mode)
19935 (easy-menu-change
19936 '("Org") "File List for Agenda"
19937 (append
19938 (list
19939 ["Edit File List" (org-edit-agenda-file-list) t]
19940 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19941 ["Remove Current File from List" org-remove-file t]
19942 ["Cycle through agenda files" org-cycle-agenda-files t]
19943 ["Occur in all agenda files" org-occur-in-agenda-files t]
19944 "--")
19945 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19947 ;;;; Documentation
19949 (defun org-require-autoloaded-modules ()
19950 (interactive)
19951 (mapc 'require
19952 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19953 org-docbook org-exp org-html org-icalendar
19954 org-id org-latex
19955 org-publish org-remember org-table
19956 org-timer org-xoxo)))
19958 ;;;###autoload
19959 (defun org-reload (&optional uncompiled)
19960 "Reload all org lisp files.
19961 With prefix arg UNCOMPILED, load the uncompiled versions."
19962 (interactive "P")
19963 (require 'find-func)
19964 (let* ((file-re "^org\\(-.*\\)?\\.el")
19965 (dir-org (file-name-directory (org-find-library-dir "org")))
19966 (dir-org-contrib (ignore-errors
19967 (file-name-directory
19968 (org-find-library-dir "org-contribdir"))))
19969 (babel-files
19970 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19971 (append (list nil "comint" "eval" "exp" "keys"
19972 "lob" "ref" "table" "tangle")
19973 (delq nil
19974 (mapcar
19975 (lambda (lang)
19976 (when (cdr lang) (symbol-name (car lang))))
19977 org-babel-load-languages)))))
19978 (files
19979 (append babel-files
19980 (and dir-org-contrib
19981 (directory-files dir-org-contrib t file-re))
19982 (directory-files dir-org t file-re)))
19983 (remove-re (concat (if (featurep 'xemacs)
19984 "org-colview" "org-colview-xemacs")
19985 "\\'")))
19986 (setq files (mapcar 'file-name-sans-extension files))
19987 (setq files (mapcar
19988 (lambda (x) (if (string-match remove-re x) nil x))
19989 files))
19990 (setq files (delq nil files))
19991 (mapc
19992 (lambda (f)
19993 (when (featurep (intern (file-name-nondirectory f)))
19994 (if (and (not uncompiled)
19995 (file-exists-p (concat f ".elc")))
19996 (load (concat f ".elc") nil nil 'nosuffix)
19997 (load (concat f ".el") nil nil 'nosuffix))))
19998 files)
19999 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20000 (org-version nil 'full 'message))
20002 ;;;###autoload
20003 (defun org-customize ()
20004 "Call the customize function with org as argument."
20005 (interactive)
20006 (org-load-modules-maybe)
20007 (org-require-autoloaded-modules)
20008 (customize-browse 'org))
20010 (defun org-create-customize-menu ()
20011 "Create a full customization menu for Org-mode, insert it into the menu."
20012 (interactive)
20013 (org-load-modules-maybe)
20014 (org-require-autoloaded-modules)
20015 (if (fboundp 'customize-menu-create)
20016 (progn
20017 (easy-menu-change
20018 '("Org") "Customize"
20019 `(["Browse Org group" org-customize t]
20020 "--"
20021 ,(customize-menu-create 'org)
20022 ["Set" Custom-set t]
20023 ["Save" Custom-save t]
20024 ["Reset to Current" Custom-reset-current t]
20025 ["Reset to Saved" Custom-reset-saved t]
20026 ["Reset to Standard Settings" Custom-reset-standard t]))
20027 (message "\"Org\"-menu now contains full customization menu"))
20028 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20030 ;;;; Miscellaneous stuff
20032 ;;; Generally useful functions
20034 (defun org-get-at-bol (property)
20035 "Get text property PROPERTY at beginning of line."
20036 (get-text-property (point-at-bol) property))
20038 (defun org-find-text-property-in-string (prop s)
20039 "Return the first non-nil value of property PROP in string S."
20040 (or (get-text-property 0 prop s)
20041 (get-text-property (or (next-single-property-change 0 prop s) 0)
20042 prop s)))
20044 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20045 "Display the given MESSAGE as a warning."
20046 (if (fboundp 'display-warning)
20047 (display-warning 'org message
20048 (if (featurep 'xemacs) 'warning :warning))
20049 (let ((buf (get-buffer-create "*Org warnings*")))
20050 (with-current-buffer buf
20051 (goto-char (point-max))
20052 (insert "Warning (Org): " message)
20053 (unless (bolp)
20054 (newline)))
20055 (display-buffer buf)
20056 (sit-for 0))))
20058 (defun org-eval (form)
20059 "Eval FORM and return result."
20060 (condition-case error
20061 (eval form)
20062 (error (format "%%![Error: %s]" error))))
20064 (defun org-in-clocktable-p ()
20065 "Check if the cursor is in a clocktable."
20066 (let ((pos (point)) start)
20067 (save-excursion
20068 (end-of-line 1)
20069 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20070 (setq start (match-beginning 0))
20071 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20072 (>= (match-end 0) pos)
20073 start))))
20075 (defun org-in-commented-line ()
20076 "Is point in a line starting with `#'?"
20077 (equal (char-after (point-at-bol)) ?#))
20079 (defun org-in-indented-comment-line ()
20080 "Is point in a line starting with `#' after some white space?"
20081 (save-excursion
20082 (save-match-data
20083 (goto-char (point-at-bol))
20084 (looking-at "[ \t]*#"))))
20086 (defun org-in-verbatim-emphasis ()
20087 (save-match-data
20088 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20090 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20091 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20092 (if (and marker (marker-buffer marker)
20093 (buffer-live-p (marker-buffer marker)))
20094 (progn
20095 (org-pop-to-buffer-same-window (marker-buffer marker))
20096 (if (or (> marker (point-max)) (< marker (point-min)))
20097 (widen))
20098 (goto-char marker)
20099 (org-show-context 'org-goto))
20100 (if bookmark
20101 (bookmark-jump bookmark)
20102 (error "Cannot find location"))))
20104 (defun org-quote-csv-field (s)
20105 "Quote field for inclusion in CSV material."
20106 (if (string-match "[\",]" s)
20107 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20110 (defun org-force-self-insert (N)
20111 "Needed to enforce self-insert under remapping."
20112 (interactive "p")
20113 (self-insert-command N))
20115 (defun org-string-width (s)
20116 "Compute width of string, ignoring invisible characters.
20117 This ignores character with invisibility property `org-link', and also
20118 characters with property `org-cwidth', because these will become invisible
20119 upon the next fontification round."
20120 (let (b l)
20121 (when (or (eq t buffer-invisibility-spec)
20122 (assq 'org-link buffer-invisibility-spec))
20123 (while (setq b (text-property-any 0 (length s)
20124 'invisible 'org-link s))
20125 (setq s (concat (substring s 0 b)
20126 (substring s (or (next-single-property-change
20127 b 'invisible s) (length s)))))))
20128 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20129 (setq s (concat (substring s 0 b)
20130 (substring s (or (next-single-property-change
20131 b 'org-cwidth s) (length s))))))
20132 (setq l (string-width s) b -1)
20133 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20134 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20137 (defun org-shorten-string (s maxlength)
20138 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20139 If the string is shorter or has length MAXLENGTH, just return the
20140 original string. If it is longer, the functions finds a space in the
20141 string, breaks this string off at that locations and adds three dots
20142 as ellipsis. Including the ellipsis, the string will not be longer
20143 than MAXLENGTH. If finding a good breaking point in the string does
20144 not work, the string is just chopped off in the middle of a word
20145 if necessary."
20146 (if (<= (length s) maxlength)
20148 (let* ((n (max (- maxlength 4) 1))
20149 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20150 (if (string-match re s)
20151 (concat (match-string 1 s) "...")
20152 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20154 (defun org-get-indentation (&optional line)
20155 "Get the indentation of the current line, interpreting tabs.
20156 When LINE is given, assume it represents a line and compute its indentation."
20157 (if line
20158 (if (string-match "^ *" (org-remove-tabs line))
20159 (match-end 0))
20160 (save-excursion
20161 (beginning-of-line 1)
20162 (skip-chars-forward " \t")
20163 (current-column))))
20165 (defun org-get-string-indentation (s)
20166 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20167 (let ((n -1) (i 0) (w tab-width) c)
20168 (catch 'exit
20169 (while (< (setq n (1+ n)) (length s))
20170 (setq c (aref s n))
20171 (cond ((= c ?\ ) (setq i (1+ i)))
20172 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20173 (t (throw 'exit t)))))
20176 (defun org-remove-tabs (s &optional width)
20177 "Replace tabulators in S with spaces.
20178 Assumes that s is a single line, starting in column 0."
20179 (setq width (or width tab-width))
20180 (while (string-match "\t" s)
20181 (setq s (replace-match
20182 (make-string
20183 (- (* width (/ (+ (match-beginning 0) width) width))
20184 (match-beginning 0)) ?\ )
20185 t t s)))
20188 (defun org-fix-indentation (line ind)
20189 "Fix indentation in LINE.
20190 IND is a cons cell with target and minimum indentation.
20191 If the current indentation in LINE is smaller than the minimum,
20192 leave it alone. If it is larger than ind, set it to the target."
20193 (let* ((l (org-remove-tabs line))
20194 (i (org-get-indentation l))
20195 (i1 (car ind)) (i2 (cdr ind)))
20196 (if (>= i i2) (setq l (substring line i2)))
20197 (if (> i1 0)
20198 (concat (make-string i1 ?\ ) l)
20199 l)))
20201 (defun org-remove-indentation (code &optional n)
20202 "Remove the maximum common indentation from the lines in CODE.
20203 N may optionally be the number of spaces to remove."
20204 (with-temp-buffer
20205 (insert code)
20206 (org-do-remove-indentation n)
20207 (buffer-string)))
20209 (defun org-do-remove-indentation (&optional n)
20210 "Remove the maximum common indentation from the buffer."
20211 (untabify (point-min) (point-max))
20212 (let ((min 10000) re)
20213 (if n
20214 (setq min n)
20215 (goto-char (point-min))
20216 (while (re-search-forward "^ *[^ \n]" nil t)
20217 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20218 (unless (or (= min 0) (= min 10000))
20219 (setq re (format "^ \\{%d\\}" min))
20220 (goto-char (point-min))
20221 (while (re-search-forward re nil t)
20222 (replace-match "")
20223 (end-of-line 1))
20224 min)))
20226 (defun org-fill-template (template alist)
20227 "Find each %key of ALIST in TEMPLATE and replace it."
20228 (let ((case-fold-search nil)
20229 entry key value)
20230 (setq alist (sort (copy-sequence alist)
20231 (lambda (a b) (< (length (car a)) (length (car b))))))
20232 (while (setq entry (pop alist))
20233 (setq template
20234 (replace-regexp-in-string
20235 (concat "%" (regexp-quote (car entry)))
20236 (or (cdr entry) "") template t t)))
20237 template))
20239 (defun org-base-buffer (buffer)
20240 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20241 (if (not buffer)
20242 buffer
20243 (or (buffer-base-buffer buffer)
20244 buffer)))
20246 (defun org-trim (s)
20247 "Remove whitespace at beginning and end of string."
20248 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20249 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20252 (defun org-wrap (string &optional width lines)
20253 "Wrap string to either a number of lines, or a width in characters.
20254 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20255 that costs. If there is a word longer than WIDTH, the text is actually
20256 wrapped to the length of that word.
20257 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20258 many lines, whatever width that takes.
20259 The return value is a list of lines, without newlines at the end."
20260 (let* ((words (org-split-string string "[ \t\n]+"))
20261 (maxword (apply 'max (mapcar 'org-string-width words)))
20262 w ll)
20263 (cond (width
20264 (org-do-wrap words (max maxword width)))
20265 (lines
20266 (setq w maxword)
20267 (setq ll (org-do-wrap words maxword))
20268 (if (<= (length ll) lines)
20270 (setq ll words)
20271 (while (> (length ll) lines)
20272 (setq w (1+ w))
20273 (setq ll (org-do-wrap words w)))
20274 ll))
20275 (t (error "Cannot wrap this")))))
20277 (defun org-do-wrap (words width)
20278 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20279 (let (lines line)
20280 (while words
20281 (setq line (pop words))
20282 (while (and words (< (+ (length line) (length (car words))) width))
20283 (setq line (concat line " " (pop words))))
20284 (setq lines (push line lines)))
20285 (nreverse lines)))
20287 (defun org-split-string (string &optional separators)
20288 "Splits STRING into substrings at SEPARATORS.
20289 No empty strings are returned if there are matches at the beginning
20290 and end of string."
20291 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20292 (start 0)
20293 notfirst
20294 (list nil))
20295 (while (and (string-match rexp string
20296 (if (and notfirst
20297 (= start (match-beginning 0))
20298 (< start (length string)))
20299 (1+ start) start))
20300 (< (match-beginning 0) (length string)))
20301 (setq notfirst t)
20302 (or (eq (match-beginning 0) 0)
20303 (and (eq (match-beginning 0) (match-end 0))
20304 (eq (match-beginning 0) start))
20305 (setq list
20306 (cons (substring string start (match-beginning 0))
20307 list)))
20308 (setq start (match-end 0)))
20309 (or (eq start (length string))
20310 (setq list
20311 (cons (substring string start)
20312 list)))
20313 (nreverse list)))
20315 (defun org-quote-vert (s)
20316 "Replace \"|\" with \"\\vert\"."
20317 (while (string-match "|" s)
20318 (setq s (replace-match "\\vert" t t s)))
20321 (defun org-uuidgen-p (s)
20322 "Is S an ID created by UUIDGEN?"
20323 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20325 (defun org-in-src-block-p (&optional inside)
20326 "Whether point is in a code source block.
20327 When INSIDE is non-nil, don't consider we are within a src block
20328 when point is at #+BEGIN_SRC or #+END_SRC."
20329 (let ((case-fold-search t) ov)
20330 (or (and (setq ov (overlays-at (point)))
20331 (memq 'org-block-background
20332 (overlay-properties (car ov))))
20333 (and (not inside)
20334 (save-match-data
20335 (save-excursion
20336 (beginning-of-line)
20337 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20339 (defun org-context ()
20340 "Return a list of contexts of the current cursor position.
20341 If several contexts apply, all are returned.
20342 Each context entry is a list with a symbol naming the context, and
20343 two positions indicating start and end of the context. Possible
20344 contexts are:
20346 :headline anywhere in a headline
20347 :headline-stars on the leading stars in a headline
20348 :todo-keyword on a TODO keyword (including DONE) in a headline
20349 :tags on the TAGS in a headline
20350 :priority on the priority cookie in a headline
20351 :item on the first line of a plain list item
20352 :item-bullet on the bullet/number of a plain list item
20353 :checkbox on the checkbox in a plain list item
20354 :table in an org-mode table
20355 :table-special on a special filed in a table
20356 :table-table in a table.el table
20357 :clocktable in a clocktable
20358 :src-block in a source block
20359 :link on a hyperlink
20360 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20361 :target on a <<target>>
20362 :radio-target on a <<<radio-target>>>
20363 :latex-fragment on a LaTeX fragment
20364 :latex-preview on a LaTeX fragment with overlaid preview image
20366 This function expects the position to be visible because it uses font-lock
20367 faces as a help to recognize the following contexts: :table-special, :link,
20368 and :keyword."
20369 (let* ((f (get-text-property (point) 'face))
20370 (faces (if (listp f) f (list f)))
20371 (case-fold-search t)
20372 (p (point)) clist o)
20373 ;; First the large context
20374 (cond
20375 ((org-at-heading-p t)
20376 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20377 (when (progn
20378 (beginning-of-line 1)
20379 (looking-at org-todo-line-tags-regexp))
20380 (push (org-point-in-group p 1 :headline-stars) clist)
20381 (push (org-point-in-group p 2 :todo-keyword) clist)
20382 (push (org-point-in-group p 4 :tags) clist))
20383 (goto-char p)
20384 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20385 (if (looking-at "\\[#[A-Z0-9]\\]")
20386 (push (org-point-in-group p 0 :priority) clist)))
20388 ((org-at-item-p)
20389 (push (org-point-in-group p 2 :item-bullet) clist)
20390 (push (list :item (point-at-bol)
20391 (save-excursion (org-end-of-item) (point)))
20392 clist)
20393 (and (org-at-item-checkbox-p)
20394 (push (org-point-in-group p 0 :checkbox) clist)))
20396 ((org-at-table-p)
20397 (push (list :table (org-table-begin) (org-table-end)) clist)
20398 (if (memq 'org-formula faces)
20399 (push (list :table-special
20400 (previous-single-property-change p 'face)
20401 (next-single-property-change p 'face)) clist)))
20402 ((org-at-table-p 'any)
20403 (push (list :table-table) clist)))
20404 (goto-char p)
20406 (let ((case-fold-search t))
20407 ;; New the "medium" contexts: clocktables, source blocks
20408 (cond ((org-in-clocktable-p)
20409 (push (list :clocktable
20410 (and (or (looking-at "#\\+BEGIN: clocktable")
20411 (search-backward "#+BEGIN: clocktable" nil t))
20412 (match-beginning 0))
20413 (and (re-search-forward "#\\+END:?" nil t)
20414 (match-end 0))) clist))
20415 ((org-in-src-block-p)
20416 (push (list :src-block
20417 (and (or (looking-at "#\\+BEGIN_SRC")
20418 (search-backward "#+BEGIN_SRC" nil t))
20419 (match-beginning 0))
20420 (and (search-forward "#+END_SRC" nil t)
20421 (match-beginning 0))) clist))))
20422 (goto-char p)
20424 ;; Now the small context
20425 (cond
20426 ((org-at-timestamp-p)
20427 (push (org-point-in-group p 0 :timestamp) clist))
20428 ((memq 'org-link faces)
20429 (push (list :link
20430 (previous-single-property-change p 'face)
20431 (next-single-property-change p 'face)) clist))
20432 ((memq 'org-special-keyword faces)
20433 (push (list :keyword
20434 (previous-single-property-change p 'face)
20435 (next-single-property-change p 'face)) clist))
20436 ((org-at-target-p)
20437 (push (org-point-in-group p 0 :target) clist)
20438 (goto-char (1- (match-beginning 0)))
20439 (if (looking-at org-radio-target-regexp)
20440 (push (org-point-in-group p 0 :radio-target) clist))
20441 (goto-char p))
20442 ((setq o (car (delq nil
20443 (mapcar
20444 (lambda (x)
20445 (if (memq x org-latex-fragment-image-overlays) x))
20446 (overlays-at (point))))))
20447 (push (list :latex-fragment
20448 (overlay-start o) (overlay-end o)) clist)
20449 (push (list :latex-preview
20450 (overlay-start o) (overlay-end o)) clist))
20451 ((org-inside-LaTeX-fragment-p)
20452 ;; FIXME: positions wrong.
20453 (push (list :latex-fragment (point) (point)) clist)))
20455 (setq clist (nreverse (delq nil clist)))
20456 clist))
20458 ;; FIXME: Compare with at-regexp-p Do we need both?
20459 (defun org-in-regexp (re &optional nlines visually)
20460 "Check if point is inside a match of regexp.
20461 Normally only the current line is checked, but you can include NLINES extra
20462 lines both before and after point into the search.
20463 If VISUALLY is set, require that the cursor is not after the match but
20464 really on, so that the block visually is on the match."
20465 (catch 'exit
20466 (let ((pos (point))
20467 (eol (point-at-eol (+ 1 (or nlines 0))))
20468 (inc (if visually 1 0)))
20469 (save-excursion
20470 (beginning-of-line (- 1 (or nlines 0)))
20471 (while (re-search-forward re eol t)
20472 (if (and (<= (match-beginning 0) pos)
20473 (>= (+ inc (match-end 0)) pos))
20474 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20476 (defun org-at-regexp-p (regexp)
20477 "Is point inside a match of REGEXP in the current line?"
20478 (catch 'exit
20479 (save-excursion
20480 (let ((pos (point)) (end (point-at-eol)))
20481 (beginning-of-line 1)
20482 (while (re-search-forward regexp end t)
20483 (if (and (<= (match-beginning 0) pos)
20484 (>= (match-end 0) pos))
20485 (throw 'exit t)))
20486 nil))))
20488 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20489 "Non-nil when point is between matches of START-RE and END-RE.
20491 Also return a non-nil value when point is on one of the matches.
20493 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20494 buffer positions. Default values are the positions of headlines
20495 surrounding the point.
20497 The functions returns a cons cell whose car (resp. cdr) is the
20498 position before START-RE (resp. after END-RE)."
20499 (save-match-data
20500 (let ((pos (point))
20501 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20502 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20503 beg end)
20504 (save-excursion
20505 ;; Point is on a block when on START-RE or if START-RE can be
20506 ;; found before it...
20507 (and (or (org-at-regexp-p start-re)
20508 (re-search-backward start-re limit-up t))
20509 (setq beg (match-beginning 0))
20510 ;; ... and END-RE after it...
20511 (goto-char (match-end 0))
20512 (re-search-forward end-re limit-down t)
20513 (> (setq end (match-end 0)) pos)
20514 ;; ... without another START-RE in-between.
20515 (goto-char (match-beginning 0))
20516 (not (re-search-backward start-re (1+ beg) t))
20517 ;; Return value.
20518 (cons beg end))))))
20520 (defun org-in-block-p (names)
20521 "Non-nil when point belongs to a block whose name belongs to NAMES.
20523 NAMES is a list of strings containing names of blocks.
20525 Return first block name matched, or nil. Beware that in case of
20526 nested blocks, the returned name may not belong to the closest
20527 block from point."
20528 (save-match-data
20529 (catch 'exit
20530 (let ((case-fold-search t)
20531 (lim-up (save-excursion (outline-previous-heading)))
20532 (lim-down (save-excursion (outline-next-heading))))
20533 (mapc (lambda (name)
20534 (let ((n (regexp-quote name)))
20535 (when (org-between-regexps-p
20536 (concat "^[ \t]*#\\+begin_" n)
20537 (concat "^[ \t]*#\\+end_" n)
20538 lim-up lim-down)
20539 (throw 'exit n))))
20540 names))
20541 nil)))
20543 (defun org-occur-in-agenda-files (regexp &optional nlines)
20544 "Call `multi-occur' with buffers for all agenda files."
20545 (interactive "sOrg-files matching: \np")
20546 (let* ((files (org-agenda-files))
20547 (tnames (mapcar 'file-truename files))
20548 (extra org-agenda-text-search-extra-files)
20550 (when (eq (car extra) 'agenda-archives)
20551 (setq extra (cdr extra))
20552 (setq files (org-add-archive-files files)))
20553 (while (setq f (pop extra))
20554 (unless (member (file-truename f) tnames)
20555 (add-to-list 'files f 'append)
20556 (add-to-list 'tnames (file-truename f) 'append)))
20557 (multi-occur
20558 (mapcar (lambda (x)
20559 (with-current-buffer
20560 (or (get-file-buffer x) (find-file-noselect x))
20561 (widen)
20562 (current-buffer)))
20563 files)
20564 regexp)))
20566 (if (boundp 'occur-mode-find-occurrence-hook)
20567 ;; Emacs 23
20568 (add-hook 'occur-mode-find-occurrence-hook
20569 (lambda ()
20570 (when (derived-mode-p 'org-mode)
20571 (org-reveal))))
20572 ;; Emacs 22
20573 (defadvice occur-mode-goto-occurrence
20574 (after org-occur-reveal activate)
20575 (and (derived-mode-p 'org-mode) (org-reveal)))
20576 (defadvice occur-mode-goto-occurrence-other-window
20577 (after org-occur-reveal activate)
20578 (and (derived-mode-p 'org-mode) (org-reveal)))
20579 (defadvice occur-mode-display-occurrence
20580 (after org-occur-reveal activate)
20581 (when (derived-mode-p 'org-mode)
20582 (let ((pos (occur-mode-find-occurrence)))
20583 (with-current-buffer (marker-buffer pos)
20584 (save-excursion
20585 (goto-char pos)
20586 (org-reveal)))))))
20588 (defun org-occur-link-in-agenda-files ()
20589 "Create a link and search for it in the agendas.
20590 The link is not stored in `org-stored-links', it is just created
20591 for the search purpose."
20592 (interactive)
20593 (let ((link (condition-case nil
20594 (org-store-link nil)
20595 (error "Unable to create a link to here"))))
20596 (org-occur-in-agenda-files (regexp-quote link))))
20598 (defun org-uniquify (list)
20599 "Remove duplicate elements from LIST."
20600 (let (res)
20601 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20602 res))
20604 (defun org-delete-all (elts list)
20605 "Remove all elements in ELTS from LIST."
20606 (while elts
20607 (setq list (delete (pop elts) list)))
20608 list)
20610 (defun org-count (cl-item cl-seq)
20611 "Count the number of occurrences of ITEM in SEQ.
20612 Taken from `count' in cl-seq.el with all keyword arguments removed."
20613 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20614 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20615 (while (< cl-start cl-end)
20616 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20617 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20618 (setq cl-start (1+ cl-start)))
20619 cl-count))
20621 (defun org-remove-if (predicate seq)
20622 "Remove everything from SEQ that fulfills PREDICATE."
20623 (let (res e)
20624 (while seq
20625 (setq e (pop seq))
20626 (if (not (funcall predicate e)) (push e res)))
20627 (nreverse res)))
20629 (defun org-remove-if-not (predicate seq)
20630 "Remove everything from SEQ that does not fulfill PREDICATE."
20631 (let (res e)
20632 (while seq
20633 (setq e (pop seq))
20634 (if (funcall predicate e) (push e res)))
20635 (nreverse res)))
20637 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20638 "Reduce two-argument FUNCTION across SEQ.
20639 Taken from `reduce' in cl-seq.el with all keyword arguments but
20640 \":initial-value\" removed."
20641 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20642 (cadr (memq :initial-value cl-keys)))
20643 (cl-seq (pop cl-seq))
20644 (t (funcall cl-func)))))
20645 (while cl-seq
20646 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20647 cl-accum))
20649 (defun org-back-over-empty-lines ()
20650 "Move backwards over whitespace, to the beginning of the first empty line.
20651 Returns the number of empty lines passed."
20652 (let ((pos (point)))
20653 (if (cdr (assoc 'heading org-blank-before-new-entry))
20654 (skip-chars-backward " \t\n\r")
20655 (unless (eobp)
20656 (forward-line -1)))
20657 (beginning-of-line 2)
20658 (goto-char (min (point) pos))
20659 (count-lines (point) pos)))
20661 (defun org-skip-whitespace ()
20662 (skip-chars-forward " \t\n\r"))
20664 (defun org-point-in-group (point group &optional context)
20665 "Check if POINT is in match-group GROUP.
20666 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20667 match. If the match group does not exist or point is not inside it,
20668 return nil."
20669 (and (match-beginning group)
20670 (>= point (match-beginning group))
20671 (<= point (match-end group))
20672 (if context
20673 (list context (match-beginning group) (match-end group))
20674 t)))
20676 (defun org-switch-to-buffer-other-window (&rest args)
20677 "Switch to buffer in a second window on the current frame.
20678 In particular, do not allow pop-up frames.
20679 Returns the newly created buffer."
20680 (org-no-popups
20681 (apply 'switch-to-buffer-other-window args)))
20683 (defun org-combine-plists (&rest plists)
20684 "Create a single property list from all plists in PLISTS.
20685 The process starts by copying the first list, and then setting properties
20686 from the other lists. Settings in the last list are the most significant
20687 ones and overrule settings in the other lists."
20688 (let ((rtn (copy-sequence (pop plists)))
20689 p v ls)
20690 (while plists
20691 (setq ls (pop plists))
20692 (while ls
20693 (setq p (pop ls) v (pop ls))
20694 (setq rtn (plist-put rtn p v))))
20695 rtn))
20697 (defun org-replace-escapes (string table)
20698 "Replace %-escapes in STRING with values in TABLE.
20699 TABLE is an association list with keys like \"%a\" and string values.
20700 The sequences in STRING may contain normal field width and padding information,
20701 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20702 so values can contain further %-escapes if they are define later in TABLE."
20703 (let ((tbl (copy-alist table))
20704 (case-fold-search nil)
20705 (pchg 0)
20706 e re rpl)
20707 (while (setq e (pop tbl))
20708 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20709 (when (and (cdr e) (string-match re (cdr e)))
20710 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20711 (safe "SREF"))
20712 (add-text-properties 0 3 (list 'sref sref) safe)
20713 (setcdr e (replace-match safe t t (cdr e)))))
20714 (while (string-match re string)
20715 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20716 (cdr e)))
20717 (setq string (replace-match rpl t t string))))
20718 (while (setq pchg (next-property-change pchg string))
20719 (let ((sref (get-text-property pchg 'sref string)))
20720 (when (and sref (string-match "SREF" string pchg))
20721 (setq string (replace-match sref t t string)))))
20722 string))
20724 (defun org-sublist (list start end)
20725 "Return a section of LIST, from START to END.
20726 Counting starts at 1."
20727 (let (rtn (c start))
20728 (setq list (nthcdr (1- start) list))
20729 (while (and list (<= c end))
20730 (push (pop list) rtn)
20731 (setq c (1+ c)))
20732 (nreverse rtn)))
20734 (defun org-find-base-buffer-visiting (file)
20735 "Like `find-buffer-visiting' but always return the base buffer and
20736 not an indirect buffer."
20737 (let ((buf (or (get-file-buffer file)
20738 (find-buffer-visiting file))))
20739 (if buf
20740 (or (buffer-base-buffer buf) buf)
20741 nil)))
20743 (defun org-image-file-name-regexp (&optional extensions)
20744 "Return regexp matching the file names of images.
20745 If EXTENSIONS is given, only match these."
20746 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20747 (image-file-name-regexp)
20748 (let ((image-file-name-extensions
20749 (or extensions
20750 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20751 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20752 (concat "\\."
20753 (regexp-opt (nconc (mapcar 'upcase
20754 image-file-name-extensions)
20755 image-file-name-extensions)
20757 "\\'"))))
20759 (defun org-file-image-p (file &optional extensions)
20760 "Return non-nil if FILE is an image."
20761 (save-match-data
20762 (string-match (org-image-file-name-regexp extensions) file)))
20764 (defun org-get-cursor-date ()
20765 "Return the date at cursor in as a time.
20766 This works in the calendar and in the agenda, anywhere else it just
20767 returns the current time."
20768 (let (date day defd)
20769 (cond
20770 ((eq major-mode 'calendar-mode)
20771 (setq date (calendar-cursor-to-date)
20772 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20773 ((eq major-mode 'org-agenda-mode)
20774 (setq day (get-text-property (point) 'day))
20775 (if day
20776 (setq date (calendar-gregorian-from-absolute day)
20777 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20778 (nth 2 date))))))
20779 (or defd (current-time))))
20781 (defun org-mark-subtree (&optional up)
20782 "Mark the current subtree.
20783 This puts point at the start of the current subtree, and mark at
20784 the end. If a numeric prefix UP is given, move up into the
20785 hierarchy of headlines by UP levels before marking the subtree."
20786 (interactive "P")
20787 (org-with-limited-levels
20788 (cond ((org-at-heading-p) (beginning-of-line))
20789 ((org-before-first-heading-p) (error "Not in a subtree"))
20790 (t (outline-previous-visible-heading 1))))
20791 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20792 (if (org-called-interactively-p 'any)
20793 (call-interactively 'org-mark-element)
20794 (org-mark-element)))
20796 ;;; Indentation
20798 (defun org-indent-line ()
20799 "Indent line depending on context."
20800 (interactive)
20801 (let* ((pos (point))
20802 (itemp (org-at-item-p))
20803 (case-fold-search t)
20804 (org-drawer-regexp (or org-drawer-regexp "\000"))
20805 (inline-task-p (and (featurep 'org-inlinetask)
20806 (org-inlinetask-in-task-p)))
20807 (inline-re (and inline-task-p
20808 (org-inlinetask-outline-regexp)))
20809 column)
20810 (if (and orgstruct-is-++ (eq pos (point)))
20811 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20812 (indent-according-to-mode))
20813 (beginning-of-line 1)
20814 (cond
20815 ;; Headings
20816 ((looking-at org-outline-regexp) (setq column 0))
20817 ;; Included files
20818 ((looking-at "#\\+include:") (setq column 0))
20819 ;; Footnote definition
20820 ((looking-at org-footnote-definition-re) (setq column 0))
20821 ;; Literal examples
20822 ((looking-at "[ \t]*:\\( \\|$\\)")
20823 (setq column (org-get-indentation))) ; do nothing
20824 ;; Lists
20825 ((ignore-errors (goto-char (org-in-item-p)))
20826 (setq column (if itemp
20827 (org-get-indentation)
20828 (org-list-item-body-column (point))))
20829 (goto-char pos))
20830 ;; Drawers
20831 ((and (looking-at "[ \t]*:END:")
20832 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20833 (save-excursion
20834 (goto-char (1- (match-beginning 1)))
20835 (setq column (current-column))))
20836 ;; Special blocks
20837 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20838 (save-excursion
20839 (re-search-backward
20840 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20841 (setq column (org-get-indentation (match-string 0))))
20842 ((and (not (looking-at "[ \t]*#\\+begin_"))
20843 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20844 (save-excursion
20845 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20846 (setq column
20847 (cond ((equal (downcase (match-string 1)) "src")
20848 ;; src blocks: let `org-edit-src-exit' handle them
20849 (org-get-indentation))
20850 ((equal (downcase (match-string 1)) "example")
20851 (max (org-get-indentation)
20852 (org-get-indentation (match-string 0))))
20854 (org-get-indentation (match-string 0))))))
20855 ;; This line has nothing special, look at the previous relevant
20856 ;; line to compute indentation
20858 (beginning-of-line 0)
20859 (while (and (not (bobp))
20860 (not (looking-at org-table-line-regexp))
20861 (not (looking-at org-drawer-regexp))
20862 ;; When point started in an inline task, do not move
20863 ;; above task starting line.
20864 (not (and inline-task-p (looking-at inline-re)))
20865 ;; Skip drawers, blocks, empty lines, verbatim,
20866 ;; comments, tables, footnotes definitions, lists,
20867 ;; inline tasks.
20868 (or (and (looking-at "[ \t]*:END:")
20869 (re-search-backward org-drawer-regexp nil t))
20870 (and (looking-at "[ \t]*#\\+end_")
20871 (re-search-backward "[ \t]*#\\+begin_"nil t))
20872 (looking-at "[ \t]*[\n:#|]")
20873 (looking-at org-footnote-definition-re)
20874 (and (ignore-errors (goto-char (org-in-item-p)))
20875 (goto-char
20876 (org-list-get-top-point (org-list-struct))))
20877 (and (not inline-task-p)
20878 (featurep 'org-inlinetask)
20879 (org-inlinetask-in-task-p)
20880 (or (org-inlinetask-goto-beginning) t))))
20881 (beginning-of-line 0))
20882 (cond
20883 ;; There was an heading above.
20884 ((looking-at "\\*+[ \t]+")
20885 (if (not org-adapt-indentation)
20886 (setq column 0)
20887 (goto-char (match-end 0))
20888 (setq column (current-column))))
20889 ;; A drawer had started and is unfinished
20890 ((looking-at org-drawer-regexp)
20891 (goto-char (1- (match-beginning 1)))
20892 (setq column (current-column)))
20893 ;; Else, nothing noticeable found: get indentation and go on.
20894 (t (setq column (org-get-indentation))))))
20895 ;; Now apply indentation and move cursor accordingly
20896 (goto-char pos)
20897 (if (<= (current-column) (current-indentation))
20898 (org-indent-line-to column)
20899 (save-excursion (org-indent-line-to column)))
20900 ;; Special polishing for properties, see `org-property-format'
20901 (setq column (current-column))
20902 (beginning-of-line 1)
20903 (if (looking-at
20904 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20905 (replace-match (concat (match-string 1)
20906 (format org-property-format
20907 (match-string 2) (match-string 3)))
20908 t t))
20909 (org-move-to-column column))))
20911 (defun org-indent-drawer ()
20912 "Indent the drawer at point."
20913 (interactive)
20914 (let ((p (point))
20915 (e (and (save-excursion (re-search-forward ":END:" nil t))
20916 (match-end 0)))
20917 (folded
20918 (save-excursion
20919 (end-of-line)
20920 (when (overlays-at (point))
20921 (member 'invisible (overlay-properties
20922 (car (overlays-at (point)))))))))
20923 (when folded (org-cycle))
20924 (indent-for-tab-command)
20925 (while (and (move-beginning-of-line 2) (< (point) e))
20926 (indent-for-tab-command))
20927 (goto-char p)
20928 (when folded (org-cycle)))
20929 (message "Drawer at point indented"))
20931 (defun org-indent-block ()
20932 "Indent the block at point."
20933 (interactive)
20934 (let ((p (point))
20935 (case-fold-search t)
20936 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20937 (match-end 0)))
20938 (folded
20939 (save-excursion
20940 (end-of-line)
20941 (when (overlays-at (point))
20942 (member 'invisible (overlay-properties
20943 (car (overlays-at (point)))))))))
20944 (when folded (org-cycle))
20945 (indent-for-tab-command)
20946 (while (and (move-beginning-of-line 2) (< (point) e))
20947 (indent-for-tab-command))
20948 (goto-char p)
20949 (when folded (org-cycle)))
20950 (message "Block at point indented"))
20952 (defun org-indent-region (start end)
20953 "Indent region."
20954 (interactive "r")
20955 (save-excursion
20956 (let ((line-end (org-current-line end)))
20957 (goto-char start)
20958 (while (< (org-current-line) line-end)
20959 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20960 (t (call-interactively 'org-indent-line)))
20961 (move-beginning-of-line 2)))))
20964 ;;; Filling
20966 ;; We use our own fill-paragraph and auto-fill functions.
20968 ;; `org-fill-paragraph' relies on adaptive filling and context
20969 ;; checking. Appropriate `fill-prefix' is computed with
20970 ;; `org-adaptive-fill-function'.
20972 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20973 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20974 ;; `org-adaptive-fill-function' value. Internally,
20975 ;; `org-comment-line-break-function' breaks the line.
20977 ;; `org-setup-filling' installs filling and auto-filling related
20978 ;; variables during `org-mode' initialization.
20980 (defun org-setup-filling ()
20981 (interactive)
20982 ;; Prevent auto-fill from inserting unwanted new items.
20983 (when (boundp 'fill-nobreak-predicate)
20984 (org-set-local
20985 'fill-nobreak-predicate
20986 (org-uniquify
20987 (append fill-nobreak-predicate
20988 '(org-fill-paragraph-separate-nobreak-p
20989 org-fill-line-break-nobreak-p
20990 org-fill-paragraph-with-timestamp-nobreak-p)))))
20991 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20992 (org-set-local 'auto-fill-inhibit-regexp nil)
20993 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20994 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20995 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20997 (defvar org-element-paragraph-separate) ; org-element.el
20998 (defun org-fill-paragraph-separate-nobreak-p ()
20999 "Non-nil when a line break at point would insert a new item."
21000 (looking-at (substring org-element-paragraph-separate 1)))
21002 (defun org-fill-line-break-nobreak-p ()
21003 "Non-nil when a line break at point would create an Org line break."
21004 (save-excursion
21005 (skip-chars-backward "[ \t]")
21006 (skip-chars-backward "\\\\")
21007 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21009 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21010 "Non-nil when a line break at point would insert a new item."
21011 (and (org-at-timestamp-p t)
21012 (not (looking-at org-ts-regexp-both))))
21014 (declare-function message-in-body-p "message" ())
21015 (defvar org-element--affiliated-re) ; From org-element.el
21016 (defvar orgtbl-line-start-regexp) ; From org-table.el
21017 (defun org-adaptive-fill-function ()
21018 "Compute a fill prefix for the current line.
21019 Return fill prefix, as a string, or nil if current line isn't
21020 meant to be filled."
21021 (let (prefix)
21022 (catch 'exit
21023 (when (derived-mode-p 'message-mode)
21024 (save-excursion
21025 (beginning-of-line)
21026 (cond ((or (not (message-in-body-p))
21027 (looking-at orgtbl-line-start-regexp))
21028 (throw 'exit nil))
21029 ((looking-at message-cite-prefix-regexp)
21030 (throw 'exit (match-string-no-properties 0)))
21031 ((looking-at org-outline-regexp)
21032 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21033 (org-with-wide-buffer
21034 (let* ((p (line-beginning-position))
21035 (element (save-excursion (beginning-of-line) (org-element-at-point)))
21036 (type (org-element-type element))
21037 (post-affiliated
21038 (save-excursion
21039 (goto-char (org-element-property :begin element))
21040 (while (looking-at org-element--affiliated-re) (forward-line))
21041 (point))))
21042 (unless (< p post-affiliated)
21043 (case type
21044 (comment (looking-at "[ \t]*# ?") (match-string 0))
21045 (footnote-definition "")
21046 ((item plain-list)
21047 (make-string (org-list-item-body-column post-affiliated) ? ))
21048 (paragraph
21049 ;; Fill prefix is usually the same as the current line,
21050 ;; except if the paragraph is at the beginning of an item.
21051 (let ((parent (org-element-property :parent element)))
21052 (cond ((eq (org-element-type parent) 'item)
21053 (make-string (org-list-item-body-column
21054 (org-element-property :begin parent))
21055 ? ))
21056 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21057 (match-string 0))
21058 (t ""))))
21059 (comment-block
21060 ;; Only fill contents if P is within block boundaries.
21061 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21062 (forward-line)
21063 (point)))
21064 (cend (save-excursion
21065 (goto-char (org-element-property :end element))
21066 (skip-chars-backward " \r\t\n")
21067 (line-beginning-position))))
21068 (when (and (>= p cbeg) (< p cend))
21069 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21070 (match-string 0)
21071 "")))))))))))
21073 (declare-function message-goto-body "message" ())
21074 (defvar message-cite-prefix-regexp) ; From message.el
21075 (defvar org-element-all-objects) ; From org-element.el
21076 (defun org-fill-paragraph (&optional justify)
21077 "Fill element at point, when applicable.
21079 This function only applies to comment blocks, comments, example
21080 blocks and paragraphs. Also, as a special case, re-align table
21081 when point is at one.
21083 If JUSTIFY is non-nil (interactively, with prefix argument),
21084 justify as well. If `sentence-end-double-space' is non-nil, then
21085 period followed by one space does not end a sentence, so don't
21086 break a line there. The variable `fill-column' controls the
21087 width for filling.
21089 For convenience, when point is at a plain list, an item or
21090 a footnote definition, try to fill the first paragraph within."
21091 (interactive)
21092 (if (and (derived-mode-p 'message-mode)
21093 (or (not (message-in-body-p))
21094 (save-excursion (move-beginning-of-line 1)
21095 (looking-at message-cite-prefix-regexp))))
21096 ;; First ensure filling is correct in message-mode.
21097 (let ((fill-paragraph-function
21098 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21099 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21100 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21101 (paragraph-separate
21102 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21103 (fill-paragraph nil))
21104 (save-excursion
21105 ;; Move to end of line in order to get the first paragraph
21106 ;; within a plain list or a footnote definition.
21107 (end-of-line)
21108 (let ((element (org-element-at-point)))
21109 ;; First check if point is in a blank line at the beginning of
21110 ;; the buffer. In that case, ignore filling.
21111 (if (< (point) (org-element-property :begin element)) t
21112 (case (org-element-type element)
21113 ;; Use major mode filling function is src blocks.
21114 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21115 ;; Align Org tables, leave table.el tables as-is.
21116 (table-row (org-table-align) t)
21117 (table
21118 (when (eq (org-element-property :type element) 'org)
21119 (org-table-align))
21121 (paragraph
21122 ;; Paragraphs may contain `line-break' type objects.
21123 (let ((beg (max (point-min)
21124 (org-element-property :contents-begin element)))
21125 (end (min (point-max)
21126 (org-element-property :contents-end element))))
21127 ;; Do nothing if point is at an affiliated keyword.
21128 (if (< (point) beg) t
21129 (when (derived-mode-p 'message-mode)
21130 ;; In `message-mode', do not fill following
21131 ;; citation in current paragraph nor text before
21132 ;; message body.
21133 (let ((body-start (save-excursion (message-goto-body))))
21134 (when body-start (setq beg (max body-start beg))))
21135 (when (save-excursion
21136 (re-search-forward
21137 (concat "^" message-cite-prefix-regexp) end t))
21138 (setq end (match-beginning 0))))
21139 ;; Fill paragraph, taking line breaks into
21140 ;; consideration. For that, slice the paragraph
21141 ;; using line breaks as separators, and fill the
21142 ;; parts in reverse order to avoid messing with
21143 ;; markers.
21144 (save-excursion
21145 (goto-char end)
21146 (mapc
21147 (lambda (pos)
21148 (fill-region-as-paragraph pos (point) justify)
21149 (goto-char pos))
21150 ;; Find the list of ending positions for line
21151 ;; breaks in the current paragraph. Add paragraph
21152 ;; beginning to include first slice.
21153 (nreverse
21154 (cons
21156 (org-element-map
21157 (org-element--parse-objects
21158 beg end nil org-element-all-objects)
21159 'line-break
21160 (lambda (lb) (org-element-property :end lb)))))))
21161 t)))
21162 ;; Contents of `comment-block' type elements should be
21163 ;; filled as plain text, but only if point is within block
21164 ;; markers.
21165 (comment-block
21166 (let* ((case-fold-search t)
21167 (beg (save-excursion
21168 (goto-char (org-element-property :begin element))
21169 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21170 (forward-line)
21171 (point)))
21172 (end (save-excursion
21173 (goto-char (org-element-property :end element))
21174 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21175 (line-beginning-position))))
21176 (when (and (>= (point) beg) (< (point) end))
21177 (fill-region-as-paragraph
21178 (save-excursion
21179 (end-of-line)
21180 (re-search-backward "^[ \t]*$" beg 'move)
21181 (line-beginning-position))
21182 (save-excursion
21183 (beginning-of-line)
21184 (re-search-forward "^[ \t]*$" end 'move)
21185 (line-beginning-position))
21186 justify)))
21188 ;; Fill comments.
21189 (comment (fill-comment-paragraph justify))
21190 ;; Ignore every other element.
21191 (otherwise t)))))))
21193 (defun org-auto-fill-function ()
21194 "Auto-fill function."
21195 ;; Check if auto-filling is meaningful.
21196 (let ((fc (current-fill-column)))
21197 (when (and fc (> (current-column) fc))
21198 (let* ((fill-prefix (org-adaptive-fill-function))
21199 ;; Enforce empty fill prefix, if required. Otherwise, it
21200 ;; will be computed again.
21201 (adaptive-fill-mode (not (equal fill-prefix ""))))
21202 (when fill-prefix (do-auto-fill))))))
21204 (defun org-comment-line-break-function (&optional soft)
21205 "Break line at point and indent, continuing comment if within one.
21206 The inserted newline is marked hard if variable
21207 `use-hard-newlines' is true, unless optional argument SOFT is
21208 non-nil."
21209 (if soft (insert-and-inherit ?\n) (newline 1))
21210 (save-excursion (forward-char -1) (delete-horizontal-space))
21211 (delete-horizontal-space)
21212 (indent-to-left-margin)
21213 (insert-before-markers-and-inherit fill-prefix))
21216 ;;; Comments
21218 ;; Org comments syntax is quite complex. It requires the entire line
21219 ;; to be just a comment. Also, even with the right syntax at the
21220 ;; beginning of line, some some elements (i.e. verse-block or
21221 ;; example-block) don't accept comments. Usual Emacs comment commands
21222 ;; cannot cope with those requirements. Therefore, Org replaces them.
21224 ;; Org still relies on `comment-dwim', but cannot trust
21225 ;; `comment-only-p'. So, `comment-region-function' and
21226 ;; `uncomment-region-function' both point
21227 ;; to`org-comment-or-uncomment-region'. Eventually,
21228 ;; `org-insert-comment' takes care of insertion of comments at the
21229 ;; beginning of line.
21231 ;; `org-setup-comments-handling' install comments related variables
21232 ;; during `org-mode' initialization.
21234 (defun org-setup-comments-handling ()
21235 (interactive)
21236 (org-set-local 'comment-use-syntax nil)
21237 (org-set-local 'comment-start "# ")
21238 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21239 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21240 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21241 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21243 (defun org-insert-comment ()
21244 "Insert an empty comment above current line.
21245 If the line is empty, insert comment at its beginning."
21246 (beginning-of-line)
21247 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21248 (org-indent-line)
21249 (insert "# "))
21251 (defvar comment-empty-lines) ; From newcomment.el.
21252 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21253 "Comment or uncomment each non-blank line in the region.
21254 Uncomment each non-blank line between BEG and END if it only
21255 contains commented lines. Otherwise, comment them."
21256 (save-restriction
21257 ;; Restrict region
21258 (narrow-to-region (save-excursion (goto-char beg)
21259 (skip-chars-forward " \r\t\n" end)
21260 (line-beginning-position))
21261 (save-excursion (goto-char end)
21262 (skip-chars-backward " \r\t\n" beg)
21263 (line-end-position)))
21264 (let ((uncommentp
21265 ;; UNCOMMENTP is non-nil when every non blank line between
21266 ;; BEG and END is a comment.
21267 (save-excursion
21268 (goto-char (point-min))
21269 (while (and (not (eobp))
21270 (let ((element (org-element-at-point)))
21271 (and (eq (org-element-type element) 'comment)
21272 (goto-char (min (point-max)
21273 (org-element-property
21274 :end element)))))))
21275 (eobp))))
21276 (if uncommentp
21277 ;; Only blank lines and comments in region: uncomment it.
21278 (save-excursion
21279 (goto-char (point-min))
21280 (while (not (eobp))
21281 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21282 (replace-match "" nil nil nil 1))
21283 (forward-line)))
21284 ;; Comment each line in region.
21285 (let ((min-indent (point-max)))
21286 ;; First find the minimum indentation across all lines.
21287 (save-excursion
21288 (goto-char (point-min))
21289 (while (and (not (eobp)) (not (zerop min-indent)))
21290 (unless (looking-at "[ \t]*$")
21291 (setq min-indent (min min-indent (current-indentation))))
21292 (forward-line)))
21293 ;; Then loop over all lines.
21294 (save-excursion
21295 (goto-char (point-min))
21296 (while (not (eobp))
21297 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21298 (org-move-to-column min-indent t)
21299 (insert comment-start))
21300 (forward-line))))))))
21303 ;;; Other stuff.
21305 (defun org-toggle-fixed-width-section (arg)
21306 "Toggle the fixed-width export.
21307 If there is no active region, the QUOTE keyword at the current headline is
21308 inserted or removed. When present, it causes the text between this headline
21309 and the next to be exported as fixed-width text, and unmodified.
21310 If there is an active region, this command adds or removes a colon as the
21311 first character of this line. If the first character of a line is a colon,
21312 this line is also exported in fixed-width font."
21313 (interactive "P")
21314 (let* ((cc 0)
21315 (regionp (org-region-active-p))
21316 (beg (if regionp (region-beginning) (point)))
21317 (end (if regionp (region-end)))
21318 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21319 (case-fold-search nil)
21320 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21321 off)
21322 (if regionp
21323 (save-excursion
21324 (goto-char beg)
21325 (setq cc (current-column))
21326 (beginning-of-line 1)
21327 (setq off (looking-at re))
21328 (while (> nlines 0)
21329 (setq nlines (1- nlines))
21330 (beginning-of-line 1)
21331 (cond
21332 (arg
21333 (org-move-to-column cc t)
21334 (insert ": \n")
21335 (forward-line -1))
21336 ((and off (looking-at re))
21337 (replace-match "" t t nil 1))
21338 ((not off) (org-move-to-column cc t) (insert ": ")))
21339 (forward-line 1)))
21340 (save-excursion
21341 (org-back-to-heading)
21342 (cond
21343 ((looking-at (format org-heading-keyword-regexp-format
21344 org-quote-string))
21345 (goto-char (match-end 1))
21346 (looking-at (concat " +" org-quote-string))
21347 (replace-match "" t t)
21348 (when (eolp) (insert " ")))
21349 ((looking-at org-outline-regexp)
21350 (goto-char (match-end 0))
21351 (insert org-quote-string " ")))))))
21353 (defun org-reftex-citation ()
21354 "Use reftex-citation to insert a citation into the buffer.
21355 This looks for a line like
21357 #+BIBLIOGRAPHY: foo plain option:-d
21359 and derives from it that foo.bib is the bibliography file relevant
21360 for this document. It then installs the necessary environment for RefTeX
21361 to work in this buffer and calls `reftex-citation' to insert a citation
21362 into the buffer.
21364 Export of such citations to both LaTeX and HTML is handled by the contributed
21365 package org-exp-bibtex by Taru Karttunen."
21366 (interactive)
21367 (let ((reftex-docstruct-symbol 'rds)
21368 (reftex-cite-format "\\cite{%l}")
21369 rds bib)
21370 (save-excursion
21371 (save-restriction
21372 (widen)
21373 (let ((case-fold-search t)
21374 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21375 (if (not (save-excursion
21376 (or (re-search-forward re nil t)
21377 (re-search-backward re nil t))))
21378 (error "No bibliography defined in file")
21379 (setq bib (concat (match-string 1) ".bib")
21380 rds (list (list 'bib bib)))))))
21381 (call-interactively 'reftex-citation)))
21383 ;;;; Functions extending outline functionality
21385 (defun org-beginning-of-line (&optional arg)
21386 "Go to the beginning of the current line. If that is invisible, continue
21387 to a visible line beginning. This makes the function of C-a more intuitive.
21388 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21389 first attempt, and only move to after the tags when the cursor is already
21390 beyond the end of the headline."
21391 (interactive "P")
21392 (let ((pos (point))
21393 (special (if (consp org-special-ctrl-a/e)
21394 (car org-special-ctrl-a/e)
21395 org-special-ctrl-a/e))
21396 refpos)
21397 (if (org-bound-and-true-p visual-line-mode)
21398 (beginning-of-visual-line 1)
21399 (beginning-of-line 1))
21400 (if (and arg (fboundp 'move-beginning-of-line))
21401 (call-interactively 'move-beginning-of-line)
21402 (if (bobp)
21404 (backward-char 1)
21405 (if (org-truely-invisible-p)
21406 (while (and (not (bobp)) (org-truely-invisible-p))
21407 (backward-char 1)
21408 (beginning-of-line 1))
21409 (forward-char 1))))
21410 (when special
21411 (cond
21412 ((and (looking-at org-complex-heading-regexp)
21413 (= (char-after (match-end 1)) ?\ ))
21414 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21415 (point-at-eol)))
21416 (goto-char
21417 (if (eq special t)
21418 (cond ((> pos refpos) refpos)
21419 ((= pos (point)) refpos)
21420 (t (point)))
21421 (cond ((> pos (point)) (point))
21422 ((not (eq last-command this-command)) (point))
21423 (t refpos)))))
21424 ((org-at-item-p)
21425 ;; Being at an item and not looking at an the item means point
21426 ;; was previously moved to beginning of a visual line, which
21427 ;; doesn't contain the item. Therefore, do nothing special,
21428 ;; just stay here.
21429 (when (looking-at org-list-full-item-re)
21430 ;; Set special position at first white space character after
21431 ;; bullet, and check-box, if any.
21432 (let ((after-bullet
21433 (let ((box (match-end 3)))
21434 (if (not box) (match-end 1)
21435 (let ((after (char-after box)))
21436 (if (and after (= after ? )) (1+ box) box))))))
21437 ;; Special case: Move point to special position when
21438 ;; currently after it or at beginning of line.
21439 (if (eq special t)
21440 (when (or (> pos after-bullet) (= (point) pos))
21441 (goto-char after-bullet))
21442 ;; Reversed case: Move point to special position when
21443 ;; point was already at beginning of line and command is
21444 ;; repeated.
21445 (when (and (= (point) pos) (eq last-command this-command))
21446 (goto-char after-bullet))))))))
21447 (org-no-warnings
21448 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21450 (defun org-end-of-line (&optional arg)
21451 "Go to the end of the line.
21452 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21453 tags on the first attempt, and only move to after the tags when
21454 the cursor is already beyond the end of the headline."
21455 (interactive "P")
21456 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21457 org-special-ctrl-a/e))
21458 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21459 'end-of-visual-line)
21460 ((fboundp 'move-end-of-line) 'move-end-of-line)
21461 (t 'end-of-line))))
21462 (if (or (not special) arg) (call-interactively move-fun)
21463 (let* ((element (save-excursion (beginning-of-line)
21464 (org-element-at-point)))
21465 (type (org-element-type element)))
21466 (cond
21467 ((memq type '(headline inlinetask))
21468 (let ((pos (point)))
21469 (beginning-of-line 1)
21470 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21471 (if (eq special t)
21472 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21473 (goto-char (match-beginning 1))
21474 (goto-char (match-end 0)))
21475 (if (or (< pos (match-end 0))
21476 (not (eq this-command last-command)))
21477 (goto-char (match-end 0))
21478 (goto-char (match-beginning 1))))
21479 (call-interactively move-fun))))
21480 ((org-element-property :hiddenp element)
21481 ;; If element is hidden, `move-end-of-line' would put point
21482 ;; after it. Use `end-of-line' to stay on current line.
21483 (call-interactively 'end-of-line))
21484 (t (call-interactively move-fun)))))
21485 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21487 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21488 (define-key org-mode-map "\C-e" 'org-end-of-line)
21490 (defun org-backward-sentence (&optional arg)
21491 "Go to beginning of sentence, or beginning of table field.
21492 This will call `backward-sentence' or `org-table-beginning-of-field',
21493 depending on context."
21494 (interactive "P")
21495 (cond
21496 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21497 (t (call-interactively 'backward-sentence))))
21499 (defun org-forward-sentence (&optional arg)
21500 "Go to end of sentence, or end of table field.
21501 This will call `forward-sentence' or `org-table-end-of-field',
21502 depending on context."
21503 (interactive "P")
21504 (cond
21505 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21506 (t (call-interactively 'forward-sentence))))
21508 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21509 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21511 (defun org-kill-line (&optional arg)
21512 "Kill line, to tags or end of line."
21513 (interactive "P")
21514 (cond
21515 ((or (not org-special-ctrl-k)
21516 (bolp)
21517 (not (org-at-heading-p)))
21518 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21519 org-ctrl-k-protect-subtree)
21520 (if (or (eq org-ctrl-k-protect-subtree 'error)
21521 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21522 (error "C-k aborted - would kill hidden subtree")))
21523 (call-interactively
21524 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21525 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21526 (kill-region (point) (match-beginning 1))
21527 (org-set-tags nil t))
21528 (t (kill-region (point) (point-at-eol)))))
21530 (define-key org-mode-map "\C-k" 'org-kill-line)
21532 (defun org-yank (&optional arg)
21533 "Yank. If the kill is a subtree, treat it specially.
21534 This command will look at the current kill and check if is a single
21535 subtree, or a series of subtrees[1]. If it passes the test, and if the
21536 cursor is at the beginning of a line or after the stars of a currently
21537 empty headline, then the yank is handled specially. How exactly depends
21538 on the value of the following variables, both set by default.
21540 org-yank-folded-subtrees
21541 When set, the subtree(s) will be folded after insertion, but only
21542 if doing so would now swallow text after the yanked text.
21544 org-yank-adjusted-subtrees
21545 When set, the subtree will be promoted or demoted in order to
21546 fit into the local outline tree structure, which means that the level
21547 will be adjusted so that it becomes the smaller one of the two
21548 *visible* surrounding headings.
21550 Any prefix to this command will cause `yank' to be called directly with
21551 no special treatment. In particular, a simple \\[universal-argument] prefix \
21552 will just
21553 plainly yank the text as it is.
21555 \[1] The test checks if the first non-white line is a heading
21556 and if there are no other headings with fewer stars."
21557 (interactive "P")
21558 (org-yank-generic 'yank arg))
21560 (defun org-yank-generic (command arg)
21561 "Perform some yank-like command.
21563 This function implements the behavior described in the `org-yank'
21564 documentation. However, it has been generalized to work for any
21565 interactive command with similar behavior."
21567 ;; pretend to be command COMMAND
21568 (setq this-command command)
21570 (if arg
21571 (call-interactively command)
21573 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21574 (and (org-kill-is-subtree-p)
21575 (or (bolp)
21576 (and (looking-at "[ \t]*$")
21577 (string-match
21578 "\\`\\*+\\'"
21579 (buffer-substring (point-at-bol) (point)))))))
21580 swallowp)
21581 (cond
21582 ((and subtreep org-yank-folded-subtrees)
21583 (let ((beg (point))
21584 end)
21585 (if (and subtreep org-yank-adjusted-subtrees)
21586 (org-paste-subtree nil nil 'for-yank)
21587 (call-interactively command))
21589 (setq end (point))
21590 (goto-char beg)
21591 (when (and (bolp) subtreep
21592 (not (setq swallowp
21593 (org-yank-folding-would-swallow-text beg end))))
21594 (org-with-limited-levels
21595 (or (looking-at org-outline-regexp)
21596 (re-search-forward org-outline-regexp-bol end t))
21597 (while (and (< (point) end) (looking-at org-outline-regexp))
21598 (hide-subtree)
21599 (org-cycle-show-empty-lines 'folded)
21600 (condition-case nil
21601 (outline-forward-same-level 1)
21602 (error (goto-char end))))))
21603 (when swallowp
21604 (message
21605 "Inserted text not folded because that would swallow text"))
21607 (goto-char end)
21608 (skip-chars-forward " \t\n\r")
21609 (beginning-of-line 1)
21610 (push-mark beg 'nomsg)))
21611 ((and subtreep org-yank-adjusted-subtrees)
21612 (let ((beg (point-at-bol)))
21613 (org-paste-subtree nil nil 'for-yank)
21614 (push-mark beg 'nomsg)))
21616 (call-interactively command))))))
21618 (defun org-yank-folding-would-swallow-text (beg end)
21619 "Would hide-subtree at BEG swallow any text after END?"
21620 (let (level)
21621 (org-with-limited-levels
21622 (save-excursion
21623 (goto-char beg)
21624 (when (or (looking-at org-outline-regexp)
21625 (re-search-forward org-outline-regexp-bol end t))
21626 (setq level (org-outline-level)))
21627 (goto-char end)
21628 (skip-chars-forward " \t\r\n\v\f")
21629 (if (or (eobp)
21630 (and (bolp) (looking-at org-outline-regexp)
21631 (<= (org-outline-level) level)))
21632 nil ; Nothing would be swallowed
21633 t))))) ; something would swallow
21635 (define-key org-mode-map "\C-y" 'org-yank)
21637 (defun org-truely-invisible-p ()
21638 "Check if point is at a character currently not visible.
21639 This version does not only check the character property, but also
21640 `visible-mode'."
21641 ;; Early versions of noutline don't have `outline-invisible-p'.
21642 (if (org-bound-and-true-p visible-mode)
21644 (outline-invisible-p)))
21646 (defun org-invisible-p2 ()
21647 "Check if point is at a character currently not visible."
21648 (save-excursion
21649 (if (and (eolp) (not (bobp))) (backward-char 1))
21650 ;; Early versions of noutline don't have `outline-invisible-p'.
21651 (outline-invisible-p)))
21653 (defun org-back-to-heading (&optional invisible-ok)
21654 "Call `outline-back-to-heading', but provide a better error message."
21655 (condition-case nil
21656 (outline-back-to-heading invisible-ok)
21657 (error (error "Before first headline at position %d in buffer %s"
21658 (point) (current-buffer)))))
21660 (defun org-before-first-heading-p ()
21661 "Before first heading?"
21662 (save-excursion
21663 (end-of-line)
21664 (null (re-search-backward org-outline-regexp-bol nil t))))
21666 (defun org-at-heading-p (&optional ignored)
21667 (outline-on-heading-p t))
21668 ;; Compatibility alias with Org versions < 7.8.03
21669 (defalias 'org-on-heading-p 'org-at-heading-p)
21671 (defun org-at-comment-p nil
21672 "Is cursor in a line starting with a # character?"
21673 (save-excursion
21674 (beginning-of-line)
21675 (looking-at "^#")))
21677 (defun org-at-drawer-p nil
21678 "Is cursor at a drawer keyword?"
21679 (save-excursion
21680 (move-beginning-of-line 1)
21681 (looking-at org-drawer-regexp)))
21683 (defun org-at-block-p nil
21684 "Is cursor at a block keyword?"
21685 (save-excursion
21686 (move-beginning-of-line 1)
21687 (looking-at org-block-regexp)))
21689 (defun org-point-at-end-of-empty-headline ()
21690 "If point is at the end of an empty headline, return t, else nil.
21691 If the heading only contains a TODO keyword, it is still still considered
21692 empty."
21693 (and (looking-at "[ \t]*$")
21694 (when org-todo-line-regexp
21695 (save-excursion
21696 (beginning-of-line 1)
21697 (let ((case-fold-search nil))
21698 (looking-at org-todo-line-regexp)
21699 (string= (match-string 3) ""))))))
21701 (defun org-at-heading-or-item-p ()
21702 (or (org-at-heading-p) (org-at-item-p)))
21704 (defun org-at-target-p ()
21705 (or (org-in-regexp org-radio-target-regexp)
21706 (org-in-regexp org-target-regexp)))
21707 ;; Compatibility alias with Org versions < 7.8.03
21708 (defalias 'org-on-target-p 'org-at-target-p)
21710 (defun org-up-heading-all (arg)
21711 "Move to the heading line of which the present line is a subheading.
21712 This function considers both visible and invisible heading lines.
21713 With argument, move up ARG levels."
21714 (if (fboundp 'outline-up-heading-all)
21715 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21716 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21718 (defun org-up-heading-safe ()
21719 "Move to the heading line of which the present line is a subheading.
21720 This version will not throw an error. It will return the level of the
21721 headline found, or nil if no higher level is found.
21723 Also, this function will be a lot faster than `outline-up-heading',
21724 because it relies on stars being the outline starters. This can really
21725 make a significant difference in outlines with very many siblings."
21726 (let (start-level re)
21727 (org-back-to-heading t)
21728 (setq start-level (funcall outline-level))
21729 (if (equal start-level 1)
21731 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21732 (if (re-search-backward re nil t)
21733 (funcall outline-level)))))
21735 (defun org-first-sibling-p ()
21736 "Is this heading the first child of its parents?"
21737 (interactive)
21738 (let ((re org-outline-regexp-bol)
21739 level l)
21740 (unless (org-at-heading-p t)
21741 (error "Not at a heading"))
21742 (setq level (funcall outline-level))
21743 (save-excursion
21744 (if (not (re-search-backward re nil t))
21746 (setq l (funcall outline-level))
21747 (< l level)))))
21749 (defun org-goto-sibling (&optional previous)
21750 "Goto the next sibling, even if it is invisible.
21751 When PREVIOUS is set, go to the previous sibling instead. Returns t
21752 when a sibling was found. When none is found, return nil and don't
21753 move point."
21754 (let ((fun (if previous 're-search-backward 're-search-forward))
21755 (pos (point))
21756 (re org-outline-regexp-bol)
21757 level l)
21758 (when (condition-case nil (org-back-to-heading t) (error nil))
21759 (setq level (funcall outline-level))
21760 (catch 'exit
21761 (or previous (forward-char 1))
21762 (while (funcall fun re nil t)
21763 (setq l (funcall outline-level))
21764 (when (< l level) (goto-char pos) (throw 'exit nil))
21765 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21766 (goto-char pos)
21767 nil))))
21769 (defun org-show-siblings ()
21770 "Show all siblings of the current headline."
21771 (save-excursion
21772 (while (org-goto-sibling) (org-flag-heading nil)))
21773 (save-excursion
21774 (while (org-goto-sibling 'previous)
21775 (org-flag-heading nil))))
21777 (defun org-goto-first-child ()
21778 "Goto the first child, even if it is invisible.
21779 Return t when a child was found. Otherwise don't move point and
21780 return nil."
21781 (let (level (pos (point)) (re org-outline-regexp-bol))
21782 (when (condition-case nil (org-back-to-heading t) (error nil))
21783 (setq level (outline-level))
21784 (forward-char 1)
21785 (if (and (re-search-forward re nil t) (> (outline-level) level))
21786 (progn (goto-char (match-beginning 0)) t)
21787 (goto-char pos) nil))))
21789 (defun org-show-hidden-entry ()
21790 "Show an entry where even the heading is hidden."
21791 (save-excursion
21792 (org-show-entry)))
21794 (defun org-flag-heading (flag &optional entry)
21795 "Flag the current heading. FLAG non-nil means make invisible.
21796 When ENTRY is non-nil, show the entire entry."
21797 (save-excursion
21798 (org-back-to-heading t)
21799 ;; Check if we should show the entire entry
21800 (if entry
21801 (progn
21802 (org-show-entry)
21803 (save-excursion
21804 (and (outline-next-heading)
21805 (org-flag-heading nil))))
21806 (outline-flag-region (max (point-min) (1- (point)))
21807 (save-excursion (outline-end-of-heading) (point))
21808 flag))))
21810 (defun org-get-next-sibling ()
21811 "Move to next heading of the same level, and return point.
21812 If there is no such heading, return nil.
21813 This is like outline-next-sibling, but invisible headings are ok."
21814 (let ((level (funcall outline-level)))
21815 (outline-next-heading)
21816 (while (and (not (eobp)) (> (funcall outline-level) level))
21817 (outline-next-heading))
21818 (if (or (eobp) (< (funcall outline-level) level))
21820 (point))))
21822 (defun org-get-last-sibling ()
21823 "Move to previous heading of the same level, and return point.
21824 If there is no such heading, return nil."
21825 (let ((opoint (point))
21826 (level (funcall outline-level)))
21827 (outline-previous-heading)
21828 (when (and (/= (point) opoint) (outline-on-heading-p t))
21829 (while (and (> (funcall outline-level) level)
21830 (not (bobp)))
21831 (outline-previous-heading))
21832 (if (< (funcall outline-level) level)
21834 (point)))))
21836 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21837 "Goto to the end of a subtree."
21838 ;; This contains an exact copy of the original function, but it uses
21839 ;; `org-back-to-heading', to make it work also in invisible
21840 ;; trees. And is uses an invisible-ok argument.
21841 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21842 ;; Furthermore, when used inside Org, finding the end of a large subtree
21843 ;; with many children and grandchildren etc, this can be much faster
21844 ;; than the outline version.
21845 (org-back-to-heading invisible-ok)
21846 (let ((first t)
21847 (level (funcall outline-level)))
21848 (if (and (derived-mode-p 'org-mode) (< level 1000))
21849 ;; A true heading (not a plain list item), in Org-mode
21850 ;; This means we can easily find the end by looking
21851 ;; only for the right number of stars. Using a regexp to do
21852 ;; this is so much faster than using a Lisp loop.
21853 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21854 (forward-char 1)
21855 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21856 ;; something else, do it the slow way
21857 (while (and (not (eobp))
21858 (or first (> (funcall outline-level) level)))
21859 (setq first nil)
21860 (outline-next-heading)))
21861 (unless to-heading
21862 (if (memq (preceding-char) '(?\n ?\^M))
21863 (progn
21864 ;; Go to end of line before heading
21865 (forward-char -1)
21866 (if (memq (preceding-char) '(?\n ?\^M))
21867 ;; leave blank line before heading
21868 (forward-char -1))))))
21869 (point))
21871 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21872 "Use Org version in org-mode, for dramatic speed-up."
21873 (if (derived-mode-p 'org-mode)
21874 (progn
21875 (org-end-of-subtree nil t)
21876 (unless (eobp) (backward-char 1)))
21877 ad-do-it))
21879 (defun org-end-of-meta-data-and-drawers ()
21880 "Jump to the first text after meta data and drawers in the current entry.
21881 This will move over empty lines, lines with planning time stamps,
21882 clocking lines, and drawers."
21883 (org-back-to-heading t)
21884 (let ((end (save-excursion (outline-next-heading) (point)))
21885 (re (concat "\\(" org-drawer-regexp "\\)"
21886 "\\|" "[ \t]*" org-keyword-time-regexp)))
21887 (forward-line 1)
21888 (while (re-search-forward re end t)
21889 (if (not (match-end 1))
21890 ;; empty or planning line
21891 (forward-line 1)
21892 ;; a drawer, find the end
21893 (re-search-forward "^[ \t]*:END:" end 'move)
21894 (forward-line 1)))
21895 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21896 (point)))
21898 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21899 "Move forward to the arg'th subheading at same level as this one.
21900 Stop at the first and last subheadings of a superior heading.
21901 Normally this only looks at visible headings, but when INVISIBLE-OK is
21902 non-nil it will also look at invisible ones."
21903 (interactive "p")
21904 (org-back-to-heading invisible-ok)
21905 (org-at-heading-p)
21906 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21907 (re (format "^\\*\\{1,%d\\} " level))
21909 (forward-char 1)
21910 (while (> arg 0)
21911 (while (and (re-search-forward re nil 'move)
21912 (setq l (- (match-end 0) (match-beginning 0) 1))
21913 (= l level)
21914 (not invisible-ok)
21915 (progn (backward-char 1) (outline-invisible-p)))
21916 (if (< l level) (setq arg 1)))
21917 (setq arg (1- arg)))
21918 (beginning-of-line 1)))
21920 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21921 "Move backward to the arg'th subheading at same level as this one.
21922 Stop at the first and last subheadings of a superior heading."
21923 (interactive "p")
21924 (org-back-to-heading)
21925 (org-at-heading-p)
21926 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21927 (re (format "^\\*\\{1,%d\\} " level))
21929 (while (> arg 0)
21930 (while (and (re-search-backward re nil 'move)
21931 (setq l (- (match-end 0) (match-beginning 0) 1))
21932 (= l level)
21933 (not invisible-ok)
21934 (outline-invisible-p))
21935 (if (< l level) (setq arg 1)))
21936 (setq arg (1- arg)))))
21938 (defun org-forward-element ()
21939 "Move forward by one element.
21940 Move to the next element at the same level, when possible."
21941 (interactive)
21942 (cond ((eobp) (error "Cannot move further down"))
21943 ((org-with-limited-levels (org-at-heading-p))
21944 (let ((origin (point)))
21945 (org-forward-heading-same-level 1)
21946 (unless (org-with-limited-levels (org-at-heading-p))
21947 (goto-char origin)
21948 (error "Cannot move further down"))))
21950 (let* ((elem (org-element-at-point))
21951 (end (org-element-property :end elem))
21952 (parent (org-element-property :parent elem)))
21953 (if (and parent (= (org-element-property :contents-end parent) end))
21954 (goto-char (org-element-property :end parent))
21955 (goto-char end))))))
21957 (defun org-backward-element ()
21958 "Move backward by one element.
21959 Move to the previous element at the same level, when possible."
21960 (interactive)
21961 (cond ((bobp) (error "Cannot move further up"))
21962 ((org-with-limited-levels (org-at-heading-p))
21963 ;; At an headline, move to the previous one, if any, or stay
21964 ;; here.
21965 (let ((origin (point)))
21966 (org-backward-heading-same-level 1)
21967 (unless (org-with-limited-levels (org-at-heading-p))
21968 (goto-char origin)
21969 (error "Cannot move further up"))))
21971 (let* ((trail (org-element-at-point 'keep-trail))
21972 (elem (car trail))
21973 (prev-elem (nth 1 trail))
21974 (beg (org-element-property :begin elem)))
21975 (cond
21976 ;; Move to beginning of current element if point isn't
21977 ;; there already.
21978 ((/= (point) beg) (goto-char beg))
21979 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21980 ((org-before-first-heading-p) (goto-char (point-min)))
21981 (t (org-back-to-heading)))))))
21983 (defun org-up-element ()
21984 "Move to upper element."
21985 (interactive)
21986 (if (org-with-limited-levels (org-at-heading-p))
21987 (unless (org-up-heading-safe) (error "No surrounding element"))
21988 (let* ((elem (org-element-at-point))
21989 (parent (org-element-property :parent elem)))
21990 (if parent (goto-char (org-element-property :begin parent))
21991 (if (org-with-limited-levels (org-before-first-heading-p))
21992 (error "No surrounding element")
21993 (org-with-limited-levels (org-back-to-heading)))))))
21995 (defvar org-element-greater-elements)
21996 (defun org-down-element ()
21997 "Move to inner element."
21998 (interactive)
21999 (let ((element (org-element-at-point)))
22000 (cond
22001 ((memq (org-element-type element) '(plain-list table))
22002 (goto-char (org-element-property :contents-begin element))
22003 (forward-char))
22004 ((memq (org-element-type element) org-element-greater-elements)
22005 ;; If contents are hidden, first disclose them.
22006 (when (org-element-property :hiddenp element) (org-cycle))
22007 (goto-char (or (org-element-property :contents-begin element)
22008 (error "No content for this element"))))
22009 (t (error "No inner element")))))
22011 (defun org-drag-element-backward ()
22012 "Move backward element at point."
22013 (interactive)
22014 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22015 (let* ((trail (org-element-at-point 'keep-trail))
22016 (elem (car trail))
22017 (prev-elem (nth 1 trail)))
22018 ;; Error out if no previous element or previous element is
22019 ;; a parent of the current one.
22020 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22021 (error "Cannot drag element backward")
22022 (let ((pos (point)))
22023 (org-element-swap-A-B prev-elem elem)
22024 (goto-char (+ (org-element-property :begin prev-elem)
22025 (- pos (org-element-property :begin elem)))))))))
22027 (defun org-drag-element-forward ()
22028 "Move forward element at point."
22029 (interactive)
22030 (let* ((pos (point))
22031 (elem (org-element-at-point)))
22032 (when (= (point-max) (org-element-property :end elem))
22033 (error "Cannot drag element forward"))
22034 (goto-char (org-element-property :end elem))
22035 (let ((next-elem (org-element-at-point)))
22036 (when (or (org-element-nested-p elem next-elem)
22037 (and (eq (org-element-type next-elem) 'headline)
22038 (not (eq (org-element-type elem) 'headline))))
22039 (goto-char pos)
22040 (error "Cannot drag element forward"))
22041 ;; Compute new position of point: it's shifted by NEXT-ELEM
22042 ;; body's length (without final blanks) and by the length of
22043 ;; blanks between ELEM and NEXT-ELEM.
22044 (let ((size-next (- (save-excursion
22045 (goto-char (org-element-property :end next-elem))
22046 (skip-chars-backward " \r\t\n")
22047 (forward-line)
22048 ;; Small correction if buffer doesn't end
22049 ;; with a newline character.
22050 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22051 (org-element-property :begin next-elem)))
22052 (size-blank (- (org-element-property :end elem)
22053 (save-excursion
22054 (goto-char (org-element-property :end elem))
22055 (skip-chars-backward " \r\t\n")
22056 (forward-line)
22057 (point)))))
22058 (org-element-swap-A-B elem next-elem)
22059 (goto-char (+ pos size-next size-blank))))))
22061 (defun org-mark-element ()
22062 "Put point at beginning of this element, mark at end.
22064 Interactively, if this command is repeated or (in Transient Mark
22065 mode) if the mark is active, it marks the next element after the
22066 ones already marked."
22067 (interactive)
22068 (let (deactivate-mark)
22069 (if (and (org-called-interactively-p 'any)
22070 (or (and (eq last-command this-command) (mark t))
22071 (and transient-mark-mode mark-active)))
22072 (set-mark
22073 (save-excursion
22074 (goto-char (mark))
22075 (goto-char (org-element-property :end (org-element-at-point)))))
22076 (let ((element (org-element-at-point)))
22077 (end-of-line)
22078 (push-mark (org-element-property :end element) t t)
22079 (goto-char (org-element-property :begin element))))))
22081 (defun org-narrow-to-element ()
22082 "Narrow buffer to current element."
22083 (interactive)
22084 (let ((elem (org-element-at-point)))
22085 (cond
22086 ((eq (car elem) 'headline)
22087 (narrow-to-region
22088 (org-element-property :begin elem)
22089 (org-element-property :end elem)))
22090 ((memq (car elem) org-element-greater-elements)
22091 (narrow-to-region
22092 (org-element-property :contents-begin elem)
22093 (org-element-property :contents-end elem)))
22095 (narrow-to-region
22096 (org-element-property :begin elem)
22097 (org-element-property :end elem))))))
22099 (defun org-transpose-element ()
22100 "Transpose current and previous elements, keeping blank lines between.
22101 Point is moved after both elements."
22102 (interactive)
22103 (org-skip-whitespace)
22104 (let ((end (org-element-property :end (org-element-at-point))))
22105 (org-drag-element-backward)
22106 (goto-char end)))
22108 (defun org-unindent-buffer ()
22109 "Un-indent the visible part of the buffer.
22110 Relative indentation (between items, inside blocks, etc.) isn't
22111 modified."
22112 (interactive)
22113 (unless (eq major-mode 'org-mode)
22114 (error "Cannot un-indent a buffer not in Org mode"))
22115 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22116 unindent-tree ; For byte-compiler.
22117 (unindent-tree
22118 (function
22119 (lambda (contents)
22120 (mapc
22121 (lambda (element)
22122 (if (memq (org-element-type element) '(headline section))
22123 (funcall unindent-tree (org-element-contents element))
22124 (save-excursion
22125 (save-restriction
22126 (narrow-to-region
22127 (org-element-property :begin element)
22128 (org-element-property :end element))
22129 (org-do-remove-indentation)))))
22130 (reverse contents))))))
22131 (funcall unindent-tree (org-element-contents parse-tree))))
22133 (defun org-show-subtree ()
22134 "Show everything after this heading at deeper levels."
22135 (interactive)
22136 (outline-flag-region
22137 (point)
22138 (save-excursion
22139 (org-end-of-subtree t t))
22140 nil))
22142 (defun org-show-entry ()
22143 "Show the body directly following this heading.
22144 Show the heading too, if it is currently invisible."
22145 (interactive)
22146 (save-excursion
22147 (condition-case nil
22148 (progn
22149 (org-back-to-heading t)
22150 (outline-flag-region
22151 (max (point-min) (1- (point)))
22152 (save-excursion
22153 (if (re-search-forward
22154 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22155 (match-beginning 1)
22156 (point-max)))
22157 nil)
22158 (org-cycle-hide-drawers 'children))
22159 (error nil))))
22161 (defun org-make-options-regexp (kwds &optional extra)
22162 "Make a regular expression for keyword lines."
22163 (concat
22164 "^#\\+\\("
22165 (mapconcat 'regexp-quote kwds "\\|")
22166 (if extra (concat "\\|" extra))
22167 "\\):[ \t]*\\(.*\\)"))
22169 ;; Make isearch reveal the necessary context
22170 (defun org-isearch-end ()
22171 "Reveal context after isearch exits."
22172 (when isearch-success ; only if search was successful
22173 (if (featurep 'xemacs)
22174 ;; Under XEmacs, the hook is run in the correct place,
22175 ;; we directly show the context.
22176 (org-show-context 'isearch)
22177 ;; In Emacs the hook runs *before* restoring the overlays.
22178 ;; So we have to use a one-time post-command-hook to do this.
22179 ;; (Emacs 22 has a special variable, see function `org-mode')
22180 (unless (and (boundp 'isearch-mode-end-hook-quit)
22181 isearch-mode-end-hook-quit)
22182 ;; Only when the isearch was not quitted.
22183 (org-add-hook 'post-command-hook 'org-isearch-post-command
22184 'append 'local)))))
22186 (defun org-isearch-post-command ()
22187 "Remove self from hook, and show context."
22188 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22189 (org-show-context 'isearch))
22192 ;;;; Integration with and fixes for other packages
22194 ;;; Imenu support
22196 (defvar org-imenu-markers nil
22197 "All markers currently used by Imenu.")
22198 (make-variable-buffer-local 'org-imenu-markers)
22200 (defun org-imenu-new-marker (&optional pos)
22201 "Return a new marker for use by Imenu, and remember the marker."
22202 (let ((m (make-marker)))
22203 (move-marker m (or pos (point)))
22204 (push m org-imenu-markers)
22207 (defun org-imenu-get-tree ()
22208 "Produce the index for Imenu."
22209 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22210 (setq org-imenu-markers nil)
22211 (let* ((n org-imenu-depth)
22212 (re (concat "^" (org-get-limited-outline-regexp)))
22213 (subs (make-vector (1+ n) nil))
22214 (last-level 0)
22215 m level head0 head)
22216 (save-excursion
22217 (save-restriction
22218 (widen)
22219 (goto-char (point-max))
22220 (while (re-search-backward re nil t)
22221 (setq level (org-reduced-level (funcall outline-level)))
22222 (when (and (<= level n)
22223 (looking-at org-complex-heading-regexp)
22224 (setq head0 (org-match-string-no-properties 4)))
22225 (setq head (org-link-display-format head0)
22226 m (org-imenu-new-marker))
22227 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22228 (if (>= level last-level)
22229 (push (cons head m) (aref subs level))
22230 (push (cons head (aref subs (1+ level))) (aref subs level))
22231 (loop for i from (1+ level) to n do (aset subs i nil)))
22232 (setq last-level level)))))
22233 (aref subs 1)))
22235 (eval-after-load "imenu"
22236 '(progn
22237 (add-hook 'imenu-after-jump-hook
22238 (lambda ()
22239 (if (derived-mode-p 'org-mode)
22240 (org-show-context 'org-goto))))))
22242 (defun org-link-display-format (link)
22243 "Replace a link with either the description, or the link target
22244 if no description is present"
22245 (save-match-data
22246 (if (string-match org-bracket-link-analytic-regexp link)
22247 (replace-match (if (match-end 5)
22248 (match-string 5 link)
22249 (concat (match-string 1 link)
22250 (match-string 3 link)))
22251 nil t link)
22252 link)))
22254 (defun org-toggle-link-display ()
22255 "Toggle the literal or descriptive display of links."
22256 (interactive)
22257 (if org-descriptive-links
22258 (progn (org-remove-from-invisibility-spec '(org-link))
22259 (org-restart-font-lock)
22260 (setq org-descriptive-links nil))
22261 (progn (add-to-invisibility-spec '(org-link))
22262 (org-restart-font-lock)
22263 (setq org-descriptive-links t))))
22265 ;; Speedbar support
22267 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22268 "Overlay marking the agenda restriction line in speedbar.")
22269 (overlay-put org-speedbar-restriction-lock-overlay
22270 'face 'org-agenda-restriction-lock)
22271 (overlay-put org-speedbar-restriction-lock-overlay
22272 'help-echo "Agendas are currently limited to this item.")
22273 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22275 (defun org-speedbar-set-agenda-restriction ()
22276 "Restrict future agenda commands to the location at point in speedbar.
22277 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22278 (interactive)
22279 (require 'org-agenda)
22280 (let (p m tp np dir txt)
22281 (cond
22282 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22283 'org-imenu t))
22284 (setq m (get-text-property p 'org-imenu-marker))
22285 (with-current-buffer (marker-buffer m)
22286 (goto-char m)
22287 (org-agenda-set-restriction-lock 'subtree)))
22288 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22289 'speedbar-function 'speedbar-find-file))
22290 (setq tp (previous-single-property-change
22291 (1+ p) 'speedbar-function)
22292 np (next-single-property-change
22293 tp 'speedbar-function)
22294 dir (speedbar-line-directory)
22295 txt (buffer-substring-no-properties (or tp (point-min))
22296 (or np (point-max))))
22297 (with-current-buffer (find-file-noselect
22298 (let ((default-directory dir))
22299 (expand-file-name txt)))
22300 (unless (derived-mode-p 'org-mode)
22301 (error "Cannot restrict to non-Org-mode file"))
22302 (org-agenda-set-restriction-lock 'file)))
22303 (t (error "Don't know how to restrict Org-mode's agenda")))
22304 (move-overlay org-speedbar-restriction-lock-overlay
22305 (point-at-bol) (point-at-eol))
22306 (setq current-prefix-arg nil)
22307 (org-agenda-maybe-redo)))
22309 (eval-after-load "speedbar"
22310 '(progn
22311 (speedbar-add-supported-extension ".org")
22312 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22313 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22314 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22315 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22316 (add-hook 'speedbar-visiting-tag-hook
22317 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22319 ;;; Fixes and Hacks for problems with other packages
22321 ;; Make flyspell not check words in links, to not mess up our keymap
22322 (defun org-mode-flyspell-verify ()
22323 "Don't let flyspell put overlays at active buttons, or on
22324 {todo,all-time,additional-option-like}-keywords."
22325 (let ((pos (max (1- (point)) (point-min)))
22326 (word (thing-at-point 'word)))
22327 (and (not (get-text-property pos 'keymap))
22328 (not (get-text-property pos 'org-no-flyspell))
22329 (not (member word org-todo-keywords-1))
22330 (not (member word org-all-time-keywords))
22331 (not (member word org-options-keywords))
22332 (not (member word (mapcar 'car org-startup-options)))
22333 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22335 (defun org-remove-flyspell-overlays-in (beg end)
22336 "Remove flyspell overlays in region."
22337 (and (org-bound-and-true-p flyspell-mode)
22338 (fboundp 'flyspell-delete-region-overlays)
22339 (flyspell-delete-region-overlays beg end))
22340 (add-text-properties beg end '(org-no-flyspell t)))
22342 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22343 (eval-after-load "bookmark"
22344 '(if (boundp 'bookmark-after-jump-hook)
22345 ;; We can use the hook
22346 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22347 ;; Hook not available, use advice
22348 (defadvice bookmark-jump (after org-make-visible activate)
22349 "Make the position visible."
22350 (org-bookmark-jump-unhide))))
22352 ;; Make sure saveplace shows the location if it was hidden
22353 (eval-after-load "saveplace"
22354 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22355 "Make the position visible."
22356 (org-bookmark-jump-unhide)))
22358 ;; Make sure ecb shows the location if it was hidden
22359 (eval-after-load "ecb"
22360 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22361 "Make hierarchy visible when jumping into location from ECB tree buffer."
22362 (if (derived-mode-p 'org-mode)
22363 (org-show-context))))
22365 (defun org-bookmark-jump-unhide ()
22366 "Unhide the current position, to show the bookmark location."
22367 (and (derived-mode-p 'org-mode)
22368 (or (outline-invisible-p)
22369 (save-excursion (goto-char (max (point-min) (1- (point))))
22370 (outline-invisible-p)))
22371 (org-show-context 'bookmark-jump)))
22373 ;; Make session.el ignore our circular variable
22374 (eval-after-load "session"
22375 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22377 ;;;; Experimental code
22379 (defun org-closed-in-range ()
22380 "Sparse tree of items closed in a certain time range.
22381 Still experimental, may disappear in the future."
22382 (interactive)
22383 ;; Get the time interval from the user.
22384 (let* ((time1 (org-float-time
22385 (org-read-date nil 'to-time nil "Starting date: ")))
22386 (time2 (org-float-time
22387 (org-read-date nil 'to-time nil "End date:")))
22388 ;; callback function
22389 (callback (lambda ()
22390 (let ((time
22391 (org-float-time
22392 (apply 'encode-time
22393 (org-parse-time-string
22394 (match-string 1))))))
22395 ;; check if time in interval
22396 (and (>= time time1) (<= time time2))))))
22397 ;; make tree, check each match with the callback
22398 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22400 ;;;; Finish up
22402 (provide 'org)
22404 (run-hooks 'org-load-hook)
22406 ;;; org.el ends here