Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob3984fc3026359b8381ebf2baffce7c228d5ae49a
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" ())
121 (declare-function org-clock-timestamps-down "org-clock" ())
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
140 (declare-function org-element-at-point "org-element" (&optional keep-trail))
141 (declare-function org-element-type "org-element" (element))
142 (declare-function org-element-context "org-element" ())
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-property "org-element" (property element))
145 (declare-function org-element-paragraph-parser "org-element" (limit))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Makefile" makefile)
209 (const :tag "Maxima" maxima)
210 (const :tag "Matlab" matlab)
211 (const :tag "Mscgen" mscgen)
212 (const :tag "Ocaml" ocaml)
213 (const :tag "Octave" octave)
214 (const :tag "Org" org)
215 (const :tag "Perl" perl)
216 (const :tag "Pico Lisp" picolisp)
217 (const :tag "PlantUML" plantuml)
218 (const :tag "Python" python)
219 (const :tag "Ruby" ruby)
220 (const :tag "Sass" sass)
221 (const :tag "Scala" scala)
222 (const :tag "Scheme" scheme)
223 (const :tag "Screen" screen)
224 (const :tag "Shell Script" sh)
225 (const :tag "Shen" shen)
226 (const :tag "Sql" sql)
227 (const :tag "Sqlite" sqlite))
228 :value-type (boolean :tag "Activate" :value t)))
230 ;;;; Customization variables
231 (defcustom org-clone-delete-id nil
232 "Remove ID property of clones of a subtree.
233 When non-nil, clones of a subtree don't inherit the ID property.
234 Otherwise they inherit the ID property with a new unique
235 identifier."
236 :type 'boolean
237 :version "24.1"
238 :group 'org-id)
240 ;;; Version
241 (require 'org-compat)
242 (org-check-version)
244 ;;;###autoload
245 (defun org-version (&optional here full message)
246 "Show the org-mode version in the echo area.
247 With prefix argument HERE, insert it at point.
248 When FULL is non-nil, use a verbose version string.
249 When MESSAGE is non-nil, display a message with the version."
250 (interactive "P")
251 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
252 (save-load-suffixes load-suffixes)
253 (load-suffixes (list ".el"))
254 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (org-trash (or
256 (and (fboundp 'org-release) (fboundp 'org-git-version))
257 (load (concat org-dir "org-version")
258 'noerror 'nomessage nil 'mustsuffix)))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (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)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search."
1244 :group 'org-edit-structure
1245 :type 'boolean)
1247 (defgroup org-sparse-trees nil
1248 "Options concerning sparse trees in Org-mode."
1249 :tag "Org Sparse Trees"
1250 :group 'org-structure)
1252 (defcustom org-highlight-sparse-tree-matches t
1253 "Non-nil means highlight all matches that define a sparse tree.
1254 The highlights will automatically disappear the next time the buffer is
1255 changed by an edit command."
1256 :group 'org-sparse-trees
1257 :type 'boolean)
1259 (defcustom org-remove-highlights-with-change t
1260 "Non-nil means any change to the buffer will remove temporary highlights.
1261 Such highlights are created by `org-occur' and `org-clock-display'.
1262 When nil, `C-c C-c needs to be used to get rid of the highlights.
1263 The highlights created by `org-preview-latex-fragment' always need
1264 `C-c C-c' to be removed."
1265 :group 'org-sparse-trees
1266 :group 'org-time
1267 :type 'boolean)
1270 (defcustom org-occur-hook '(org-first-headline-recenter)
1271 "Hook that is run after `org-occur' has constructed a sparse tree.
1272 This can be used to recenter the window to show as much of the structure
1273 as possible."
1274 :group 'org-sparse-trees
1275 :type 'hook)
1277 (defgroup org-imenu-and-speedbar nil
1278 "Options concerning imenu and speedbar in Org-mode."
1279 :tag "Org Imenu and Speedbar"
1280 :group 'org-structure)
1282 (defcustom org-imenu-depth 2
1283 "The maximum level for Imenu access to Org-mode headlines.
1284 This also applied for speedbar access."
1285 :group 'org-imenu-and-speedbar
1286 :type 'integer)
1288 (defgroup org-table nil
1289 "Options concerning tables in Org-mode."
1290 :tag "Org Table"
1291 :group 'org)
1293 (defcustom org-enable-table-editor 'optimized
1294 "Non-nil means lines starting with \"|\" are handled by the table editor.
1295 When nil, such lines will be treated like ordinary lines.
1297 When equal to the symbol `optimized', the table editor will be optimized to
1298 do the following:
1299 - Automatic overwrite mode in front of whitespace in table fields.
1300 This makes the structure of the table stay in tact as long as the edited
1301 field does not exceed the column width.
1302 - Minimize the number of realigns. Normally, the table is aligned each time
1303 TAB or RET are pressed to move to another field. With optimization this
1304 happens only if changes to a field might have changed the column width.
1305 Optimization requires replacing the functions `self-insert-command',
1306 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1307 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1308 very good at guessing when a re-align will be necessary, but you can always
1309 force one with \\[org-ctrl-c-ctrl-c].
1311 If you would like to use the optimized version in Org-mode, but the
1312 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1314 This variable can be used to turn on and off the table editor during a session,
1315 but in order to toggle optimization, a restart is required.
1317 See also the variable `org-table-auto-blank-field'."
1318 :group 'org-table
1319 :type '(choice
1320 (const :tag "off" nil)
1321 (const :tag "on" t)
1322 (const :tag "on, optimized" optimized)))
1324 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1325 (version<= emacs-version "24.1"))
1326 "Non-nil means cluster self-insert commands for undo when possible.
1327 If this is set, then, like in the Emacs command loop, 20 consecutive
1328 characters will be undone together.
1329 This is configurable, because there is some impact on typing performance."
1330 :group 'org-table
1331 :type 'boolean)
1333 (defcustom org-table-tab-recognizes-table.el t
1334 "Non-nil means TAB will automatically notice a table.el table.
1335 When it sees such a table, it moves point into it and - if necessary -
1336 calls `table-recognize-table'."
1337 :group 'org-table-editing
1338 :type 'boolean)
1340 (defgroup org-link nil
1341 "Options concerning links in Org-mode."
1342 :tag "Org Link"
1343 :group 'org)
1345 (defvar org-link-abbrev-alist-local nil
1346 "Buffer-local version of `org-link-abbrev-alist', which see.
1347 The value of this is taken from the #+LINK lines.")
1348 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1350 (defcustom org-link-abbrev-alist nil
1351 "Alist of link abbreviations.
1352 The car of each element is a string, to be replaced at the start of a link.
1353 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1354 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1356 [[linkkey:tag][description]]
1358 The 'linkkey' must be a word word, starting with a letter, followed
1359 by letters, numbers, '-' or '_'.
1361 If REPLACE is a string, the tag will simply be appended to create the link.
1362 If the string contains \"%s\", the tag will be inserted there. If the string
1363 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1364 at that point (see the function `url-hexify-string'). If the string contains
1365 the specifier \"%(my-function)\", then the custom function `my-function' will
1366 be invoked: this function takes the tag as its only argument and must return
1367 a string.
1369 REPLACE may also be a function that will be called with the tag as the
1370 only argument to create the link, which should be returned as a string.
1372 See the manual for examples."
1373 :group 'org-link
1374 :type '(repeat
1375 (cons
1376 (string :tag "Protocol")
1377 (choice
1378 (string :tag "Format")
1379 (function)))))
1381 (defcustom org-descriptive-links t
1382 "Non-nil means Org will display descriptive links.
1383 E.g. [[http://orgmode.org][Org website]] will be displayed as
1384 \"Org Website\", hiding the link itself and just displaying its
1385 description. When set to `nil', Org will display the full links
1386 literally.
1388 You can interactively set the value of this variable by calling
1389 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1390 :group 'org-link
1391 :type 'boolean)
1393 (defcustom org-link-file-path-type 'adaptive
1394 "How the path name in file links should be stored.
1395 Valid values are:
1397 relative Relative to the current directory, i.e. the directory of the file
1398 into which the link is being inserted.
1399 absolute Absolute path, if possible with ~ for home directory.
1400 noabbrev Absolute path, no abbreviation of home directory.
1401 adaptive Use relative path for files in the current directory and sub-
1402 directories of it. For other files, use an absolute path."
1403 :group 'org-link
1404 :type '(choice
1405 (const relative)
1406 (const absolute)
1407 (const noabbrev)
1408 (const adaptive)))
1410 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1411 "Types of links that should be activated in Org-mode files.
1412 This is a list of symbols, each leading to the activation of a certain link
1413 type. In principle, it does not hurt to turn on most link types - there may
1414 be a small gain when turning off unused link types. The types are:
1416 bracket The recommended [[link][description]] or [[link]] links with hiding.
1417 angle Links in angular brackets that may contain whitespace like
1418 <bbdb:Carsten Dominik>.
1419 plain Plain links in normal text, no whitespace, like http://google.com.
1420 radio Text that is matched by a radio target, see manual for details.
1421 tag Tag settings in a headline (link to tag search).
1422 date Time stamps (link to calendar).
1423 footnote Footnote labels.
1425 Changing this variable requires a restart of Emacs to become effective."
1426 :group 'org-link
1427 :type '(set :greedy t
1428 (const :tag "Double bracket links" bracket)
1429 (const :tag "Angular bracket links" angle)
1430 (const :tag "Plain text links" plain)
1431 (const :tag "Radio target matches" radio)
1432 (const :tag "Tags" tag)
1433 (const :tag "Timestamps" date)
1434 (const :tag "Footnotes" footnote)))
1436 (defcustom org-make-link-description-function nil
1437 "Function to use for generating link descriptions from links.
1438 When nil, the link location will be used. This function must take
1439 two parameters: the first one is the link, the second one is the
1440 description generated by `org-insert-link'. The function should
1441 return the description to use."
1442 :group 'org-link
1443 :type 'function)
1445 (defgroup org-link-store nil
1446 "Options concerning storing links in Org-mode."
1447 :tag "Org Store Link"
1448 :group 'org-link)
1450 (defcustom org-url-hexify-p t
1451 "When non-nil, hexify URL when creating a link."
1452 :type 'boolean
1453 :version "24.3"
1454 :group 'org-link-store)
1456 (defcustom org-email-link-description-format "Email %c: %.30s"
1457 "Format of the description part of a link to an email or usenet message.
1458 The following %-escapes will be replaced by corresponding information:
1460 %F full \"From\" field
1461 %f name, taken from \"From\" field, address if no name
1462 %T full \"To\" field
1463 %t first name in \"To\" field, address if no name
1464 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1465 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1466 %s subject
1467 %d date
1468 %m message-id.
1470 You may use normal field width specification between the % and the letter.
1471 This is for example useful to limit the length of the subject.
1473 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1474 :group 'org-link-store
1475 :type 'string)
1477 (defcustom org-from-is-user-regexp
1478 (let (r1 r2)
1479 (when (and user-mail-address (not (string= user-mail-address "")))
1480 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1481 (when (and user-full-name (not (string= user-full-name "")))
1482 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1483 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1484 "Regexp matched against the \"From:\" header of an email or usenet message.
1485 It should match if the message is from the user him/herself."
1486 :group 'org-link-store
1487 :type 'regexp)
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a capture template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a capture note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type 'directory)
1882 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1883 "Default target for storing notes.
1884 Used as a fall back file for org-remember.el and org-capture.el, for
1885 templates that do not specify a target file."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-capture
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Each function gets as its single argument a property list, see
2261 `org-trigger-hook' for more information about this list.
2263 If any of the functions in this hook returns nil, the state change
2264 is blocked.")
2266 (defvar org-trigger-hook nil
2267 "Hook for functions that are triggered by a state change.
2269 Each function gets as its single argument a property list with at least
2270 the following elements:
2272 (:type type-of-change :position pos-at-entry-start
2273 :from old-state :to new-state)
2275 Depending on the type, more properties may be present.
2277 This mechanism is currently implemented for:
2279 TODO state changes
2280 ------------------
2281 :type todo-state-change
2282 :from previous state (keyword as a string), or nil, or a symbol
2283 'todo' or 'done', to indicate the general type of state.
2284 :to new state, like in :from")
2286 (defcustom org-enforce-todo-dependencies nil
2287 "Non-nil means undone TODO entries will block switching the parent to DONE.
2288 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2289 be blocked if any prior sibling is not yet done.
2290 Finally, if the parent is blocked because of ordered siblings of its own,
2291 the child will also be blocked."
2292 :set (lambda (var val)
2293 (set var val)
2294 (if val
2295 (add-hook 'org-blocker-hook
2296 'org-block-todo-from-children-or-siblings-or-parent)
2297 (remove-hook 'org-blocker-hook
2298 'org-block-todo-from-children-or-siblings-or-parent)))
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-enforce-todo-checkbox-dependencies nil
2303 "Non-nil means unchecked boxes will block switching the parent to DONE.
2304 When this is nil, checkboxes have no influence on switching TODO states.
2305 When non-nil, you first need to check off all check boxes before the TODO
2306 entry can be switched to DONE.
2307 This variable needs to be set before org.el is loaded, and you need to
2308 restart Emacs after a change to make the change effective. The only way
2309 to change is while Emacs is running is through the customize interface."
2310 :set (lambda (var val)
2311 (set var val)
2312 (if val
2313 (add-hook 'org-blocker-hook
2314 'org-block-todo-from-checkboxes)
2315 (remove-hook 'org-blocker-hook
2316 'org-block-todo-from-checkboxes)))
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-treat-insert-todo-heading-as-state-change nil
2321 "Non-nil means inserting a TODO heading is treated as state change.
2322 So when the command \\[org-insert-todo-heading] is used, state change
2323 logging will apply if appropriate. When nil, the new TODO item will
2324 be inserted directly, and no logging will take place."
2325 :group 'org-todo
2326 :type 'boolean)
2328 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2329 "Non-nil means switching TODO states with S-cursor counts as state change.
2330 This is the default behavior. However, setting this to nil allows a
2331 convenient way to select a TODO state and bypass any logging associated
2332 with that."
2333 :group 'org-todo
2334 :type 'boolean)
2336 (defcustom org-todo-state-tags-triggers nil
2337 "Tag changes that should be triggered by TODO state changes.
2338 This is a list. Each entry is
2340 (state-change (tag . flag) .......)
2342 State-change can be a string with a state, and empty string to indicate the
2343 state that has no TODO keyword, or it can be one of the symbols `todo'
2344 or `done', meaning any not-done or done state, respectively."
2345 :group 'org-todo
2346 :group 'org-tags
2347 :type '(repeat
2348 (cons (choice :tag "When changing to"
2349 (const :tag "Not-done state" todo)
2350 (const :tag "Done state" done)
2351 (string :tag "State"))
2352 (repeat
2353 (cons :tag "Tag action"
2354 (string :tag "Tag")
2355 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2357 (defcustom org-log-done nil
2358 "Information to record when a task moves to the DONE state.
2360 Possible values are:
2362 nil Don't add anything, just change the keyword
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologdone
2369 #+STARTUP: logdone
2370 #+STARTUP: lognotedone
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords."
2374 :group 'org-todo
2375 :group 'org-progress
2376 :type '(choice
2377 (const :tag "No logging" nil)
2378 (const :tag "Record CLOSED timestamp" time)
2379 (const :tag "Record CLOSED timestamp with note." note)))
2381 ;; Normalize old uses of org-log-done.
2382 (cond
2383 ((eq org-log-done t) (setq org-log-done 'time))
2384 ((and (listp org-log-done) (memq 'done org-log-done))
2385 (setq org-log-done 'note)))
2387 (defcustom org-log-reschedule nil
2388 "Information to record when the scheduling date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologreschedule
2399 #+STARTUP: logreschedule
2400 #+STARTUP: lognotereschedule"
2401 :group 'org-todo
2402 :group 'org-progress
2403 :type '(choice
2404 (const :tag "No logging" nil)
2405 (const :tag "Record timestamp" time)
2406 (const :tag "Record timestamp with note." note)))
2408 (defcustom org-log-redeadline nil
2409 "Information to record when the deadline date of a tasks is modified.
2411 Possible values are:
2413 nil Don't add anything, just change the date
2414 time Add a time stamp to the task
2415 note Prompt for a note and add it with template `org-log-note-headings'
2417 This option can also be set with on a per-file-basis with
2419 #+STARTUP: nologredeadline
2420 #+STARTUP: logredeadline
2421 #+STARTUP: lognoteredeadline
2423 You can have local logging settings for a subtree by setting the LOGGING
2424 property to one or more of these keywords."
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type '(choice
2428 (const :tag "No logging" nil)
2429 (const :tag "Record timestamp" time)
2430 (const :tag "Record timestamp with note." note)))
2432 (defcustom org-log-note-clock-out nil
2433 "Non-nil means record a note when clocking out of an item.
2434 This can also be configured on a per-file basis by adding one of
2435 the following lines anywhere in the buffer:
2437 #+STARTUP: lognoteclock-out
2438 #+STARTUP: nolognoteclock-out"
2439 :group 'org-todo
2440 :group 'org-progress
2441 :type 'boolean)
2443 (defcustom org-log-done-with-time t
2444 "Non-nil means the CLOSED time stamp will contain date and time.
2445 When nil, only the date will be recorded."
2446 :group 'org-progress
2447 :type 'boolean)
2449 (defcustom org-log-note-headings
2450 '((done . "CLOSING NOTE %t")
2451 (state . "State %-12s from %-12S %t")
2452 (note . "Note taken on %t")
2453 (reschedule . "Rescheduled from %S on %t")
2454 (delschedule . "Not scheduled, was %S on %t")
2455 (redeadline . "New deadline from %S on %t")
2456 (deldeadline . "Removed deadline, was %S on %t")
2457 (refile . "Refiled on %t")
2458 (clock-out . ""))
2459 "Headings for notes added to entries.
2460 The value is an alist, with the car being a symbol indicating the note
2461 context, and the cdr is the heading to be used. The heading may also be the
2462 empty string.
2463 %t in the heading will be replaced by a time stamp.
2464 %T will be an active time stamp instead the default inactive one
2465 %d will be replaced by a short-format time stamp.
2466 %D will be replaced by an active short-format time stamp.
2467 %s will be replaced by the new TODO state, in double quotes.
2468 %S will be replaced by the old TODO state, in double quotes.
2469 %u will be replaced by the user name.
2470 %U will be replaced by the full user name.
2472 In fact, it is not a good idea to change the `state' entry, because
2473 agenda log mode depends on the format of these entries."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(list :greedy t
2477 (cons (const :tag "Heading when closing an item" done) string)
2478 (cons (const :tag
2479 "Heading when changing todo state (todo sequence only)"
2480 state) string)
2481 (cons (const :tag "Heading when just taking a note" note) string)
2482 (cons (const :tag "Heading when clocking out" clock-out) string)
2483 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2484 (cons (const :tag "Heading when rescheduling" reschedule) string)
2485 (cons (const :tag "Heading when changing deadline" redeadline) string)
2486 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2487 (cons (const :tag "Heading when refiling" refile) string)))
2489 (unless (assq 'note org-log-note-headings)
2490 (push '(note . "%t") org-log-note-headings))
2492 (defcustom org-log-into-drawer nil
2493 "Non-nil means insert state change notes and time stamps into a drawer.
2494 When nil, state changes notes will be inserted after the headline and
2495 any scheduling and clock lines, but not inside a drawer.
2497 The value of this variable should be the name of the drawer to use.
2498 LOGBOOK is proposed as the default drawer for this purpose, you can
2499 also set this to a string to define the drawer of your choice.
2501 A value of t is also allowed, representing \"LOGBOOK\".
2503 If this variable is set, `org-log-state-notes-insert-after-drawers'
2504 will be ignored.
2506 You can set the property LOG_INTO_DRAWER to overrule this setting for
2507 a subtree."
2508 :group 'org-todo
2509 :group 'org-progress
2510 :type '(choice
2511 (const :tag "Not into a drawer" nil)
2512 (const :tag "LOGBOOK" t)
2513 (string :tag "Other")))
2515 (if (fboundp 'defvaralias)
2516 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2518 (defun org-log-into-drawer ()
2519 "Return the value of `org-log-into-drawer', but let properties overrule.
2520 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2521 used instead of the default value."
2522 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2523 (cond
2524 ((or (not p) (equal p "nil")) org-log-into-drawer)
2525 ((equal p "t") "LOGBOOK")
2526 (t p))))
2528 (defcustom org-log-state-notes-insert-after-drawers nil
2529 "Non-nil means insert state change notes after any drawers in entry.
2530 Only the drawers that *immediately* follow the headline and the
2531 deadline/scheduled line are skipped.
2532 When nil, insert notes right after the heading and perhaps the line
2533 with deadline/scheduling if present.
2535 This variable will have no effect if `org-log-into-drawer' is
2536 set."
2537 :group 'org-todo
2538 :group 'org-progress
2539 :type 'boolean)
2541 (defcustom org-log-states-order-reversed t
2542 "Non-nil means the latest state note will be directly after heading.
2543 When nil, the state change notes will be ordered according to time."
2544 :group 'org-todo
2545 :group 'org-progress
2546 :type 'boolean)
2548 (defcustom org-todo-repeat-to-state nil
2549 "The TODO state to which a repeater should return the repeating task.
2550 By default this is the first task in a TODO sequence, or the previous state
2551 in a TODO_TYP set. But you can specify another task here.
2552 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2553 :group 'org-todo
2554 :version "24.1"
2555 :type '(choice (const :tag "Head of sequence" nil)
2556 (string :tag "Specific state")))
2558 (defcustom org-log-repeat 'time
2559 "Non-nil means record moving through the DONE state when triggering repeat.
2560 An auto-repeating task is immediately switched back to TODO when
2561 marked DONE. If you are not logging state changes (by adding \"@\"
2562 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2563 record a closing note, there will be no record of the task moving
2564 through DONE. This variable forces taking a note anyway.
2566 nil Don't force a record
2567 time Record a time stamp
2568 note Prompt for a note and add it with template `org-log-note-headings'
2570 This option can also be set with on a per-file-basis with
2572 #+STARTUP: nologrepeat
2573 #+STARTUP: logrepeat
2574 #+STARTUP: lognoterepeat
2576 You can have local logging settings for a subtree by setting the LOGGING
2577 property to one or more of these keywords."
2578 :group 'org-todo
2579 :group 'org-progress
2580 :type '(choice
2581 (const :tag "Don't force a record" nil)
2582 (const :tag "Force recording the DONE state" time)
2583 (const :tag "Force recording a note with the DONE state" note)))
2586 (defgroup org-priorities nil
2587 "Priorities in Org-mode."
2588 :tag "Org Priorities"
2589 :group 'org-todo)
2591 (defcustom org-enable-priority-commands t
2592 "Non-nil means priority commands are active.
2593 When nil, these commands will be disabled, so that you never accidentally
2594 set a priority."
2595 :group 'org-priorities
2596 :type 'boolean)
2598 (defcustom org-highest-priority ?A
2599 "The highest priority of TODO items. A character like ?A, ?B etc.
2600 Must have a smaller ASCII number than `org-lowest-priority'."
2601 :group 'org-priorities
2602 :type 'character)
2604 (defcustom org-lowest-priority ?C
2605 "The lowest priority of TODO items. A character like ?A, ?B etc.
2606 Must have a larger ASCII number than `org-highest-priority'."
2607 :group 'org-priorities
2608 :type 'character)
2610 (defcustom org-default-priority ?B
2611 "The default priority of TODO items.
2612 This is the priority an item gets if no explicit priority is given.
2613 When starting to cycle on an empty priority the first step in the cycle
2614 depends on `org-priority-start-cycle-with-default'. The resulting first
2615 step priority must not exceed the range from `org-highest-priority' to
2616 `org-lowest-priority' which means that `org-default-priority' has to be
2617 in this range exclusive or inclusive the range boundaries. Else the
2618 first step refuses to set the default and the second will fall back
2619 to (depending on the command used) the highest or lowest priority."
2620 :group 'org-priorities
2621 :type 'character)
2623 (defcustom org-priority-start-cycle-with-default t
2624 "Non-nil means start with default priority when starting to cycle.
2625 When this is nil, the first step in the cycle will be (depending on the
2626 command used) one higher or lower than the default priority.
2627 See also `org-default-priority'."
2628 :group 'org-priorities
2629 :type 'boolean)
2631 (defcustom org-get-priority-function nil
2632 "Function to extract the priority from a string.
2633 The string is normally the headline. If this is nil Org computes the
2634 priority from the priority cookie like [#A] in the headline. It returns
2635 an integer, increasing by 1000 for each priority level.
2636 The user can set a different function here, which should take a string
2637 as an argument and return the numeric priority."
2638 :group 'org-priorities
2639 :version "24.1"
2640 :type 'function)
2642 (defgroup org-time nil
2643 "Options concerning time stamps and deadlines in Org-mode."
2644 :tag "Org Time"
2645 :group 'org)
2647 (defcustom org-insert-labeled-timestamps-at-point nil
2648 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2649 When nil, these labeled time stamps are forces into the second line of an
2650 entry, just after the headline. When scheduling from the global TODO list,
2651 the time stamp will always be forced into the second line."
2652 :group 'org-time
2653 :type 'boolean)
2655 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2656 "Formats for `format-time-string' which are used for time stamps.
2657 It is not recommended to change this constant.")
2659 (defcustom org-time-stamp-rounding-minutes '(0 5)
2660 "Number of minutes to round time stamps to.
2661 These are two values, the first applies when first creating a time stamp.
2662 The second applies when changing it with the commands `S-up' and `S-down'.
2663 When changing the time stamp, this means that it will change in steps
2664 of N minutes, as given by the second value.
2666 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2667 numbers should be factors of 60, so for example 5, 10, 15.
2669 When this is larger than 1, you can still force an exact time stamp by using
2670 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2671 and by using a prefix arg to `S-up/down' to specify the exact number
2672 of minutes to shift."
2673 :group 'org-time
2674 :get #'(lambda (var) ; Make sure both elements are there
2675 (if (integerp (default-value var))
2676 (list (default-value var) 5)
2677 (default-value var)))
2678 :type '(list
2679 (integer :tag "when inserting times")
2680 (integer :tag "when modifying times")))
2682 ;; Normalize old customizations of this variable.
2683 (when (integerp org-time-stamp-rounding-minutes)
2684 (setq org-time-stamp-rounding-minutes
2685 (list org-time-stamp-rounding-minutes
2686 org-time-stamp-rounding-minutes)))
2688 (defcustom org-display-custom-times nil
2689 "Non-nil means overlay custom formats over all time stamps.
2690 The formats are defined through the variable `org-time-stamp-custom-formats'.
2691 To turn this on on a per-file basis, insert anywhere in the file:
2692 #+STARTUP: customtime"
2693 :group 'org-time
2694 :set 'set-default
2695 :type 'sexp)
2696 (make-variable-buffer-local 'org-display-custom-times)
2698 (defcustom org-time-stamp-custom-formats
2699 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2700 "Custom formats for time stamps. See `format-time-string' for the syntax.
2701 These are overlaid over the default ISO format if the variable
2702 `org-display-custom-times' is set. Time like %H:%M should be at the
2703 end of the second format. The custom formats are also honored by export
2704 commands, if custom time display is turned on at the time of export."
2705 :group 'org-time
2706 :type 'sexp)
2708 (defun org-time-stamp-format (&optional long inactive)
2709 "Get the right format for a time string."
2710 (let ((f (if long (cdr org-time-stamp-formats)
2711 (car org-time-stamp-formats))))
2712 (if inactive
2713 (concat "[" (substring f 1 -1) "]")
2714 f)))
2716 (defcustom org-time-clocksum-format "%d:%02d"
2717 "The format string used when creating CLOCKSUM lines.
2718 This is also used when org-mode generates a time duration."
2719 :group 'org-time
2720 :type 'string)
2722 (defcustom org-time-clocksum-use-fractional nil
2723 "If non-nil, \\[org-clock-display] uses fractional times.
2724 org-mode generates a time duration."
2725 :group 'org-time
2726 :type 'boolean)
2728 (defcustom org-time-clocksum-fractional-format "%.2f"
2729 "The format string used when creating CLOCKSUM lines, or when
2730 org-mode generates a time duration."
2731 :group 'org-time
2732 :type 'string)
2734 (defcustom org-deadline-warning-days 14
2735 "No. of days before expiration during which a deadline becomes active.
2736 This variable governs the display in sparse trees and in the agenda.
2737 When 0 or negative, it means use this number (the absolute value of it)
2738 even if a deadline has a different individual lead time specified.
2740 Custom commands can set this variable in the options section."
2741 :group 'org-time
2742 :group 'org-agenda-daily/weekly
2743 :type 'integer)
2745 (defcustom org-read-date-prefer-future t
2746 "Non-nil means assume future for incomplete date input from user.
2747 This affects the following situations:
2748 1. The user gives a month but not a year.
2749 For example, if it is April and you enter \"feb 2\", this will be read
2750 as Feb 2, *next* year. \"May 5\", however, will be this year.
2751 2. The user gives a day, but no month.
2752 For example, if today is the 15th, and you enter \"3\", Org-mode will
2753 read this as the third of *next* month. However, if you enter \"17\",
2754 it will be considered as *this* month.
2756 If you set this variable to the symbol `time', then also the following
2757 will work:
2759 3. If the user gives a time.
2760 If the time is before now, it will be interpreted as tomorrow.
2762 Currently none of this works for ISO week specifications.
2764 When this option is nil, the current day, month and year will always be
2765 used as defaults.
2767 See also `org-agenda-jump-prefer-future'."
2768 :group 'org-time
2769 :type '(choice
2770 (const :tag "Never" nil)
2771 (const :tag "Check month and day" t)
2772 (const :tag "Check month, day, and time" time)))
2774 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2775 "Should the agenda jump command prefer the future for incomplete dates?
2776 The default is to do the same as configured in `org-read-date-prefer-future'.
2777 But you can also set a deviating value here.
2778 This may t or nil, or the symbol `org-read-date-prefer-future'."
2779 :group 'org-agenda
2780 :group 'org-time
2781 :version "24.1"
2782 :type '(choice
2783 (const :tag "Use org-read-date-prefer-future"
2784 org-read-date-prefer-future)
2785 (const :tag "Never" nil)
2786 (const :tag "Always" t)))
2788 (defcustom org-read-date-force-compatible-dates t
2789 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2791 Depending on the system Emacs is running on, certain dates cannot
2792 be represented with the type used internally to represent time.
2793 Dates between 1970-1-1 and 2038-1-1 can always be represented
2794 correctly. Some systems allow for earlier dates, some for later,
2795 some for both. One way to find out it to insert any date into an
2796 Org buffer, putting the cursor on the year and hitting S-up and
2797 S-down to test the range.
2799 When this variable is set to t, the date/time prompt will not let
2800 you specify dates outside the 1970-2037 range, so it is certain that
2801 these dates will work in whatever version of Emacs you are
2802 running, and also that you can move a file from one Emacs implementation
2803 to another. WHenever Org is forcing the year for you, it will display
2804 a message and beep.
2806 When this variable is nil, Org will check if the date is
2807 representable in the specific Emacs implementation you are using.
2808 If not, it will force a year, usually the current year, and beep
2809 to remind you. Currently this setting is not recommended because
2810 the likelihood that you will open your Org files in an Emacs that
2811 has limited date range is not negligible.
2813 A workaround for this problem is to use diary sexp dates for time
2814 stamps outside of this range."
2815 :group 'org-time
2816 :version "24.1"
2817 :type 'boolean)
2819 (defcustom org-read-date-display-live t
2820 "Non-nil means display current interpretation of date prompt live.
2821 This display will be in an overlay, in the minibuffer."
2822 :group 'org-time
2823 :type 'boolean)
2825 (defcustom org-read-date-popup-calendar t
2826 "Non-nil means pop up a calendar when prompting for a date.
2827 In the calendar, the date can be selected with mouse-1. However, the
2828 minibuffer will also be active, and you can simply enter the date as well.
2829 When nil, only the minibuffer will be available."
2830 :group 'org-time
2831 :type 'boolean)
2832 (if (fboundp 'defvaralias)
2833 (defvaralias 'org-popup-calendar-for-date-prompt
2834 'org-read-date-popup-calendar))
2836 (defcustom org-read-date-minibuffer-setup-hook nil
2837 "Hook to be used to set up keys for the date/time interface.
2838 Add key definitions to `minibuffer-local-map', which will be a temporary
2839 copy."
2840 :group 'org-time
2841 :type 'hook)
2843 (defcustom org-extend-today-until 0
2844 "The hour when your day really ends. Must be an integer.
2845 This has influence for the following applications:
2846 - When switching the agenda to \"today\". It it is still earlier than
2847 the time given here, the day recognized as TODAY is actually yesterday.
2848 - When a date is read from the user and it is still before the time given
2849 here, the current date and time will be assumed to be yesterday, 23:59.
2850 Also, timestamps inserted in capture templates follow this rule.
2852 IMPORTANT: This is a feature whose implementation is and likely will
2853 remain incomplete. Really, it is only here because past midnight seems to
2854 be the favorite working time of John Wiegley :-)"
2855 :group 'org-time
2856 :type 'integer)
2858 (defcustom org-use-effective-time nil
2859 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2860 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2861 \"effective time\" of any timestamps between midnight and 8am will be
2862 23:59 of the previous day."
2863 :group 'org-time
2864 :version "24.1"
2865 :type 'boolean)
2867 (defcustom org-use-last-clock-out-time-as-effective-time nil
2868 "When non-nil, use the last clock out time for `org-todo'.
2869 Note that this option has precedence over the combined use of
2870 `org-use-effective-time' and `org-extend-today-until'."
2871 :group 'org-time
2872 ;; :version "24.3"
2873 :type 'boolean)
2875 (defcustom org-edit-timestamp-down-means-later nil
2876 "Non-nil means S-down will increase the time in a time stamp.
2877 When nil, S-up will increase."
2878 :group 'org-time
2879 :type 'boolean)
2881 (defcustom org-calendar-follow-timestamp-change t
2882 "Non-nil means make the calendar window follow timestamp changes.
2883 When a timestamp is modified and the calendar window is visible, it will be
2884 moved to the new date."
2885 :group 'org-time
2886 :type 'boolean)
2888 (defgroup org-tags nil
2889 "Options concerning tags in Org-mode."
2890 :tag "Org Tags"
2891 :group 'org)
2893 (defcustom org-tag-alist nil
2894 "List of tags allowed in Org-mode files.
2895 When this list is nil, Org-mode will base TAG input on what is already in the
2896 buffer.
2897 The value of this variable is an alist, the car of each entry must be a
2898 keyword as a string, the cdr may be a character that is used to select
2899 that tag through the fast-tag-selection interface.
2900 See the manual for details."
2901 :group 'org-tags
2902 :type '(repeat
2903 (choice
2904 (cons (string :tag "Tag name")
2905 (character :tag "Access char"))
2906 (list :tag "Start radio group"
2907 (const :startgroup)
2908 (option (string :tag "Group description")))
2909 (list :tag "End radio group"
2910 (const :endgroup)
2911 (option (string :tag "Group description")))
2912 (const :tag "New line" (:newline)))))
2914 (defcustom org-tag-persistent-alist nil
2915 "List of tags that will always appear in all Org-mode files.
2916 This is in addition to any in buffer settings or customizations
2917 of `org-tag-alist'.
2918 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2919 The value of this variable is an alist, the car of each entry must be a
2920 keyword as a string, the cdr may be a character that is used to select
2921 that tag through the fast-tag-selection interface.
2922 See the manual for details.
2923 To disable these tags on a per-file basis, insert anywhere in the file:
2924 #+STARTUP: noptag"
2925 :group 'org-tags
2926 :type '(repeat
2927 (choice
2928 (cons (string :tag "Tag name")
2929 (character :tag "Access char"))
2930 (const :tag "Start radio group" (:startgroup))
2931 (const :tag "End radio group" (:endgroup))
2932 (const :tag "New line" (:newline)))))
2934 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2935 "If non-nil, always offer completion for all tags of all agenda files.
2936 Instead of customizing this variable directly, you might want to
2937 set it locally for capture buffers, because there no list of
2938 tags in that file can be created dynamically (there are none).
2940 (add-hook 'org-capture-mode-hook
2941 (lambda ()
2942 (set (make-local-variable
2943 'org-complete-tags-always-offer-all-agenda-tags)
2944 t)))"
2945 :group 'org-tags
2946 :version "24.1"
2947 :type 'boolean)
2949 (defvar org-file-tags nil
2950 "List of tags that can be inherited by all entries in the file.
2951 The tags will be inherited if the variable `org-use-tag-inheritance'
2952 says they should be.
2953 This variable is populated from #+FILETAGS lines.")
2955 (defcustom org-use-fast-tag-selection 'auto
2956 "Non-nil means use fast tag selection scheme.
2957 This is a special interface to select and deselect tags with single keys.
2958 When nil, fast selection is never used.
2959 When the symbol `auto', fast selection is used if and only if selection
2960 characters for tags have been configured, either through the variable
2961 `org-tag-alist' or through a #+TAGS line in the buffer.
2962 When t, fast selection is always used and selection keys are assigned
2963 automatically if necessary."
2964 :group 'org-tags
2965 :type '(choice
2966 (const :tag "Always" t)
2967 (const :tag "Never" nil)
2968 (const :tag "When selection characters are configured" 'auto)))
2970 (defcustom org-fast-tag-selection-single-key nil
2971 "Non-nil means fast tag selection exits after first change.
2972 When nil, you have to press RET to exit it.
2973 During fast tag selection, you can toggle this flag with `C-c'.
2974 This variable can also have the value `expert'. In this case, the window
2975 displaying the tags menu is not even shown, until you press C-c again."
2976 :group 'org-tags
2977 :type '(choice
2978 (const :tag "No" nil)
2979 (const :tag "Yes" t)
2980 (const :tag "Expert" expert)))
2982 (defvar org-fast-tag-selection-include-todo nil
2983 "Non-nil means fast tags selection interface will also offer TODO states.
2984 This is an undocumented feature, you should not rely on it.")
2986 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2987 "The column to which tags should be indented in a headline.
2988 If this number is positive, it specifies the column. If it is negative,
2989 it means that the tags should be flushright to that column. For example,
2990 -80 works well for a normal 80 character screen.
2991 When 0, place tags directly after headline text, with only one space in
2992 between."
2993 :group 'org-tags
2994 :type 'integer)
2996 (defcustom org-auto-align-tags t
2997 "Non-nil keeps tags aligned when modifying headlines.
2998 Some operations (i.e. demoting) change the length of a headline and
2999 therefore shift the tags around. With this option turned on, after
3000 each such operation the tags are again aligned to `org-tags-column'."
3001 :group 'org-tags
3002 :type 'boolean)
3004 (defcustom org-use-tag-inheritance t
3005 "Non-nil means tags in levels apply also for sublevels.
3006 When nil, only the tags directly given in a specific line apply there.
3007 This may also be a list of tags that should be inherited, or a regexp that
3008 matches tags that should be inherited. Additional control is possible
3009 with the variable `org-tags-exclude-from-inheritance' which gives an
3010 explicit list of tags to be excluded from inheritance., even if the value of
3011 `org-use-tag-inheritance' would select it for inheritance.
3013 If this option is t, a match early-on in a tree can lead to a large
3014 number of matches in the subtree when constructing the agenda or creating
3015 a sparse tree. If you only want to see the first match in a tree during
3016 a search, check out the variable `org-tags-match-list-sublevels'."
3017 :group 'org-tags
3018 :type '(choice
3019 (const :tag "Not" nil)
3020 (const :tag "Always" t)
3021 (repeat :tag "Specific tags" (string :tag "Tag"))
3022 (regexp :tag "Tags matched by regexp")))
3024 (defcustom org-tags-exclude-from-inheritance nil
3025 "List of tags that should never be inherited.
3026 This is a way to exclude a few tags from inheritance. For way to do
3027 the opposite, to actively allow inheritance for selected tags,
3028 see the variable `org-use-tag-inheritance'."
3029 :group 'org-tags
3030 :type '(repeat (string :tag "Tag")))
3032 (defun org-tag-inherit-p (tag)
3033 "Check if TAG is one that should be inherited."
3034 (cond
3035 ((member tag org-tags-exclude-from-inheritance) nil)
3036 ((eq org-use-tag-inheritance t) t)
3037 ((not org-use-tag-inheritance) nil)
3038 ((stringp org-use-tag-inheritance)
3039 (string-match org-use-tag-inheritance tag))
3040 ((listp org-use-tag-inheritance)
3041 (member tag org-use-tag-inheritance))
3042 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3044 (defcustom org-tags-match-list-sublevels t
3045 "Non-nil means list also sublevels of headlines matching a search.
3046 This variable applies to tags/property searches, and also to stuck
3047 projects because this search is based on a tags match as well.
3049 When set to the symbol `indented', sublevels are indented with
3050 leading dots.
3052 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3053 the sublevels of a headline matching a tag search often also match
3054 the same search. Listing all of them can create very long lists.
3055 Setting this variable to nil causes subtrees of a match to be skipped.
3057 This variable is semi-obsolete and probably should always be true. It
3058 is better to limit inheritance to certain tags using the variables
3059 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3060 :group 'org-tags
3061 :type '(choice
3062 (const :tag "No, don't list them" nil)
3063 (const :tag "Yes, do list them" t)
3064 (const :tag "List them, indented with leading dots" indented)))
3066 (defcustom org-tags-sort-function nil
3067 "When set, tags are sorted using this function as a comparator."
3068 :group 'org-tags
3069 :type '(choice
3070 (const :tag "No sorting" nil)
3071 (const :tag "Alphabetical" string<)
3072 (const :tag "Reverse alphabetical" string>)
3073 (function :tag "Custom function" nil)))
3075 (defvar org-tags-history nil
3076 "History of minibuffer reads for tags.")
3077 (defvar org-last-tags-completion-table nil
3078 "The last used completion table for tags.")
3079 (defvar org-after-tags-change-hook nil
3080 "Hook that is run after the tags in a line have changed.")
3082 (defgroup org-properties nil
3083 "Options concerning properties in Org-mode."
3084 :tag "Org Properties"
3085 :group 'org)
3087 (defcustom org-property-format "%-10s %s"
3088 "How property key/value pairs should be formatted by `indent-line'.
3089 When `indent-line' hits a property definition, it will format the line
3090 according to this format, mainly to make sure that the values are
3091 lined-up with respect to each other."
3092 :group 'org-properties
3093 :type 'string)
3095 (defcustom org-properties-postprocess-alist nil
3096 "Alist of properties and functions to adjust inserted values.
3097 Elements of this alist must be of the form
3099 ([string] [function])
3101 where [string] must be a property name and [function] must be a
3102 lambda expression: this lambda expression must take one argument,
3103 the value to adjust, and return the new value as a string.
3105 For example, this element will allow the property \"Remaining\"
3106 to be updated wrt the relation between the \"Effort\" property
3107 and the clock summary:
3109 ((\"Remaining\" (lambda(value)
3110 (let ((clocksum (org-clock-sum-current-item))
3111 (effort (org-duration-string-to-minutes
3112 (org-entry-get (point) \"Effort\"))))
3113 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3114 :group 'org-properties
3115 :version "24.1"
3116 :type '(alist :key-type (string :tag "Property")
3117 :value-type (function :tag "Function")))
3119 (defcustom org-use-property-inheritance nil
3120 "Non-nil means properties apply also for sublevels.
3122 This setting is chiefly used during property searches. Turning it on can
3123 cause significant overhead when doing a search, which is why it is not
3124 on by default.
3126 When nil, only the properties directly given in the current entry count.
3127 When t, every property is inherited. The value may also be a list of
3128 properties that should have inheritance, or a regular expression matching
3129 properties that should be inherited.
3131 However, note that some special properties use inheritance under special
3132 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3133 and the properties ending in \"_ALL\" when they are used as descriptor
3134 for valid values of a property.
3136 Note for programmers:
3137 When querying an entry with `org-entry-get', you can control if inheritance
3138 should be used. By default, `org-entry-get' looks only at the local
3139 properties. You can request inheritance by setting the inherit argument
3140 to t (to force inheritance) or to `selective' (to respect the setting
3141 in this variable)."
3142 :group 'org-properties
3143 :type '(choice
3144 (const :tag "Not" nil)
3145 (const :tag "Always" t)
3146 (repeat :tag "Specific properties" (string :tag "Property"))
3147 (regexp :tag "Properties matched by regexp")))
3149 (defun org-property-inherit-p (property)
3150 "Check if PROPERTY is one that should be inherited."
3151 (cond
3152 ((eq org-use-property-inheritance t) t)
3153 ((not org-use-property-inheritance) nil)
3154 ((stringp org-use-property-inheritance)
3155 (string-match org-use-property-inheritance property))
3156 ((listp org-use-property-inheritance)
3157 (member property org-use-property-inheritance))
3158 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3160 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3161 "The default column format, if no other format has been defined.
3162 This variable can be set on the per-file basis by inserting a line
3164 #+COLUMNS: %25ITEM ....."
3165 :group 'org-properties
3166 :type 'string)
3168 (defcustom org-columns-ellipses ".."
3169 "The ellipses to be used when a field in column view is truncated.
3170 When this is the empty string, as many characters as possible are shown,
3171 but then there will be no visual indication that the field has been truncated.
3172 When this is a string of length N, the last N characters of a truncated
3173 field are replaced by this string. If the column is narrower than the
3174 ellipses string, only part of the ellipses string will be shown."
3175 :group 'org-properties
3176 :type 'string)
3178 (defcustom org-columns-modify-value-for-display-function nil
3179 "Function that modifies values for display in column view.
3180 For example, it can be used to cut out a certain part from a time stamp.
3181 The function must take 2 arguments:
3183 column-title The title of the column (*not* the property name)
3184 value The value that should be modified.
3186 The function should return the value that should be displayed,
3187 or nil if the normal value should be used."
3188 :group 'org-properties
3189 :type 'function)
3191 (defcustom org-effort-property "Effort"
3192 "The property that is being used to keep track of effort estimates.
3193 Effort estimates given in this property need to have the format H:MM."
3194 :group 'org-properties
3195 :group 'org-progress
3196 :type '(string :tag "Property"))
3198 (defconst org-global-properties-fixed
3199 '(("VISIBILITY_ALL" . "folded children content all")
3200 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3201 "List of property/value pairs that can be inherited by any entry.
3203 These are fixed values, for the preset properties. The user variable
3204 that can be used to add to this list is `org-global-properties'.
3206 The entries in this list are cons cells where the car is a property
3207 name and cdr is a string with the value. If the value represents
3208 multiple items like an \"_ALL\" property, separate the items by
3209 spaces.")
3211 (defcustom org-global-properties nil
3212 "List of property/value pairs that can be inherited by any entry.
3214 This list will be combined with the constant `org-global-properties-fixed'.
3216 The entries in this list are cons cells where the car is a property
3217 name and cdr is a string with the value.
3219 You can set buffer-local values for the same purpose in the variable
3220 `org-file-properties' this by adding lines like
3222 #+PROPERTY: NAME VALUE"
3223 :group 'org-properties
3224 :type '(repeat
3225 (cons (string :tag "Property")
3226 (string :tag "Value"))))
3228 (defvar org-file-properties nil
3229 "List of property/value pairs that can be inherited by any entry.
3230 Valid for the current buffer.
3231 This variable is populated from #+PROPERTY lines.")
3232 (make-variable-buffer-local 'org-file-properties)
3234 (defgroup org-agenda nil
3235 "Options concerning agenda views in Org-mode."
3236 :tag "Org Agenda"
3237 :group 'org)
3239 (defvar org-category nil
3240 "Variable used by org files to set a category for agenda display.
3241 Such files should use a file variable to set it, for example
3243 # -*- mode: org; org-category: \"ELisp\"
3245 or contain a special line
3247 #+CATEGORY: ELisp
3249 If the file does not specify a category, then file's base name
3250 is used instead.")
3251 (make-variable-buffer-local 'org-category)
3252 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3254 (defcustom org-agenda-files nil
3255 "The files to be used for agenda display.
3256 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3257 \\[org-remove-file]. You can also use customize to edit the list.
3259 If an entry is a directory, all files in that directory that are matched by
3260 `org-agenda-file-regexp' will be part of the file list.
3262 If the value of the variable is not a list but a single file name, then
3263 the list of agenda files is actually stored and maintained in that file, one
3264 agenda file per line. In this file paths can be given relative to
3265 `org-directory'. Tilde expansion and environment variable substitution
3266 are also made."
3267 :group 'org-agenda
3268 :type '(choice
3269 (repeat :tag "List of files and directories" file)
3270 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3272 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3273 "Regular expression to match files for `org-agenda-files'.
3274 If any element in the list in that variable contains a directory instead
3275 of a normal file, all files in that directory that are matched by this
3276 regular expression will be included."
3277 :group 'org-agenda
3278 :type 'regexp)
3280 (defcustom org-agenda-text-search-extra-files nil
3281 "List of extra files to be searched by text search commands.
3282 These files will be search in addition to the agenda files by the
3283 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3284 Note that these files will only be searched for text search commands,
3285 not for the other agenda views like todo lists, tag searches or the weekly
3286 agenda. This variable is intended to list notes and possibly archive files
3287 that should also be searched by these two commands.
3288 In fact, if the first element in the list is the symbol `agenda-archives',
3289 than all archive files of all agenda files will be added to the search
3290 scope."
3291 :group 'org-agenda
3292 :type '(set :greedy t
3293 (const :tag "Agenda Archives" agenda-archives)
3294 (repeat :inline t (file))))
3296 (if (fboundp 'defvaralias)
3297 (defvaralias 'org-agenda-multi-occur-extra-files
3298 'org-agenda-text-search-extra-files))
3300 (defcustom org-agenda-skip-unavailable-files nil
3301 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3302 A nil value means to remove them, after a query, from the list."
3303 :group 'org-agenda
3304 :type 'boolean)
3306 (defcustom org-calendar-to-agenda-key [?c]
3307 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3308 The command `org-calendar-goto-agenda' will be bound to this key. The
3309 default is the character `c' because then `c' can be used to switch back and
3310 forth between agenda and calendar."
3311 :group 'org-agenda
3312 :type 'sexp)
3314 (defcustom org-calendar-insert-diary-entry-key [?i]
3315 "The key to be installed in `calendar-mode-map' for adding diary entries.
3316 This option is irrelevant until `org-agenda-diary-file' has been configured
3317 to point to an Org-mode file. When that is the case, the command
3318 `org-agenda-diary-entry' will be bound to the key given here, by default
3319 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3320 if you want to continue doing this, you need to change this to a different
3321 key."
3322 :group 'org-agenda
3323 :type 'sexp)
3325 (defcustom org-agenda-diary-file 'diary-file
3326 "File to which to add new entries with the `i' key in agenda and calendar.
3327 When this is the symbol `diary-file', the functionality in the Emacs
3328 calendar will be used to add entries to the `diary-file'. But when this
3329 points to a file, `org-agenda-diary-entry' will be used instead."
3330 :group 'org-agenda
3331 :type '(choice
3332 (const :tag "The standard Emacs diary file" diary-file)
3333 (file :tag "Special Org file diary entries")))
3335 (eval-after-load "calendar"
3336 '(progn
3337 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3338 'org-calendar-goto-agenda)
3339 (add-hook 'calendar-mode-hook
3340 (lambda ()
3341 (unless (eq org-agenda-diary-file 'diary-file)
3342 (define-key calendar-mode-map
3343 org-calendar-insert-diary-entry-key
3344 'org-agenda-diary-entry))))))
3346 (defgroup org-latex nil
3347 "Options for embedding LaTeX code into Org-mode."
3348 :tag "Org LaTeX"
3349 :group 'org)
3351 (defcustom org-format-latex-options
3352 '(:foreground default :background default :scale 1.0
3353 :html-foreground "Black" :html-background "Transparent"
3354 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3355 "Options for creating images from LaTeX fragments.
3356 This is a property list with the following properties:
3357 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3358 `default' means use the foreground of the default face.
3359 `auto' means use the foreground from the text face.
3360 :background the background color, or \"Transparent\".
3361 `default' means use the background of the default face.
3362 `auto' means use the background from the text face.
3363 :scale a scaling factor for the size of the images, to get more pixels
3364 :html-foreground, :html-background, :html-scale
3365 the same numbers for HTML export.
3366 :matchers a list indicating which matchers should be used to
3367 find LaTeX fragments. Valid members of this list are:
3368 \"begin\" find environments
3369 \"$1\" find single characters surrounded by $.$
3370 \"$\" find math expressions surrounded by $...$
3371 \"$$\" find math expressions surrounded by $$....$$
3372 \"\\(\" find math expressions surrounded by \\(...\\)
3373 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3374 :group 'org-latex
3375 :type 'plist)
3377 (defcustom org-format-latex-signal-error t
3378 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3379 When nil, just push out a message."
3380 :group 'org-latex
3381 :version "24.1"
3382 :type 'boolean)
3384 (defcustom org-latex-to-mathml-jar-file nil
3385 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3386 Use this to specify additional executable file say a jar file.
3388 When using MathToWeb as the converter, specify the full-path to
3389 your mathtoweb.jar file."
3390 :group 'org-latex
3391 :version "24.1"
3392 :type '(choice
3393 (const :tag "None" nil)
3394 (file :tag "JAR file" :must-match t)))
3396 (defcustom org-latex-to-mathml-convert-command nil
3397 "Command to convert LaTeX fragments to MathML.
3398 Replace format-specifiers in the command as noted below and use
3399 `shell-command' to convert LaTeX to MathML.
3400 %j: Executable file in fully expanded form as specified by
3401 `org-latex-to-mathml-jar-file'.
3402 %I: Input LaTeX file in fully expanded form
3403 %o: Output MathML file
3404 This command is used by `org-create-math-formula'.
3406 When using MathToWeb as the converter, set this to
3407 \"java -jar %j -unicode -force -df %o %I\"."
3408 :group 'org-latex
3409 :version "24.1"
3410 :type '(choice
3411 (const :tag "None" nil)
3412 (string :tag "\nShell command")))
3414 (defcustom org-latex-create-formula-image-program 'dvipng
3415 "Program to convert LaTeX fragments with.
3417 dvipng Process the LaTeX fragments to dvi file, then convert
3418 dvi files to png files using dvipng.
3419 This will also include processing of non-math environments.
3420 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3421 to convert pdf files to png files"
3422 :group 'org-latex
3423 :version "24.1"
3424 :type '(choice
3425 (const :tag "dvipng" dvipng)
3426 (const :tag "imagemagick" imagemagick)))
3428 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3429 "Path to store latex preview images. A relative path here creates many
3430 directories relative to the processed org files paths. An absolute path
3431 puts all preview images at the same place."
3432 :group 'org-latex
3433 :version "24.3"
3434 :type 'string)
3436 (defun org-format-latex-mathml-available-p ()
3437 "Return t if `org-latex-to-mathml-convert-command' is usable."
3438 (save-match-data
3439 (when (and (boundp 'org-latex-to-mathml-convert-command)
3440 org-latex-to-mathml-convert-command)
3441 (let ((executable (car (split-string
3442 org-latex-to-mathml-convert-command))))
3443 (when (executable-find executable)
3444 (if (string-match
3445 "%j" org-latex-to-mathml-convert-command)
3446 (file-readable-p org-latex-to-mathml-jar-file)
3447 t))))))
3449 (defcustom org-format-latex-header "\\documentclass{article}
3450 \\usepackage[usenames]{color}
3451 \\usepackage{amsmath}
3452 \\usepackage[mathscr]{eucal}
3453 \\pagestyle{empty} % do not remove
3454 \[PACKAGES]
3455 \[DEFAULT-PACKAGES]
3456 % The settings below are copied from fullpage.sty
3457 \\setlength{\\textwidth}{\\paperwidth}
3458 \\addtolength{\\textwidth}{-3cm}
3459 \\setlength{\\oddsidemargin}{1.5cm}
3460 \\addtolength{\\oddsidemargin}{-2.54cm}
3461 \\setlength{\\evensidemargin}{\\oddsidemargin}
3462 \\setlength{\\textheight}{\\paperheight}
3463 \\addtolength{\\textheight}{-\\headheight}
3464 \\addtolength{\\textheight}{-\\headsep}
3465 \\addtolength{\\textheight}{-\\footskip}
3466 \\addtolength{\\textheight}{-3cm}
3467 \\setlength{\\topmargin}{1.5cm}
3468 \\addtolength{\\topmargin}{-2.54cm}"
3469 "The document header used for processing LaTeX fragments.
3470 It is imperative that this header make sure that no page number
3471 appears on the page. The package defined in the variables
3472 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3473 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3474 will be appended."
3475 :group 'org-latex
3476 :type 'string)
3478 (defvar org-format-latex-header-extra nil)
3480 (defun org-set-packages-alist (var val)
3481 "Set the packages alist and make sure it has 3 elements per entry."
3482 (set var (mapcar (lambda (x)
3483 (if (and (consp x) (= (length x) 2))
3484 (list (car x) (nth 1 x) t)
3486 val)))
3488 (defun org-get-packages-alist (var)
3490 "Get the packages alist and make sure it has 3 elements per entry."
3491 (mapcar (lambda (x)
3492 (if (and (consp x) (= (length x) 2))
3493 (list (car x) (nth 1 x) t)
3495 (default-value var)))
3497 ;; The following variables are defined here because is it also used
3498 ;; when formatting latex fragments. Originally it was part of the
3499 ;; LaTeX exporter, which is why the name includes "export".
3500 (defcustom org-export-latex-default-packages-alist
3501 '(("AUTO" "inputenc" t)
3502 ("T1" "fontenc" t)
3503 ("" "fixltx2e" nil)
3504 ("" "graphicx" t)
3505 ("" "longtable" nil)
3506 ("" "float" nil)
3507 ("" "wrapfig" nil)
3508 ("" "soul" t)
3509 ("" "textcomp" t)
3510 ("" "marvosym" t)
3511 ("" "wasysym" t)
3512 ("" "latexsym" t)
3513 ("" "amssymb" t)
3514 ("" "hyperref" nil)
3515 "\\tolerance=1000"
3517 "Alist of default packages to be inserted in the header.
3518 Change this only if one of the packages here causes an incompatibility
3519 with another package you are using.
3520 The packages in this list are needed by one part or another of Org-mode
3521 to function properly.
3523 - inputenc, fontenc: for basic font and character selection
3524 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3525 for interpreting the entities in `org-entities'. You can skip some of these
3526 packages if you don't use any of the symbols in it.
3527 - graphicx: for including images
3528 - float, wrapfig: for figure placement
3529 - longtable: for long tables
3530 - hyperref: for cross references
3532 Therefore you should not modify this variable unless you know what you
3533 are doing. The one reason to change it anyway is that you might be loading
3534 some other package that conflicts with one of the default packages.
3535 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3536 If SNIPPET-FLAG is t, the package also needs to be included when
3537 compiling LaTeX snippets into images for inclusion into HTML."
3538 :group 'org-export-latex
3539 :set 'org-set-packages-alist
3540 :get 'org-get-packages-alist
3541 :version "24.1"
3542 :type '(repeat
3543 (choice
3544 (list :tag "options/package pair"
3545 (string :tag "options")
3546 (string :tag "package")
3547 (boolean :tag "Snippet"))
3548 (string :tag "A line of LaTeX"))))
3550 (defcustom org-export-latex-packages-alist nil
3551 "Alist of packages to be inserted in every LaTeX header.
3552 These will be inserted after `org-export-latex-default-packages-alist'.
3553 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3554 SNIPPET-FLAG, when t, indicates that this package is also needed when
3555 turning LaTeX snippets into images for inclusion into HTML.
3556 Make sure that you only list packages here which:
3557 - you want in every file
3558 - do not conflict with the default packages in
3559 `org-export-latex-default-packages-alist'
3560 - do not conflict with the setup in `org-format-latex-header'."
3561 :group 'org-export-latex
3562 :set 'org-set-packages-alist
3563 :get 'org-get-packages-alist
3564 :type '(repeat
3565 (choice
3566 (list :tag "options/package pair"
3567 (string :tag "options")
3568 (string :tag "package")
3569 (boolean :tag "Snippet"))
3570 (string :tag "A line of LaTeX"))))
3573 (defgroup org-appearance nil
3574 "Settings for Org-mode appearance."
3575 :tag "Org Appearance"
3576 :group 'org)
3578 (defcustom org-level-color-stars-only nil
3579 "Non-nil means fontify only the stars in each headline.
3580 When nil, the entire headline is fontified.
3581 Changing it requires restart of `font-lock-mode' to become effective
3582 also in regions already fontified."
3583 :group 'org-appearance
3584 :type 'boolean)
3586 (defcustom org-hide-leading-stars nil
3587 "Non-nil means hide the first N-1 stars in a headline.
3588 This works by using the face `org-hide' for these stars. This
3589 face is white for a light background, and black for a dark
3590 background. You may have to customize the face `org-hide' to
3591 make this work.
3592 Changing it requires restart of `font-lock-mode' to become effective
3593 also in regions already fontified.
3594 You may also set this on a per-file basis by adding one of the following
3595 lines to the buffer:
3597 #+STARTUP: hidestars
3598 #+STARTUP: showstars"
3599 :group 'org-appearance
3600 :type 'boolean)
3602 (defcustom org-hidden-keywords nil
3603 "List of symbols corresponding to keywords to be hidden the org buffer.
3604 For example, a value '(title) for this list will make the document's title
3605 appear in the buffer without the initial #+TITLE: keyword."
3606 :group 'org-appearance
3607 :version "24.1"
3608 :type '(set (const :tag "#+AUTHOR" author)
3609 (const :tag "#+DATE" date)
3610 (const :tag "#+EMAIL" email)
3611 (const :tag "#+TITLE" title)))
3613 (defcustom org-custom-properties nil
3614 "List of properties (as strings) with a special meaning.
3615 The default use of these custom properties is to let the user
3616 hide them with `org-toggle-custom-properties-visibility'."
3617 :group 'org-properties
3618 :group 'org-appearance
3619 :version "24.3"
3620 :type '(repeat (string :tag "Property Name")))
3622 (defcustom org-fontify-done-headline nil
3623 "Non-nil means change the face of a headline if it is marked DONE.
3624 Normally, only the TODO/DONE keyword indicates the state of a headline.
3625 When this is non-nil, the headline after the keyword is set to the
3626 `org-headline-done' as an additional indication."
3627 :group 'org-appearance
3628 :type 'boolean)
3630 (defcustom org-fontify-emphasized-text t
3631 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3632 Changing this variable requires a restart of Emacs to take effect."
3633 :group 'org-appearance
3634 :type 'boolean)
3636 (defcustom org-fontify-whole-heading-line nil
3637 "Non-nil means fontify the whole line for headings.
3638 This is useful when setting a background color for the
3639 org-level-* faces."
3640 :group 'org-appearance
3641 :type 'boolean)
3643 (defcustom org-highlight-latex-fragments-and-specials nil
3644 "Non-nil means fontify what is treated specially by the exporters."
3645 :group 'org-appearance
3646 :type 'boolean)
3648 (defcustom org-hide-emphasis-markers nil
3649 "Non-nil mean font-lock should hide the emphasis marker characters."
3650 :group 'org-appearance
3651 :type 'boolean)
3653 (defcustom org-pretty-entities nil
3654 "Non-nil means show entities as UTF8 characters.
3655 When nil, the \\name form remains in the buffer."
3656 :group 'org-appearance
3657 :version "24.1"
3658 :type 'boolean)
3660 (defcustom org-pretty-entities-include-sub-superscripts t
3661 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3662 :group 'org-appearance
3663 :version "24.1"
3664 :type 'boolean)
3666 (defvar org-emph-re nil
3667 "Regular expression for matching emphasis.
3668 After a match, the match groups contain these elements:
3669 0 The match of the full regular expression, including the characters
3670 before and after the proper match
3671 1 The character before the proper match, or empty at beginning of line
3672 2 The proper match, including the leading and trailing markers
3673 3 The leading marker like * or /, indicating the type of highlighting
3674 4 The text between the emphasis markers, not including the markers
3675 5 The character after the match, empty at the end of a line")
3676 (defvar org-verbatim-re nil
3677 "Regular expression for matching verbatim text.")
3678 (defvar org-emphasis-regexp-components) ; defined just below
3679 (defvar org-emphasis-alist) ; defined just below
3680 (defun org-set-emph-re (var val)
3681 "Set variable and compute the emphasis regular expression."
3682 (set var val)
3683 (when (and (boundp 'org-emphasis-alist)
3684 (boundp 'org-emphasis-regexp-components)
3685 org-emphasis-alist org-emphasis-regexp-components)
3686 (let* ((e org-emphasis-regexp-components)
3687 (pre (car e))
3688 (post (nth 1 e))
3689 (border (nth 2 e))
3690 (body (nth 3 e))
3691 (nl (nth 4 e))
3692 (body1 (concat body "*?"))
3693 (markers (mapconcat 'car org-emphasis-alist ""))
3694 (vmarkers (mapconcat
3695 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3696 org-emphasis-alist "")))
3697 ;; make sure special characters appear at the right position in the class
3698 (if (string-match "\\^" markers)
3699 (setq markers (concat (replace-match "" t t markers) "^")))
3700 (if (string-match "-" markers)
3701 (setq markers (concat (replace-match "" t t markers) "-")))
3702 (if (string-match "\\^" vmarkers)
3703 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3704 (if (string-match "-" vmarkers)
3705 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3706 (if (> nl 0)
3707 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3708 (int-to-string nl) "\\}")))
3709 ;; Make the regexp
3710 (setq org-emph-re
3711 (concat "\\([" pre "]\\|^\\)"
3712 "\\("
3713 "\\([" markers "]\\)"
3714 "\\("
3715 "[^" border "]\\|"
3716 "[^" border "]"
3717 body1
3718 "[^" border "]"
3719 "\\)"
3720 "\\3\\)"
3721 "\\([" post "]\\|$\\)"))
3722 (setq org-verbatim-re
3723 (concat "\\([" pre "]\\|^\\)"
3724 "\\("
3725 "\\([" vmarkers "]\\)"
3726 "\\("
3727 "[^" border "]\\|"
3728 "[^" border "]"
3729 body1
3730 "[^" border "]"
3731 "\\)"
3732 "\\3\\)"
3733 "\\([" post "]\\|$\\)")))))
3735 (defcustom org-emphasis-regexp-components
3736 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3737 "Components used to build the regular expression for emphasis.
3738 This is a list with five entries. Terminology: In an emphasis string
3739 like \" *strong word* \", we call the initial space PREMATCH, the final
3740 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3741 and \"trong wor\" is the body. The different components in this variable
3742 specify what is allowed/forbidden in each part:
3744 pre Chars allowed as prematch. Beginning of line will be allowed too.
3745 post Chars allowed as postmatch. End of line will be allowed too.
3746 border The chars *forbidden* as border characters.
3747 body-regexp A regexp like \".\" to match a body character. Don't use
3748 non-shy groups here, and don't allow newline here.
3749 newline The maximum number of newlines allowed in an emphasis exp.
3751 Use customize to modify this, or restart Emacs after changing it."
3752 :group 'org-appearance
3753 :set 'org-set-emph-re
3754 :type '(list
3755 (sexp :tag "Allowed chars in pre ")
3756 (sexp :tag "Allowed chars in post ")
3757 (sexp :tag "Forbidden chars in border ")
3758 (sexp :tag "Regexp for body ")
3759 (integer :tag "number of newlines allowed")
3760 (option (boolean :tag "Please ignore this button"))))
3762 (defcustom org-emphasis-alist
3763 `(("*" bold "<b>" "</b>")
3764 ("/" italic "<i>" "</i>")
3765 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3766 ("=" org-code "<code>" "</code>" verbatim)
3767 ("~" org-verbatim "<code>" "</code>" verbatim)
3768 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3769 "<del>" "</del>")
3771 "Special syntax for emphasized text.
3772 Text starting and ending with a special character will be emphasized, for
3773 example *bold*, _underlined_ and /italic/. This variable sets the marker
3774 characters, the face to be used by font-lock for highlighting in Org-mode
3775 Emacs buffers, and the HTML tags to be used for this.
3776 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3777 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3778 Use customize to modify this, or restart Emacs after changing it."
3779 :group 'org-appearance
3780 :set 'org-set-emph-re
3781 :type '(repeat
3782 (list
3783 (string :tag "Marker character")
3784 (choice
3785 (face :tag "Font-lock-face")
3786 (plist :tag "Face property list"))
3787 (string :tag "HTML start tag")
3788 (string :tag "HTML end tag")
3789 (option (const verbatim)))))
3791 (defvar org-protecting-blocks
3792 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3793 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3794 This is needed for font-lock setup.")
3796 ;;; Miscellaneous options
3798 (defgroup org-completion nil
3799 "Completion in Org-mode."
3800 :tag "Org Completion"
3801 :group 'org)
3803 (defcustom org-completion-use-ido nil
3804 "Non-nil means use ido completion wherever possible.
3805 Note that `ido-mode' must be active for this variable to be relevant.
3806 If you decide to turn this variable on, you might well want to turn off
3807 `org-outline-path-complete-in-steps'.
3808 See also `org-completion-use-iswitchb'."
3809 :group 'org-completion
3810 :type 'boolean)
3812 (defcustom org-completion-use-iswitchb nil
3813 "Non-nil means use iswitchb completion wherever possible.
3814 Note that `iswitchb-mode' must be active for this variable to be relevant.
3815 If you decide to turn this variable on, you might well want to turn off
3816 `org-outline-path-complete-in-steps'.
3817 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3818 :group 'org-completion
3819 :type 'boolean)
3821 (defcustom org-completion-fallback-command 'hippie-expand
3822 "The expansion command called by \\[pcomplete] in normal context.
3823 Normal means, no org-mode-specific context."
3824 :group 'org-completion
3825 :type 'function)
3827 ;;; Functions and variables from their packages
3828 ;; Declared here to avoid compiler warnings
3830 ;; XEmacs only
3831 (defvar outline-mode-menu-heading)
3832 (defvar outline-mode-menu-show)
3833 (defvar outline-mode-menu-hide)
3834 (defvar zmacs-regions) ; XEmacs regions
3836 ;; Emacs only
3837 (defvar mark-active)
3839 ;; Various packages
3840 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3841 (declare-function calendar-forward-day "cal-move" (arg))
3842 (declare-function calendar-goto-date "cal-move" (date))
3843 (declare-function calendar-goto-today "cal-move" ())
3844 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3845 (defvar calc-embedded-close-formula)
3846 (defvar calc-embedded-open-formula)
3847 (declare-function cdlatex-tab "ext:cdlatex" ())
3848 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3849 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3850 (defvar font-lock-unfontify-region-function)
3851 (declare-function iswitchb-read-buffer "iswitchb"
3852 (prompt &optional default require-match start matches-set))
3853 (defvar iswitchb-temp-buflist)
3854 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3855 (defvar org-agenda-tags-todo-honor-ignore-options)
3856 (declare-function org-agenda-skip "org-agenda" ())
3857 (declare-function
3858 org-agenda-format-item "org-agenda"
3859 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3860 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3861 (declare-function org-agenda-change-all-lines "org-agenda"
3862 (newhead hdmarker &optional fixface just-this))
3863 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3864 (declare-function org-agenda-maybe-redo "org-agenda" ())
3865 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3866 (beg end))
3867 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3868 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3869 "org-agenda" (&optional end))
3870 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3871 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3872 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3873 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3874 (declare-function org-indent-mode "org-indent" (&optional arg))
3875 (declare-function parse-time-string "parse-time" (string))
3876 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3877 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3878 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3879 (defvar remember-data-file)
3880 (defvar texmathp-why)
3881 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3882 (declare-function table--at-cell-p "table" (position &optional object at-column))
3884 (defvar w3m-current-url)
3885 (defvar w3m-current-title)
3887 (defvar org-latex-regexps)
3889 ;;; Autoload and prepare some org modules
3891 ;; Some table stuff that needs to be defined here, because it is used
3892 ;; by the functions setting up org-mode or checking for table context.
3894 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3895 "Detect an org-type or table-type table.")
3896 (defconst org-table-line-regexp "^[ \t]*|"
3897 "Detect an org-type table line.")
3898 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3899 "Detect an org-type table line.")
3900 (defconst org-table-hline-regexp "^[ \t]*|-"
3901 "Detect an org-type table hline.")
3902 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3903 "Detect a table-type table hline.")
3904 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3905 "Detect the first line outside a table when searching from within it.
3906 This works for both table types.")
3908 ;; Autoload the functions in org-table.el that are needed by functions here.
3910 (eval-and-compile
3911 (org-autoload "org-table"
3912 '(org-table-begin org-table-blank-field org-table-end)))
3914 ;;;###autoload
3915 (defun turn-on-orgtbl ()
3916 "Unconditionally turn on `orgtbl-mode'."
3917 (require 'org-table)
3918 (orgtbl-mode 1))
3920 (defun org-at-table-p (&optional table-type)
3921 "Return t if the cursor is inside an org-type table.
3922 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3923 (if org-enable-table-editor
3924 (save-excursion
3925 (beginning-of-line 1)
3926 (looking-at (if table-type org-table-any-line-regexp
3927 org-table-line-regexp)))
3928 nil))
3929 (defsubst org-table-p () (org-at-table-p))
3931 (defun org-at-table.el-p ()
3932 "Return t if and only if we are at a table.el table."
3933 (and (org-at-table-p 'any)
3934 (save-excursion
3935 (goto-char (org-table-begin 'any))
3936 (looking-at org-table1-hline-regexp))))
3937 (defun org-table-recognize-table.el ()
3938 "If there is a table.el table nearby, recognize it and move into it."
3939 (if org-table-tab-recognizes-table.el
3940 (if (org-at-table.el-p)
3941 (progn
3942 (beginning-of-line 1)
3943 (if (looking-at org-table-dataline-regexp)
3945 (if (looking-at org-table1-hline-regexp)
3946 (progn
3947 (beginning-of-line 2)
3948 (if (looking-at org-table-any-border-regexp)
3949 (beginning-of-line -1)))))
3950 (if (re-search-forward "|" (org-table-end t) t)
3951 (progn
3952 (require 'table)
3953 (if (table--at-cell-p (point))
3955 (message "recognizing table.el table...")
3956 (table-recognize-table)
3957 (message "recognizing table.el table...done")))
3958 (error "This should not happen"))
3960 nil)
3961 nil))
3963 (defun org-at-table-hline-p ()
3964 "Return t if the cursor is inside a hline in a table."
3965 (if org-enable-table-editor
3966 (save-excursion
3967 (beginning-of-line 1)
3968 (looking-at org-table-hline-regexp))
3969 nil))
3971 (defvar org-table-clean-did-remove-column nil)
3973 (defun org-table-map-tables (function &optional quietly)
3974 "Apply FUNCTION to the start of all tables in the buffer."
3975 (save-excursion
3976 (save-restriction
3977 (widen)
3978 (goto-char (point-min))
3979 (while (re-search-forward org-table-any-line-regexp nil t)
3980 (unless quietly
3981 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3982 (beginning-of-line 1)
3983 (when (and (looking-at org-table-line-regexp)
3984 ;; Exclude tables in src/example/verbatim/clocktable blocks
3985 (not (org-in-block-p '("src" "example"))))
3986 (save-excursion (funcall function))
3987 (or (looking-at org-table-line-regexp)
3988 (forward-char 1)))
3989 (re-search-forward org-table-any-border-regexp nil 1))))
3990 (unless quietly (message "Mapping tables: done")))
3992 ;; Declare and autoload functions from org-exp.el & Co
3994 (declare-function org-default-export-plist "org-exp")
3995 (declare-function org-infile-export-plist "org-exp")
3996 (declare-function org-get-current-options "org-exp")
3998 ;; Declare and autoload functions from org-agenda.el
4000 (eval-and-compile
4001 (org-autoload "org-agenda"
4002 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4004 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4005 (declare-function org-clock-update-mode-line "org-clock" ())
4006 (declare-function org-resolve-clocks "org-clock"
4007 (&optional also-non-dangling-p prompt last-valid))
4008 (defvar org-clock-start-time)
4009 (defvar org-clock-marker (make-marker)
4010 "Marker recording the last clock-in.")
4011 (defvar org-clock-hd-marker (make-marker)
4012 "Marker recording the last clock-in, but the headline position.")
4013 (defvar org-clock-heading ""
4014 "The heading of the current clock entry.")
4015 (defun org-clock-is-active ()
4016 "Return non-nil if clock is currently running.
4017 The return value is actually the clock marker."
4018 (marker-buffer org-clock-marker))
4020 (eval-and-compile
4021 (org-autoload "org-clock" '(org-clock-remove-overlays
4022 org-clock-update-time-maybe
4023 org-clocktable-shift)))
4025 (defun org-check-running-clock ()
4026 "Check if the current buffer contains the running clock.
4027 If yes, offer to stop it and to save the buffer with the changes."
4028 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4029 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4030 (buffer-name))))
4031 (org-clock-out)
4032 (when (y-or-n-p "Save changed buffer?")
4033 (save-buffer))))
4035 (defun org-clocktable-try-shift (dir n)
4036 "Check if this line starts a clock table, if yes, shift the time block."
4037 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4038 (org-clocktable-shift dir n)))
4040 ;;;###autoload
4041 (defun org-clock-persistence-insinuate ()
4042 "Set up hooks for clock persistence."
4043 (require 'org-clock)
4044 (add-hook 'org-mode-hook 'org-clock-load)
4045 (add-hook 'kill-emacs-hook 'org-clock-save))
4047 ;; Define the variable already here, to make sure we have it.
4048 (defvar org-indent-mode nil
4049 "Non-nil if Org-Indent mode is enabled.
4050 Use the command `org-indent-mode' to change this variable.")
4052 ;; Autoload archiving code
4053 ;; The stuff that is needed for cycling and tags has to be defined here.
4055 (defgroup org-archive nil
4056 "Options concerning archiving in Org-mode."
4057 :tag "Org Archive"
4058 :group 'org-structure)
4060 (defcustom org-archive-location "%s_archive::"
4061 "The location where subtrees should be archived.
4063 The value of this variable is a string, consisting of two parts,
4064 separated by a double-colon. The first part is a filename and
4065 the second part is a headline.
4067 When the filename is omitted, archiving happens in the same file.
4068 %s in the filename will be replaced by the current file
4069 name (without the directory part). Archiving to a different file
4070 is useful to keep archived entries from contributing to the
4071 Org-mode Agenda.
4073 The archived entries will be filed as subtrees of the specified
4074 headline. When the headline is omitted, the subtrees are simply
4075 filed away at the end of the file, as top-level entries. Also in
4076 the heading you can use %s to represent the file name, this can be
4077 useful when using the same archive for a number of different files.
4079 Here are a few examples:
4080 \"%s_archive::\"
4081 If the current file is Projects.org, archive in file
4082 Projects.org_archive, as top-level trees. This is the default.
4084 \"::* Archived Tasks\"
4085 Archive in the current file, under the top-level headline
4086 \"* Archived Tasks\".
4088 \"~/org/archive.org::\"
4089 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4091 \"~/org/archive.org::* From %s\"
4092 Archive in file ~/org/archive.org (absolute path), under headlines
4093 \"From FILENAME\" where file name is the current file name.
4095 \"~/org/datetree.org::datetree/* Finished Tasks\"
4096 The \"datetree/\" string is special, signifying to archive
4097 items to the datetree. Items are placed in either the CLOSED
4098 date of the item, or the current date if there is no CLOSED date.
4099 The heading will be a subentry to the current date. There doesn't
4100 need to be a heading, but there always needs to be a slash after
4101 datetree. For example, to store archived items directly in the
4102 datetree, use \"~/org/datetree.org::datetree/\".
4104 \"basement::** Finished Tasks\"
4105 Archive in file ./basement (relative path), as level 3 trees
4106 below the level 2 heading \"** Finished Tasks\".
4108 You may set this option on a per-file basis by adding to the buffer a
4109 line like
4111 #+ARCHIVE: basement::** Finished Tasks
4113 You may also define it locally for a subtree by setting an ARCHIVE property
4114 in the entry. If such a property is found in an entry, or anywhere up
4115 the hierarchy, it will be used."
4116 :group 'org-archive
4117 :type 'string)
4119 (defcustom org-archive-tag "ARCHIVE"
4120 "The tag that marks a subtree as archived.
4121 An archived subtree does not open during visibility cycling, and does
4122 not contribute to the agenda listings.
4123 After changing this, font-lock must be restarted in the relevant buffers to
4124 get the proper fontification."
4125 :group 'org-archive
4126 :group 'org-keywords
4127 :type 'string)
4129 (defcustom org-agenda-skip-archived-trees t
4130 "Non-nil means the agenda will skip any items located in archived trees.
4131 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4132 variable is no longer recommended, you should leave it at the value t.
4133 Instead, use the key `v' to cycle the archives-mode in the agenda."
4134 :group 'org-archive
4135 :group 'org-agenda-skip
4136 :type 'boolean)
4138 (defcustom org-columns-skip-archived-trees t
4139 "Non-nil means ignore archived trees when creating column view."
4140 :group 'org-archive
4141 :group 'org-properties
4142 :type 'boolean)
4144 (defcustom org-cycle-open-archived-trees nil
4145 "Non-nil means `org-cycle' will open archived trees.
4146 An archived tree is a tree marked with the tag ARCHIVE.
4147 When nil, archived trees will stay folded. You can still open them with
4148 normal outline commands like `show-all', but not with the cycling commands."
4149 :group 'org-archive
4150 :group 'org-cycle
4151 :type 'boolean)
4153 (defcustom org-sparse-tree-open-archived-trees nil
4154 "Non-nil means sparse tree construction shows matches in archived trees.
4155 When nil, matches in these trees are highlighted, but the trees are kept in
4156 collapsed state."
4157 :group 'org-archive
4158 :group 'org-sparse-trees
4159 :type 'boolean)
4161 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4162 "The default date type when building a sparse tree.
4163 When this is nil, a date is a scheduled or a deadline timestamp.
4164 Otherwise, these types are allowed:
4166 all: all timestamps
4167 active: only active timestamps (<...>)
4168 inactive: only inactive timestamps (<...)
4169 scheduled: only scheduled timestamps
4170 deadline: only deadline timestamps"
4171 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4172 (const :tag "All timestamps" all)
4173 (const :tag "Only active timestamps" active)
4174 (const :tag "Only inactive timestamps" inactive)
4175 (const :tag "Only scheduled timestamps" scheduled)
4176 (const :tag "Only deadline timestamps" deadline))
4177 :version "24.3"
4178 :group 'org-sparse-trees)
4180 (defun org-cycle-hide-archived-subtrees (state)
4181 "Re-hide all archived subtrees after a visibility state change."
4182 (when (and (not org-cycle-open-archived-trees)
4183 (not (memq state '(overview folded))))
4184 (save-excursion
4185 (let* ((globalp (memq state '(contents all)))
4186 (beg (if globalp (point-min) (point)))
4187 (end (if globalp (point-max) (org-end-of-subtree t))))
4188 (org-hide-archived-subtrees beg end)
4189 (goto-char beg)
4190 (if (looking-at (concat ".*:" org-archive-tag ":"))
4191 (message "%s" (substitute-command-keys
4192 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4194 (defun org-force-cycle-archived ()
4195 "Cycle subtree even if it is archived."
4196 (interactive)
4197 (setq this-command 'org-cycle)
4198 (let ((org-cycle-open-archived-trees t))
4199 (call-interactively 'org-cycle)))
4201 (defun org-hide-archived-subtrees (beg end)
4202 "Re-hide all archived subtrees after a visibility state change."
4203 (save-excursion
4204 (let* ((re (concat ":" org-archive-tag ":")))
4205 (goto-char beg)
4206 (while (re-search-forward re end t)
4207 (when (org-at-heading-p)
4208 (org-flag-subtree t)
4209 (org-end-of-subtree t))))))
4211 (declare-function outline-end-of-heading "outline" ())
4212 (declare-function outline-flag-region "outline" (from to flag))
4213 (defun org-flag-subtree (flag)
4214 (save-excursion
4215 (org-back-to-heading t)
4216 (outline-end-of-heading)
4217 (outline-flag-region (point)
4218 (progn (org-end-of-subtree t) (point))
4219 flag)))
4221 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4223 (eval-and-compile
4224 (org-autoload "org-archive"
4225 '(org-add-archive-files)))
4227 ;; Autoload Column View Code
4229 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4230 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4231 (declare-function org-columns-compute "org-colview" (property))
4233 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4234 '(org-columns-number-to-string
4235 org-columns-get-format-and-top-level
4236 org-columns-compute
4237 org-columns-remove-overlays))
4239 ;; Autoload ID code
4241 (declare-function org-id-store-link "org-id")
4242 (declare-function org-id-locations-load "org-id")
4243 (declare-function org-id-locations-save "org-id")
4244 (defvar org-id-track-globally)
4245 (org-autoload "org-id"
4246 '(org-id-new
4247 org-id-copy
4248 org-id-get-with-outline-path-completion
4249 org-id-get-with-outline-drilling))
4251 ;;; Variables for pre-computed regular expressions, all buffer local
4253 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4254 "Matches first line of a hidden block.")
4255 (make-variable-buffer-local 'org-drawer-regexp)
4256 (defvar org-todo-regexp nil
4257 "Matches any of the TODO state keywords.")
4258 (make-variable-buffer-local 'org-todo-regexp)
4259 (defvar org-not-done-regexp nil
4260 "Matches any of the TODO state keywords except the last one.")
4261 (make-variable-buffer-local 'org-not-done-regexp)
4262 (defvar org-not-done-heading-regexp nil
4263 "Matches a TODO headline that is not done.")
4264 (make-variable-buffer-local 'org-not-done-regexp)
4265 (defvar org-todo-line-regexp nil
4266 "Matches a headline and puts TODO state into group 2 if present.")
4267 (make-variable-buffer-local 'org-todo-line-regexp)
4268 (defvar org-complex-heading-regexp nil
4269 "Matches a headline and puts everything into groups:
4270 group 1: the stars
4271 group 2: The todo keyword, maybe
4272 group 3: Priority cookie
4273 group 4: True headline
4274 group 5: Tags")
4275 (make-variable-buffer-local 'org-complex-heading-regexp)
4276 (defvar org-complex-heading-regexp-format nil
4277 "Printf format to make regexp to match an exact headline.
4278 This regexp will match the headline of any node which has the
4279 exact headline text that is put into the format, but may have any
4280 TODO state, priority and tags.")
4281 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4282 (defvar org-todo-line-tags-regexp nil
4283 "Matches a headline and puts TODO state into group 2 if present.
4284 Also put tags into group 4 if tags are present.")
4285 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4286 (defvar org-ds-keyword-length 12
4287 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4288 (make-variable-buffer-local 'org-ds-keyword-length)
4289 (defvar org-deadline-regexp nil
4290 "Matches the DEADLINE keyword.")
4291 (make-variable-buffer-local 'org-deadline-regexp)
4292 (defvar org-deadline-time-regexp nil
4293 "Matches the DEADLINE keyword together with a time stamp.")
4294 (make-variable-buffer-local 'org-deadline-time-regexp)
4295 (defvar org-deadline-line-regexp nil
4296 "Matches the DEADLINE keyword and the rest of the line.")
4297 (make-variable-buffer-local 'org-deadline-line-regexp)
4298 (defvar org-scheduled-regexp nil
4299 "Matches the SCHEDULED keyword.")
4300 (make-variable-buffer-local 'org-scheduled-regexp)
4301 (defvar org-scheduled-time-regexp nil
4302 "Matches the SCHEDULED keyword together with a time stamp.")
4303 (make-variable-buffer-local 'org-scheduled-time-regexp)
4304 (defvar org-closed-time-regexp nil
4305 "Matches the CLOSED keyword together with a time stamp.")
4306 (make-variable-buffer-local 'org-closed-time-regexp)
4308 (defvar org-keyword-time-regexp nil
4309 "Matches any of the 4 keywords, together with the time stamp.")
4310 (make-variable-buffer-local 'org-keyword-time-regexp)
4311 (defvar org-keyword-time-not-clock-regexp nil
4312 "Matches any of the 3 keywords, together with the time stamp.")
4313 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4314 (defvar org-maybe-keyword-time-regexp nil
4315 "Matches a timestamp, possibly preceded by a keyword.")
4316 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4317 (defvar org-all-time-keywords nil
4318 "List of time keywords.")
4319 (make-variable-buffer-local 'org-all-time-keywords)
4321 (defconst org-plain-time-of-day-regexp
4322 (concat
4323 "\\(\\<[012]?[0-9]"
4324 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4325 "\\(--?"
4326 "\\(\\<[012]?[0-9]"
4327 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4328 "\\)?")
4329 "Regular expression to match a plain time or time range.
4330 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4331 groups carry important information:
4332 0 the full match
4333 1 the first time, range or not
4334 8 the second time, if it is a range.")
4336 (defconst org-plain-time-extension-regexp
4337 (concat
4338 "\\(\\<[012]?[0-9]"
4339 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4340 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4341 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4342 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4343 groups carry important information:
4344 0 the full match
4345 7 hours of duration
4346 9 minutes of duration")
4348 (defconst org-stamp-time-of-day-regexp
4349 (concat
4350 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4351 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4352 "\\(--?"
4353 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4354 "Regular expression to match a timestamp time or time range.
4355 After a match, the following groups carry important information:
4356 0 the full match
4357 1 date plus weekday, for back referencing to make sure both times are on the same day
4358 2 the first time, range or not
4359 4 the second time, if it is a range.")
4361 (defconst org-startup-options
4362 '(("fold" org-startup-folded t)
4363 ("overview" org-startup-folded t)
4364 ("nofold" org-startup-folded nil)
4365 ("showall" org-startup-folded nil)
4366 ("showeverything" org-startup-folded showeverything)
4367 ("content" org-startup-folded content)
4368 ("indent" org-startup-indented t)
4369 ("noindent" org-startup-indented nil)
4370 ("hidestars" org-hide-leading-stars t)
4371 ("showstars" org-hide-leading-stars nil)
4372 ("odd" org-odd-levels-only t)
4373 ("oddeven" org-odd-levels-only nil)
4374 ("align" org-startup-align-all-tables t)
4375 ("noalign" org-startup-align-all-tables nil)
4376 ("inlineimages" org-startup-with-inline-images t)
4377 ("noinlineimages" org-startup-with-inline-images nil)
4378 ("customtime" org-display-custom-times t)
4379 ("logdone" org-log-done time)
4380 ("lognotedone" org-log-done note)
4381 ("nologdone" org-log-done nil)
4382 ("lognoteclock-out" org-log-note-clock-out t)
4383 ("nolognoteclock-out" org-log-note-clock-out nil)
4384 ("logrepeat" org-log-repeat state)
4385 ("lognoterepeat" org-log-repeat note)
4386 ("nologrepeat" org-log-repeat nil)
4387 ("logreschedule" org-log-reschedule time)
4388 ("lognotereschedule" org-log-reschedule note)
4389 ("nologreschedule" org-log-reschedule nil)
4390 ("logredeadline" org-log-redeadline time)
4391 ("lognoteredeadline" org-log-redeadline note)
4392 ("nologredeadline" org-log-redeadline nil)
4393 ("logrefile" org-log-refile time)
4394 ("lognoterefile" org-log-refile note)
4395 ("nologrefile" org-log-refile nil)
4396 ("fninline" org-footnote-define-inline t)
4397 ("nofninline" org-footnote-define-inline nil)
4398 ("fnlocal" org-footnote-section nil)
4399 ("fnauto" org-footnote-auto-label t)
4400 ("fnprompt" org-footnote-auto-label nil)
4401 ("fnconfirm" org-footnote-auto-label confirm)
4402 ("fnplain" org-footnote-auto-label plain)
4403 ("fnadjust" org-footnote-auto-adjust t)
4404 ("nofnadjust" org-footnote-auto-adjust nil)
4405 ("constcgs" constants-unit-system cgs)
4406 ("constSI" constants-unit-system SI)
4407 ("noptag" org-tag-persistent-alist nil)
4408 ("hideblocks" org-hide-block-startup t)
4409 ("nohideblocks" org-hide-block-startup nil)
4410 ("beamer" org-startup-with-beamer-mode t)
4411 ("entitiespretty" org-pretty-entities t)
4412 ("entitiesplain" org-pretty-entities nil))
4413 "Variable associated with STARTUP options for org-mode.
4414 Each element is a list of three items: the startup options (as written
4415 in the #+STARTUP line), the corresponding variable, and the value to set
4416 this variable to if the option is found. An optional forth element PUSH
4417 means to push this value onto the list in the variable.")
4419 (defun org-update-property-plist (key val props)
4420 "Update PROPS with KEY and VAL."
4421 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4422 (key (if appending (substring key 0 (- (length key) 1)) key))
4423 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4424 (previous (cdr (assoc key props))))
4425 (if appending
4426 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4427 (cons (cons key val) remainder))))
4429 (defconst org-block-regexp
4430 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4431 "Regular expression for hiding blocks.")
4432 (defconst org-heading-keyword-regexp-format
4433 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4434 "Printf format for a regexp matching an headline with some keyword.
4435 This regexp will match the headline of any node which has the
4436 exact keyword that is put into the format. The keyword isn't in
4437 any group by default, but the stars and the body are.")
4438 (defconst org-heading-keyword-maybe-regexp-format
4439 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4440 "Printf format for a regexp matching an headline, possibly with some keyword.
4441 This regexp can match any headline with the specified keyword, or
4442 without a keyword. The keyword isn't in any group by default,
4443 but the stars and the body are.")
4445 (defun org-set-regexps-and-options ()
4446 "Precompute regular expressions for current buffer."
4447 (when (derived-mode-p 'org-mode)
4448 (org-set-local 'org-todo-kwd-alist nil)
4449 (org-set-local 'org-todo-key-alist nil)
4450 (org-set-local 'org-todo-key-trigger nil)
4451 (org-set-local 'org-todo-keywords-1 nil)
4452 (org-set-local 'org-done-keywords nil)
4453 (org-set-local 'org-todo-heads nil)
4454 (org-set-local 'org-todo-sets nil)
4455 (org-set-local 'org-todo-log-states nil)
4456 (org-set-local 'org-file-properties nil)
4457 (org-set-local 'org-file-tags nil)
4458 (let ((re (org-make-options-regexp
4459 '("CATEGORY" "TODO" "COLUMNS"
4460 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4461 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4462 "OPTIONS")
4463 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4464 (splitre "[ \t]+")
4465 (scripts org-use-sub-superscripts)
4466 kwds kws0 kwsa key log value cat arch tags const links hw dws
4467 tail sep kws1 prio props ftags drawers beamer-p
4468 ext-setup-or-nil setup-contents (start 0))
4469 (save-excursion
4470 (save-restriction
4471 (widen)
4472 (goto-char (point-min))
4473 (while (or (and ext-setup-or-nil
4474 (string-match re ext-setup-or-nil start)
4475 (setq start (match-end 0)))
4476 (and (setq ext-setup-or-nil nil start 0)
4477 (re-search-forward re nil t)))
4478 (setq key (upcase (match-string 1 ext-setup-or-nil))
4479 value (org-match-string-no-properties 2 ext-setup-or-nil))
4480 (if (stringp value) (setq value (org-trim value)))
4481 (cond
4482 ((equal key "CATEGORY")
4483 (setq cat value))
4484 ((member key '("SEQ_TODO" "TODO"))
4485 (push (cons 'sequence (org-split-string value splitre)) kwds))
4486 ((equal key "TYP_TODO")
4487 (push (cons 'type (org-split-string value splitre)) kwds))
4488 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4489 ;; general TODO-like setup
4490 (push (cons (intern (downcase (match-string 1 key)))
4491 (org-split-string value splitre)) kwds))
4492 ((equal key "TAGS")
4493 (setq tags (append tags (if tags '("\\n") nil)
4494 (org-split-string value splitre))))
4495 ((equal key "COLUMNS")
4496 (org-set-local 'org-columns-default-format value))
4497 ((equal key "LINK")
4498 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4499 (push (cons (match-string 1 value)
4500 (org-trim (match-string 2 value)))
4501 links)))
4502 ((equal key "PRIORITIES")
4503 (setq prio (org-split-string value " +")))
4504 ((equal key "PROPERTY")
4505 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4506 (setq props (org-update-property-plist (match-string 1 value)
4507 (match-string 2 value)
4508 props))))
4509 ((equal key "FILETAGS")
4510 (when (string-match "\\S-" value)
4511 (setq ftags
4512 (append
4513 ftags
4514 (apply 'append
4515 (mapcar (lambda (x) (org-split-string x ":"))
4516 (org-split-string value)))))))
4517 ((equal key "DRAWERS")
4518 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4519 ((equal key "CONSTANTS")
4520 (setq const (append const (org-split-string value splitre))))
4521 ((equal key "STARTUP")
4522 (let ((opts (org-split-string value splitre))
4523 l var val)
4524 (while (setq l (pop opts))
4525 (when (setq l (assoc l org-startup-options))
4526 (setq var (nth 1 l) val (nth 2 l))
4527 (if (not (nth 3 l))
4528 (set (make-local-variable var) val)
4529 (if (not (listp (symbol-value var)))
4530 (set (make-local-variable var) nil))
4531 (set (make-local-variable var) (symbol-value var))
4532 (add-to-list var val))))))
4533 ((equal key "ARCHIVE")
4534 (setq arch value)
4535 (remove-text-properties 0 (length arch)
4536 '(face t fontified t) arch))
4537 ((equal key "LATEX_CLASS")
4538 (setq beamer-p (equal value "beamer")))
4539 ((equal key "OPTIONS")
4540 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4541 (setq scripts (read (match-string 2 value)))))
4542 ((equal key "SETUPFILE")
4543 (setq setup-contents (org-file-contents
4544 (expand-file-name
4545 (org-remove-double-quotes value))
4546 'noerror))
4547 (if (not ext-setup-or-nil)
4548 (setq ext-setup-or-nil setup-contents start 0)
4549 (setq ext-setup-or-nil
4550 (concat (substring ext-setup-or-nil 0 start)
4551 "\n" setup-contents "\n"
4552 (substring ext-setup-or-nil start)))))))
4553 ;; search for property blocks
4554 (goto-char (point-min))
4555 (while (re-search-forward org-block-regexp nil t)
4556 (when (equal "PROPERTY" (upcase (match-string 1)))
4557 (setq value (replace-regexp-in-string
4558 "[\n\r]" " " (match-string 4)))
4559 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4560 (setq props (org-update-property-plist (match-string 1 value)
4561 (match-string 2 value)
4562 props)))))))
4563 (org-set-local 'org-use-sub-superscripts scripts)
4564 (when cat
4565 (org-set-local 'org-category (intern cat))
4566 (push (cons "CATEGORY" cat) props))
4567 (when prio
4568 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4569 (setq prio (mapcar 'string-to-char prio))
4570 (org-set-local 'org-highest-priority (nth 0 prio))
4571 (org-set-local 'org-lowest-priority (nth 1 prio))
4572 (org-set-local 'org-default-priority (nth 2 prio)))
4573 (and props (org-set-local 'org-file-properties (nreverse props)))
4574 (and ftags (org-set-local 'org-file-tags
4575 (mapcar 'org-add-prop-inherited ftags)))
4576 (and drawers (org-set-local 'org-drawers drawers))
4577 (and arch (org-set-local 'org-archive-location arch))
4578 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4579 ;; Process the TODO keywords
4580 (unless kwds
4581 ;; Use the global values as if they had been given locally.
4582 (setq kwds (default-value 'org-todo-keywords))
4583 (if (stringp (car kwds))
4584 (setq kwds (list (cons org-todo-interpretation
4585 (default-value 'org-todo-keywords)))))
4586 (setq kwds (reverse kwds)))
4587 (setq kwds (nreverse kwds))
4588 (let (inter kws kw)
4589 (while (setq kws (pop kwds))
4590 (let ((kws (or
4591 (run-hook-with-args-until-success
4592 'org-todo-setup-filter-hook kws)
4593 kws)))
4594 (setq inter (pop kws) sep (member "|" kws)
4595 kws0 (delete "|" (copy-sequence kws))
4596 kwsa nil
4597 kws1 (mapcar
4598 (lambda (x)
4599 ;; 1 2
4600 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4601 (progn
4602 (setq kw (match-string 1 x)
4603 key (and (match-end 2) (match-string 2 x))
4604 log (org-extract-log-state-settings x))
4605 (push (cons kw (and key (string-to-char key))) kwsa)
4606 (and log (push log org-todo-log-states))
4608 (error "Invalid TODO keyword %s" x)))
4609 kws0)
4610 kwsa (if kwsa (append '((:startgroup))
4611 (nreverse kwsa)
4612 '((:endgroup))))
4613 hw (car kws1)
4614 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4615 tail (list inter hw (car dws) (org-last dws))))
4616 (add-to-list 'org-todo-heads hw 'append)
4617 (push kws1 org-todo-sets)
4618 (setq org-done-keywords (append org-done-keywords dws nil))
4619 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4620 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4621 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4622 (setq org-todo-sets (nreverse org-todo-sets)
4623 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4624 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4625 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4626 ;; Process the constants
4627 (when const
4628 (let (e cst)
4629 (while (setq e (pop const))
4630 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4631 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4632 (setq org-table-formula-constants-local cst)))
4634 ;; Process the tags.
4635 (when tags
4636 (let (e tgs)
4637 (while (setq e (pop tags))
4638 (cond
4639 ((equal e "{") (push '(:startgroup) tgs))
4640 ((equal e "}") (push '(:endgroup) tgs))
4641 ((equal e "\\n") (push '(:newline) tgs))
4642 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4643 (push (cons (match-string 1 e)
4644 (string-to-char (match-string 2 e)))
4645 tgs))
4646 (t (push (list e) tgs))))
4647 (org-set-local 'org-tag-alist nil)
4648 (while (setq e (pop tgs))
4649 (or (and (stringp (car e))
4650 (assoc (car e) org-tag-alist))
4651 (push e org-tag-alist)))))
4653 ;; Compute the regular expressions and other local variables.
4654 ;; Using `org-outline-regexp-bol' would complicate them much,
4655 ;; because of the fixed white space at the end of that string.
4656 (if (not org-done-keywords)
4657 (setq org-done-keywords (and org-todo-keywords-1
4658 (list (org-last org-todo-keywords-1)))))
4659 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4660 (length org-scheduled-string)
4661 (length org-clock-string)
4662 (length org-closed-string)))
4663 org-drawer-regexp
4664 (concat "^[ \t]*:\\("
4665 (mapconcat 'regexp-quote org-drawers "\\|")
4666 "\\):[ \t]*$")
4667 org-not-done-keywords
4668 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4669 org-todo-regexp
4670 (concat "\\("
4671 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4672 "\\)")
4673 org-not-done-regexp
4674 (concat "\\("
4675 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4676 "\\)")
4677 org-not-done-heading-regexp
4678 (format org-heading-keyword-regexp-format org-not-done-regexp)
4679 org-todo-line-regexp
4680 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4681 org-complex-heading-regexp
4682 (concat "^\\(\\*+\\)"
4683 "\\(?: +" org-todo-regexp "\\)?"
4684 "\\(?: +\\(\\[#.\\]\\)\\)?"
4685 "\\(?: +\\(.*?\\)\\)??"
4686 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4687 "[ \t]*$")
4688 org-complex-heading-regexp-format
4689 (concat "^\\(\\*+\\)"
4690 "\\(?: +" org-todo-regexp "\\)?"
4691 "\\(?: +\\(\\[#.\\]\\)\\)?"
4692 "\\(?: +"
4693 ;; Stats cookies can be stuck to body.
4694 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4695 "\\(%s\\)"
4696 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4697 "\\)"
4698 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4699 "[ \t]*$")
4700 org-todo-line-tags-regexp
4701 (concat "^\\(\\*+\\)"
4702 "\\(?: +" org-todo-regexp "\\)?"
4703 "\\(?: +\\(.*?\\)\\)??"
4704 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4705 "[ \t]*$")
4706 org-deadline-regexp (concat "\\<" org-deadline-string)
4707 org-deadline-time-regexp
4708 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4709 org-deadline-line-regexp
4710 (concat "\\<\\(" org-deadline-string "\\).*")
4711 org-scheduled-regexp
4712 (concat "\\<" org-scheduled-string)
4713 org-scheduled-time-regexp
4714 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4715 org-closed-time-regexp
4716 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4717 org-keyword-time-regexp
4718 (concat "\\<\\(" org-scheduled-string
4719 "\\|" org-deadline-string
4720 "\\|" org-closed-string
4721 "\\|" org-clock-string "\\)"
4722 " *[[<]\\([^]>]+\\)[]>]")
4723 org-keyword-time-not-clock-regexp
4724 (concat "\\<\\(" org-scheduled-string
4725 "\\|" org-deadline-string
4726 "\\|" org-closed-string
4727 "\\)"
4728 " *[[<]\\([^]>]+\\)[]>]")
4729 org-maybe-keyword-time-regexp
4730 (concat "\\(\\<\\(" org-scheduled-string
4731 "\\|" org-deadline-string
4732 "\\|" org-closed-string
4733 "\\|" org-clock-string "\\)\\)?"
4734 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4735 org-all-time-keywords
4736 (mapcar (lambda (w) (substring w 0 -1))
4737 (list org-scheduled-string org-deadline-string
4738 org-clock-string org-closed-string))
4740 (org-compute-latex-and-specials-regexp)
4741 (org-set-font-lock-defaults))))
4743 (defun org-file-contents (file &optional noerror)
4744 "Return the contents of FILE, as a string."
4745 (if (or (not file)
4746 (not (file-readable-p file)))
4747 (if noerror
4748 (progn
4749 (message "Cannot read file \"%s\"" file)
4750 (ding) (sit-for 2)
4752 (error "Cannot read file \"%s\"" file))
4753 (with-temp-buffer
4754 (insert-file-contents file)
4755 (buffer-string))))
4757 (defun org-extract-log-state-settings (x)
4758 "Extract the log state setting from a TODO keyword string.
4759 This will extract info from a string like \"WAIT(w@/!)\"."
4760 (let (kw key log1 log2)
4761 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4762 (setq kw (match-string 1 x)
4763 key (and (match-end 2) (match-string 2 x))
4764 log1 (and (match-end 3) (match-string 3 x))
4765 log2 (and (match-end 4) (match-string 4 x)))
4766 (and (or log1 log2)
4767 (list kw
4768 (and log1 (if (equal log1 "!") 'time 'note))
4769 (and log2 (if (equal log2 "!") 'time 'note)))))))
4771 (defun org-remove-keyword-keys (list)
4772 "Remove a pair of parenthesis at the end of each string in LIST."
4773 (mapcar (lambda (x)
4774 (if (string-match "(.*)$" x)
4775 (substring x 0 (match-beginning 0))
4777 list))
4779 (defun org-assign-fast-keys (alist)
4780 "Assign fast keys to a keyword-key alist.
4781 Respect keys that are already there."
4782 (let (new e (alt ?0))
4783 (while (setq e (pop alist))
4784 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4785 (cdr e)) ;; Key already assigned.
4786 (push e new)
4787 (let ((clist (string-to-list (downcase (car e))))
4788 (used (append new alist)))
4789 (when (= (car clist) ?@)
4790 (pop clist))
4791 (while (and clist (rassoc (car clist) used))
4792 (pop clist))
4793 (unless clist
4794 (while (rassoc alt used)
4795 (incf alt)))
4796 (push (cons (car e) (or (car clist) alt)) new))))
4797 (nreverse new)))
4799 ;;; Some variables used in various places
4801 (defvar org-window-configuration nil
4802 "Used in various places to store a window configuration.")
4803 (defvar org-selected-window nil
4804 "Used in various places to store a window configuration.")
4805 (defvar org-finish-function nil
4806 "Function to be called when `C-c C-c' is used.
4807 This is for getting out of special buffers like capture.")
4810 ;; FIXME: Occasionally check by commenting these, to make sure
4811 ;; no other functions uses these, forgetting to let-bind them.
4812 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4813 (defvar org-last-state)
4814 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4816 ;; Defined somewhere in this file, but used before definition.
4817 (defvar org-entities) ;; defined in org-entities.el
4818 (defvar org-struct-menu)
4819 (defvar org-org-menu)
4820 (defvar org-tbl-menu)
4822 ;;;; Define the Org-mode
4824 ;; We use a before-change function to check if a table might need
4825 ;; an update.
4826 (defvar org-table-may-need-update t
4827 "Indicates that a table might need an update.
4828 This variable is set by `org-before-change-function'.
4829 `org-table-align' sets it back to nil.")
4830 (defun org-before-change-function (beg end)
4831 "Every change indicates that a table might need an update."
4832 (setq org-table-may-need-update t))
4833 (defvar org-mode-map)
4834 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4835 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4836 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4837 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4838 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4839 (defvar org-table-buffer-is-an nil)
4841 (defvar bidi-paragraph-direction)
4842 (defvar buffer-face-mode-face)
4844 (require 'outline)
4845 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4846 (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"))
4847 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4849 ;; Other stuff we need.
4850 (require 'time-date)
4851 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4852 (require 'easymenu)
4853 (require 'overlay)
4855 (require 'org-macs)
4856 (require 'org-entities)
4857 ;; (require 'org-compat) moved higher up in the file before it is first used
4858 (require 'org-faces)
4859 (require 'org-list)
4860 (require 'org-pcomplete)
4861 (require 'org-src)
4862 (require 'org-footnote)
4864 ;; babel
4865 (require 'ob)
4866 (require 'ob-table)
4867 (require 'ob-lob)
4868 (require 'ob-ref)
4869 (require 'ob-tangle)
4870 (require 'ob-comint)
4871 (require 'ob-keys)
4873 ;;;###autoload
4874 (define-derived-mode org-mode outline-mode "Org"
4875 "Outline-based notes management and organizer, alias
4876 \"Carsten's outline-mode for keeping track of everything.\"
4878 Org-mode develops organizational tasks around a NOTES file which
4879 contains information about projects as plain text. Org-mode is
4880 implemented on top of outline-mode, which is ideal to keep the content
4881 of large files well structured. It supports ToDo items, deadlines and
4882 time stamps, which magically appear in the diary listing of the Emacs
4883 calendar. Tables are easily created with a built-in table editor.
4884 Plain text URL-like links connect to websites, emails (VM), Usenet
4885 messages (Gnus), BBDB entries, and any files related to the project.
4886 For printing and sharing of notes, an Org-mode file (or a part of it)
4887 can be exported as a structured ASCII or HTML file.
4889 The following commands are available:
4891 \\{org-mode-map}"
4893 ;; Get rid of Outline menus, they are not needed
4894 ;; Need to do this here because define-derived-mode sets up
4895 ;; the keymap so late. Still, it is a waste to call this each time
4896 ;; we switch another buffer into org-mode.
4897 (if (featurep 'xemacs)
4898 (when (boundp 'outline-mode-menu-heading)
4899 ;; Assume this is Greg's port, it uses easymenu
4900 (easy-menu-remove outline-mode-menu-heading)
4901 (easy-menu-remove outline-mode-menu-show)
4902 (easy-menu-remove outline-mode-menu-hide))
4903 (define-key org-mode-map [menu-bar headings] 'undefined)
4904 (define-key org-mode-map [menu-bar hide] 'undefined)
4905 (define-key org-mode-map [menu-bar show] 'undefined))
4907 (org-load-modules-maybe)
4908 (easy-menu-add org-org-menu)
4909 (easy-menu-add org-tbl-menu)
4910 (org-install-agenda-files-menu)
4911 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4912 (add-to-invisibility-spec '(org-cwidth))
4913 (add-to-invisibility-spec '(org-hide-block . t))
4914 (when (featurep 'xemacs)
4915 (org-set-local 'line-move-ignore-invisible t))
4916 (org-set-local 'outline-regexp org-outline-regexp)
4917 (org-set-local 'outline-level 'org-outline-level)
4918 (setq bidi-paragraph-direction 'left-to-right)
4919 (when (and org-ellipsis
4920 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4921 (fboundp 'make-glyph-code))
4922 (unless org-display-table
4923 (setq org-display-table (make-display-table)))
4924 (set-display-table-slot
4925 org-display-table 4
4926 (vconcat (mapcar
4927 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4928 org-ellipsis)))
4929 (if (stringp org-ellipsis) org-ellipsis "..."))))
4930 (setq buffer-display-table org-display-table))
4931 (org-set-regexps-and-options)
4932 (when (and org-tag-faces (not org-tags-special-faces-re))
4933 ;; tag faces set outside customize.... force initialization.
4934 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4935 ;; Calc embedded
4936 (org-set-local 'calc-embedded-open-mode "# ")
4937 (modify-syntax-entry ?@ "w")
4938 (modify-syntax-entry ?\" "\"")
4939 (if org-startup-truncated (setq truncate-lines t))
4940 (org-set-local 'font-lock-unfontify-region-function
4941 'org-unfontify-region)
4942 ;; Activate before-change-function
4943 (org-set-local 'org-table-may-need-update t)
4944 (org-add-hook 'before-change-functions 'org-before-change-function nil
4945 'local)
4946 ;; Check for running clock before killing a buffer
4947 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4948 ;; Initialize macros templates.
4949 (org-macro-initialize-templates)
4950 ;; Initialize radio targets.
4951 (org-update-radio-target-regexp)
4952 ;; Indentation.
4953 (org-set-local 'indent-line-function 'org-indent-line)
4954 (org-set-local 'indent-region-function 'org-indent-region)
4955 ;; Filling and auto-filling.
4956 (org-setup-filling)
4957 ;; Comments.
4958 (org-setup-comments-handling)
4959 ;; Beginning/end of defun
4960 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4961 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4962 ;; Next error for sparse trees
4963 (org-set-local 'next-error-function 'org-occur-next-match)
4964 ;; Make sure dependence stuff works reliably, even for users who set it
4965 ;; too late :-(
4966 (if org-enforce-todo-dependencies
4967 (add-hook 'org-blocker-hook
4968 'org-block-todo-from-children-or-siblings-or-parent)
4969 (remove-hook 'org-blocker-hook
4970 'org-block-todo-from-children-or-siblings-or-parent))
4971 (if org-enforce-todo-checkbox-dependencies
4972 (add-hook 'org-blocker-hook
4973 'org-block-todo-from-checkboxes)
4974 (remove-hook 'org-blocker-hook
4975 'org-block-todo-from-checkboxes))
4977 ;; Align options lines
4978 (org-set-local
4979 'align-mode-rules-list
4980 '((org-in-buffer-settings
4981 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4982 (modes . '(org-mode)))))
4984 ;; Imenu
4985 (org-set-local 'imenu-create-index-function
4986 'org-imenu-get-tree)
4988 ;; Make isearch reveal context
4989 (if (or (featurep 'xemacs)
4990 (not (boundp 'outline-isearch-open-invisible-function)))
4991 ;; Emacs 21 and XEmacs make use of the hook
4992 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4993 ;; Emacs 22 deals with this through a special variable
4994 (org-set-local 'outline-isearch-open-invisible-function
4995 (lambda (&rest ignore) (org-show-context 'isearch))))
4997 ;; Turn on org-beamer-mode?
4998 (and org-startup-with-beamer-mode (org-beamer-mode))
5000 ;; Setup the pcomplete hooks
5001 (set (make-local-variable 'pcomplete-command-completion-function)
5002 'org-pcomplete-initial)
5003 (set (make-local-variable 'pcomplete-command-name-function)
5004 'org-command-at-point)
5005 (set (make-local-variable 'pcomplete-default-completion-function)
5006 'ignore)
5007 (set (make-local-variable 'pcomplete-parse-arguments-function)
5008 'org-parse-arguments)
5009 (set (make-local-variable 'pcomplete-termination-string) "")
5010 (when (>= emacs-major-version 23)
5011 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5013 ;; If empty file that did not turn on org-mode automatically, make it to.
5014 (if (and org-insert-mode-line-in-empty-file
5015 (org-called-interactively-p 'any)
5016 (= (point-min) (point-max)))
5017 (insert "# -*- mode: org -*-\n\n"))
5018 (unless org-inhibit-startup
5019 (when org-startup-align-all-tables
5020 (let ((bmp (buffer-modified-p)))
5021 (org-table-map-tables 'org-table-align 'quietly)
5022 (set-buffer-modified-p bmp)))
5023 (when org-startup-with-inline-images
5024 (org-display-inline-images))
5025 (when org-startup-indented
5026 (require 'org-indent)
5027 (org-indent-mode 1))
5028 (unless org-inhibit-startup-visibility-stuff
5029 (org-set-startup-visibility)))
5030 ;; Try to set org-hide correctly
5031 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5033 (when (fboundp 'abbrev-table-put)
5034 (abbrev-table-put org-mode-abbrev-table
5035 :parents (list text-mode-abbrev-table)))
5037 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5040 (defun org-find-invisible-foreground ()
5041 (let ((candidates (remove
5042 "unspecified-bg"
5043 (list
5044 (face-background 'default)
5045 (face-background 'org-default)
5046 (cdr (assoc 'background-color default-frame-alist))
5047 (cdr (assoc 'background-color initial-frame-alist))
5048 (cdr (assoc 'background-color window-system-default-frame-alist))
5049 (face-foreground 'org-hide)))))
5050 (car (remove nil candidates))))
5052 (defun org-current-time ()
5053 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5054 (if (> (car org-time-stamp-rounding-minutes) 1)
5055 (let ((r (car org-time-stamp-rounding-minutes))
5056 (time (decode-time)))
5057 (apply 'encode-time
5058 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5059 (nthcdr 2 time))))
5060 (current-time)))
5062 (defun org-today ()
5063 "Return today date, considering `org-extend-today-until'."
5064 (time-to-days
5065 (time-subtract (current-time)
5066 (list 0 (* 3600 org-extend-today-until) 0))))
5068 ;;;; Font-Lock stuff, including the activators
5070 (defvar org-mouse-map (make-sparse-keymap))
5071 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5072 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5073 (when org-mouse-1-follows-link
5074 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5075 (when org-tab-follows-link
5076 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5077 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5079 (require 'font-lock)
5081 (defconst org-non-link-chars "]\t\n\r<>")
5082 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5083 "shell" "elisp" "doi" "message"))
5084 (defvar org-link-types-re nil
5085 "Matches a link that has a url-like prefix like \"http:\"")
5086 (defvar org-link-re-with-space nil
5087 "Matches a link with spaces, optional angular brackets around it.")
5088 (defvar org-link-re-with-space2 nil
5089 "Matches a link with spaces, optional angular brackets around it.")
5090 (defvar org-link-re-with-space3 nil
5091 "Matches a link with spaces, only for internal part in bracket links.")
5092 (defvar org-angle-link-re nil
5093 "Matches link with angular brackets, spaces are allowed.")
5094 (defvar org-plain-link-re nil
5095 "Matches plain link, without spaces.")
5096 (defvar org-bracket-link-regexp nil
5097 "Matches a link in double brackets.")
5098 (defvar org-bracket-link-analytic-regexp nil
5099 "Regular expression used to analyze links.
5100 Here is what the match groups contain after a match:
5101 1: http:
5102 2: http
5103 3: path
5104 4: [desc]
5105 5: desc")
5106 (defvar org-bracket-link-analytic-regexp++ nil
5107 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5108 (defvar org-any-link-re nil
5109 "Regular expression matching any link.")
5111 (defcustom org-match-sexp-depth 3
5112 "Number of stacked braces for sub/superscript matching.
5113 This has to be set before loading org.el to be effective."
5114 :group 'org-export-translation ; ??????????????????????????/
5115 :type 'integer)
5117 (defun org-create-multibrace-regexp (left right n)
5118 "Create a regular expression which will match a balanced sexp.
5119 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5120 as single character strings.
5121 The regexp returned will match the entire expression including the
5122 delimiters. It will also define a single group which contains the
5123 match except for the outermost delimiters. The maximum depth of
5124 stacked delimiters is N. Escaping delimiters is not possible."
5125 (let* ((nothing (concat "[^" left right "]*?"))
5126 (or "\\|")
5127 (re nothing)
5128 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5129 (while (> n 1)
5130 (setq n (1- n)
5131 re (concat re or next)
5132 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5133 (concat left "\\(" re "\\)" right)))
5135 (defvar org-match-substring-regexp
5136 (concat
5137 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5138 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5139 "\\|"
5140 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5141 "\\|"
5142 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5143 "The regular expression matching a sub- or superscript.")
5145 (defvar org-match-substring-with-braces-regexp
5146 (concat
5147 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5148 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5149 "\\)")
5150 "The regular expression matching a sub- or superscript, forcing braces.")
5152 (defun org-make-link-regexps ()
5153 "Update the link regular expressions.
5154 This should be called after the variable `org-link-types' has changed."
5155 (setq org-link-types-re
5156 (concat
5157 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5158 org-link-re-with-space
5159 (concat
5160 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5161 "\\([^" org-non-link-chars " ]"
5162 "[^" org-non-link-chars "]*"
5163 "[^" org-non-link-chars " ]\\)>?")
5164 org-link-re-with-space2
5165 (concat
5166 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5167 "\\([^" org-non-link-chars " ]"
5168 "[^\t\n\r]*"
5169 "[^" org-non-link-chars " ]\\)>?")
5170 org-link-re-with-space3
5171 (concat
5172 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5173 "\\([^" org-non-link-chars " ]"
5174 "[^\t\n\r]*\\)")
5175 org-angle-link-re
5176 (concat
5177 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5178 "\\([^" org-non-link-chars " ]"
5179 "[^" org-non-link-chars "]*"
5180 "\\)>")
5181 org-plain-link-re
5182 (concat
5183 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5184 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5185 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5186 org-bracket-link-regexp
5187 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5188 org-bracket-link-analytic-regexp
5189 (concat
5190 "\\[\\["
5191 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5192 "\\([^]]+\\)"
5193 "\\]"
5194 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5195 "\\]")
5196 org-bracket-link-analytic-regexp++
5197 (concat
5198 "\\[\\["
5199 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5200 "\\([^]]+\\)"
5201 "\\]"
5202 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5203 "\\]")
5204 org-any-link-re
5205 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5206 org-angle-link-re "\\)\\|\\("
5207 org-plain-link-re "\\)")))
5209 (org-make-link-regexps)
5211 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5212 "Regular expression for fast time stamp matching.")
5213 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5214 "Regular expression for fast time stamp matching.")
5215 (defconst org-ts-regexp0
5216 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5217 "Regular expression matching time strings for analysis.
5218 This one does not require the space after the date, so it can be used
5219 on a string that terminates immediately after the date.")
5220 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5221 "Regular expression matching time strings for analysis.")
5222 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5223 "Regular expression matching time stamps, with groups.")
5224 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5225 "Regular expression matching time stamps (also [..]), with groups.")
5226 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5227 "Regular expression matching a time stamp range.")
5228 (defconst org-tr-regexp-both
5229 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5230 "Regular expression matching a time stamp range.")
5231 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5232 org-ts-regexp "\\)?")
5233 "Regular expression matching a time stamp or time stamp range.")
5234 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5235 org-ts-regexp-both "\\)?")
5236 "Regular expression matching a time stamp or time stamp range.
5237 The time stamps may be either active or inactive.")
5239 (defvar org-emph-face nil)
5241 (defun org-do-emphasis-faces (limit)
5242 "Run through the buffer and add overlays to emphasized strings."
5243 (let (rtn a)
5244 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5245 (if (not (= (char-after (match-beginning 3))
5246 (char-after (match-beginning 4))))
5247 (progn
5248 (setq rtn t)
5249 (setq a (assoc (match-string 3) org-emphasis-alist))
5250 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5251 'face
5252 (nth 1 a))
5253 (and (nth 4 a)
5254 (org-remove-flyspell-overlays-in
5255 (match-beginning 0) (match-end 0)))
5256 (add-text-properties (match-beginning 2) (match-end 2)
5257 '(font-lock-multiline t org-emphasis t))
5258 (when org-hide-emphasis-markers
5259 (add-text-properties (match-end 4) (match-beginning 5)
5260 '(invisible org-link))
5261 (add-text-properties (match-beginning 3) (match-end 3)
5262 '(invisible org-link)))))
5263 (backward-char 1))
5264 rtn))
5266 (defun org-emphasize (&optional char)
5267 "Insert or change an emphasis, i.e. a font like bold or italic.
5268 If there is an active region, change that region to a new emphasis.
5269 If there is no region, just insert the marker characters and position
5270 the cursor between them.
5271 CHAR should be either the marker character, or the first character of the
5272 HTML tag associated with that emphasis. If CHAR is a space, the means
5273 to remove the emphasis of the selected region.
5274 If char is not given (for example in an interactive call) it
5275 will be prompted for."
5276 (interactive)
5277 (let ((eal org-emphasis-alist) e det
5278 (erc org-emphasis-regexp-components)
5279 (prompt "")
5280 (string "") beg end move tag c s)
5281 (if (org-region-active-p)
5282 (setq beg (region-beginning) end (region-end)
5283 string (buffer-substring beg end))
5284 (setq move t))
5286 (while (setq e (pop eal))
5287 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5288 c (aref tag 0))
5289 (push (cons c (string-to-char (car e))) det)
5290 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5291 (substring tag 1)))))
5292 (setq det (nreverse det))
5293 (unless char
5294 (message "%s" (concat "Emphasis marker or tag:" prompt))
5295 (setq char (read-char-exclusive)))
5296 (setq char (or (cdr (assoc char det)) char))
5297 (if (equal char ?\ )
5298 (setq s "" move nil)
5299 (unless (assoc (char-to-string char) org-emphasis-alist)
5300 (error "No such emphasis marker: \"%c\"" char))
5301 (setq s (char-to-string char)))
5302 (while (and (> (length string) 1)
5303 (equal (substring string 0 1) (substring string -1))
5304 (assoc (substring string 0 1) org-emphasis-alist))
5305 (setq string (substring string 1 -1)))
5306 (setq string (concat s string s))
5307 (if beg (delete-region beg end))
5308 (unless (or (bolp)
5309 (string-match (concat "[" (nth 0 erc) "\n]")
5310 (char-to-string (char-before (point)))))
5311 (insert " "))
5312 (unless (or (eobp)
5313 (string-match (concat "[" (nth 1 erc) "\n]")
5314 (char-to-string (char-after (point)))))
5315 (insert " ") (backward-char 1))
5316 (insert string)
5317 (and move (backward-char 1))))
5319 (defconst org-nonsticky-props
5320 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5322 (defsubst org-rear-nonsticky-at (pos)
5323 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5325 (defun org-activate-plain-links (limit)
5326 "Run through the buffer and add overlays to links."
5327 (catch 'exit
5328 (let (f hl)
5329 (when (re-search-forward (concat org-plain-link-re) limit t)
5330 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5331 (setq f (get-text-property (match-beginning 0) 'face))
5332 (setq hl (org-match-string-no-properties 0))
5333 (if (or (eq f 'org-tag)
5334 (and (listp f) (memq 'org-tag f)))
5336 (add-text-properties (match-beginning 0) (match-end 0)
5337 (list 'mouse-face 'highlight
5338 'face 'org-link
5339 'htmlize-link `(:uri ,hl)
5340 'keymap org-mouse-map))
5341 (org-rear-nonsticky-at (match-end 0)))
5342 t))))
5344 (defun org-activate-code (limit)
5345 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5346 (progn
5347 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5348 (remove-text-properties (match-beginning 0) (match-end 0)
5349 '(display t invisible t intangible t))
5350 t)))
5352 (defcustom org-src-fontify-natively nil
5353 "When non-nil, fontify code in code blocks."
5354 :type 'boolean
5355 :version "24.1"
5356 :group 'org-appearance
5357 :group 'org-babel)
5359 (defcustom org-allow-promoting-top-level-subtree nil
5360 "When non-nil, allow promoting a top level subtree.
5361 The leading star of the top level headline will be replaced
5362 by a #."
5363 :type 'boolean
5364 :version "24.1"
5365 :group 'org-appearance)
5367 (defun org-fontify-meta-lines-and-blocks (limit)
5368 (condition-case nil
5369 (org-fontify-meta-lines-and-blocks-1 limit)
5370 (error (message "org-mode fontification error"))))
5372 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5373 "Fontify #+ lines and blocks, in the correct ways."
5374 (let ((case-fold-search t))
5375 (if (re-search-forward
5376 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5377 limit t)
5378 (let ((beg (match-beginning 0))
5379 (block-start (match-end 0))
5380 (block-end nil)
5381 (lang (match-string 7))
5382 (beg1 (line-beginning-position 2))
5383 (dc1 (downcase (match-string 2)))
5384 (dc3 (downcase (match-string 3)))
5385 end end1 quoting block-type ovl)
5386 (cond
5387 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5388 ;; a single line of backend-specific content
5389 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5390 (remove-text-properties (match-beginning 0) (match-end 0)
5391 '(display t invisible t intangible t))
5392 (add-text-properties (match-beginning 1) (match-end 3)
5393 '(font-lock-fontified t face org-meta-line))
5394 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5395 '(font-lock-fontified t face org-block))
5396 ; for backend-specific code
5398 ((and (match-end 4) (equal dc3 "+begin"))
5399 ;; Truly a block
5400 (setq block-type (downcase (match-string 5))
5401 quoting (member block-type org-protecting-blocks))
5402 (when (re-search-forward
5403 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5404 nil t) ;; on purpose, we look further than LIMIT
5405 (setq end (min (point-max) (match-end 0))
5406 end1 (min (point-max) (1- (match-beginning 0))))
5407 (setq block-end (match-beginning 0))
5408 (when quoting
5409 (remove-text-properties beg end
5410 '(display t invisible t intangible t)))
5411 (add-text-properties
5412 beg end
5413 '(font-lock-fontified t font-lock-multiline t))
5414 (add-text-properties beg beg1 '(face org-meta-line))
5415 (add-text-properties end1 (min (point-max) (1+ end))
5416 '(face org-meta-line)) ; for end_src
5417 (cond
5418 ((and lang (not (string= lang "")) org-src-fontify-natively)
5419 (org-src-font-lock-fontify-block lang block-start block-end)
5420 ;; remove old background overlays
5421 (mapc (lambda (ov)
5422 (if (eq (overlay-get ov 'face) 'org-block-background)
5423 (delete-overlay ov)))
5424 (overlays-at (/ (+ beg1 block-end) 2)))
5425 ;; add a background overlay
5426 (setq ovl (make-overlay beg1 block-end))
5427 (overlay-put ovl 'face 'org-block-background)
5428 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5429 (quoting
5430 (add-text-properties beg1 (min (point-max) (1+ end1))
5431 '(face org-block))) ; end of source block
5432 ((not org-fontify-quote-and-verse-blocks))
5433 ((string= block-type "quote")
5434 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5435 ((string= block-type "verse")
5436 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5437 (add-text-properties beg beg1 '(face org-block-begin-line))
5438 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5439 '(face org-block-end-line))
5441 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5442 (add-text-properties
5443 beg (match-end 3)
5444 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5445 '(font-lock-fontified t invisible t)
5446 '(font-lock-fontified t face org-document-info-keyword)))
5447 (add-text-properties
5448 (match-beginning 6) (match-end 6)
5449 (if (string-equal dc1 "+title:")
5450 '(font-lock-fontified t face org-document-title)
5451 '(font-lock-fontified t face org-document-info))))
5452 ((or (equal dc1 "+results")
5453 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5454 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5455 "+call:" "+header:" "+headers:" "+name:"))
5456 (and (match-end 4) (equal dc3 "+attr")))
5457 (add-text-properties
5458 beg (match-end 0)
5459 '(font-lock-fontified t face org-meta-line))
5461 ((member dc3 '(" " ""))
5462 (add-text-properties
5463 beg (match-end 0)
5464 '(font-lock-fontified t face font-lock-comment-face)))
5465 ((not (member (char-after beg) '(?\ ?\t)))
5466 ;; just any other in-buffer setting, but not indented
5467 (add-text-properties
5468 beg (match-end 0)
5469 '(font-lock-fontified t face org-meta-line))
5471 (t nil))))))
5473 (defun org-activate-angle-links (limit)
5474 "Run through the buffer and add overlays to links."
5475 (if (re-search-forward org-angle-link-re limit t)
5476 (progn
5477 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5478 (add-text-properties (match-beginning 0) (match-end 0)
5479 (list 'mouse-face 'highlight
5480 'keymap org-mouse-map))
5481 (org-rear-nonsticky-at (match-end 0))
5482 t)))
5484 (defun org-activate-footnote-links (limit)
5485 "Run through the buffer and add overlays to footnotes."
5486 (let ((fn (org-footnote-next-reference-or-definition limit)))
5487 (when fn
5488 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5489 (org-remove-flyspell-overlays-in beg end)
5490 (add-text-properties beg end
5491 (list 'mouse-face 'highlight
5492 'keymap org-mouse-map
5493 'help-echo
5494 (if (= (point-at-bol) beg)
5495 "Footnote definition"
5496 "Footnote reference")
5497 'font-lock-fontified t
5498 'font-lock-multiline t
5499 'face 'org-footnote))))))
5501 (defun org-activate-bracket-links (limit)
5502 "Run through the buffer and add overlays to bracketed links."
5503 (if (re-search-forward org-bracket-link-regexp limit t)
5504 (let* ((hl (org-match-string-no-properties 1))
5505 (help (concat "LINK: " hl))
5506 ;; FIXME: Above we should remove the escapes. But that
5507 ;; requires another match, protecting match data, a lot
5508 ;; of overhead for font-lock.
5509 (ip (org-maybe-intangible
5510 (list 'invisible 'org-link
5511 'keymap org-mouse-map 'mouse-face 'highlight
5512 'font-lock-multiline t 'help-echo help
5513 'htmlize-link `(:uri ,hl))))
5514 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5515 'font-lock-multiline t 'help-echo help
5516 'htmlize-link `(:uri ,hl))))
5517 ;; We need to remove the invisible property here. Table narrowing
5518 ;; may have made some of this invisible.
5519 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5520 (remove-text-properties (match-beginning 0) (match-end 0)
5521 '(invisible nil))
5522 (if (match-end 3)
5523 (progn
5524 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5525 (org-rear-nonsticky-at (match-beginning 3))
5526 (add-text-properties (match-beginning 3) (match-end 3) vp)
5527 (org-rear-nonsticky-at (match-end 3))
5528 (add-text-properties (match-end 3) (match-end 0) ip)
5529 (org-rear-nonsticky-at (match-end 0)))
5530 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5531 (org-rear-nonsticky-at (match-beginning 1))
5532 (add-text-properties (match-beginning 1) (match-end 1) vp)
5533 (org-rear-nonsticky-at (match-end 1))
5534 (add-text-properties (match-end 1) (match-end 0) ip)
5535 (org-rear-nonsticky-at (match-end 0)))
5536 t)))
5538 (defun org-activate-dates (limit)
5539 "Run through the buffer and add overlays to dates."
5540 (if (re-search-forward org-tsr-regexp-both limit t)
5541 (progn
5542 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5543 (add-text-properties (match-beginning 0) (match-end 0)
5544 (list 'mouse-face 'highlight
5545 'keymap org-mouse-map))
5546 (org-rear-nonsticky-at (match-end 0))
5547 (when org-display-custom-times
5548 (if (match-end 3)
5549 (org-display-custom-time (match-beginning 3) (match-end 3)))
5550 (org-display-custom-time (match-beginning 1) (match-end 1)))
5551 t)))
5553 (defvar org-target-link-regexp nil
5554 "Regular expression matching radio targets in plain text.")
5555 (make-variable-buffer-local 'org-target-link-regexp)
5556 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5557 "Regular expression matching a link target.")
5558 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5559 "Regular expression matching a radio target.")
5560 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5561 "Regular expression matching any target.")
5563 (defun org-activate-target-links (limit)
5564 "Run through the buffer and add overlays to target matches."
5565 (when org-target-link-regexp
5566 (let ((case-fold-search t))
5567 (if (re-search-forward org-target-link-regexp limit t)
5568 (progn
5569 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5570 (add-text-properties (match-beginning 0) (match-end 0)
5571 (list 'mouse-face 'highlight
5572 'keymap org-mouse-map
5573 'help-echo "Radio target link"
5574 'org-linked-text t))
5575 (org-rear-nonsticky-at (match-end 0))
5576 t)))))
5578 (defun org-update-radio-target-regexp ()
5579 "Find all radio targets in this file and update the regular expression."
5580 (interactive)
5581 (when (memq 'radio org-activate-links)
5582 (setq org-target-link-regexp
5583 (org-make-target-link-regexp (org-all-targets 'radio)))
5584 (org-restart-font-lock)))
5586 (defun org-hide-wide-columns (limit)
5587 (let (s e)
5588 (setq s (text-property-any (point) (or limit (point-max))
5589 'org-cwidth t))
5590 (when s
5591 (setq e (next-single-property-change s 'org-cwidth))
5592 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5593 (goto-char e)
5594 t)))
5596 (defvar org-latex-and-specials-regexp nil
5597 "Regular expression for highlighting export special stuff.")
5598 (defvar org-match-substring-regexp)
5599 (defvar org-match-substring-with-braces-regexp)
5601 ;; This should be with the exporter code, but we also use if for font-locking
5602 (defconst org-export-html-special-string-regexps
5603 '(("\\\\-" . "&shy;")
5604 ("---\\([^-]\\)" . "&mdash;\\1")
5605 ("--\\([^-]\\)" . "&ndash;\\1")
5606 ("\\.\\.\\." . "&hellip;"))
5607 "Regular expressions for special string conversion.")
5610 (defun org-compute-latex-and-specials-regexp ()
5611 "Compute regular expression for stuff treated specially by exporters."
5612 (if (not org-highlight-latex-fragments-and-specials)
5613 (org-set-local 'org-latex-and-specials-regexp nil)
5614 (require 'org-exp)
5615 (let*
5616 ((matchers (plist-get org-format-latex-options :matchers))
5617 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5618 org-latex-regexps)))
5619 (org-export-allow-BIND nil)
5620 (options (org-combine-plists (org-default-export-plist)
5621 (org-infile-export-plist)))
5622 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5623 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5624 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5625 (org-export-html-expand (plist-get options :expand-quoted-html))
5626 (org-export-with-special-strings (plist-get options :special-strings))
5627 (re-sub
5628 (cond
5629 ((equal org-export-with-sub-superscripts '{})
5630 (list org-match-substring-with-braces-regexp))
5631 (org-export-with-sub-superscripts
5632 (list org-match-substring-regexp))))
5633 (re-latex
5634 (if org-export-with-LaTeX-fragments
5635 (mapcar (lambda (x) (nth 1 x)) latexs)))
5636 (re-macros
5637 (if org-export-with-TeX-macros
5638 (list (concat "\\\\"
5639 (regexp-opt
5640 (append
5642 (delq nil
5643 (mapcar 'car-safe
5644 (append org-entities-user
5645 org-entities)))
5646 (if (boundp 'org-latex-entities)
5647 (mapcar (lambda (x)
5648 (or (car-safe x) x))
5649 org-latex-entities)
5650 nil))
5651 'words))) ; FIXME
5653 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5654 (re-special (if org-export-with-special-strings
5655 (mapcar (lambda (x) (car x))
5656 org-export-html-special-string-regexps)))
5657 (re-rest
5658 (delq nil
5659 (list
5660 (if org-export-html-expand "@<[^>\n]+>")
5661 ))))
5662 (org-set-local
5663 'org-latex-and-specials-regexp
5664 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5665 re-rest) "\\|")))))
5667 (defun org-do-latex-and-special-faces (limit)
5668 "Run through the buffer and add overlays to links."
5669 (when org-latex-and-specials-regexp
5670 (let (rtn d)
5671 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5672 limit t))
5673 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5674 'face))
5675 '(org-code org-verbatim underline)))
5676 (progn
5677 (setq rtn t
5678 d (cond ((member (char-after (1+ (match-beginning 0)))
5679 '(?_ ?^)) 1)
5680 (t 0)))
5681 (font-lock-prepend-text-property
5682 (+ d (match-beginning 0)) (match-end 0)
5683 'face 'org-latex-and-export-specials)
5684 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5685 '(font-lock-multiline t)))))
5686 rtn)))
5688 (defun org-restart-font-lock ()
5689 "Restart `font-lock-mode', to force refontification."
5690 (when (and (boundp 'font-lock-mode) font-lock-mode)
5691 (font-lock-mode -1)
5692 (font-lock-mode 1)))
5694 (defun org-all-targets (&optional radio)
5695 "Return a list of all targets in this file.
5696 When optional argument RADIO is non-nil, only find radio
5697 targets."
5698 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5699 (save-excursion
5700 (goto-char (point-min))
5701 (while (re-search-forward re nil t)
5702 (let ((obj (org-element-context)))
5703 (when (memq (org-element-type obj) '(radio-target target))
5704 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5705 rtn)))
5707 (defun org-make-target-link-regexp (targets)
5708 "Make regular expression matching all strings in TARGETS.
5709 The regular expression finds the targets also if there is a line break
5710 between words."
5711 (and targets
5712 (concat
5713 "\\<\\("
5714 (mapconcat
5715 (lambda (x)
5716 (setq x (regexp-quote x))
5717 (while (string-match " +" x)
5718 (setq x (replace-match "\\s-+" t t x)))
5720 targets
5721 "\\|")
5722 "\\)\\>")))
5724 (defun org-activate-tags (limit)
5725 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5726 (progn
5727 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5728 (add-text-properties (match-beginning 1) (match-end 1)
5729 (list 'mouse-face 'highlight
5730 'keymap org-mouse-map))
5731 (org-rear-nonsticky-at (match-end 1))
5732 t)))
5734 (defun org-outline-level ()
5735 "Compute the outline level of the heading at point.
5736 If this is called at a normal headline, the level is the number of stars.
5737 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5738 (save-excursion
5739 (if (not (condition-case nil
5740 (org-back-to-heading t)
5741 (error nil)))
5743 (looking-at org-outline-regexp)
5744 (1- (- (match-end 0) (match-beginning 0))))))
5746 (defvar org-font-lock-keywords nil)
5748 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5749 "Regular expression matching a property line.")
5751 (defvar org-font-lock-hook nil
5752 "Functions to be called for special font lock stuff.")
5754 (defvar org-font-lock-set-keywords-hook nil
5755 "Functions that can manipulate `org-font-lock-extra-keywords'.
5756 This is called after `org-font-lock-extra-keywords' is defined, but before
5757 it is installed to be used by font lock. This can be useful if something
5758 needs to be inserted at a specific position in the font-lock sequence.")
5760 (defun org-font-lock-hook (limit)
5761 "Run `org-font-lock-hook' within LIMIT."
5762 (run-hook-with-args 'org-font-lock-hook limit))
5764 (defun org-set-font-lock-defaults ()
5765 "Set font lock defaults for the current buffer."
5766 (let* ((em org-fontify-emphasized-text)
5767 (lk org-activate-links)
5768 (org-font-lock-extra-keywords
5769 (list
5770 ;; Call the hook
5771 '(org-font-lock-hook)
5772 ;; Headlines
5773 `(,(if org-fontify-whole-heading-line
5774 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5775 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5776 (1 (org-get-level-face 1))
5777 (2 (org-get-level-face 2))
5778 (3 (org-get-level-face 3)))
5779 ;; Table lines
5780 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5781 (1 'org-table t))
5782 ;; Table internals
5783 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5784 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5785 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5786 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5787 ;; Drawers
5788 (list org-drawer-regexp '(0 'org-special-keyword t))
5789 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5790 ;; Properties
5791 (list org-property-re
5792 '(1 'org-special-keyword t)
5793 '(3 'org-property-value t))
5794 ;; Links
5795 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5796 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5797 (if (memq 'plain lk) '(org-activate-plain-links))
5798 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5799 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5800 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5801 (if (memq 'footnote lk) '(org-activate-footnote-links))
5802 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5803 '(org-hide-wide-columns (0 nil append))
5804 ;; TODO keyword
5805 (list (format org-heading-keyword-regexp-format
5806 org-todo-regexp)
5807 '(2 (org-get-todo-face 2) t))
5808 ;; DONE
5809 (if org-fontify-done-headline
5810 (list (format org-heading-keyword-regexp-format
5811 (concat
5812 "\\(?:"
5813 (mapconcat 'regexp-quote org-done-keywords "\\|")
5814 "\\)"))
5815 '(2 'org-headline-done t))
5816 nil)
5817 ;; Priorities
5818 '(org-font-lock-add-priority-faces)
5819 ;; Tags
5820 '(org-font-lock-add-tag-faces)
5821 ;; Special keywords
5822 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5823 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5824 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5825 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5826 ;; Emphasis
5827 (if em
5828 (if (featurep 'xemacs)
5829 '(org-do-emphasis-faces (0 nil append))
5830 '(org-do-emphasis-faces)))
5831 ;; Checkboxes
5832 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5833 1 'org-checkbox prepend)
5834 (if (cdr (assq 'checkbox org-list-automatic-rules))
5835 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5836 (0 (org-get-checkbox-statistics-face) t)))
5837 ;; Description list items
5838 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5839 1 'org-list-dt prepend)
5840 ;; ARCHIVEd headings
5841 (list (concat
5842 org-outline-regexp-bol
5843 "\\(.*:" org-archive-tag ":.*\\)")
5844 '(1 'org-archived prepend))
5845 ;; Specials
5846 '(org-do-latex-and-special-faces)
5847 '(org-fontify-entities)
5848 '(org-raise-scripts)
5849 ;; Code
5850 '(org-activate-code (1 'org-code t))
5851 ;; COMMENT
5852 (list (format org-heading-keyword-regexp-format
5853 (concat "\\("
5854 org-comment-string "\\|" org-quote-string
5855 "\\)"))
5856 '(2 'org-special-keyword t))
5857 ;; Blocks and meta lines
5858 '(org-fontify-meta-lines-and-blocks)
5860 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5861 (run-hooks 'org-font-lock-set-keywords-hook)
5862 ;; Now set the full font-lock-keywords
5863 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5864 (org-set-local 'font-lock-defaults
5865 '(org-font-lock-keywords t nil nil backward-paragraph))
5866 (kill-local-variable 'font-lock-keywords) nil))
5868 (defun org-toggle-pretty-entities ()
5869 "Toggle the composition display of entities as UTF8 characters."
5870 (interactive)
5871 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5872 (org-restart-font-lock)
5873 (if org-pretty-entities
5874 (message "Entities are displayed as UTF8 characters")
5875 (save-restriction
5876 (widen)
5877 (org-decompose-region (point-min) (point-max))
5878 (message "Entities are displayed plain"))))
5880 (defvar org-custom-properties-overlays nil
5881 "List of overlays used for custom properties.")
5882 (make-variable-buffer-local 'org-custom-properties-overlays)
5884 (defun org-toggle-custom-properties-visibility ()
5885 "Display or hide properties in `org-custom-properties'."
5886 (interactive)
5887 (if org-custom-properties-overlays
5888 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5889 (setq org-custom-properties-overlays nil))
5890 (unless (not org-custom-properties)
5891 (save-excursion
5892 (save-restriction
5893 (widen)
5894 (goto-char (point-min))
5895 (while (re-search-forward org-property-re nil t)
5896 (mapc (lambda(p)
5897 (when (equal p (substring (match-string 1) 1 -1))
5898 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5899 (overlay-put o 'invisible t)
5900 (overlay-put o 'org-custom-property t)
5901 (push o org-custom-properties-overlays))))
5902 org-custom-properties)))))))
5904 (defun org-fontify-entities (limit)
5905 "Find an entity to fontify."
5906 (let (ee)
5907 (when org-pretty-entities
5908 (catch 'match
5909 (while (re-search-forward
5910 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5911 limit t)
5912 (if (and (not (org-in-indented-comment-line))
5913 (setq ee (org-entity-get (match-string 1)))
5914 (= (length (nth 6 ee)) 1))
5915 (let*
5916 ((end (if (equal (match-string 2) "{}")
5917 (match-end 2)
5918 (match-end 1))))
5919 (add-text-properties
5920 (match-beginning 0) end
5921 (list 'font-lock-fontified t))
5922 (compose-region (match-beginning 0) end
5923 (nth 6 ee) nil)
5924 (backward-char 1)
5925 (throw 'match t))))
5926 nil))))
5928 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5929 "Fontify string S like in Org-mode."
5930 (with-temp-buffer
5931 (insert s)
5932 (let ((org-odd-levels-only odd-levels))
5933 (org-mode)
5934 (font-lock-fontify-buffer)
5935 (buffer-string))))
5937 (defvar org-m nil)
5938 (defvar org-l nil)
5939 (defvar org-f nil)
5940 (defun org-get-level-face (n)
5941 "Get the right face for match N in font-lock matching of headlines."
5942 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5943 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5944 (if org-cycle-level-faces
5945 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5946 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5947 (cond
5948 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5949 ((eq n 2) org-f)
5950 (t (if org-level-color-stars-only nil org-f))))
5953 (defun org-get-todo-face (kwd)
5954 "Get the right face for a TODO keyword KWD.
5955 If KWD is a number, get the corresponding match group."
5956 (if (numberp kwd) (setq kwd (match-string kwd)))
5957 (or (org-face-from-face-or-color
5958 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5959 (and (member kwd org-done-keywords) 'org-done)
5960 'org-todo))
5962 (defun org-face-from-face-or-color (context inherit face-or-color)
5963 "Create a face list that inherits INHERIT, but sets the foreground color.
5964 When FACE-OR-COLOR is not a string, just return it."
5965 (if (stringp face-or-color)
5966 (list :inherit inherit
5967 (cdr (assoc context org-faces-easy-properties))
5968 face-or-color)
5969 face-or-color))
5971 (defun org-font-lock-add-tag-faces (limit)
5972 "Add the special tag faces."
5973 (when (and org-tag-faces org-tags-special-faces-re)
5974 (while (re-search-forward org-tags-special-faces-re limit t)
5975 (add-text-properties (match-beginning 1) (match-end 1)
5976 (list 'face (org-get-tag-face 1)
5977 'font-lock-fontified t))
5978 (backward-char 1))))
5980 (defun org-font-lock-add-priority-faces (limit)
5981 "Add the special priority faces."
5982 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5983 (when (save-match-data (org-at-heading-p))
5984 (add-text-properties
5985 (match-beginning 0) (match-end 0)
5986 (list 'face (or (org-face-from-face-or-color
5987 'priority 'org-special-keyword
5988 (cdr (assoc (char-after (match-beginning 1))
5989 org-priority-faces)))
5990 'org-special-keyword)
5991 'font-lock-fontified t)))))
5993 (defun org-get-tag-face (kwd)
5994 "Get the right face for a TODO keyword KWD.
5995 If KWD is a number, get the corresponding match group."
5996 (if (numberp kwd) (setq kwd (match-string kwd)))
5997 (or (org-face-from-face-or-color
5998 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5999 'org-tag))
6001 (defun org-unfontify-region (beg end &optional maybe_loudly)
6002 "Remove fontification and activation overlays from links."
6003 (font-lock-default-unfontify-region beg end)
6004 (let* ((buffer-undo-list t)
6005 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6006 (inhibit-modification-hooks t)
6007 deactivate-mark buffer-file-name buffer-file-truename)
6008 (org-decompose-region beg end)
6009 (remove-text-properties beg end
6010 '(mouse-face t keymap t org-linked-text t
6011 invisible t intangible t
6012 org-no-flyspell t org-emphasis t))
6013 (org-remove-font-lock-display-properties beg end)))
6015 (defconst org-script-display '(((raise -0.3) (height 0.7))
6016 ((raise 0.3) (height 0.7))
6017 ((raise -0.5))
6018 ((raise 0.5)))
6019 "Display properties for showing superscripts and subscripts.")
6021 (defun org-remove-font-lock-display-properties (beg end)
6022 "Remove specific display properties that have been added by font lock.
6023 The will remove the raise properties that are used to show superscripts
6024 and subscripts."
6025 (let (next prop)
6026 (while (< beg end)
6027 (setq next (next-single-property-change beg 'display nil end)
6028 prop (get-text-property beg 'display))
6029 (if (member prop org-script-display)
6030 (put-text-property beg next 'display nil))
6031 (setq beg next))))
6033 (defun org-raise-scripts (limit)
6034 "Add raise properties to sub/superscripts."
6035 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6036 (if (re-search-forward
6037 (if (eq org-use-sub-superscripts t)
6038 org-match-substring-regexp
6039 org-match-substring-with-braces-regexp)
6040 limit t)
6041 (let* ((pos (point)) table-p comment-p
6042 (mpos (match-beginning 3))
6043 (emph-p (get-text-property mpos 'org-emphasis))
6044 (link-p (get-text-property mpos 'mouse-face))
6045 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6046 (goto-char (point-at-bol))
6047 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6048 comment-p (org-looking-at-p "[ \t]*#"))
6049 (goto-char pos)
6050 ;; FIXME: Should we go back one character here, for a_b^c
6051 ;; (goto-char (1- pos)) ;????????????????????
6052 (if (or comment-p emph-p link-p keyw-p)
6054 (put-text-property (match-beginning 3) (match-end 0)
6055 'display
6056 (if (equal (char-after (match-beginning 2)) ?^)
6057 (nth (if table-p 3 1) org-script-display)
6058 (nth (if table-p 2 0) org-script-display)))
6059 (add-text-properties (match-beginning 2) (match-end 2)
6060 (list 'invisible t
6061 'org-dwidth t 'org-dwidth-n 1))
6062 (if (and (eq (char-after (match-beginning 3)) ?{)
6063 (eq (char-before (match-end 3)) ?}))
6064 (progn
6065 (add-text-properties
6066 (match-beginning 3) (1+ (match-beginning 3))
6067 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6068 (add-text-properties
6069 (1- (match-end 3)) (match-end 3)
6070 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6071 t)))))
6073 ;;;; Visibility cycling, including org-goto and indirect buffer
6075 ;;; Cycling
6077 (defvar org-cycle-global-status nil)
6078 (make-variable-buffer-local 'org-cycle-global-status)
6079 (defvar org-cycle-subtree-status nil)
6080 (make-variable-buffer-local 'org-cycle-subtree-status)
6082 (defvar org-inlinetask-min-level)
6084 ;;;###autoload
6085 (defun org-cycle (&optional arg)
6086 "TAB-action and visibility cycling for Org-mode.
6088 This is the command invoked in Org-mode by the TAB key. Its main purpose
6089 is outline visibility cycling, but it also invokes other actions
6090 in special contexts.
6092 - When this function is called with a prefix argument, rotate the entire
6093 buffer through 3 states (global cycling)
6094 1. OVERVIEW: Show only top-level headlines.
6095 2. CONTENTS: Show all headlines of all levels, but no body text.
6096 3. SHOW ALL: Show everything.
6097 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6098 determined by the variable `org-startup-folded', and by any VISIBILITY
6099 properties in the buffer.
6100 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6101 including any drawers.
6103 - When inside a table, re-align the table and move to the next field.
6105 - When point is at the beginning of a headline, rotate the subtree started
6106 by this line through 3 different states (local cycling)
6107 1. FOLDED: Only the main headline is shown.
6108 2. CHILDREN: The main headline and the direct children are shown.
6109 From this state, you can move to one of the children
6110 and zoom in further.
6111 3. SUBTREE: Show the entire subtree, including body text.
6112 If there is no subtree, switch directly from CHILDREN to FOLDED.
6114 - When point is at the beginning of an empty headline and the variable
6115 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6116 of the headline by demoting and promoting it to likely levels. This
6117 speeds up creation document structure by pressing TAB once or several
6118 times right after creating a new headline.
6120 - When there is a numeric prefix, go up to a heading with level ARG, do
6121 a `show-subtree' and return to the previous cursor position. If ARG
6122 is negative, go up that many levels.
6124 - When point is not at the beginning of a headline, execute the global
6125 binding for TAB, which is re-indenting the line. See the option
6126 `org-cycle-emulate-tab' for details.
6128 - Special case: if point is at the beginning of the buffer and there is
6129 no headline in line 1, this function will act as if called with prefix arg
6130 (C-u TAB, same as S-TAB) also when called without prefix arg.
6131 But only if also the variable `org-cycle-global-at-bob' is t."
6132 (interactive "P")
6133 (org-load-modules-maybe)
6134 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6135 (and org-cycle-level-after-item/entry-creation
6136 (or (org-cycle-level)
6137 (org-cycle-item-indentation))))
6138 (let* ((limit-level
6139 (or org-cycle-max-level
6140 (and (boundp 'org-inlinetask-min-level)
6141 org-inlinetask-min-level
6142 (1- org-inlinetask-min-level))))
6143 (nstars (and limit-level
6144 (if org-odd-levels-only
6145 (and limit-level (1- (* limit-level 2)))
6146 limit-level)))
6147 (org-outline-regexp
6148 (if (not (derived-mode-p 'org-mode))
6149 outline-regexp
6150 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6151 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6152 (not (looking-at org-outline-regexp))))
6153 (org-cycle-hook
6154 (if bob-special
6155 (delq 'org-optimize-window-after-visibility-change
6156 (copy-sequence org-cycle-hook))
6157 org-cycle-hook))
6158 (pos (point)))
6160 (if (or bob-special (equal arg '(4)))
6161 ;; special case: use global cycling
6162 (setq arg t))
6164 (cond
6166 ((equal arg '(16))
6167 (setq last-command 'dummy)
6168 (org-set-startup-visibility)
6169 (message "Startup visibility, plus VISIBILITY properties"))
6171 ((equal arg '(64))
6172 (show-all)
6173 (message "Entire buffer visible, including drawers"))
6175 ;; Table: enter it or move to the next field.
6176 ((org-at-table-p 'any)
6177 (if (org-at-table.el-p)
6178 (message "Use C-c ' to edit table.el tables")
6179 (if arg (org-table-edit-field t)
6180 (org-table-justify-field-maybe)
6181 (call-interactively 'org-table-next-field))))
6183 ((run-hook-with-args-until-success
6184 'org-tab-after-check-for-table-hook))
6186 ;; Global cycling: delegate to `org-cycle-internal-global'.
6187 ((eq arg t) (org-cycle-internal-global))
6189 ;; Drawers: delegate to `org-flag-drawer'.
6190 ((and org-drawers org-drawer-regexp
6191 (save-excursion
6192 (beginning-of-line 1)
6193 (looking-at org-drawer-regexp)))
6194 (org-flag-drawer ; toggle block visibility
6195 (not (get-char-property (match-end 0) 'invisible))))
6197 ;; Show-subtree, ARG levels up from here.
6198 ((integerp arg)
6199 (save-excursion
6200 (org-back-to-heading)
6201 (outline-up-heading (if (< arg 0) (- arg)
6202 (- (funcall outline-level) arg)))
6203 (org-show-subtree)))
6205 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6206 ((and (featurep 'org-inlinetask)
6207 (org-inlinetask-at-task-p)
6208 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6209 (org-inlinetask-toggle-visibility))
6211 ((org-try-cdlatex-tab))
6213 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6214 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6215 (save-excursion (beginning-of-line 1)
6216 (looking-at org-outline-regexp)))
6217 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6218 (org-cycle-internal-local))
6220 ;; From there: TAB emulation and template completion.
6221 (buffer-read-only (org-back-to-heading))
6223 ((run-hook-with-args-until-success
6224 'org-tab-after-check-for-cycling-hook))
6226 ((org-try-structure-completion))
6228 ((run-hook-with-args-until-success
6229 'org-tab-before-tab-emulation-hook))
6231 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6232 (or (not (bolp))
6233 (not (looking-at org-outline-regexp))))
6234 (call-interactively (global-key-binding "\t")))
6236 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6237 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6238 (or (and (eq org-cycle-emulate-tab 'white)
6239 (= (match-end 0) (point-at-eol)))
6240 (and (eq org-cycle-emulate-tab 'whitestart)
6241 (>= (match-end 0) pos))))
6243 (eq org-cycle-emulate-tab t))
6244 (call-interactively (global-key-binding "\t")))
6246 (t (save-excursion
6247 (org-back-to-heading)
6248 (org-cycle)))))))
6250 (defun org-cycle-internal-global ()
6251 "Do the global cycling action."
6252 ;; Hack to avoid display of messages for .org attachments in Gnus
6253 (let ((ga (string-match "\\*fontification" (buffer-name))))
6254 (cond
6255 ((and (eq last-command this-command)
6256 (eq org-cycle-global-status 'overview))
6257 ;; We just created the overview - now do table of contents
6258 ;; This can be slow in very large buffers, so indicate action
6259 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6260 (unless ga (message "CONTENTS..."))
6261 (org-content)
6262 (unless ga (message "CONTENTS...done"))
6263 (setq org-cycle-global-status 'contents)
6264 (run-hook-with-args 'org-cycle-hook 'contents))
6266 ((and (eq last-command this-command)
6267 (eq org-cycle-global-status 'contents))
6268 ;; We just showed the table of contents - now show everything
6269 (run-hook-with-args 'org-pre-cycle-hook 'all)
6270 (show-all)
6271 (unless ga (message "SHOW ALL"))
6272 (setq org-cycle-global-status 'all)
6273 (run-hook-with-args 'org-cycle-hook 'all))
6276 ;; Default action: go to overview
6277 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6278 (org-overview)
6279 (unless ga (message "OVERVIEW"))
6280 (setq org-cycle-global-status 'overview)
6281 (run-hook-with-args 'org-cycle-hook 'overview)))))
6283 (defun org-cycle-internal-local ()
6284 "Do the local cycling action."
6285 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6286 ;; First, determine end of headline (EOH), end of subtree or item
6287 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6288 (save-excursion
6289 (if (org-at-item-p)
6290 (progn
6291 (beginning-of-line)
6292 (setq struct (org-list-struct))
6293 (setq eoh (point-at-eol))
6294 (setq eos (org-list-get-item-end-before-blank (point) struct))
6295 (setq has-children (org-list-has-child-p (point) struct)))
6296 (org-back-to-heading)
6297 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6298 (setq eos (save-excursion
6299 (org-end-of-subtree t)
6300 (unless (eobp)
6301 (skip-chars-forward " \t\n"))
6302 (if (eobp) (point) (1- (point)))))
6303 (setq has-children
6304 (or (save-excursion
6305 (let ((level (funcall outline-level)))
6306 (outline-next-heading)
6307 (and (org-at-heading-p t)
6308 (> (funcall outline-level) level))))
6309 (save-excursion
6310 (org-list-search-forward (org-item-beginning-re) eos t)))))
6311 ;; Determine end invisible part of buffer (EOL)
6312 (beginning-of-line 2)
6313 ;; XEmacs doesn't have `next-single-char-property-change'
6314 (if (featurep 'xemacs)
6315 (while (and (not (eobp)) ;; this is like `next-line'
6316 (get-char-property (1- (point)) 'invisible))
6317 (beginning-of-line 2))
6318 (while (and (not (eobp)) ;; this is like `next-line'
6319 (get-char-property (1- (point)) 'invisible))
6320 (goto-char (next-single-char-property-change (point) 'invisible))
6321 (and (eolp) (beginning-of-line 2))))
6322 (setq eol (point)))
6323 ;; Find out what to do next and set `this-command'
6324 (cond
6325 ((= eos eoh)
6326 ;; Nothing is hidden behind this heading
6327 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6328 (message "EMPTY ENTRY")
6329 (setq org-cycle-subtree-status nil)
6330 (save-excursion
6331 (goto-char eos)
6332 (outline-next-heading)
6333 (if (outline-invisible-p) (org-flag-heading nil))))
6334 ((and (or (>= eol eos)
6335 (not (string-match "\\S-" (buffer-substring eol eos))))
6336 (or has-children
6337 (not (setq children-skipped
6338 org-cycle-skip-children-state-if-no-children))))
6339 ;; Entire subtree is hidden in one line: children view
6340 (run-hook-with-args 'org-pre-cycle-hook 'children)
6341 (if (org-at-item-p)
6342 (org-list-set-item-visibility (point-at-bol) struct 'children)
6343 (org-show-entry)
6344 (org-with-limited-levels (show-children))
6345 ;; FIXME: This slows down the func way too much.
6346 ;; How keep drawers hidden in subtree anyway?
6347 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6348 ;; (org-cycle-hide-drawers 'subtree))
6350 ;; Fold every list in subtree to top-level items.
6351 (when (eq org-cycle-include-plain-lists 'integrate)
6352 (save-excursion
6353 (org-back-to-heading)
6354 (while (org-list-search-forward (org-item-beginning-re) eos t)
6355 (beginning-of-line 1)
6356 (let* ((struct (org-list-struct))
6357 (prevs (org-list-prevs-alist struct))
6358 (end (org-list-get-bottom-point struct)))
6359 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6360 (org-list-get-all-items (point) struct prevs))
6361 (goto-char end))))))
6362 (message "CHILDREN")
6363 (save-excursion
6364 (goto-char eos)
6365 (outline-next-heading)
6366 (if (outline-invisible-p) (org-flag-heading nil)))
6367 (setq org-cycle-subtree-status 'children)
6368 (run-hook-with-args 'org-cycle-hook 'children))
6369 ((or children-skipped
6370 (and (eq last-command this-command)
6371 (eq org-cycle-subtree-status 'children)))
6372 ;; We just showed the children, or no children are there,
6373 ;; now show everything.
6374 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6375 (outline-flag-region eoh eos nil)
6376 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6377 (setq org-cycle-subtree-status 'subtree)
6378 (run-hook-with-args 'org-cycle-hook 'subtree))
6380 ;; Default action: hide the subtree.
6381 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6382 (outline-flag-region eoh eos t)
6383 (message "FOLDED")
6384 (setq org-cycle-subtree-status 'folded)
6385 (run-hook-with-args 'org-cycle-hook 'folded)))))
6387 ;;;###autoload
6388 (defun org-global-cycle (&optional arg)
6389 "Cycle the global visibility. For details see `org-cycle'.
6390 With \\[universal-argument] prefix arg, switch to startup visibility.
6391 With a numeric prefix, show all headlines up to that level."
6392 (interactive "P")
6393 (let ((org-cycle-include-plain-lists
6394 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6395 (cond
6396 ((integerp arg)
6397 (show-all)
6398 (hide-sublevels arg)
6399 (setq org-cycle-global-status 'contents))
6400 ((equal arg '(4))
6401 (org-set-startup-visibility)
6402 (message "Startup visibility, plus VISIBILITY properties."))
6404 (org-cycle '(4))))))
6406 (defun org-set-startup-visibility ()
6407 "Set the visibility required by startup options and properties."
6408 (cond
6409 ((eq org-startup-folded t)
6410 (org-cycle '(4)))
6411 ((eq org-startup-folded 'content)
6412 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6413 (org-cycle '(4)) (org-cycle '(4)))))
6414 (unless (eq org-startup-folded 'showeverything)
6415 (if org-hide-block-startup (org-hide-block-all))
6416 (org-set-visibility-according-to-property 'no-cleanup)
6417 (org-cycle-hide-archived-subtrees 'all)
6418 (org-cycle-hide-drawers 'all)
6419 (org-cycle-show-empty-lines t)))
6421 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6422 "Switch subtree visibilities according to :VISIBILITY: property."
6423 (interactive)
6424 (let (org-show-entry-below state)
6425 (save-excursion
6426 (goto-char (point-min))
6427 (while (re-search-forward
6428 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6429 nil t)
6430 (setq state (match-string 1))
6431 (save-excursion
6432 (org-back-to-heading t)
6433 (hide-subtree)
6434 (org-reveal)
6435 (cond
6436 ((equal state '("fold" "folded"))
6437 (hide-subtree))
6438 ((equal state "children")
6439 (org-show-hidden-entry)
6440 (show-children))
6441 ((equal state "content")
6442 (save-excursion
6443 (save-restriction
6444 (org-narrow-to-subtree)
6445 (org-content))))
6446 ((member state '("all" "showall"))
6447 (show-subtree)))))
6448 (unless no-cleanup
6449 (org-cycle-hide-archived-subtrees 'all)
6450 (org-cycle-hide-drawers 'all)
6451 (org-cycle-show-empty-lines 'all)))))
6453 ;; This function uses outline-regexp instead of the more fundamental
6454 ;; org-outline-regexp so that org-cycle-global works outside of Org
6455 ;; buffers, where outline-regexp is needed.
6456 (defun org-overview ()
6457 "Switch to overview mode, showing only top-level headlines.
6458 Really, this shows all headlines with level equal or greater than the level
6459 of the first headline in the buffer. This is important, because if the
6460 first headline is not level one, then (hide-sublevels 1) gives confusing
6461 results."
6462 (interactive)
6463 (let ((level (save-excursion
6464 (goto-char (point-min))
6465 (if (re-search-forward (concat "^" outline-regexp) nil t)
6466 (progn
6467 (goto-char (match-beginning 0))
6468 (funcall outline-level))))))
6469 (and level (hide-sublevels level))))
6471 (defun org-content (&optional arg)
6472 "Show all headlines in the buffer, like a table of contents.
6473 With numerical argument N, show content up to level N."
6474 (interactive "P")
6475 (save-excursion
6476 ;; Visit all headings and show their offspring
6477 (and (integerp arg) (org-overview))
6478 (goto-char (point-max))
6479 (catch 'exit
6480 (while (and (progn (condition-case nil
6481 (outline-previous-visible-heading 1)
6482 (error (goto-char (point-min))))
6484 (looking-at org-outline-regexp))
6485 (if (integerp arg)
6486 (show-children (1- arg))
6487 (show-branches))
6488 (if (bobp) (throw 'exit nil))))))
6491 (defun org-optimize-window-after-visibility-change (state)
6492 "Adjust the window after a change in outline visibility.
6493 This function is the default value of the hook `org-cycle-hook'."
6494 (when (get-buffer-window (current-buffer))
6495 (cond
6496 ((eq state 'content) nil)
6497 ((eq state 'all) nil)
6498 ((eq state 'folded) nil)
6499 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6500 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6502 (defun org-remove-empty-overlays-at (pos)
6503 "Remove outline overlays that do not contain non-white stuff."
6504 (mapc
6505 (lambda (o)
6506 (and (eq 'outline (overlay-get o 'invisible))
6507 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6508 (overlay-end o))))
6509 (delete-overlay o)))
6510 (overlays-at pos)))
6512 (defun org-clean-visibility-after-subtree-move ()
6513 "Fix visibility issues after moving a subtree."
6514 ;; First, find a reasonable region to look at:
6515 ;; Start two siblings above, end three below
6516 (let* ((beg (save-excursion
6517 (and (org-get-last-sibling)
6518 (org-get-last-sibling))
6519 (point)))
6520 (end (save-excursion
6521 (and (org-get-next-sibling)
6522 (org-get-next-sibling)
6523 (org-get-next-sibling))
6524 (if (org-at-heading-p)
6525 (point-at-eol)
6526 (point))))
6527 (level (looking-at "\\*+"))
6528 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6529 (save-excursion
6530 (save-restriction
6531 (narrow-to-region beg end)
6532 (when re
6533 ;; Properly fold already folded siblings
6534 (goto-char (point-min))
6535 (while (re-search-forward re nil t)
6536 (if (and (not (outline-invisible-p))
6537 (save-excursion
6538 (goto-char (point-at-eol)) (outline-invisible-p)))
6539 (hide-entry))))
6540 (org-cycle-show-empty-lines 'overview)
6541 (org-cycle-hide-drawers 'overview)))))
6543 (defun org-cycle-show-empty-lines (state)
6544 "Show empty lines above all visible headlines.
6545 The region to be covered depends on STATE when called through
6546 `org-cycle-hook'. Lisp program can use t for STATE to get the
6547 entire buffer covered. Note that an empty line is only shown if there
6548 are at least `org-cycle-separator-lines' empty lines before the headline."
6549 (when (not (= org-cycle-separator-lines 0))
6550 (save-excursion
6551 (let* ((n (abs org-cycle-separator-lines))
6552 (re (cond
6553 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6554 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6555 (t (let ((ns (number-to-string (- n 2))))
6556 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6557 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6558 beg end b e)
6559 (cond
6560 ((memq state '(overview contents t))
6561 (setq beg (point-min) end (point-max)))
6562 ((memq state '(children folded))
6563 (setq beg (point) end (progn (org-end-of-subtree t t)
6564 (beginning-of-line 2)
6565 (point)))))
6566 (when beg
6567 (goto-char beg)
6568 (while (re-search-forward re end t)
6569 (unless (get-char-property (match-end 1) 'invisible)
6570 (setq e (match-end 1))
6571 (if (< org-cycle-separator-lines 0)
6572 (setq b (save-excursion
6573 (goto-char (match-beginning 0))
6574 (org-back-over-empty-lines)
6575 (if (save-excursion
6576 (goto-char (max (point-min) (1- (point))))
6577 (org-at-heading-p))
6578 (1- (point))
6579 (point))))
6580 (setq b (match-beginning 1)))
6581 (outline-flag-region b e nil)))))))
6582 ;; Never hide empty lines at the end of the file.
6583 (save-excursion
6584 (goto-char (point-max))
6585 (outline-previous-heading)
6586 (outline-end-of-heading)
6587 (if (and (looking-at "[ \t\n]+")
6588 (= (match-end 0) (point-max)))
6589 (outline-flag-region (point) (match-end 0) nil))))
6591 (defun org-show-empty-lines-in-parent ()
6592 "Move to the parent and re-show empty lines before visible headlines."
6593 (save-excursion
6594 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6595 (org-cycle-show-empty-lines context))))
6597 (defun org-files-list ()
6598 "Return `org-agenda-files' list, plus all open org-mode files.
6599 This is useful for operations that need to scan all of a user's
6600 open and agenda-wise Org files."
6601 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6602 (dolist (buf (buffer-list))
6603 (with-current-buffer buf
6604 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6605 (let ((file (expand-file-name (buffer-file-name))))
6606 (unless (member file files)
6607 (push file files))))))
6608 files))
6610 (defsubst org-entry-beginning-position ()
6611 "Return the beginning position of the current entry."
6612 (save-excursion (outline-back-to-heading t) (point)))
6614 (defsubst org-entry-end-position ()
6615 "Return the end position of the current entry."
6616 (save-excursion (outline-next-heading) (point)))
6618 (defun org-cycle-hide-drawers (state)
6619 "Re-hide all drawers after a visibility state change."
6620 (when (and (derived-mode-p 'org-mode)
6621 (not (memq state '(overview folded contents))))
6622 (save-excursion
6623 (let* ((globalp (memq state '(contents all)))
6624 (beg (if globalp (point-min) (point)))
6625 (end (if globalp (point-max)
6626 (if (eq state 'children)
6627 (save-excursion (outline-next-heading) (point))
6628 (org-end-of-subtree t)))))
6629 (goto-char beg)
6630 (while (re-search-forward org-drawer-regexp end t)
6631 (org-flag-drawer t))))))
6633 (defun org-cycle-hide-inline-tasks (state)
6634 "Re-hide inline task when switching to 'contents visibility state."
6635 (when (and (eq state 'contents)
6636 (boundp 'org-inlinetask-min-level)
6637 org-inlinetask-min-level)
6638 (hide-sublevels (1- org-inlinetask-min-level))))
6640 (defun org-flag-drawer (flag)
6641 "When FLAG is non-nil, hide the drawer we are within.
6642 Otherwise make it visible."
6643 (save-excursion
6644 (beginning-of-line 1)
6645 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6646 (let ((b (match-end 0)))
6647 (if (re-search-forward
6648 "^[ \t]*:END:"
6649 (save-excursion (outline-next-heading) (point)) t)
6650 (outline-flag-region b (point-at-eol) flag)
6651 (error ":END: line missing at position %s" b))))))
6653 (defun org-subtree-end-visible-p ()
6654 "Is the end of the current subtree visible?"
6655 (pos-visible-in-window-p
6656 (save-excursion (org-end-of-subtree t) (point))))
6658 (defun org-first-headline-recenter (&optional N)
6659 "Move cursor to the first headline and recenter the headline.
6660 Optional argument N means put the headline into the Nth line of the window."
6661 (goto-char (point-min))
6662 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6663 (beginning-of-line)
6664 (recenter (prefix-numeric-value N))))
6666 ;;; Saving and restoring visibility
6668 (defun org-outline-overlay-data (&optional use-markers)
6669 "Return a list of the locations of all outline overlays.
6670 These are overlays with the `invisible' property value `outline'.
6671 The return value is a list of cons cells, with start and stop
6672 positions for each overlay.
6673 If USE-MARKERS is set, return the positions as markers."
6674 (let (beg end)
6675 (save-excursion
6676 (save-restriction
6677 (widen)
6678 (delq nil
6679 (mapcar (lambda (o)
6680 (when (eq (overlay-get o 'invisible) 'outline)
6681 (setq beg (overlay-start o)
6682 end (overlay-end o))
6683 (and beg end (> end beg)
6684 (if use-markers
6685 (cons (move-marker (make-marker) beg)
6686 (move-marker (make-marker) end))
6687 (cons beg end)))))
6688 (overlays-in (point-min) (point-max))))))))
6690 (defun org-set-outline-overlay-data (data)
6691 "Create visibility overlays for all positions in DATA.
6692 DATA should have been made by `org-outline-overlay-data'."
6693 (let (o)
6694 (save-excursion
6695 (save-restriction
6696 (widen)
6697 (show-all)
6698 (mapc (lambda (c)
6699 (outline-flag-region (car c) (cdr c) t))
6700 data)))))
6702 ;;; Folding of blocks
6704 (defvar org-hide-block-overlays nil
6705 "Overlays hiding blocks.")
6706 (make-variable-buffer-local 'org-hide-block-overlays)
6708 (defun org-block-map (function &optional start end)
6709 "Call FUNCTION at the head of all source blocks in the current buffer.
6710 Optional arguments START and END can be used to limit the range."
6711 (let ((start (or start (point-min)))
6712 (end (or end (point-max))))
6713 (save-excursion
6714 (goto-char start)
6715 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6716 (save-excursion
6717 (save-match-data
6718 (goto-char (match-beginning 0))
6719 (funcall function)))))))
6721 (defun org-hide-block-toggle-all ()
6722 "Toggle the visibility of all blocks in the current buffer."
6723 (org-block-map #'org-hide-block-toggle))
6725 (defun org-hide-block-all ()
6726 "Fold all blocks in the current buffer."
6727 (interactive)
6728 (org-show-block-all)
6729 (org-block-map #'org-hide-block-toggle-maybe))
6731 (defun org-show-block-all ()
6732 "Unfold all blocks in the current buffer."
6733 (interactive)
6734 (mapc 'delete-overlay org-hide-block-overlays)
6735 (setq org-hide-block-overlays nil))
6737 (defun org-hide-block-toggle-maybe ()
6738 "Toggle visibility of block at point."
6739 (interactive)
6740 (let ((case-fold-search t))
6741 (if (save-excursion
6742 (beginning-of-line 1)
6743 (looking-at org-block-regexp))
6744 (progn (org-hide-block-toggle)
6745 t) ;; to signal that we took action
6746 nil))) ;; to signal that we did not
6748 (defun org-hide-block-toggle (&optional force)
6749 "Toggle the visibility of the current block."
6750 (interactive)
6751 (save-excursion
6752 (beginning-of-line)
6753 (if (re-search-forward org-block-regexp nil t)
6754 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6755 (end (match-end 0)) ;; end of entire body
6757 (if (memq t (mapcar (lambda (overlay)
6758 (eq (overlay-get overlay 'invisible)
6759 'org-hide-block))
6760 (overlays-at start)))
6761 (if (or (not force) (eq force 'off))
6762 (mapc (lambda (ov)
6763 (when (member ov org-hide-block-overlays)
6764 (setq org-hide-block-overlays
6765 (delq ov org-hide-block-overlays)))
6766 (when (eq (overlay-get ov 'invisible)
6767 'org-hide-block)
6768 (delete-overlay ov)))
6769 (overlays-at start)))
6770 (setq ov (make-overlay start end))
6771 (overlay-put ov 'invisible 'org-hide-block)
6772 ;; make the block accessible to isearch
6773 (overlay-put
6774 ov 'isearch-open-invisible
6775 (lambda (ov)
6776 (when (member ov org-hide-block-overlays)
6777 (setq org-hide-block-overlays
6778 (delq ov org-hide-block-overlays)))
6779 (when (eq (overlay-get ov 'invisible)
6780 'org-hide-block)
6781 (delete-overlay ov))))
6782 (push ov org-hide-block-overlays)))
6783 (error "Not looking at a source block"))))
6785 ;; org-tab-after-check-for-cycling-hook
6786 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6787 ;; Remove overlays when changing major mode
6788 (add-hook 'org-mode-hook
6789 (lambda () (org-add-hook 'change-major-mode-hook
6790 'org-show-block-all 'append 'local)))
6792 ;;; Org-goto
6794 (defvar org-goto-window-configuration nil)
6795 (defvar org-goto-marker nil)
6796 (defvar org-goto-map
6797 (let ((map (make-sparse-keymap)))
6798 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6799 (while (setq cmd (pop cmds))
6800 (substitute-key-definition cmd cmd map global-map)))
6801 (suppress-keymap map)
6802 (org-defkey map "\C-m" 'org-goto-ret)
6803 (org-defkey map [(return)] 'org-goto-ret)
6804 (org-defkey map [(left)] 'org-goto-left)
6805 (org-defkey map [(right)] 'org-goto-right)
6806 (org-defkey map [(control ?g)] 'org-goto-quit)
6807 (org-defkey map "\C-i" 'org-cycle)
6808 (org-defkey map [(tab)] 'org-cycle)
6809 (org-defkey map [(down)] 'outline-next-visible-heading)
6810 (org-defkey map [(up)] 'outline-previous-visible-heading)
6811 (if org-goto-auto-isearch
6812 (if (fboundp 'define-key-after)
6813 (define-key-after map [t] 'org-goto-local-auto-isearch)
6814 nil)
6815 (org-defkey map "q" 'org-goto-quit)
6816 (org-defkey map "n" 'outline-next-visible-heading)
6817 (org-defkey map "p" 'outline-previous-visible-heading)
6818 (org-defkey map "f" 'outline-forward-same-level)
6819 (org-defkey map "b" 'outline-backward-same-level)
6820 (org-defkey map "u" 'outline-up-heading))
6821 (org-defkey map "/" 'org-occur)
6822 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6823 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6824 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6825 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6826 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6827 map))
6829 (defconst org-goto-help
6830 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6831 RET=jump to location [Q]uit and return to previous location
6832 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6834 (defvar org-goto-start-pos) ; dynamically scoped parameter
6836 ;; FIXME: Docstring does not mention both interfaces
6837 (defun org-goto (&optional alternative-interface)
6838 "Look up a different location in the current file, keeping current visibility.
6840 When you want look-up or go to a different location in a
6841 document, the fastest way is often to fold the entire buffer and
6842 then dive into the tree. This method has the disadvantage, that
6843 the previous location will be folded, which may not be what you
6844 want.
6846 This command works around this by showing a copy of the current
6847 buffer in an indirect buffer, in overview mode. You can dive
6848 into the tree in that copy, use org-occur and incremental search
6849 to find a location. When pressing RET or `Q', the command
6850 returns to the original buffer in which the visibility is still
6851 unchanged. After RET it will also jump to the location selected
6852 in the indirect buffer and expose the headline hierarchy above.
6854 With a prefix argument, use the alternative interface: e.g. if
6855 `org-goto-interface' is 'outline use 'outline-path-completion."
6856 (interactive "P")
6857 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6858 (org-refile-use-outline-path t)
6859 (org-refile-target-verify-function nil)
6860 (interface
6861 (if (not alternative-interface)
6862 org-goto-interface
6863 (if (eq org-goto-interface 'outline)
6864 'outline-path-completion
6865 'outline)))
6866 (org-goto-start-pos (point))
6867 (selected-point
6868 (if (eq interface 'outline)
6869 (car (org-get-location (current-buffer) org-goto-help))
6870 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6871 (org-refile-check-position pa)
6872 (nth 3 pa)))))
6873 (if selected-point
6874 (progn
6875 (org-mark-ring-push org-goto-start-pos)
6876 (goto-char selected-point)
6877 (if (or (outline-invisible-p) (org-invisible-p2))
6878 (org-show-context 'org-goto)))
6879 (message "Quit"))))
6881 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6882 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6883 (defvar org-goto-local-auto-isearch-map) ; defined below
6885 (defun org-get-location (buf help)
6886 "Let the user select a location in the Org-mode buffer BUF.
6887 This function uses a recursive edit. It returns the selected position
6888 or nil."
6889 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6890 (isearch-hide-immediately nil)
6891 (isearch-search-fun-function
6892 (lambda () 'org-goto-local-search-headings))
6893 (org-goto-selected-point org-goto-exit-command)
6894 (pop-up-frames nil)
6895 (special-display-buffer-names nil)
6896 (special-display-regexps nil)
6897 (special-display-function nil))
6898 (save-excursion
6899 (save-window-excursion
6900 (delete-other-windows)
6901 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6902 (org-pop-to-buffer-same-window
6903 (condition-case nil
6904 (make-indirect-buffer (current-buffer) "*org-goto*")
6905 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6906 (with-output-to-temp-buffer "*Help*"
6907 (princ help))
6908 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6909 (setq buffer-read-only nil)
6910 (let ((org-startup-truncated t)
6911 (org-startup-folded nil)
6912 (org-startup-align-all-tables nil))
6913 (org-mode)
6914 (org-overview))
6915 (setq buffer-read-only t)
6916 (if (and (boundp 'org-goto-start-pos)
6917 (integer-or-marker-p org-goto-start-pos))
6918 (let ((org-show-hierarchy-above t)
6919 (org-show-siblings t)
6920 (org-show-following-heading t))
6921 (goto-char org-goto-start-pos)
6922 (and (outline-invisible-p) (org-show-context)))
6923 (goto-char (point-min)))
6924 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6925 (message "Select location and press RET")
6926 (use-local-map org-goto-map)
6927 (recursive-edit)
6929 (kill-buffer "*org-goto*")
6930 (cons org-goto-selected-point org-goto-exit-command)))
6932 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6933 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6934 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6935 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6937 (defun org-goto-local-search-headings (string bound noerror)
6938 "Search and make sure that any matches are in headlines."
6939 (catch 'return
6940 (while (if isearch-forward
6941 (search-forward string bound noerror)
6942 (search-backward string bound noerror))
6943 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6944 (and (member :headline context)
6945 (not (member :tags context))))
6946 (throw 'return (point))))))
6948 (defun org-goto-local-auto-isearch ()
6949 "Start isearch."
6950 (interactive)
6951 (goto-char (point-min))
6952 (let ((keys (this-command-keys)))
6953 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6954 (isearch-mode t)
6955 (isearch-process-search-char (string-to-char keys)))))
6957 (defun org-goto-ret (&optional arg)
6958 "Finish `org-goto' by going to the new location."
6959 (interactive "P")
6960 (setq org-goto-selected-point (point)
6961 org-goto-exit-command 'return)
6962 (throw 'exit nil))
6964 (defun org-goto-left ()
6965 "Finish `org-goto' by going to the new location."
6966 (interactive)
6967 (if (org-at-heading-p)
6968 (progn
6969 (beginning-of-line 1)
6970 (setq org-goto-selected-point (point)
6971 org-goto-exit-command 'left)
6972 (throw 'exit nil))
6973 (error "Not on a heading")))
6975 (defun org-goto-right ()
6976 "Finish `org-goto' by going to the new location."
6977 (interactive)
6978 (if (org-at-heading-p)
6979 (progn
6980 (setq org-goto-selected-point (point)
6981 org-goto-exit-command 'right)
6982 (throw 'exit nil))
6983 (error "Not on a heading")))
6985 (defun org-goto-quit ()
6986 "Finish `org-goto' without cursor motion."
6987 (interactive)
6988 (setq org-goto-selected-point nil)
6989 (setq org-goto-exit-command 'quit)
6990 (throw 'exit nil))
6992 ;;; Indirect buffer display of subtrees
6994 (defvar org-indirect-dedicated-frame nil
6995 "This is the frame being used for indirect tree display.")
6996 (defvar org-last-indirect-buffer nil)
6998 (defun org-tree-to-indirect-buffer (&optional arg)
6999 "Create indirect buffer and narrow it to current subtree.
7000 With a numerical prefix ARG, go up to this level and then take that tree.
7001 If ARG is negative, go up that many levels.
7003 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7004 indirect buffer previously made with this command, to avoid proliferation of
7005 indirect buffers. However, when you call the command with a \
7006 \\[universal-argument] prefix, or
7007 when `org-indirect-buffer-display' is `new-frame', the last buffer
7008 is kept so that you can work with several indirect buffers at the same time.
7009 If `org-indirect-buffer-display' is `dedicated-frame', the \
7010 \\[universal-argument] prefix also
7011 requests that a new frame be made for the new buffer, so that the dedicated
7012 frame is not changed."
7013 (interactive "P")
7014 (let ((cbuf (current-buffer))
7015 (cwin (selected-window))
7016 (pos (point))
7017 beg end level heading ibuf)
7018 (save-excursion
7019 (org-back-to-heading t)
7020 (when (numberp arg)
7021 (setq level (org-outline-level))
7022 (if (< arg 0) (setq arg (+ level arg)))
7023 (while (> (setq level (org-outline-level)) arg)
7024 (org-up-heading-safe)))
7025 (setq beg (point)
7026 heading (org-get-heading))
7027 (org-end-of-subtree t t)
7028 (if (org-at-heading-p) (backward-char 1))
7029 (setq end (point)))
7030 (if (and (buffer-live-p org-last-indirect-buffer)
7031 (not (eq org-indirect-buffer-display 'new-frame))
7032 (not arg))
7033 (kill-buffer org-last-indirect-buffer))
7034 (setq ibuf (org-get-indirect-buffer cbuf)
7035 org-last-indirect-buffer ibuf)
7036 (cond
7037 ((or (eq org-indirect-buffer-display 'new-frame)
7038 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7039 (select-frame (make-frame))
7040 (delete-other-windows)
7041 (org-pop-to-buffer-same-window ibuf)
7042 (org-set-frame-title heading))
7043 ((eq org-indirect-buffer-display 'dedicated-frame)
7044 (raise-frame
7045 (select-frame (or (and org-indirect-dedicated-frame
7046 (frame-live-p org-indirect-dedicated-frame)
7047 org-indirect-dedicated-frame)
7048 (setq org-indirect-dedicated-frame (make-frame)))))
7049 (delete-other-windows)
7050 (org-pop-to-buffer-same-window ibuf)
7051 (org-set-frame-title (concat "Indirect: " heading)))
7052 ((eq org-indirect-buffer-display 'current-window)
7053 (org-pop-to-buffer-same-window ibuf))
7054 ((eq org-indirect-buffer-display 'other-window)
7055 (pop-to-buffer ibuf))
7056 (t (error "Invalid value")))
7057 (if (featurep 'xemacs)
7058 (save-excursion (org-mode) (turn-on-font-lock)))
7059 (narrow-to-region beg end)
7060 (show-all)
7061 (goto-char pos)
7062 (run-hook-with-args 'org-cycle-hook 'all)
7063 (and (window-live-p cwin) (select-window cwin))))
7065 (defun org-get-indirect-buffer (&optional buffer)
7066 (setq buffer (or buffer (current-buffer)))
7067 (let ((n 1) (base (buffer-name buffer)) bname)
7068 (while (buffer-live-p
7069 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7070 (setq n (1+ n)))
7071 (condition-case nil
7072 (make-indirect-buffer buffer bname 'clone)
7073 (error (make-indirect-buffer buffer bname)))))
7075 (defun org-set-frame-title (title)
7076 "Set the title of the current frame to the string TITLE."
7077 ;; FIXME: how to name a single frame in XEmacs???
7078 (unless (featurep 'xemacs)
7079 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7081 ;;;; Structure editing
7083 ;;; Inserting headlines
7085 (defun org-previous-line-empty-p ()
7086 (save-excursion
7087 (and (not (bobp))
7088 (or (beginning-of-line 0) t)
7089 (save-match-data
7090 (looking-at "[ \t]*$")))))
7092 (defun org-insert-heading (&optional force-heading invisible-ok)
7093 "Insert a new heading or item with same depth at point.
7094 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7095 If point is at the beginning of a headline, insert a sibling before the
7096 current headline. If point is not at the beginning, split the line,
7097 create the new headline with the text in the current line after point
7098 \(but see also the variable `org-M-RET-may-split-line').
7100 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7101 This is important for non-interactive uses of the command."
7102 (interactive "P")
7103 (if (or (= (buffer-size) 0)
7104 (and (not (save-excursion
7105 (and (ignore-errors (org-back-to-heading invisible-ok))
7106 (org-at-heading-p))))
7107 (or force-heading (not (org-in-item-p)))))
7108 (progn
7109 (insert "\n* ")
7110 (run-hooks 'org-insert-heading-hook))
7111 (when (or force-heading (not (org-insert-item)))
7112 (let* ((empty-line-p nil)
7113 (level nil)
7114 (on-heading (org-at-heading-p))
7115 (head (save-excursion
7116 (condition-case nil
7117 (progn
7118 (org-back-to-heading invisible-ok)
7119 (when (and (not on-heading)
7120 (featurep 'org-inlinetask)
7121 (integerp org-inlinetask-min-level)
7122 (>= (length (match-string 0))
7123 org-inlinetask-min-level))
7124 ;; Find a heading level before the inline task
7125 (while (and (setq level (org-up-heading-safe))
7126 (>= level org-inlinetask-min-level)))
7127 (if (org-at-heading-p)
7128 (org-back-to-heading invisible-ok)
7129 (error "This should not happen")))
7130 (setq empty-line-p (org-previous-line-empty-p))
7131 (match-string 0))
7132 (error "*"))))
7133 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7134 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7135 pos hide-previous previous-pos)
7136 (cond
7137 ((and (org-at-heading-p) (bolp)
7138 (or (bobp)
7139 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7140 ;; insert before the current line
7141 (open-line (if blank 2 1)))
7142 ((and (bolp)
7143 (not org-insert-heading-respect-content)
7144 (or (bobp)
7145 (save-excursion
7146 (backward-char 1) (not (outline-invisible-p)))))
7147 ;; insert right here
7148 nil)
7150 ;; somewhere in the line
7151 (save-excursion
7152 (setq previous-pos (point-at-bol))
7153 (end-of-line)
7154 (setq hide-previous (outline-invisible-p)))
7155 (and org-insert-heading-respect-content (org-show-subtree))
7156 (let ((split
7157 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7158 (save-excursion
7159 (let ((p (point)))
7160 (goto-char (point-at-bol))
7161 (and (looking-at org-complex-heading-regexp)
7162 (match-beginning 4)
7163 (> p (match-beginning 4)))))))
7164 tags pos)
7165 (cond
7166 (org-insert-heading-respect-content
7167 (org-end-of-subtree nil t)
7168 (when (featurep 'org-inlinetask)
7169 (while (and (not (eobp))
7170 (looking-at "\\(\\*+\\)[ \t]+")
7171 (>= (length (match-string 1))
7172 org-inlinetask-min-level))
7173 (org-end-of-subtree nil t)))
7174 (or (bolp) (newline))
7175 (or (org-previous-line-empty-p)
7176 (and blank (newline)))
7177 (open-line 1))
7178 ((org-at-heading-p)
7179 (when hide-previous
7180 (show-children)
7181 (org-show-entry))
7182 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7183 (setq tags (and (match-end 2) (match-string 2)))
7184 (and (match-end 1)
7185 (delete-region (match-beginning 1) (match-end 1)))
7186 (setq pos (point-at-bol))
7187 (or split (end-of-line 1))
7188 (delete-horizontal-space)
7189 (if (string-match "\\`\\*+\\'"
7190 (buffer-substring (point-at-bol) (point)))
7191 (insert " "))
7192 (newline (if blank 2 1))
7193 (when tags
7194 (save-excursion
7195 (goto-char pos)
7196 (end-of-line 1)
7197 (insert " " tags)
7198 (org-set-tags nil 'align))))
7200 (or split (end-of-line 1))
7201 (newline (if blank 2 1)))))))
7202 (insert head) (just-one-space)
7203 (setq pos (point))
7204 (end-of-line 1)
7205 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7206 (when (and org-insert-heading-respect-content hide-previous)
7207 (save-excursion
7208 (goto-char previous-pos)
7209 (hide-subtree)))
7210 (run-hooks 'org-insert-heading-hook)))))
7212 (defun org-get-heading (&optional no-tags no-todo)
7213 "Return the heading of the current entry, without the stars.
7214 When NO-TAGS is non-nil, don't include tags.
7215 When NO-TODO is non-nil, don't include TODO keywords."
7216 (save-excursion
7217 (org-back-to-heading t)
7218 (cond
7219 ((and no-tags no-todo)
7220 (looking-at org-complex-heading-regexp)
7221 (match-string 4))
7222 (no-tags
7223 (looking-at (concat org-outline-regexp
7224 "\\(.*?\\)"
7225 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7226 (match-string 1))
7227 (no-todo
7228 (looking-at org-todo-line-regexp)
7229 (match-string 3))
7230 (t (looking-at org-heading-regexp)
7231 (match-string 2)))))
7233 (defun org-heading-components ()
7234 "Return the components of the current heading.
7235 This is a list with the following elements:
7236 - the level as an integer
7237 - the reduced level, different if `org-odd-levels-only' is set.
7238 - the TODO keyword, or nil
7239 - the priority character, like ?A, or nil if no priority is given
7240 - the headline text itself, or the tags string if no headline text
7241 - the tags string, or nil."
7242 (save-excursion
7243 (org-back-to-heading t)
7244 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7245 (list (length (match-string 1))
7246 (org-reduced-level (length (match-string 1)))
7247 (org-match-string-no-properties 2)
7248 (and (match-end 3) (aref (match-string 3) 2))
7249 (org-match-string-no-properties 4)
7250 (org-match-string-no-properties 5)))))
7252 (defun org-get-entry ()
7253 "Get the entry text, after heading, entire subtree."
7254 (save-excursion
7255 (org-back-to-heading t)
7256 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7258 (defun org-insert-heading-after-current ()
7259 "Insert a new heading with same level as current, after current subtree."
7260 (interactive)
7261 (org-back-to-heading)
7262 (org-insert-heading)
7263 (org-move-subtree-down)
7264 (end-of-line 1))
7266 (defun org-insert-heading-respect-content ()
7267 (interactive)
7268 (let ((org-insert-heading-respect-content t))
7269 (org-insert-heading t)))
7271 (defun org-insert-todo-heading-respect-content (&optional force-state)
7272 (interactive "P")
7273 (let ((org-insert-heading-respect-content t))
7274 (org-insert-todo-heading force-state t)))
7276 (defun org-insert-todo-heading (arg &optional force-heading)
7277 "Insert a new heading with the same level and TODO state as current heading.
7278 If the heading has no TODO state, or if the state is DONE, use the first
7279 state (TODO by default). Also with prefix arg, force first state."
7280 (interactive "P")
7281 (when (or force-heading (not (org-insert-item 'checkbox)))
7282 (org-insert-heading force-heading)
7283 (save-excursion
7284 (org-back-to-heading)
7285 (outline-previous-heading)
7286 (looking-at org-todo-line-regexp))
7287 (let*
7288 ((new-mark-x
7289 (if (or arg
7290 (not (match-beginning 2))
7291 (member (match-string 2) org-done-keywords))
7292 (car org-todo-keywords-1)
7293 (match-string 2)))
7294 (new-mark
7296 (run-hook-with-args-until-success
7297 'org-todo-get-default-hook new-mark-x nil)
7298 new-mark-x)))
7299 (beginning-of-line 1)
7300 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7301 (if org-treat-insert-todo-heading-as-state-change
7302 (org-todo new-mark)
7303 (insert new-mark " "))))
7304 (when org-provide-todo-statistics
7305 (org-update-parent-todo-statistics))))
7307 (defun org-insert-subheading (arg)
7308 "Insert a new subheading and demote it.
7309 Works for outline headings and for plain lists alike."
7310 (interactive "P")
7311 (org-insert-heading arg)
7312 (cond
7313 ((org-at-heading-p) (org-do-demote))
7314 ((org-at-item-p) (org-indent-item))))
7316 (defun org-insert-todo-subheading (arg)
7317 "Insert a new subheading with TODO keyword or checkbox and demote it.
7318 Works for outline headings and for plain lists alike."
7319 (interactive "P")
7320 (org-insert-todo-heading arg)
7321 (cond
7322 ((org-at-heading-p) (org-do-demote))
7323 ((org-at-item-p) (org-indent-item))))
7325 ;;; Promotion and Demotion
7327 (defvar org-after-demote-entry-hook nil
7328 "Hook run after an entry has been demoted.
7329 The cursor will be at the beginning of the entry.
7330 When a subtree is being demoted, the hook will be called for each node.")
7332 (defvar org-after-promote-entry-hook nil
7333 "Hook run after an entry has been promoted.
7334 The cursor will be at the beginning of the entry.
7335 When a subtree is being promoted, the hook will be called for each node.")
7337 (defun org-promote-subtree ()
7338 "Promote the entire subtree.
7339 See also `org-promote'."
7340 (interactive)
7341 (save-excursion
7342 (org-with-limited-levels (org-map-tree 'org-promote)))
7343 (org-fix-position-after-promote))
7345 (defun org-demote-subtree ()
7346 "Demote the entire subtree. See `org-demote'.
7347 See also `org-promote'."
7348 (interactive)
7349 (save-excursion
7350 (org-with-limited-levels (org-map-tree 'org-demote)))
7351 (org-fix-position-after-promote))
7354 (defun org-do-promote ()
7355 "Promote the current heading higher up the tree.
7356 If the region is active in `transient-mark-mode', promote all headings
7357 in the region."
7358 (interactive)
7359 (save-excursion
7360 (if (org-region-active-p)
7361 (org-map-region 'org-promote (region-beginning) (region-end))
7362 (org-promote)))
7363 (org-fix-position-after-promote))
7365 (defun org-do-demote ()
7366 "Demote the current heading lower down the tree.
7367 If the region is active in `transient-mark-mode', demote all headings
7368 in the region."
7369 (interactive)
7370 (save-excursion
7371 (if (org-region-active-p)
7372 (org-map-region 'org-demote (region-beginning) (region-end))
7373 (org-demote)))
7374 (org-fix-position-after-promote))
7376 (defun org-fix-position-after-promote ()
7377 "Make sure that after pro/demotion cursor position is right."
7378 (let ((pos (point)))
7379 (when (save-excursion
7380 (beginning-of-line 1)
7381 (looking-at org-todo-line-regexp)
7382 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7383 (cond ((eobp) (insert " "))
7384 ((eolp) (insert " "))
7385 ((equal (char-after) ?\ ) (forward-char 1))))))
7387 (defun org-current-level ()
7388 "Return the level of the current entry, or nil if before the first headline.
7389 The level is the number of stars at the beginning of the headline."
7390 (save-excursion
7391 (org-with-limited-levels
7392 (if (ignore-errors (org-back-to-heading t))
7393 (funcall outline-level)))))
7395 (defun org-get-previous-line-level ()
7396 "Return the outline depth of the last headline before the current line.
7397 Returns 0 for the first headline in the buffer, and nil if before the
7398 first headline."
7399 (let ((current-level (org-current-level))
7400 (prev-level (when (> (line-number-at-pos) 1)
7401 (save-excursion
7402 (beginning-of-line 0)
7403 (org-current-level)))))
7404 (cond ((null current-level) nil) ; Before first headline
7405 ((null prev-level) 0) ; At first headline
7406 (prev-level))))
7408 (defun org-reduced-level (l)
7409 "Compute the effective level of a heading.
7410 This takes into account the setting of `org-odd-levels-only'."
7411 (cond
7412 ((zerop l) 0)
7413 (org-odd-levels-only (1+ (floor (/ l 2))))
7414 (t l)))
7416 (defun org-level-increment ()
7417 "Return the number of stars that will be added or removed at a
7418 time to headlines when structure editing, based on the value of
7419 `org-odd-levels-only'."
7420 (if org-odd-levels-only 2 1))
7422 (defun org-get-valid-level (level &optional change)
7423 "Rectify a level change under the influence of `org-odd-levels-only'
7424 LEVEL is a current level, CHANGE is by how much the level should be
7425 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7426 even level numbers will become the next higher odd number."
7427 (if org-odd-levels-only
7428 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7429 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7430 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7431 (max 1 (+ level (or change 0)))))
7433 (if (boundp 'define-obsolete-function-alias)
7434 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7435 (define-obsolete-function-alias 'org-get-legal-level
7436 'org-get-valid-level)
7437 (define-obsolete-function-alias 'org-get-legal-level
7438 'org-get-valid-level "23.1")))
7440 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7441 ;; ̀org-with-limited-levels'
7442 (defun org-promote ()
7443 "Promote the current heading higher up the tree.
7444 If the region is active in `transient-mark-mode', promote all headings
7445 in the region."
7446 (org-back-to-heading t)
7447 (let* ((level (save-match-data (funcall outline-level)))
7448 (after-change-functions (remove 'flyspell-after-change-function
7449 after-change-functions))
7450 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7451 (diff (abs (- level (length up-head) -1))))
7452 (cond ((and (= level 1) org-called-with-limited-levels
7453 org-allow-promoting-top-level-subtree)
7454 (replace-match "# " nil t))
7455 ((= level 1)
7456 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7457 (t (replace-match up-head nil t)))
7458 ;; Fixup tag positioning
7459 (unless (= level 1)
7460 (and org-auto-align-tags (org-set-tags nil t))
7461 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7462 (run-hooks 'org-after-promote-entry-hook)))
7464 (defun org-demote ()
7465 "Demote the current heading lower down the tree.
7466 If the region is active in `transient-mark-mode', demote all headings
7467 in the region."
7468 (org-back-to-heading t)
7469 (let* ((level (save-match-data (funcall outline-level)))
7470 (after-change-functions (remove 'flyspell-after-change-function
7471 after-change-functions))
7472 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7473 (diff (abs (- level (length down-head) -1))))
7474 (replace-match down-head nil t)
7475 ;; Fixup tag positioning
7476 (and org-auto-align-tags (org-set-tags nil t))
7477 (if org-adapt-indentation (org-fixup-indentation diff))
7478 (run-hooks 'org-after-demote-entry-hook)))
7480 (defun org-cycle-level ()
7481 "Cycle the level of an empty headline through possible states.
7482 This goes first to child, then to parent, level, then up the hierarchy.
7483 After top level, it switches back to sibling level."
7484 (interactive)
7485 (let ((org-adapt-indentation nil))
7486 (when (org-point-at-end-of-empty-headline)
7487 (setq this-command 'org-cycle-level) ; Only needed for caching
7488 (let ((cur-level (org-current-level))
7489 (prev-level (org-get-previous-line-level)))
7490 (cond
7491 ;; If first headline in file, promote to top-level.
7492 ((= prev-level 0)
7493 (loop repeat (/ (- cur-level 1) (org-level-increment))
7494 do (org-do-promote)))
7495 ;; If same level as prev, demote one.
7496 ((= prev-level cur-level)
7497 (org-do-demote))
7498 ;; If parent is top-level, promote to top level if not already.
7499 ((= prev-level 1)
7500 (loop repeat (/ (- cur-level 1) (org-level-increment))
7501 do (org-do-promote)))
7502 ;; If top-level, return to prev-level.
7503 ((= cur-level 1)
7504 (loop repeat (/ (- prev-level 1) (org-level-increment))
7505 do (org-do-demote)))
7506 ;; If less than prev-level, promote one.
7507 ((< cur-level prev-level)
7508 (org-do-promote))
7509 ;; If deeper than prev-level, promote until higher than
7510 ;; prev-level.
7511 ((> cur-level prev-level)
7512 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7513 do (org-do-promote))))
7514 t))))
7516 (defun org-map-tree (fun)
7517 "Call FUN for every heading underneath the current one."
7518 (org-back-to-heading)
7519 (let ((level (funcall outline-level)))
7520 (save-excursion
7521 (funcall fun)
7522 (while (and (progn
7523 (outline-next-heading)
7524 (> (funcall outline-level) level))
7525 (not (eobp)))
7526 (funcall fun)))))
7528 (defun org-map-region (fun beg end)
7529 "Call FUN for every heading between BEG and END."
7530 (let ((org-ignore-region t))
7531 (save-excursion
7532 (setq end (copy-marker end))
7533 (goto-char beg)
7534 (if (and (re-search-forward org-outline-regexp-bol nil t)
7535 (< (point) end))
7536 (funcall fun))
7537 (while (and (progn
7538 (outline-next-heading)
7539 (< (point) end))
7540 (not (eobp)))
7541 (funcall fun)))))
7543 (defvar org-property-end-re) ; silence byte-compiler
7544 (defun org-fixup-indentation (diff)
7545 "Change the indentation in the current entry by DIFF.
7546 However, if any line in the current entry has no indentation, or if it
7547 would end up with no indentation after the change, nothing at all is done."
7548 (save-excursion
7549 (let ((end (save-excursion (outline-next-heading)
7550 (point-marker)))
7551 (prohibit (if (> diff 0)
7552 "^\\S-"
7553 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7554 col)
7555 (unless (save-excursion (end-of-line 1)
7556 (re-search-forward prohibit end t))
7557 (while (and (< (point) end)
7558 (re-search-forward "^[ \t]+" end t))
7559 (goto-char (match-end 0))
7560 (setq col (current-column))
7561 (if (< diff 0) (replace-match ""))
7562 (org-indent-to-column (+ diff col))))
7563 (move-marker end nil))))
7565 (defun org-convert-to-odd-levels ()
7566 "Convert an org-mode file with all levels allowed to one with odd levels.
7567 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7568 level 5 etc."
7569 (interactive)
7570 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7571 (let ((outline-level 'org-outline-level)
7572 (org-odd-levels-only nil) n)
7573 (save-excursion
7574 (goto-char (point-min))
7575 (while (re-search-forward "^\\*\\*+ " nil t)
7576 (setq n (- (length (match-string 0)) 2))
7577 (while (>= (setq n (1- n)) 0)
7578 (org-demote))
7579 (end-of-line 1))))))
7581 (defun org-convert-to-oddeven-levels ()
7582 "Convert an org-mode file with only odd levels to one with odd/even levels.
7583 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7584 file contains a section with an even level, conversion would
7585 destroy the structure of the file. An error is signaled in this
7586 case."
7587 (interactive)
7588 (goto-char (point-min))
7589 ;; First check if there are no even levels
7590 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7591 (org-show-context t)
7592 (error "Not all levels are odd in this file. Conversion not possible"))
7593 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7594 (let ((outline-regexp org-outline-regexp)
7595 (outline-level 'org-outline-level)
7596 (org-odd-levels-only nil) n)
7597 (save-excursion
7598 (goto-char (point-min))
7599 (while (re-search-forward "^\\*\\*+ " nil t)
7600 (setq n (/ (1- (length (match-string 0))) 2))
7601 (while (>= (setq n (1- n)) 0)
7602 (org-promote))
7603 (end-of-line 1))))))
7605 (defun org-tr-level (n)
7606 "Make N odd if required."
7607 (if org-odd-levels-only (1+ (/ n 2)) n))
7609 ;;; Vertical tree motion, cutting and pasting of subtrees
7611 (defun org-move-subtree-up (&optional arg)
7612 "Move the current subtree up past ARG headlines of the same level."
7613 (interactive "p")
7614 (org-move-subtree-down (- (prefix-numeric-value arg))))
7616 (defun org-move-subtree-down (&optional arg)
7617 "Move the current subtree down past ARG headlines of the same level."
7618 (interactive "p")
7619 (setq arg (prefix-numeric-value arg))
7620 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7621 'org-get-last-sibling))
7622 (ins-point (make-marker))
7623 (cnt (abs arg))
7624 (col (current-column))
7625 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7626 ;; Select the tree
7627 (org-back-to-heading)
7628 (setq beg0 (point))
7629 (save-excursion
7630 (setq ne-beg (org-back-over-empty-lines))
7631 (setq beg (point)))
7632 (save-match-data
7633 (save-excursion (outline-end-of-heading)
7634 (setq folded (outline-invisible-p)))
7635 (outline-end-of-subtree))
7636 (outline-next-heading)
7637 (setq ne-end (org-back-over-empty-lines))
7638 (setq end (point))
7639 (goto-char beg0)
7640 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7641 ;; include less whitespace
7642 (save-excursion
7643 (goto-char beg)
7644 (forward-line (- ne-beg ne-end))
7645 (setq beg (point))))
7646 ;; Find insertion point, with error handling
7647 (while (> cnt 0)
7648 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7649 (progn (goto-char beg0)
7650 (error "Cannot move past superior level or buffer limit")))
7651 (setq cnt (1- cnt)))
7652 (if (> arg 0)
7653 ;; Moving forward - still need to move over subtree
7654 (progn (org-end-of-subtree t t)
7655 (save-excursion
7656 (org-back-over-empty-lines)
7657 (or (bolp) (newline)))))
7658 (setq ne-ins (org-back-over-empty-lines))
7659 (move-marker ins-point (point))
7660 (setq txt (buffer-substring beg end))
7661 (org-save-markers-in-region beg end)
7662 (delete-region beg end)
7663 (org-remove-empty-overlays-at beg)
7664 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7665 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7666 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7667 (let ((bbb (point)))
7668 (insert-before-markers txt)
7669 (org-reinstall-markers-in-region bbb)
7670 (move-marker ins-point bbb))
7671 (or (bolp) (insert "\n"))
7672 (setq ins-end (point))
7673 (goto-char ins-point)
7674 (org-skip-whitespace)
7675 (when (and (< arg 0)
7676 (org-first-sibling-p)
7677 (> ne-ins ne-beg))
7678 ;; Move whitespace back to beginning
7679 (save-excursion
7680 (goto-char ins-end)
7681 (let ((kill-whole-line t))
7682 (kill-line (- ne-ins ne-beg)) (point)))
7683 (insert (make-string (- ne-ins ne-beg) ?\n)))
7684 (move-marker ins-point nil)
7685 (if folded
7686 (hide-subtree)
7687 (org-show-entry)
7688 (show-children)
7689 (org-cycle-hide-drawers 'children))
7690 (org-clean-visibility-after-subtree-move)
7691 ;; move back to the initial column we were at
7692 (move-to-column col)))
7694 (defvar org-subtree-clip ""
7695 "Clipboard for cut and paste of subtrees.
7696 This is actually only a copy of the kill, because we use the normal kill
7697 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7699 (defvar org-subtree-clip-folded nil
7700 "Was the last copied subtree folded?
7701 This is used to fold the tree back after pasting.")
7703 (defun org-cut-subtree (&optional n)
7704 "Cut the current subtree into the clipboard.
7705 With prefix arg N, cut this many sequential subtrees.
7706 This is a short-hand for marking the subtree and then cutting it."
7707 (interactive "p")
7708 (org-copy-subtree n 'cut))
7710 (defun org-copy-subtree (&optional n cut force-store-markers)
7711 "Cut the current subtree into the clipboard.
7712 With prefix arg N, cut this many sequential subtrees.
7713 This is a short-hand for marking the subtree and then copying it.
7714 If CUT is non-nil, actually cut the subtree.
7715 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7716 of some markers in the region, even if CUT is non-nil. This is
7717 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7718 (interactive "p")
7719 (let (beg end folded (beg0 (point)))
7720 (if (org-called-interactively-p 'any)
7721 (org-back-to-heading nil) ; take what looks like a subtree
7722 (org-back-to-heading t)) ; take what is really there
7723 (org-back-over-empty-lines)
7724 (setq beg (point))
7725 (skip-chars-forward " \t\r\n")
7726 (save-match-data
7727 (save-excursion (outline-end-of-heading)
7728 (setq folded (outline-invisible-p)))
7729 (condition-case nil
7730 (org-forward-heading-same-level (1- n) t)
7731 (error nil))
7732 (org-end-of-subtree t t))
7733 (org-back-over-empty-lines)
7734 (setq end (point))
7735 (goto-char beg0)
7736 (when (> end beg)
7737 (setq org-subtree-clip-folded folded)
7738 (when (or cut force-store-markers)
7739 (org-save-markers-in-region beg end))
7740 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7741 (setq org-subtree-clip (current-kill 0))
7742 (message "%s: Subtree(s) with %d characters"
7743 (if cut "Cut" "Copied")
7744 (length org-subtree-clip)))))
7746 (defun org-paste-subtree (&optional level tree for-yank)
7747 "Paste the clipboard as a subtree, with modification of headline level.
7748 The entire subtree is promoted or demoted in order to match a new headline
7749 level.
7751 If the cursor is at the beginning of a headline, the same level as
7752 that headline is used to paste the tree
7754 If not, the new level is derived from the *visible* headings
7755 before and after the insertion point, and taken to be the inferior headline
7756 level of the two. So if the previous visible heading is level 3 and the
7757 next is level 4 (or vice versa), level 4 will be used for insertion.
7758 This makes sure that the subtree remains an independent subtree and does
7759 not swallow low level entries.
7761 You can also force a different level, either by using a numeric prefix
7762 argument, or by inserting the heading marker by hand. For example, if the
7763 cursor is after \"*****\", then the tree will be shifted to level 5.
7765 If optional TREE is given, use this text instead of the kill ring.
7767 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7768 move back over whitespace before inserting, and move point to the end of
7769 the inserted text when done."
7770 (interactive "P")
7771 (setq tree (or tree (and kill-ring (current-kill 0))))
7772 (unless (org-kill-is-subtree-p tree)
7773 (error "%s"
7774 (substitute-command-keys
7775 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7776 (org-with-limited-levels
7777 (let* ((visp (not (outline-invisible-p)))
7778 (txt tree)
7779 (^re_ "\\(\\*+\\)[ \t]*")
7780 (old-level (if (string-match org-outline-regexp-bol txt)
7781 (- (match-end 0) (match-beginning 0) 1)
7782 -1))
7783 (force-level (cond (level (prefix-numeric-value level))
7784 ((and (looking-at "[ \t]*$")
7785 (string-match
7786 "^\\*+$" (buffer-substring
7787 (point-at-bol) (point))))
7788 (- (match-end 1) (match-beginning 1)))
7789 ((and (bolp)
7790 (looking-at org-outline-regexp))
7791 (- (match-end 0) (point) 1))))
7792 (previous-level (save-excursion
7793 (condition-case nil
7794 (progn
7795 (outline-previous-visible-heading 1)
7796 (if (looking-at ^re_)
7797 (- (match-end 0) (match-beginning 0) 1)
7799 (error 1))))
7800 (next-level (save-excursion
7801 (condition-case nil
7802 (progn
7803 (or (looking-at org-outline-regexp)
7804 (outline-next-visible-heading 1))
7805 (if (looking-at ^re_)
7806 (- (match-end 0) (match-beginning 0) 1)
7808 (error 1))))
7809 (new-level (or force-level (max previous-level next-level)))
7810 (shift (if (or (= old-level -1)
7811 (= new-level -1)
7812 (= old-level new-level))
7814 (- new-level old-level)))
7815 (delta (if (> shift 0) -1 1))
7816 (func (if (> shift 0) 'org-demote 'org-promote))
7817 (org-odd-levels-only nil)
7818 beg end newend)
7819 ;; Remove the forced level indicator
7820 (if force-level
7821 (delete-region (point-at-bol) (point)))
7822 ;; Paste
7823 (beginning-of-line (if (bolp) 1 2))
7824 (unless for-yank (org-back-over-empty-lines))
7825 (setq beg (point))
7826 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7827 (insert-before-markers txt)
7828 (unless (string-match "\n\\'" txt) (insert "\n"))
7829 (setq newend (point))
7830 (org-reinstall-markers-in-region beg)
7831 (setq end (point))
7832 (goto-char beg)
7833 (skip-chars-forward " \t\n\r")
7834 (setq beg (point))
7835 (if (and (outline-invisible-p) visp)
7836 (save-excursion (outline-show-heading)))
7837 ;; Shift if necessary
7838 (unless (= shift 0)
7839 (save-restriction
7840 (narrow-to-region beg end)
7841 (while (not (= shift 0))
7842 (org-map-region func (point-min) (point-max))
7843 (setq shift (+ delta shift)))
7844 (goto-char (point-min))
7845 (setq newend (point-max))))
7846 (when (or (org-called-interactively-p 'interactive) for-yank)
7847 (message "Clipboard pasted as level %d subtree" new-level))
7848 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7849 kill-ring
7850 (eq org-subtree-clip (current-kill 0))
7851 org-subtree-clip-folded)
7852 ;; The tree was folded before it was killed/copied
7853 (hide-subtree))
7854 (and for-yank (goto-char newend)))))
7856 (defun org-kill-is-subtree-p (&optional txt)
7857 "Check if the current kill is an outline subtree, or a set of trees.
7858 Returns nil if kill does not start with a headline, or if the first
7859 headline level is not the largest headline level in the tree.
7860 So this will actually accept several entries of equal levels as well,
7861 which is OK for `org-paste-subtree'.
7862 If optional TXT is given, check this string instead of the current kill."
7863 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7864 (re (org-get-limited-outline-regexp))
7865 (^re (concat "^" re))
7866 (start-level (and kill
7867 (string-match
7868 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7869 kill)
7870 (- (match-end 2) (match-beginning 2) 1)))
7871 (start (1+ (or (match-beginning 2) -1))))
7872 (if (not start-level)
7873 (progn
7874 nil) ;; does not even start with a heading
7875 (catch 'exit
7876 (while (setq start (string-match ^re kill (1+ start)))
7877 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7878 (throw 'exit nil)))
7879 t))))
7881 (defvar org-markers-to-move nil
7882 "Markers that should be moved with a cut-and-paste operation.
7883 Those markers are stored together with their positions relative to
7884 the start of the region.")
7886 (defun org-save-markers-in-region (beg end)
7887 "Check markers in region.
7888 If these markers are between BEG and END, record their position relative
7889 to BEG, so that after moving the block of text, we can put the markers back
7890 into place.
7891 This function gets called just before an entry or tree gets cut from the
7892 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7893 called immediately, to move the markers with the entries."
7894 (setq org-markers-to-move nil)
7895 (when (featurep 'org-clock)
7896 (org-clock-save-markers-for-cut-and-paste beg end))
7897 (when (featurep 'org-agenda)
7898 (org-agenda-save-markers-for-cut-and-paste beg end)))
7900 (defun org-check-and-save-marker (marker beg end)
7901 "Check if MARKER is between BEG and END.
7902 If yes, remember the marker and the distance to BEG."
7903 (when (and (marker-buffer marker)
7904 (equal (marker-buffer marker) (current-buffer)))
7905 (if (and (>= marker beg) (< marker end))
7906 (push (cons marker (- marker beg)) org-markers-to-move))))
7908 (defun org-reinstall-markers-in-region (beg)
7909 "Move all remembered markers to their position relative to BEG."
7910 (mapc (lambda (x)
7911 (move-marker (car x) (+ beg (cdr x))))
7912 org-markers-to-move)
7913 (setq org-markers-to-move nil))
7915 (defun org-narrow-to-subtree ()
7916 "Narrow buffer to the current subtree."
7917 (interactive)
7918 (save-excursion
7919 (save-match-data
7920 (org-with-limited-levels
7921 (narrow-to-region
7922 (progn (org-back-to-heading t) (point))
7923 (progn (org-end-of-subtree t t)
7924 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7925 (point)))))))
7927 (defun org-narrow-to-block ()
7928 "Narrow buffer to the current block."
7929 (interactive)
7930 (let* ((case-fold-search t)
7931 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7932 "^[ \t]*#\\+end_.*")))
7933 (if blockp
7934 (narrow-to-region (car blockp) (cdr blockp))
7935 (error "Not in a block"))))
7937 (eval-when-compile
7938 (defvar org-property-drawer-re))
7940 (defvar org-property-start-re) ;; defined below
7941 (defun org-clone-subtree-with-time-shift (n &optional shift)
7942 "Clone the task (subtree) at point N times.
7943 The clones will be inserted as siblings.
7945 In interactive use, the user will be prompted for the number of
7946 clones to be produced, and for a time SHIFT, which may be a
7947 repeater as used in time stamps, for example `+3d'.
7949 When a valid repeater is given and the entry contains any time
7950 stamps, the clones will become a sequence in time, with time
7951 stamps in the subtree shifted for each clone produced. If SHIFT
7952 is nil or the empty string, time stamps will be left alone. The
7953 ID property of the original subtree is removed.
7955 If the original subtree did contain time stamps with a repeater,
7956 the following will happen:
7957 - the repeater will be removed in each clone
7958 - an additional clone will be produced, with the current, unshifted
7959 date(s) in the entry.
7960 - the original entry will be placed *after* all the clones, with
7961 repeater intact.
7962 - the start days in the repeater in the original entry will be shifted
7963 to past the last clone.
7964 In this way you can spell out a number of instances of a repeating task,
7965 and still retain the repeater to cover future instances of the task."
7966 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7967 (let (beg end template task idprop
7968 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7969 (drawer-re org-drawer-regexp))
7970 (if (not (and (integerp n) (> n 0)))
7971 (error "Invalid number of replications %s" n))
7972 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7973 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7974 shift)))
7975 (error "Invalid shift specification %s" shift))
7976 (when doshift
7977 (setq shift-n (string-to-number (match-string 1 shift))
7978 shift-what (cdr (assoc (match-string 2 shift)
7979 '(("d" . day) ("w" . week)
7980 ("m" . month) ("y" . year))))))
7981 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7982 (setq nmin 1 nmax n)
7983 (org-back-to-heading t)
7984 (setq beg (point))
7985 (setq idprop (org-entry-get nil "ID"))
7986 (org-end-of-subtree t t)
7987 (or (bolp) (insert "\n"))
7988 (setq end (point))
7989 (setq template (buffer-substring beg end))
7990 (when (and doshift
7991 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7992 (delete-region beg end)
7993 (setq end beg)
7994 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7995 (goto-char end)
7996 (loop for n from nmin to nmax do
7997 ;; prepare clone
7998 (with-temp-buffer
7999 (insert template)
8000 (org-mode)
8001 (goto-char (point-min))
8002 (org-show-subtree)
8003 (and idprop (if org-clone-delete-id
8004 (org-entry-delete nil "ID")
8005 (org-id-get-create t)))
8006 (unless (= n 0)
8007 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8008 (kill-whole-line))
8009 (goto-char (point-min))
8010 (while (re-search-forward drawer-re nil t)
8011 (mapc (lambda (d)
8012 (org-remove-empty-drawer-at d (point))) org-drawers)))
8013 (goto-char (point-min))
8014 (when doshift
8015 (while (re-search-forward org-ts-regexp-both nil t)
8016 (org-timestamp-change (* n shift-n) shift-what))
8017 (unless (= n n-no-remove)
8018 (goto-char (point-min))
8019 (while (re-search-forward org-ts-regexp nil t)
8020 (save-excursion
8021 (goto-char (match-beginning 0))
8022 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8023 (delete-region (match-beginning 1) (match-end 1)))))))
8024 (setq task (buffer-string)))
8025 (insert task))
8026 (goto-char beg)))
8028 ;;; Outline Sorting
8030 (defun org-sort (with-case)
8031 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8032 Optional argument WITH-CASE means sort case-sensitively."
8033 (interactive "P")
8034 (cond
8035 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8036 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8038 (org-call-with-arg 'org-sort-entries with-case))))
8040 (defun org-sort-remove-invisible (s)
8041 (remove-text-properties 0 (length s) org-rm-props s)
8042 (while (string-match org-bracket-link-regexp s)
8043 (setq s (replace-match (if (match-end 2)
8044 (match-string 3 s)
8045 (match-string 1 s)) t t s)))
8048 (defvar org-priority-regexp) ; defined later in the file
8050 (defvar org-after-sorting-entries-or-items-hook nil
8051 "Hook that is run after a bunch of entries or items have been sorted.
8052 When children are sorted, the cursor is in the parent line when this
8053 hook gets called. When a region or a plain list is sorted, the cursor
8054 will be in the first entry of the sorted region/list.")
8056 (defun org-sort-entries
8057 (&optional with-case sorting-type getkey-func compare-func property)
8058 "Sort entries on a certain level of an outline tree.
8059 If there is an active region, the entries in the region are sorted.
8060 Else, if the cursor is before the first entry, sort the top-level items.
8061 Else, the children of the entry at point are sorted.
8063 Sorting can be alphabetically, numerically, by date/time as given by
8064 a time stamp, by a property or by priority.
8066 The command prompts for the sorting type unless it has been given to the
8067 function through the SORTING-TYPE argument, which needs to be a character,
8068 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8069 precise meaning of each character:
8071 n Numerically, by converting the beginning of the entry/item to a number.
8072 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8073 t By date/time, either the first active time stamp in the entry, or, if
8074 none exist, by the first inactive one.
8075 s By the scheduled date/time.
8076 d By deadline date/time.
8077 c By creation time, which is assumed to be the first inactive time stamp
8078 at the beginning of a line.
8079 p By priority according to the cookie.
8080 r By the value of a property.
8082 Capital letters will reverse the sort order.
8084 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8085 called with point at the beginning of the record. It must return either
8086 a string or a number that should serve as the sorting key for that record.
8088 Comparing entries ignores case by default. However, with an optional argument
8089 WITH-CASE, the sorting considers case as well."
8090 (interactive "P")
8091 (let ((case-func (if with-case 'identity 'downcase))
8092 start beg end stars re re2
8093 txt what tmp)
8094 ;; Find beginning and end of region to sort
8095 (cond
8096 ((org-region-active-p)
8097 ;; we will sort the region
8098 (setq end (region-end)
8099 what "region")
8100 (goto-char (region-beginning))
8101 (if (not (org-at-heading-p)) (outline-next-heading))
8102 (setq start (point)))
8103 ((or (org-at-heading-p)
8104 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8105 ;; we will sort the children of the current headline
8106 (org-back-to-heading)
8107 (setq start (point)
8108 end (progn (org-end-of-subtree t t)
8109 (or (bolp) (insert "\n"))
8110 (org-back-over-empty-lines)
8111 (point))
8112 what "children")
8113 (goto-char start)
8114 (show-subtree)
8115 (outline-next-heading))
8117 ;; we will sort the top-level entries in this file
8118 (goto-char (point-min))
8119 (or (org-at-heading-p) (outline-next-heading))
8120 (setq start (point))
8121 (goto-char (point-max))
8122 (beginning-of-line 1)
8123 (when (looking-at ".*?\\S-")
8124 ;; File ends in a non-white line
8125 (end-of-line 1)
8126 (insert "\n"))
8127 (setq end (point-max))
8128 (setq what "top-level")
8129 (goto-char start)
8130 (show-all)))
8132 (setq beg (point))
8133 (if (>= beg end) (error "Nothing to sort"))
8135 (looking-at "\\(\\*+\\)")
8136 (setq stars (match-string 1)
8137 re (concat "^" (regexp-quote stars) " +")
8138 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8139 txt (buffer-substring beg end))
8140 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8141 (if (and (not (equal stars "*")) (string-match re2 txt))
8142 (error "Region to sort contains a level above the first entry"))
8144 (unless sorting-type
8145 (message
8146 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8147 [t]ime [s]cheduled [d]eadline [c]reated
8148 A/N/T/S/D/C/P/O/F means reversed:"
8149 what)
8150 (setq sorting-type (read-char-exclusive))
8152 (unless getkey-func
8153 (and (= (downcase sorting-type) ?f)
8154 (setq getkey-func
8155 (org-icompleting-read "Sort using function: "
8156 obarray 'fboundp t nil nil))
8157 (setq getkey-func (intern getkey-func))))
8159 (and (= (downcase sorting-type) ?r)
8160 (not property)
8161 (setq property
8162 (org-icompleting-read "Property: "
8163 (mapcar 'list (org-buffer-property-keys t))
8164 nil t))))
8166 (message "Sorting entries...")
8168 (save-restriction
8169 (narrow-to-region start end)
8170 (let ((dcst (downcase sorting-type))
8171 (case-fold-search nil)
8172 (now (current-time)))
8173 (sort-subr
8174 (/= dcst sorting-type)
8175 ;; This function moves to the beginning character of the "record" to
8176 ;; be sorted.
8177 (lambda nil
8178 (if (re-search-forward re nil t)
8179 (goto-char (match-beginning 0))
8180 (goto-char (point-max))))
8181 ;; This function moves to the last character of the "record" being
8182 ;; sorted.
8183 (lambda nil
8184 (save-match-data
8185 (condition-case nil
8186 (outline-forward-same-level 1)
8187 (error
8188 (goto-char (point-max))))))
8189 ;; This function returns the value that gets sorted against.
8190 (lambda nil
8191 (cond
8192 ((= dcst ?n)
8193 (if (looking-at org-complex-heading-regexp)
8194 (string-to-number (match-string 4))
8195 nil))
8196 ((= dcst ?a)
8197 (if (looking-at org-complex-heading-regexp)
8198 (funcall case-func (match-string 4))
8199 nil))
8200 ((= dcst ?t)
8201 (let ((end (save-excursion (outline-next-heading) (point))))
8202 (if (or (re-search-forward org-ts-regexp end t)
8203 (re-search-forward org-ts-regexp-both end t))
8204 (org-time-string-to-seconds (match-string 0))
8205 (org-float-time now))))
8206 ((= dcst ?c)
8207 (let ((end (save-excursion (outline-next-heading) (point))))
8208 (if (re-search-forward
8209 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8210 end t)
8211 (org-time-string-to-seconds (match-string 0))
8212 (org-float-time now))))
8213 ((= dcst ?s)
8214 (let ((end (save-excursion (outline-next-heading) (point))))
8215 (if (re-search-forward org-scheduled-time-regexp end t)
8216 (org-time-string-to-seconds (match-string 1))
8217 (org-float-time now))))
8218 ((= dcst ?d)
8219 (let ((end (save-excursion (outline-next-heading) (point))))
8220 (if (re-search-forward org-deadline-time-regexp end t)
8221 (org-time-string-to-seconds (match-string 1))
8222 (org-float-time now))))
8223 ((= dcst ?p)
8224 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8225 (string-to-char (match-string 2))
8226 org-default-priority))
8227 ((= dcst ?r)
8228 (or (org-entry-get nil property) ""))
8229 ((= dcst ?o)
8230 (if (looking-at org-complex-heading-regexp)
8231 (- 9999 (length (member (match-string 2)
8232 org-todo-keywords-1)))))
8233 ((= dcst ?f)
8234 (if getkey-func
8235 (progn
8236 (setq tmp (funcall getkey-func))
8237 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8238 tmp)
8239 (error "Invalid key function `%s'" getkey-func)))
8240 (t (error "Invalid sorting type `%c'" sorting-type))))
8242 (cond
8243 ((= dcst ?a) 'string<)
8244 ((= dcst ?f) compare-func)
8245 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8246 (run-hooks 'org-after-sorting-entries-or-items-hook)
8247 (message "Sorting entries...done")))
8249 (defun org-do-sort (table what &optional with-case sorting-type)
8250 "Sort TABLE of WHAT according to SORTING-TYPE.
8251 The user will be prompted for the SORTING-TYPE if the call to this
8252 function does not specify it. WHAT is only for the prompt, to indicate
8253 what is being sorted. The sorting key will be extracted from
8254 the car of the elements of the table.
8255 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8256 (unless sorting-type
8257 (message
8258 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8259 what)
8260 (setq sorting-type (read-char-exclusive)))
8261 (let ((dcst (downcase sorting-type))
8262 extractfun comparefun)
8263 ;; Define the appropriate functions
8264 (cond
8265 ((= dcst ?n)
8266 (setq extractfun 'string-to-number
8267 comparefun (if (= dcst sorting-type) '< '>)))
8268 ((= dcst ?a)
8269 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8270 (lambda(x) (downcase (org-sort-remove-invisible x))))
8271 comparefun (if (= dcst sorting-type)
8272 'string<
8273 (lambda (a b) (and (not (string< a b))
8274 (not (string= a b)))))))
8275 ((= dcst ?t)
8276 (setq extractfun
8277 (lambda (x)
8278 (if (or (string-match org-ts-regexp x)
8279 (string-match org-ts-regexp-both x))
8280 (org-float-time
8281 (org-time-string-to-time (match-string 0 x)))
8283 comparefun (if (= dcst sorting-type) '< '>)))
8284 (t (error "Invalid sorting type `%c'" sorting-type)))
8286 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8287 table)
8288 (lambda (a b) (funcall comparefun (car a) (car b))))))
8291 ;;; The orgstruct minor mode
8293 ;; Define a minor mode which can be used in other modes in order to
8294 ;; integrate the org-mode structure editing commands.
8296 ;; This is really a hack, because the org-mode structure commands use
8297 ;; keys which normally belong to the major mode. Here is how it
8298 ;; works: The minor mode defines all the keys necessary to operate the
8299 ;; structure commands, but wraps the commands into a function which
8300 ;; tests if the cursor is currently at a headline or a plain list
8301 ;; item. If that is the case, the structure command is used,
8302 ;; temporarily setting many Org-mode variables like regular
8303 ;; expressions for filling etc. However, when any of those keys is
8304 ;; used at a different location, function uses `key-binding' to look
8305 ;; up if the key has an associated command in another currently active
8306 ;; keymap (minor modes, major mode, global), and executes that
8307 ;; command. There might be problems if any of the keys is otherwise
8308 ;; used as a prefix key.
8310 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8311 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8312 ;; addresses this by checking explicitly for both bindings.
8314 (defvar orgstruct-mode-map (make-sparse-keymap)
8315 "Keymap for the minor `orgstruct-mode'.")
8317 (defvar org-local-vars nil
8318 "List of local variables, for use by `orgstruct-mode'.")
8320 ;;;###autoload
8321 (define-minor-mode orgstruct-mode
8322 "Toggle the minor mode `orgstruct-mode'.
8323 This mode is for using Org-mode structure commands in other
8324 modes. The following keys behave as if Org-mode were active, if
8325 the cursor is on a headline, or on a plain list item (both as
8326 defined by Org-mode).
8328 M-up Move entry/item up
8329 M-down Move entry/item down
8330 M-left Promote
8331 M-right Demote
8332 M-S-up Move entry/item up
8333 M-S-down Move entry/item down
8334 M-S-left Promote subtree
8335 M-S-right Demote subtree
8336 M-q Fill paragraph and items like in Org-mode
8337 C-c ^ Sort entries
8338 C-c - Cycle list bullet
8339 TAB Cycle item visibility
8340 M-RET Insert new heading/item
8341 S-M-RET Insert new TODO heading / Checkbox item
8342 C-c C-c Set tags / toggle checkbox"
8343 nil " OrgStruct" nil
8344 (org-load-modules-maybe)
8345 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8347 ;;;###autoload
8348 (defun turn-on-orgstruct ()
8349 "Unconditionally turn on `orgstruct-mode'."
8350 (orgstruct-mode 1))
8352 (defvar org-fb-vars nil)
8353 (make-variable-buffer-local 'org-fb-vars)
8354 (defun orgstruct++-mode (&optional arg)
8355 "Toggle `orgstruct-mode', the enhanced version of it.
8356 In addition to setting orgstruct-mode, this also exports all
8357 indentation and autofilling variables from org-mode into the
8358 buffer. It will also recognize item context in multiline items."
8359 (interactive "P")
8360 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8361 (if (< arg 1)
8362 (progn (orgstruct-mode -1)
8363 (mapc (lambda(v)
8364 (org-set-local (car v)
8365 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8366 org-fb-vars))
8367 (orgstruct-mode 1)
8368 (setq org-fb-vars nil)
8369 (let (var val)
8370 (mapc
8371 (lambda (x)
8372 (when (string-match
8373 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8374 (symbol-name (car x)))
8375 (setq var (car x) val (nth 1 x))
8376 (push (list var `(quote ,(eval var))) org-fb-vars)
8377 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8378 org-local-vars)
8379 (org-set-local 'orgstruct-is-++ t))))
8381 (defvar orgstruct-is-++ nil
8382 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8383 (make-variable-buffer-local 'orgstruct-is-++)
8385 ;;;###autoload
8386 (defun turn-on-orgstruct++ ()
8387 "Unconditionally turn on `orgstruct++-mode'."
8388 (orgstruct++-mode 1))
8390 (defun orgstruct-error ()
8391 "Error when there is no default binding for a structure key."
8392 (interactive)
8393 (error "This key has no function outside structure elements"))
8395 (defun orgstruct-setup ()
8396 "Setup orgstruct keymaps."
8397 (let ((nfunc 0)
8398 (bindings
8399 (list
8400 '([(meta up)] org-metaup)
8401 '([(meta down)] org-metadown)
8402 '([(meta left)] org-metaleft)
8403 '([(meta right)] org-metaright)
8404 '([(meta shift up)] org-shiftmetaup)
8405 '([(meta shift down)] org-shiftmetadown)
8406 '([(meta shift left)] org-shiftmetaleft)
8407 '([(meta shift right)] org-shiftmetaright)
8408 '([?\e (up)] org-metaup)
8409 '([?\e (down)] org-metadown)
8410 '([?\e (left)] org-metaleft)
8411 '([?\e (right)] org-metaright)
8412 '([?\e (shift up)] org-shiftmetaup)
8413 '([?\e (shift down)] org-shiftmetadown)
8414 '([?\e (shift left)] org-shiftmetaleft)
8415 '([?\e (shift right)] org-shiftmetaright)
8416 '([(shift up)] org-shiftup)
8417 '([(shift down)] org-shiftdown)
8418 '([(shift left)] org-shiftleft)
8419 '([(shift right)] org-shiftright)
8420 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8421 '("\M-q" fill-paragraph)
8422 '("\C-c^" org-sort)
8423 '("\C-c-" org-cycle-list-bullet)))
8424 elt key fun cmd)
8425 (while (setq elt (pop bindings))
8426 (setq nfunc (1+ nfunc))
8427 (setq key (org-key (car elt))
8428 fun (nth 1 elt)
8429 cmd (orgstruct-make-binding fun nfunc key))
8430 (org-defkey orgstruct-mode-map key cmd))
8432 ;; Prevent an error for users who forgot to make autoloads
8433 (require 'org-element)
8435 ;; Special treatment needed for TAB and RET
8436 (org-defkey orgstruct-mode-map [(tab)]
8437 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8438 (org-defkey orgstruct-mode-map "\C-i"
8439 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8441 (org-defkey orgstruct-mode-map "\M-\C-m"
8442 (orgstruct-make-binding 'org-insert-heading 105
8443 "\M-\C-m" [(meta return)]))
8444 (org-defkey orgstruct-mode-map [(meta return)]
8445 (orgstruct-make-binding 'org-insert-heading 106
8446 [(meta return)] "\M-\C-m"))
8448 (org-defkey orgstruct-mode-map [(shift meta return)]
8449 (orgstruct-make-binding 'org-insert-todo-heading 107
8450 [(meta return)] "\M-\C-m"))
8452 (org-defkey orgstruct-mode-map "\e\C-m"
8453 (orgstruct-make-binding 'org-insert-heading 108
8454 "\e\C-m" [?\e (return)]))
8455 (org-defkey orgstruct-mode-map [?\e (return)]
8456 (orgstruct-make-binding 'org-insert-heading 109
8457 [?\e (return)] "\e\C-m"))
8458 (org-defkey orgstruct-mode-map [?\e (shift return)]
8459 (orgstruct-make-binding 'org-insert-todo-heading 110
8460 [?\e (return)] "\e\C-m"))
8462 (unless org-local-vars
8463 (setq org-local-vars (org-get-local-variables)))
8467 (defun orgstruct-make-binding (fun n &rest keys)
8468 "Create a function for binding in the structure minor mode.
8469 FUN is the command to call inside a table. N is used to create a unique
8470 command name. KEYS are keys that should be checked in for a command
8471 to execute outside of tables."
8472 (eval
8473 (list 'defun
8474 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8475 '(arg)
8476 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8477 "Outside of structure, run the binding of `"
8478 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8479 "'.")
8480 '(interactive "p")
8481 (list 'if
8482 `(org-context-p 'headline 'item
8483 (and orgstruct-is-++
8484 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8485 'item-body))
8486 (list 'org-run-like-in-org-mode (list 'quote fun))
8487 (list 'let '(orgstruct-mode)
8488 (list 'call-interactively
8489 (append '(or)
8490 (mapcar (lambda (k)
8491 (list 'key-binding k))
8492 keys)
8493 '('orgstruct-error))))))))
8495 (defun org-contextualize-keys (alist contexts)
8496 "Return valid elements in ALIST depending on CONTEXTS.
8498 `org-agenda-custom-commands' or `org-capture-templates' are the
8499 values used for ALIST, and `org-agenda-custom-commands-contexts'
8500 or `org-capture-templates-contexts' are the associated contexts
8501 definitions."
8502 (let ((contexts
8503 ;; normalize contexts
8504 (mapcar
8505 (lambda(c) (cond ((listp (cadr c))
8506 (list (car c) (car c) (cadr c)))
8507 ((string= "" (cadr c))
8508 (list (car c) (car c) (caddr c)))
8509 (t c))) contexts))
8510 (a alist) c r s)
8511 ;; loop over all commands or templates
8512 (while (setq c (pop a))
8513 (let (vrules repl)
8514 (cond
8515 ((not (assoc (car c) contexts))
8516 (push c r))
8517 ((and (assoc (car c) contexts)
8518 (setq vrules (org-contextualize-validate-key
8519 (car c) contexts)))
8520 (mapc (lambda (vr)
8521 (when (not (equal (car vr) (cadr vr)))
8522 (setq repl vr))) vrules)
8523 (if (not repl) (push c r)
8524 (push (cadr repl) s)
8525 (push
8526 (cons (car c)
8527 (cdr (or (assoc (cadr repl) alist)
8528 (error "Undefined key `%s' as contextual replacement for `%s'"
8529 (cadr repl) (car c)))))
8530 r))))))
8531 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8532 (delq
8534 (delete-dups
8535 (mapcar (lambda (x)
8536 (let ((tpl (car x)))
8537 (when (not (delq
8539 (mapcar (lambda(y)
8540 (equal y tpl)) s))) x)))
8541 (reverse r))))))
8543 (defun org-contextualize-validate-key (key contexts)
8544 "Check CONTEXTS for agenda or capture KEY."
8545 (let (r rr res)
8546 (while (setq r (pop contexts))
8547 (mapc
8548 (lambda (rr)
8549 (when
8550 (and (equal key (car r))
8551 (if (functionp rr) (funcall rr)
8552 (or (and (eq (car rr) 'in-file)
8553 (buffer-file-name)
8554 (string-match (cdr rr) (buffer-file-name)))
8555 (and (eq (car rr) 'in-mode)
8556 (string-match (cdr rr) (symbol-name major-mode)))
8557 (when (and (eq (car rr) 'not-in-file)
8558 (buffer-file-name))
8559 (not (string-match (cdr rr) (buffer-file-name))))
8560 (when (eq (car rr) 'not-in-mode)
8561 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8562 (push r res)))
8563 (car (last r))))
8564 (delete-dups (delq nil res))))
8566 (defun org-context-p (&rest contexts)
8567 "Check if local context is any of CONTEXTS.
8568 Possible values in the list of contexts are `table', `headline', and `item'."
8569 (let ((pos (point)))
8570 (goto-char (point-at-bol))
8571 (prog1 (or (and (memq 'table contexts)
8572 (looking-at "[ \t]*|"))
8573 (and (memq 'headline contexts)
8574 (looking-at org-outline-regexp))
8575 (and (memq 'item contexts)
8576 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8577 (and (memq 'item-body contexts)
8578 (org-in-item-p)))
8579 (goto-char pos))))
8581 (defun org-get-local-variables ()
8582 "Return a list of all local variables in an Org mode buffer."
8583 (let (varlist)
8584 (with-current-buffer (get-buffer-create "*Org tmp*")
8585 (erase-buffer)
8586 (org-mode)
8587 (setq varlist (buffer-local-variables)))
8588 (kill-buffer "*Org tmp*")
8589 (delq nil
8590 (mapcar
8591 (lambda (x)
8592 (setq x
8593 (if (symbolp x)
8594 (list x)
8595 (list (car x) (list 'quote (cdr x)))))
8596 (if (string-match
8597 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8598 (symbol-name (car x)))
8599 x nil))
8600 varlist))))
8602 (defun org-clone-local-variables (from-buffer &optional regexp)
8603 "Clone local variables from FROM-BUFFER.
8604 Optional argument REGEXP selects variables to clone."
8605 (mapc
8606 (lambda (pair)
8607 (and (symbolp (car pair))
8608 (or (null regexp)
8609 (string-match regexp (symbol-name (car pair))))
8610 (set (make-local-variable (car pair))
8611 (cdr pair))))
8612 (buffer-local-variables from-buffer)))
8614 ;;;###autoload
8615 (defun org-run-like-in-org-mode (cmd)
8616 "Run a command, pretending that the current buffer is in Org-mode.
8617 This will temporarily bind local variables that are typically bound in
8618 Org-mode to the values they have in Org-mode, and then interactively
8619 call CMD."
8620 (org-load-modules-maybe)
8621 (unless org-local-vars
8622 (setq org-local-vars (org-get-local-variables)))
8623 (eval (list 'let org-local-vars
8624 (list 'call-interactively (list 'quote cmd)))))
8626 ;;;; Archiving
8628 (defun org-get-category (&optional pos force-refresh)
8629 "Get the category applying to position POS."
8630 (save-match-data
8631 (if force-refresh (org-refresh-category-properties))
8632 (let ((pos (or pos (point))))
8633 (or (get-text-property pos 'org-category)
8634 (progn (org-refresh-category-properties)
8635 (get-text-property pos 'org-category))))))
8637 (defun org-refresh-category-properties ()
8638 "Refresh category text properties in the buffer."
8639 (let ((case-fold-search t)
8640 (inhibit-read-only t)
8641 (def-cat (cond
8642 ((null org-category)
8643 (if buffer-file-name
8644 (file-name-sans-extension
8645 (file-name-nondirectory buffer-file-name))
8646 "???"))
8647 ((symbolp org-category) (symbol-name org-category))
8648 (t org-category)))
8649 beg end cat pos optionp)
8650 (org-unmodified
8651 (save-excursion
8652 (save-restriction
8653 (widen)
8654 (goto-char (point-min))
8655 (put-text-property (point) (point-max) 'org-category def-cat)
8656 (while (re-search-forward
8657 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8658 (setq pos (match-end 0)
8659 optionp (equal (char-after (match-beginning 0)) ?#)
8660 cat (org-trim (match-string 2)))
8661 (if optionp
8662 (setq beg (point-at-bol) end (point-max))
8663 (org-back-to-heading t)
8664 (setq beg (point) end (org-end-of-subtree t t)))
8665 (put-text-property beg end 'org-category cat)
8666 (put-text-property beg end 'org-category-position beg)
8667 (goto-char pos)))))))
8670 ;;;; Link Stuff
8672 ;;; Link abbreviations
8674 (defun org-link-expand-abbrev (link)
8675 "Apply replacements as defined in `org-link-abbrev-alist'."
8676 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8677 (let* ((key (match-string 1 link))
8678 (as (or (assoc key org-link-abbrev-alist-local)
8679 (assoc key org-link-abbrev-alist)))
8680 (tag (and (match-end 2) (match-string 3 link)))
8681 rpl)
8682 (if (not as)
8683 link
8684 (setq rpl (cdr as))
8685 (cond
8686 ((symbolp rpl) (funcall rpl tag))
8687 ((string-match "%(\\([^)]+\\))" rpl)
8688 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8689 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8690 ((string-match "%h" rpl)
8691 (replace-match (url-hexify-string (or tag "")) t t rpl))
8692 (t (concat rpl tag)))))
8693 link))
8695 ;;; Storing and inserting links
8697 (defvar org-insert-link-history nil
8698 "Minibuffer history for links inserted with `org-insert-link'.")
8700 (defvar org-stored-links nil
8701 "Contains the links stored with `org-store-link'.")
8703 (defvar org-store-link-plist nil
8704 "Plist with info about the most recently link created with `org-store-link'.")
8706 (defvar org-link-protocols nil
8707 "Link protocols added to Org-mode using `org-add-link-type'.")
8709 (defvar org-store-link-functions nil
8710 "List of functions that are called to create and store a link.
8711 Each function will be called in turn until one returns a non-nil
8712 value. Each function should check if it is responsible for creating
8713 this link (for example by looking at the major mode).
8714 If not, it must exit and return nil.
8715 If yes, it should return a non-nil value after a calling
8716 `org-store-link-props' with a list of properties and values.
8717 Special properties are:
8719 :type The link prefix, like \"http\". This must be given.
8720 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8721 This is obligatory as well.
8722 :description Optional default description for the second pair
8723 of brackets in an Org-mode link. The user can still change
8724 this when inserting this link into an Org-mode buffer.
8726 In addition to these, any additional properties can be specified
8727 and then used in capture templates.")
8729 (defun org-add-link-type (type &optional follow export)
8730 "Add TYPE to the list of `org-link-types'.
8731 Re-compute all regular expressions depending on `org-link-types'
8733 FOLLOW and EXPORT are two functions.
8735 FOLLOW should take the link path as the single argument and do whatever
8736 is necessary to follow the link, for example find a file or display
8737 a mail message.
8739 EXPORT should format the link path for export to one of the export formats.
8740 It should be a function accepting three arguments:
8742 path the path of the link, the text after the prefix (like \"http:\")
8743 desc the description of the link, if any, or a description added by
8744 org-export-normalize-links if there is none
8745 format the export format, a symbol like `html' or `latex' or `ascii'..
8747 The function may use the FORMAT information to return different values
8748 depending on the format. The return value will be put literally into
8749 the exported file. If the return value is nil, this means Org should
8750 do what it normally does with links which do not have EXPORT defined.
8752 Org-mode has a built-in default for exporting links. If you are happy with
8753 this default, there is no need to define an export function for the link
8754 type. For a simple example of an export function, see `org-bbdb.el'."
8755 (add-to-list 'org-link-types type t)
8756 (org-make-link-regexps)
8757 (if (assoc type org-link-protocols)
8758 (setcdr (assoc type org-link-protocols) (list follow export))
8759 (push (list type follow export) org-link-protocols)))
8761 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8762 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8764 ;;;###autoload
8765 (defun org-store-link (arg)
8766 "\\<org-mode-map>Store an org-link to the current location.
8767 This link is added to `org-stored-links' and can later be inserted
8768 into an org-buffer with \\[org-insert-link].
8770 For some link types, a prefix arg is interpreted:
8771 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8772 For file links, arg negates `org-context-in-file-links'."
8773 (interactive "P")
8774 (org-load-modules-maybe)
8775 (setq org-store-link-plist nil) ; reset
8776 (org-with-limited-levels
8777 (let (link cpltxt desc description search txt custom-id agenda-link)
8778 (cond
8780 ((run-hook-with-args-until-success 'org-store-link-functions)
8781 (setq link (plist-get org-store-link-plist :link)
8782 desc (or (plist-get org-store-link-plist :description) link)))
8784 ((org-src-edit-buffer-p)
8785 (let (label gc)
8786 (while (or (not label)
8787 (save-excursion
8788 (save-restriction
8789 (widen)
8790 (goto-char (point-min))
8791 (re-search-forward
8792 (regexp-quote (format org-coderef-label-format label))
8793 nil t))))
8794 (when label (message "Label exists already") (sit-for 2))
8795 (setq label (read-string "Code line label: " label)))
8796 (end-of-line 1)
8797 (setq link (format org-coderef-label-format label))
8798 (setq gc (- 79 (length link)))
8799 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8800 (insert link)
8801 (setq link (concat "(" label ")") desc nil)))
8803 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8804 ;; We are in the agenda, link to referenced location
8805 (let ((m (or (get-text-property (point) 'org-hd-marker)
8806 (get-text-property (point) 'org-marker))))
8807 (when m
8808 (org-with-point-at m
8809 (setq agenda-link
8810 (if (org-called-interactively-p 'any)
8811 (call-interactively 'org-store-link)
8812 (org-store-link nil)))))))
8814 ((eq major-mode 'calendar-mode)
8815 (let ((cd (calendar-cursor-to-date)))
8816 (setq link
8817 (format-time-string
8818 (car org-time-stamp-formats)
8819 (apply 'encode-time
8820 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8821 nil nil nil))))
8822 (org-store-link-props :type "calendar" :date cd)))
8824 ((eq major-mode 'help-mode)
8825 (setq link (concat "help:" (save-excursion
8826 (goto-char (point-min))
8827 (looking-at "^[^ ]+")
8828 (match-string 0))))
8829 (org-store-link-props :type "help"))
8831 ((eq major-mode 'w3-mode)
8832 (setq cpltxt (if (and (buffer-name)
8833 (not (string-match "Untitled" (buffer-name))))
8834 (buffer-name)
8835 (url-view-url t))
8836 link (url-view-url t))
8837 (org-store-link-props :type "w3" :url (url-view-url t)))
8839 ((eq major-mode 'w3m-mode)
8840 (setq cpltxt (or w3m-current-title w3m-current-url)
8841 link w3m-current-url)
8842 (org-store-link-props :type "w3m" :url (url-view-url t)))
8844 ((setq search (run-hook-with-args-until-success
8845 'org-create-file-search-functions))
8846 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8847 "::" search))
8848 (setq cpltxt (or description link)))
8850 ((eq major-mode 'image-mode)
8851 (setq cpltxt (concat "file:"
8852 (abbreviate-file-name buffer-file-name))
8853 link cpltxt)
8854 (org-store-link-props :type "image" :file buffer-file-name))
8856 ((eq major-mode 'dired-mode)
8857 ;; link to the file in the current line
8858 (let ((file (dired-get-filename nil t)))
8859 (setq file (if file
8860 (abbreviate-file-name
8861 (expand-file-name (dired-get-filename nil t)))
8862 ;; otherwise, no file so use current directory.
8863 default-directory))
8864 (setq cpltxt (concat "file:" file)
8865 link cpltxt)))
8867 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8868 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8869 (cond
8870 ((org-in-regexp "<<\\(.*?\\)>>")
8871 (setq cpltxt
8872 (concat "file:"
8873 (abbreviate-file-name
8874 (buffer-file-name (buffer-base-buffer)))
8875 "::" (match-string 1))
8876 link cpltxt))
8877 ((and (featurep 'org-id)
8878 (or (eq org-link-to-org-use-id t)
8879 (and (org-called-interactively-p 'any)
8880 (or (eq org-link-to-org-use-id 'create-if-interactive)
8881 (and (eq org-link-to-org-use-id
8882 'create-if-interactive-and-no-custom-id)
8883 (not custom-id))))
8884 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8885 ;; We can make a link using the ID.
8886 (setq link (condition-case nil
8887 (prog1 (org-id-store-link)
8888 (setq desc (plist-get org-store-link-plist :description)))
8889 (error
8890 ;; probably before first headline, link to file only
8891 (concat "file:"
8892 (abbreviate-file-name
8893 (buffer-file-name (buffer-base-buffer))))))))
8895 ;; Just link to current headline
8896 (setq cpltxt (concat "file:"
8897 (abbreviate-file-name
8898 (buffer-file-name (buffer-base-buffer)))))
8899 ;; Add a context search string
8900 (when (org-xor org-context-in-file-links arg)
8901 (setq txt (cond
8902 ((org-at-heading-p) nil)
8903 ((org-region-active-p)
8904 (buffer-substring (region-beginning) (region-end)))))
8905 (when (or (null txt) (string-match "\\S-" txt))
8906 (setq cpltxt
8907 (concat cpltxt "::"
8908 (condition-case nil
8909 (org-make-org-heading-search-string txt)
8910 (error "")))
8911 desc (or (nth 4 (ignore-errors
8912 (org-heading-components))) "NONE"))))
8913 (if (string-match "::\\'" cpltxt)
8914 (setq cpltxt (substring cpltxt 0 -2)))
8915 (setq link cpltxt))))
8917 ((buffer-file-name (buffer-base-buffer))
8918 ;; Just link to this file here.
8919 (setq cpltxt (concat "file:"
8920 (abbreviate-file-name
8921 (buffer-file-name (buffer-base-buffer)))))
8922 ;; Add a context string
8923 (when (org-xor org-context-in-file-links arg)
8924 (setq txt (if (org-region-active-p)
8925 (buffer-substring (region-beginning) (region-end))
8926 (buffer-substring (point-at-bol) (point-at-eol))))
8927 ;; Only use search option if there is some text.
8928 (when (string-match "\\S-" txt)
8929 (setq cpltxt
8930 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8931 desc "NONE")))
8932 (setq link cpltxt))
8934 ((org-called-interactively-p 'interactive)
8935 (error "Cannot link to a buffer which is not visiting a file"))
8937 (t (setq link nil)))
8939 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8940 (setq link (or link cpltxt)
8941 desc (or desc cpltxt))
8942 (if (equal desc "NONE") (setq desc nil))
8944 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8945 (progn
8946 (setq org-stored-links
8947 (cons (list link desc) org-stored-links))
8948 (message "Stored: %s" (or desc link))
8949 (when custom-id
8950 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8951 "::#" custom-id))
8952 (setq org-stored-links
8953 (cons (list link desc) org-stored-links))))
8954 (or agenda-link (and link (org-make-link-string link desc)))))))
8956 (defun org-store-link-props (&rest plist)
8957 "Store link properties, extract names and addresses."
8958 (let (x adr)
8959 (when (setq x (plist-get plist :from))
8960 (setq adr (mail-extract-address-components x))
8961 (setq plist (plist-put plist :fromname (car adr)))
8962 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8963 (when (setq x (plist-get plist :to))
8964 (setq adr (mail-extract-address-components x))
8965 (setq plist (plist-put plist :toname (car adr)))
8966 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8967 (let ((from (plist-get plist :from))
8968 (to (plist-get plist :to)))
8969 (when (and from to org-from-is-user-regexp)
8970 (setq plist
8971 (plist-put plist :fromto
8972 (if (string-match org-from-is-user-regexp from)
8973 (concat "to %t")
8974 (concat "from %f"))))))
8975 (setq org-store-link-plist plist))
8977 (defun org-add-link-props (&rest plist)
8978 "Add these properties to the link property list."
8979 (let (key value)
8980 (while plist
8981 (setq key (pop plist) value (pop plist))
8982 (setq org-store-link-plist
8983 (plist-put org-store-link-plist key value)))))
8985 (defun org-email-link-description (&optional fmt)
8986 "Return the description part of an email link.
8987 This takes information from `org-store-link-plist' and formats it
8988 according to FMT (default from `org-email-link-description-format')."
8989 (setq fmt (or fmt org-email-link-description-format))
8990 (let* ((p org-store-link-plist)
8991 (to (plist-get p :toaddress))
8992 (from (plist-get p :fromaddress))
8993 (table
8994 (list
8995 (cons "%c" (plist-get p :fromto))
8996 (cons "%F" (plist-get p :from))
8997 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8998 (cons "%T" (plist-get p :to))
8999 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9000 (cons "%s" (plist-get p :subject))
9001 (cons "%d" (plist-get p :date))
9002 (cons "%m" (plist-get p :message-id)))))
9003 (when (string-match "%c" fmt)
9004 ;; Check if the user wrote this message
9005 (if (and org-from-is-user-regexp from to
9006 (save-match-data (string-match org-from-is-user-regexp from)))
9007 (setq fmt (replace-match "to %t" t t fmt))
9008 (setq fmt (replace-match "from %f" t t fmt))))
9009 (org-replace-escapes fmt table)))
9011 (defun org-make-org-heading-search-string (&optional string heading)
9012 "Make search string for STRING or current headline."
9013 (interactive)
9014 (let ((s (or string (org-get-heading)))
9015 (lines org-context-in-file-links))
9016 (unless (and string (not heading))
9017 ;; We are using a headline, clean up garbage in there.
9018 (if (string-match org-todo-regexp s)
9019 (setq s (replace-match "" t t s)))
9020 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9021 (setq s (replace-match "" t t s)))
9022 (setq s (org-trim s))
9023 (if (string-match (concat "^\\(" org-quote-string "\\|"
9024 org-comment-string "\\)") s)
9025 (setq s (replace-match "" t t s)))
9026 (while (string-match org-ts-regexp s)
9027 (setq s (replace-match "" t t s))))
9028 (or string (setq s (concat "*" s))) ; Add * for headlines
9029 (when (and string (integerp lines) (> lines 0))
9030 (let ((slines (org-split-string s "\n")))
9031 (when (< lines (length slines))
9032 (setq s (mapconcat
9033 'identity
9034 (reverse (nthcdr (- (length slines) lines)
9035 (reverse slines))) "\n")))))
9036 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9038 (defun org-make-link-string (link &optional description)
9039 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9040 (unless (string-match "\\S-" link)
9041 (error "Empty link"))
9042 (when (and description
9043 (stringp description)
9044 (not (string-match "\\S-" description)))
9045 (setq description nil))
9046 (when (stringp description)
9047 ;; Remove brackets from the description, they are fatal.
9048 (while (string-match "\\[" description)
9049 (setq description (replace-match "{" t t description)))
9050 (while (string-match "\\]" description)
9051 (setq description (replace-match "}" t t description))))
9052 (when (equal link description)
9053 ;; No description needed, it is identical
9054 (setq description nil))
9055 (when (and (not description)
9056 (not (string-match (org-image-file-name-regexp) link))
9057 (not (equal link (org-link-escape link))))
9058 (setq description (org-extract-attributes link)))
9059 (setq link
9060 (cond ((string-match (org-image-file-name-regexp) link) link)
9061 ((string-match org-link-types-re link)
9062 (concat (match-string 1 link)
9063 (org-link-escape (substring link (match-end 1)))))
9064 (t (org-link-escape link))))
9065 (concat "[[" link "]"
9066 (if description (concat "[" description "]") "")
9067 "]"))
9069 (defconst org-link-escape-chars
9070 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9071 "List of characters that should be escaped in link.
9072 This is the list that is used for internal purposes.")
9074 (defconst org-link-escape-chars-browser
9075 '(?\ )
9076 "List of escapes for characters that are problematic in links.
9077 This is the list that is used before handing over to the browser.")
9079 (defun org-link-escape (text &optional table merge)
9080 "Return percent escaped representation of TEXT.
9081 TEXT is a string with the text to escape.
9082 Optional argument TABLE is a list with characters that should be
9083 escaped. When nil, `org-link-escape-chars' is used.
9084 If optional argument MERGE is set, merge TABLE into
9085 `org-link-escape-chars'."
9086 (cond
9087 ((and table merge)
9088 (mapc (lambda (defchr)
9089 (unless (member defchr table)
9090 (setq table (cons defchr table)))) org-link-escape-chars))
9091 ((null table)
9092 (setq table org-link-escape-chars)))
9093 (mapconcat
9094 (lambda (char)
9095 (if (or (member char table)
9096 (and (or (< char 32) (= char 37) (> char 126))
9097 org-url-hexify-p))
9098 (mapconcat (lambda (sequence-element)
9099 (format "%%%.2X" sequence-element))
9100 (or (encode-coding-char char 'utf-8)
9101 (error "Unable to percent escape character: %s"
9102 (char-to-string char))) "")
9103 (char-to-string char))) text ""))
9105 (defun org-link-unescape (str)
9106 "Unhex hexified Unicode strings as returned from the JavaScript function
9107 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9108 (unless (and (null str) (string= "" str))
9109 (let ((pos 0) (case-fold-search t) unhexed)
9110 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9111 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9112 (setq str (replace-match unhexed t t str))
9113 (setq pos (+ pos (length unhexed))))))
9114 str)
9116 (defun org-link-unescape-compound (hex)
9117 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9118 Note: this function also decodes single byte encodings like
9119 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9120 (save-match-data
9121 (let* ((bytes (cdr (split-string hex "%")))
9122 (ret "")
9123 (eat 0)
9124 (sum 0))
9125 (while bytes
9126 (let* ((val (string-to-number (pop bytes) 16))
9127 (shift-xor
9128 (if (= 0 eat)
9129 (cond
9130 ((>= val 252) (cons 6 252))
9131 ((>= val 248) (cons 5 248))
9132 ((>= val 240) (cons 4 240))
9133 ((>= val 224) (cons 3 224))
9134 ((>= val 192) (cons 2 192))
9135 (t (cons 0 0)))
9136 (cons 6 128))))
9137 (if (>= val 192) (setq eat (car shift-xor)))
9138 (setq val (logxor val (cdr shift-xor)))
9139 (setq sum (+ (lsh sum (car shift-xor)) val))
9140 (if (> eat 0) (setq eat (- eat 1)))
9141 (cond
9142 ((= 0 eat) ;multi byte
9143 (setq ret (concat ret (org-char-to-string sum)))
9144 (setq sum 0))
9145 ((not bytes) ; single byte(s)
9146 (setq ret (org-link-unescape-single-byte-sequence hex))))
9147 )) ;; end (while bytes
9148 ret )))
9150 (defun org-link-unescape-single-byte-sequence (hex)
9151 "Unhexify hex-encoded single byte character sequences."
9152 (mapconcat (lambda (byte)
9153 (char-to-string (string-to-number byte 16)))
9154 (cdr (split-string hex "%")) ""))
9156 (defun org-xor (a b)
9157 "Exclusive or."
9158 (if a (not b) b))
9160 (defun org-fixup-message-id-for-http (s)
9161 "Replace special characters in a message id, so it can be used in an http query."
9162 (when (string-match "%" s)
9163 (setq s (mapconcat (lambda (c)
9164 (if (eq c ?%)
9165 "%25"
9166 (char-to-string c)))
9167 s "")))
9168 (while (string-match "<" s)
9169 (setq s (replace-match "%3C" t t s)))
9170 (while (string-match ">" s)
9171 (setq s (replace-match "%3E" t t s)))
9172 (while (string-match "@" s)
9173 (setq s (replace-match "%40" t t s)))
9176 (defun org-link-prettify (link)
9177 "Return a human-readable representation of LINK.
9178 The car of LINK must be a raw link the cdr of LINK must be either
9179 a link description or nil."
9180 (let ((desc (or (cadr link) "<no description>")))
9181 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9182 "<" (car link) ">")))
9184 ;;;###autoload
9185 (defun org-insert-link-global ()
9186 "Insert a link like Org-mode does.
9187 This command can be called in any mode to insert a link in Org-mode syntax."
9188 (interactive)
9189 (org-load-modules-maybe)
9190 (org-run-like-in-org-mode 'org-insert-link))
9192 (defun org-insert-all-links (&optional keep)
9193 "Insert all links in `org-stored-links'."
9194 (interactive "P")
9195 (let ((links (copy-sequence org-stored-links)) l)
9196 (while (setq l (if keep (pop links) (pop org-stored-links)))
9197 (insert "- ")
9198 (org-insert-link nil (car l) (cadr l))
9199 (insert "\n"))))
9201 (defun org-link-fontify-links-to-this-file ()
9202 "Fontify links to the current file in `org-stored-links'."
9203 (let ((f (buffer-file-name)) a b)
9204 (setq a (mapcar (lambda(l)
9205 (let ((ll (car l)))
9206 (when (and (string-match "^file:\\(.+\\)::" ll)
9207 (equal f (expand-file-name (match-string 1 ll))))
9208 ll)))
9209 org-stored-links))
9210 (when (featurep 'org-id)
9211 (setq b (mapcar (lambda(l)
9212 (let ((ll (car l)))
9213 (when (and (string-match "^id:\\(.+\\)$" ll)
9214 (equal f (expand-file-name
9215 (or (org-id-find-id-file
9216 (match-string 1 ll)) ""))))
9217 ll)))
9218 org-stored-links)))
9219 (mapcar (lambda(l)
9220 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9221 (delq nil (append a b)))))
9223 (defvar org-link-links-in-this-file nil)
9224 (defun org-insert-link (&optional complete-file link-location default-description)
9225 "Insert a link. At the prompt, enter the link.
9227 Completion can be used to insert any of the link protocol prefixes like
9228 http or ftp in use.
9230 The history can be used to select a link previously stored with
9231 `org-store-link'. When the empty string is entered (i.e. if you just
9232 press RET at the prompt), the link defaults to the most recently
9233 stored link. As SPC triggers completion in the minibuffer, you need to
9234 use M-SPC or C-q SPC to force the insertion of a space character.
9236 You will also be prompted for a description, and if one is given, it will
9237 be displayed in the buffer instead of the link.
9239 If there is already a link at point, this command will allow you to edit link
9240 and description parts.
9242 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9243 be selected using completion. The path to the file will be relative to the
9244 current directory if the file is in the current directory or a subdirectory.
9245 Otherwise, the link will be the absolute path as completed in the minibuffer
9246 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9247 option `org-link-file-path-type'.
9249 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9250 the current directory or below.
9252 With three \\[universal-argument] prefixes, negate the meaning of
9253 `org-keep-stored-link-after-insertion'.
9255 If `org-make-link-description-function' is non-nil, this function will be
9256 called with the link target, and the result will be the default
9257 link description.
9259 If the LINK-LOCATION parameter is non-nil, this value will be
9260 used as the link location instead of reading one interactively.
9262 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9263 be used as the default description."
9264 (interactive "P")
9265 (let* ((wcf (current-window-configuration))
9266 (origbuf (current-buffer))
9267 (region (if (org-region-active-p)
9268 (buffer-substring (region-beginning) (region-end))))
9269 (remove (and region (list (region-beginning) (region-end))))
9270 (desc region)
9271 tmphist ; byte-compile incorrectly complains about this
9272 (link link-location)
9273 (abbrevs org-link-abbrev-alist-local)
9274 entry file all-prefixes auto-desc)
9275 (cond
9276 (link-location) ; specified by arg, just use it.
9277 ((org-in-regexp org-bracket-link-regexp 1)
9278 ;; We do have a link at point, and we are going to edit it.
9279 (setq remove (list (match-beginning 0) (match-end 0)))
9280 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9281 (setq link (read-string "Link: "
9282 (org-link-unescape
9283 (org-match-string-no-properties 1)))))
9284 ((or (org-in-regexp org-angle-link-re)
9285 (org-in-regexp org-plain-link-re))
9286 ;; Convert to bracket link
9287 (setq remove (list (match-beginning 0) (match-end 0))
9288 link (read-string "Link: "
9289 (org-remove-angle-brackets (match-string 0)))))
9290 ((member complete-file '((4) (16)))
9291 ;; Completing read for file names.
9292 (setq link (org-file-complete-link complete-file)))
9294 ;; Read link, with completion for stored links.
9295 (org-link-fontify-links-to-this-file)
9296 (org-switch-to-buffer-other-window "*Org Links*")
9297 (with-current-buffer "*Org Links*"
9298 (erase-buffer)
9299 (insert "Insert a link.
9300 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9301 (when org-stored-links
9302 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9303 (insert (mapconcat 'org-link-prettify
9304 (reverse org-stored-links) "\n")))
9305 (goto-char (point-min)))
9306 (let ((cw (selected-window)))
9307 (select-window (get-buffer-window "*Org Links*" 'visible))
9308 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9309 (unless (pos-visible-in-window-p (point-max))
9310 (org-fit-window-to-buffer))
9311 (and (window-live-p cw) (select-window cw)))
9312 ;; Fake a link history, containing the stored links.
9313 (setq tmphist (append (mapcar 'car org-stored-links)
9314 org-insert-link-history))
9315 (setq all-prefixes (append (mapcar 'car abbrevs)
9316 (mapcar 'car org-link-abbrev-alist)
9317 org-link-types))
9318 (unwind-protect
9319 (progn
9320 (setq link
9321 (org-completing-read
9322 "Link: "
9323 (append
9324 (mapcar (lambda (x) (concat x ":"))
9325 all-prefixes)
9326 (mapcar 'car org-stored-links))
9327 nil nil nil
9328 'tmphist
9329 (caar org-stored-links)))
9330 (if (not (string-match "\\S-" link))
9331 (error "No link selected"))
9332 (mapc (lambda(l)
9333 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9334 org-stored-links)
9335 (if (or (member link all-prefixes)
9336 (and (equal ":" (substring link -1))
9337 (member (substring link 0 -1) all-prefixes)
9338 (setq link (substring link 0 -1))))
9339 (setq link (with-current-buffer origbuf
9340 (org-link-try-special-completion link)))))
9341 (set-window-configuration wcf)
9342 (kill-buffer "*Org Links*"))
9343 (setq entry (assoc link org-stored-links))
9344 (or entry (push link org-insert-link-history))
9345 (setq desc (or desc (nth 1 entry)))))
9347 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9348 (not org-keep-stored-link-after-insertion))
9349 (setq org-stored-links (delq (assoc link org-stored-links)
9350 org-stored-links)))
9352 (if (string-match org-plain-link-re link)
9353 ;; URL-like link, normalize the use of angular brackets.
9354 (setq link (org-remove-angle-brackets link)))
9356 ;; Check if we are linking to the current file with a search option
9357 ;; If yes, simplify the link by using only the search option.
9358 (when (and buffer-file-name
9359 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9360 (let* ((path (match-string 1 link))
9361 (case-fold-search nil)
9362 (search (match-string 2 link)))
9363 (save-match-data
9364 (if (equal (file-truename buffer-file-name) (file-truename path))
9365 ;; We are linking to this same file, with a search option
9366 (setq link search)))))
9368 ;; Check if we can/should use a relative path. If yes, simplify the link
9369 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9370 (let* ((type (match-string 1 link))
9371 (path (match-string 2 link))
9372 (origpath path)
9373 (case-fold-search nil))
9374 (cond
9375 ((or (eq org-link-file-path-type 'absolute)
9376 (equal complete-file '(16)))
9377 (setq path (abbreviate-file-name (expand-file-name path))))
9378 ((eq org-link-file-path-type 'noabbrev)
9379 (setq path (expand-file-name path)))
9380 ((eq org-link-file-path-type 'relative)
9381 (setq path (file-relative-name path)))
9383 (save-match-data
9384 (if (string-match (concat "^" (regexp-quote
9385 (expand-file-name
9386 (file-name-as-directory
9387 default-directory))))
9388 (expand-file-name path))
9389 ;; We are linking a file with relative path name.
9390 (setq path (substring (expand-file-name path)
9391 (match-end 0)))
9392 (setq path (abbreviate-file-name (expand-file-name path)))))))
9393 (setq link (concat type path))
9394 (if (equal desc origpath)
9395 (setq desc path))))
9397 (if org-make-link-description-function
9398 (setq desc
9399 (or (condition-case nil
9400 (funcall org-make-link-description-function link desc)
9401 (error (progn (message "Can't get link description from `%s'"
9402 (symbol-name org-make-link-description-function))
9403 (sit-for 2) nil)))
9404 (read-string "Description: " default-description)))
9405 (if default-description (setq desc default-description)
9406 (setq desc (or (and auto-desc desc)
9407 (read-string "Description: " desc)))))
9409 (unless (string-match "\\S-" desc) (setq desc nil))
9410 (if remove (apply 'delete-region remove))
9411 (insert (org-make-link-string link desc))))
9413 (defun org-link-try-special-completion (type)
9414 "If there is completion support for link type TYPE, offer it."
9415 (let ((fun (intern (concat "org-" type "-complete-link"))))
9416 (if (functionp fun)
9417 (funcall fun)
9418 (read-string "Link (no completion support): " (concat type ":")))))
9420 (defun org-file-complete-link (&optional arg)
9421 "Create a file link using completion."
9422 (let (file link)
9423 (setq file (org-iread-file-name "File: "))
9424 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9425 (pwd1 (file-name-as-directory (abbreviate-file-name
9426 (expand-file-name ".")))))
9427 (cond
9428 ((equal arg '(16))
9429 (setq link (concat
9430 "file:"
9431 (abbreviate-file-name (expand-file-name file)))))
9432 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9433 (setq link (concat "file:" (match-string 1 file))))
9434 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9435 (expand-file-name file))
9436 (setq link (concat
9437 "file:" (match-string 1 (expand-file-name file)))))
9438 (t (setq link (concat "file:" file)))))
9439 link))
9441 (defun org-iread-file-name (&rest args)
9442 "Read-file-name using `ido-mode' speedup if available.
9443 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9444 See `read-file-name' for a description of parameters."
9445 (org-without-partial-completion
9446 (if (and org-completion-use-ido
9447 (fboundp 'ido-read-file-name)
9448 (boundp 'ido-mode) ido-mode
9449 (listp (second args)))
9450 (let ((ido-enter-matching-directory nil))
9451 (apply 'ido-read-file-name args))
9452 (apply 'read-file-name args))))
9454 (defun org-completing-read (&rest args)
9455 "Completing-read with SPACE being a normal character."
9456 (let ((enable-recursive-minibuffers t)
9457 (minibuffer-local-completion-map
9458 (copy-keymap minibuffer-local-completion-map)))
9459 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9460 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9461 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9462 (apply 'org-icompleting-read args)))
9464 (defun org-completing-read-no-i (&rest args)
9465 (let (org-completion-use-ido org-completion-use-iswitchb)
9466 (apply 'org-completing-read args)))
9468 (defun org-iswitchb-completing-read (prompt choices &rest args)
9469 "Use iswitch as a completing-read replacement to choose from choices.
9470 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9471 from."
9472 (let* ((iswitchb-use-virtual-buffers nil)
9473 (iswitchb-make-buflist-hook
9474 (lambda ()
9475 (setq iswitchb-temp-buflist choices))))
9476 (iswitchb-read-buffer prompt)))
9478 (defun org-icompleting-read (&rest args)
9479 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9480 (org-without-partial-completion
9481 (if (and org-completion-use-ido
9482 (fboundp 'ido-completing-read)
9483 (boundp 'ido-mode) ido-mode
9484 (listp (second args)))
9485 (let ((ido-enter-matching-directory nil))
9486 (apply 'ido-completing-read (concat (car args))
9487 (if (consp (car (nth 1 args)))
9488 (mapcar 'car (nth 1 args))
9489 (nth 1 args))
9490 (cddr args)))
9491 (if (and org-completion-use-iswitchb
9492 (boundp 'iswitchb-mode) iswitchb-mode
9493 (listp (second args)))
9494 (apply 'org-iswitchb-completing-read (concat (car args))
9495 (if (consp (car (nth 1 args)))
9496 (mapcar 'car (nth 1 args))
9497 (nth 1 args))
9498 (cddr args))
9499 (apply 'completing-read args)))))
9501 (defun org-extract-attributes (s)
9502 "Extract the attributes cookie from a string and set as text property."
9503 (let (a attr (start 0) key value)
9504 (save-match-data
9505 (when (string-match "{{\\([^}]+\\)}}$" s)
9506 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9507 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9508 (setq key (match-string 1 a) value (match-string 2 a)
9509 start (match-end 0)
9510 attr (plist-put attr (intern key) value))))
9511 (org-add-props s nil 'org-attr attr))
9514 (defun org-extract-attributes-from-string (tag)
9515 (let (key value attr)
9516 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9517 (setq key (match-string 1 tag) value (match-string 2 tag)
9518 tag (replace-match "" t t tag)
9519 attr (plist-put attr (intern key) value)))
9520 (cons tag attr)))
9522 (defun org-attributes-to-string (plist)
9523 "Format a property list into an HTML attribute list."
9524 (let ((s "") key value)
9525 (while plist
9526 (setq key (pop plist) value (pop plist))
9527 (and value
9528 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9531 ;;; Opening/following a link
9533 (defvar org-link-search-failed nil)
9535 (defvar org-open-link-functions nil
9536 "Hook for functions finding a plain text link.
9537 These functions must take a single argument, the link content.
9538 They will be called for links that look like [[link text][description]]
9539 when LINK TEXT does not have a protocol like \"http:\" and does not look
9540 like a filename (e.g. \"./blue.png\").
9542 These functions will be called *before* Org attempts to resolve the
9543 link by doing text searches in the current buffer - so if you want a
9544 link \"[[target]]\" to still find \"<<target>>\", your function should
9545 handle this as a special case.
9547 When the function does handle the link, it must return a non-nil value.
9548 If it decides that it is not responsible for this link, it must return
9549 nil to indicate that that Org-mode can continue with other options
9550 like exact and fuzzy text search.")
9552 (defun org-next-link ()
9553 "Move forward to the next link.
9554 If the link is in hidden text, expose it."
9555 (interactive)
9556 (when (and org-link-search-failed (eq this-command last-command))
9557 (goto-char (point-min))
9558 (message "Link search wrapped back to beginning of buffer"))
9559 (setq org-link-search-failed nil)
9560 (let* ((pos (point))
9561 (ct (org-context))
9562 (a (assoc :link ct)))
9563 (if a (goto-char (nth 2 a)))
9564 (if (re-search-forward org-any-link-re nil t)
9565 (progn
9566 (goto-char (match-beginning 0))
9567 (if (outline-invisible-p) (org-show-context)))
9568 (goto-char pos)
9569 (setq org-link-search-failed t)
9570 (error "No further link found"))))
9572 (defun org-previous-link ()
9573 "Move backward to the previous link.
9574 If the link is in hidden text, expose it."
9575 (interactive)
9576 (when (and org-link-search-failed (eq this-command last-command))
9577 (goto-char (point-max))
9578 (message "Link search wrapped back to end of buffer"))
9579 (setq org-link-search-failed nil)
9580 (let* ((pos (point))
9581 (ct (org-context))
9582 (a (assoc :link ct)))
9583 (if a (goto-char (nth 1 a)))
9584 (if (re-search-backward org-any-link-re nil t)
9585 (progn
9586 (goto-char (match-beginning 0))
9587 (if (outline-invisible-p) (org-show-context)))
9588 (goto-char pos)
9589 (setq org-link-search-failed t)
9590 (error "No further link found"))))
9592 (defun org-translate-link (s)
9593 "Translate a link string if a translation function has been defined."
9594 (if (and org-link-translation-function
9595 (fboundp org-link-translation-function)
9596 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9597 (progn
9598 (setq s (funcall org-link-translation-function
9599 (match-string 1 s) (match-string 2 s)))
9600 (concat (car s) ":" (cdr s)))
9603 (defun org-translate-link-from-planner (type path)
9604 "Translate a link from Emacs Planner syntax so that Org can follow it.
9605 This is still an experimental function, your mileage may vary."
9606 (cond
9607 ((member type '("http" "https" "news" "ftp"))
9608 ;; standard Internet links are the same.
9609 nil)
9610 ((and (equal type "irc") (string-match "^//" path))
9611 ;; Planner has two / at the beginning of an irc link, we have 1.
9612 ;; We should have zero, actually....
9613 (setq path (substring path 1)))
9614 ((and (equal type "lisp") (string-match "^/" path))
9615 ;; Planner has a slash, we do not.
9616 (setq type "elisp" path (substring path 1)))
9617 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9618 ;; A typical message link. Planner has the id after the final slash,
9619 ;; we separate it with a hash mark
9620 (setq path (concat (match-string 1 path) "#"
9621 (org-remove-angle-brackets (match-string 2 path)))))
9623 (cons type path))
9625 (defun org-find-file-at-mouse (ev)
9626 "Open file link or URL at mouse."
9627 (interactive "e")
9628 (mouse-set-point ev)
9629 (org-open-at-point 'in-emacs))
9631 (defun org-open-at-mouse (ev)
9632 "Open file link or URL at mouse.
9633 See the docstring of `org-open-file' for details."
9634 (interactive "e")
9635 (mouse-set-point ev)
9636 (if (eq major-mode 'org-agenda-mode)
9637 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9638 (org-open-at-point))
9640 (defvar org-window-config-before-follow-link nil
9641 "The window configuration before following a link.
9642 This is saved in case the need arises to restore it.")
9644 (defvar org-open-link-marker (make-marker)
9645 "Marker pointing to the location where `org-open-at-point; was called.")
9647 ;;;###autoload
9648 (defun org-open-at-point-global ()
9649 "Follow a link like Org-mode does.
9650 This command can be called in any mode to follow a link that has
9651 Org-mode syntax."
9652 (interactive)
9653 (org-run-like-in-org-mode 'org-open-at-point))
9655 ;;;###autoload
9656 (defun org-open-link-from-string (s &optional arg reference-buffer)
9657 "Open a link in the string S, as if it was in Org-mode."
9658 (interactive "sLink: \nP")
9659 (let ((reference-buffer (or reference-buffer (current-buffer))))
9660 (with-temp-buffer
9661 (let ((org-inhibit-startup (not reference-buffer)))
9662 (org-mode)
9663 (insert s)
9664 (goto-char (point-min))
9665 (when reference-buffer
9666 (setq org-link-abbrev-alist-local
9667 (with-current-buffer reference-buffer
9668 org-link-abbrev-alist-local)))
9669 (org-open-at-point arg reference-buffer)))))
9671 (defvar org-open-at-point-functions nil
9672 "Hook that is run when following a link at point.
9674 Functions in this hook must return t if they identify and follow
9675 a link at point. If they don't find anything interesting at point,
9676 they must return nil.")
9678 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9679 (defun org-open-at-point (&optional arg reference-buffer)
9680 "Open link at or after point.
9681 If there is no link at point, this function will search forward up to
9682 the end of the current line.
9683 Normally, files will be opened by an appropriate application. If the
9684 optional prefix argument ARG is non-nil, Emacs will visit the file.
9685 With a double prefix argument, try to open outside of Emacs, in the
9686 application the system uses for this file type."
9687 (interactive "P")
9688 ;; if in a code block, then open the block's results
9689 (unless (call-interactively #'org-babel-open-src-block-result)
9690 (org-load-modules-maybe)
9691 (move-marker org-open-link-marker (point))
9692 (setq org-window-config-before-follow-link (current-window-configuration))
9693 (org-remove-occur-highlights nil nil t)
9694 (cond
9695 ((and (org-at-heading-p)
9696 (not (org-at-timestamp-p t))
9697 (not (org-in-regexp
9698 (concat org-plain-link-re "\\|"
9699 org-bracket-link-regexp "\\|"
9700 org-angle-link-re "\\|"
9701 "[ \t]:[^ \t\n]+:[ \t]*$")))
9702 (not (get-text-property (point) 'org-linked-text)))
9703 (or (org-offer-links-in-entry arg)
9704 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9705 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9706 ((and (org-at-timestamp-p t)
9707 (not (org-in-regexp org-bracket-link-regexp)))
9708 (org-follow-timestamp-link))
9709 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9710 (not (org-in-regexp org-bracket-link-regexp)))
9711 (org-footnote-action))
9713 (let (type path link line search (pos (point)))
9714 (catch 'match
9715 (save-excursion
9716 (skip-chars-forward "^]\n\r")
9717 (when (org-in-regexp org-bracket-link-regexp 1)
9718 (setq link (org-extract-attributes
9719 (org-link-unescape (org-match-string-no-properties 1))))
9720 (while (string-match " *\n *" link)
9721 (setq link (replace-match " " t t link)))
9722 (setq link (org-link-expand-abbrev link))
9723 (cond
9724 ((or (file-name-absolute-p link)
9725 (string-match "^\\.\\.?/" link))
9726 (setq type "file" path link))
9727 ((string-match org-link-re-with-space3 link)
9728 (setq type (match-string 1 link) path (match-string 2 link)))
9729 ((string-match "^help:+\\(.+\\)" link)
9730 (setq type "help" path (match-string 1 link)))
9731 (t (setq type "thisfile" path link)))
9732 (throw 'match t)))
9734 (when (get-text-property (point) 'org-linked-text)
9735 (setq type "thisfile"
9736 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9737 (1+ (point)) (point))
9738 path (buffer-substring
9739 (or (previous-single-property-change pos 'org-linked-text)
9740 (point-min))
9741 (or (next-single-property-change pos 'org-linked-text)
9742 (point-max))))
9743 (throw 'match t))
9745 (save-excursion
9746 (when (or (org-in-regexp org-angle-link-re)
9747 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9748 (save-match-data (not (looking-back "\\[\\[")))))
9749 (setq type (match-string 1)
9750 path (org-link-unescape (match-string 2)))
9751 (throw 'match t)))
9752 (save-excursion
9753 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9754 (setq type "tags"
9755 path (match-string 1))
9756 (while (string-match ":" path)
9757 (setq path (replace-match "+" t t path)))
9758 (throw 'match t)))
9759 (when (org-in-regexp "<\\([^><\n]+\\)>")
9760 (setq type "tree-match"
9761 path (match-string 1))
9762 (throw 'match t)))
9763 (unless path
9764 (error "No link found"))
9766 ;; switch back to reference buffer
9767 ;; needed when if called in a temporary buffer through
9768 ;; org-open-link-from-string
9769 (with-current-buffer (or reference-buffer (current-buffer))
9771 ;; Remove any trailing spaces in path
9772 (if (string-match " +\\'" path)
9773 (setq path (replace-match "" t t path)))
9774 (if (and org-link-translation-function
9775 (fboundp org-link-translation-function))
9776 ;; Check if we need to translate the link
9777 (let ((tmp (funcall org-link-translation-function type path)))
9778 (setq type (car tmp) path (cdr tmp))))
9780 (cond
9782 ((assoc type org-link-protocols)
9783 (funcall (nth 1 (assoc type org-link-protocols)) path))
9785 ((equal type "help")
9786 (let ((f-or-v (intern path)))
9787 (cond ((fboundp f-or-v)
9788 (describe-function f-or-v))
9789 ((boundp f-or-v)
9790 (describe-variable f-or-v))
9791 (t (error "Not a known function or variable")))))
9793 ((equal type "mailto")
9794 (let ((cmd (car org-link-mailto-program))
9795 (args (cdr org-link-mailto-program)) args1
9796 (address path) (subject "") a)
9797 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9798 (setq address (match-string 1 path)
9799 subject (org-link-escape (match-string 2 path))))
9800 (while args
9801 (cond
9802 ((not (stringp (car args))) (push (pop args) args1))
9803 (t (setq a (pop args))
9804 (if (string-match "%a" a)
9805 (setq a (replace-match address t t a)))
9806 (if (string-match "%s" a)
9807 (setq a (replace-match subject t t a)))
9808 (push a args1))))
9809 (apply cmd (nreverse args1))))
9811 ((member type '("http" "https" "ftp" "news"))
9812 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9813 (org-link-escape
9814 path org-link-escape-chars-browser)
9815 path))))
9817 ((string= type "doi")
9818 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9819 (org-link-escape
9820 path org-link-escape-chars-browser)
9821 path))))
9823 ((member type '("message"))
9824 (browse-url (concat type ":" path)))
9826 ((string= type "tags")
9827 (org-tags-view arg path))
9829 ((string= type "tree-match")
9830 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9832 ((string= type "file")
9833 (if (string-match "::\\([0-9]+\\)\\'" path)
9834 (setq line (string-to-number (match-string 1 path))
9835 path (substring path 0 (match-beginning 0)))
9836 (if (string-match "::\\(.+\\)\\'" path)
9837 (setq search (match-string 1 path)
9838 path (substring path 0 (match-beginning 0)))))
9839 (if (string-match "[*?{]" (file-name-nondirectory path))
9840 (dired path)
9841 (org-open-file path arg line search)))
9843 ((string= type "shell")
9844 (let ((buf (generate-new-buffer "*Org Shell Output"))
9845 (cmd path))
9846 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9847 (string-match org-confirm-shell-link-not-regexp cmd))
9848 (not org-confirm-shell-link-function)
9849 (funcall org-confirm-shell-link-function
9850 (format "Execute \"%s\" in shell? "
9851 (org-add-props cmd nil
9852 'face 'org-warning))))
9853 (progn
9854 (message "Executing %s" cmd)
9855 (shell-command cmd buf)
9856 (if (featurep 'midnight)
9857 (setq clean-buffer-list-kill-buffer-names
9858 (cons buf clean-buffer-list-kill-buffer-names))))
9859 (error "Abort"))))
9861 ((string= type "elisp")
9862 (let ((cmd path))
9863 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9864 (string-match org-confirm-elisp-link-not-regexp cmd))
9865 (not org-confirm-elisp-link-function)
9866 (funcall org-confirm-elisp-link-function
9867 (format "Execute \"%s\" as elisp? "
9868 (org-add-props cmd nil
9869 'face 'org-warning))))
9870 (message "%s => %s" cmd
9871 (if (equal (string-to-char cmd) ?\()
9872 (eval (read cmd))
9873 (call-interactively (read cmd))))
9874 (error "Abort"))))
9876 ((and (string= type "thisfile")
9877 (run-hook-with-args-until-success
9878 'org-open-link-functions path)))
9880 ((string= type "thisfile")
9881 (if arg
9882 (switch-to-buffer-other-window
9883 (org-get-buffer-for-internal-link (current-buffer)))
9884 (org-mark-ring-push))
9885 (let ((cmd `(org-link-search
9886 ,path
9887 ,(cond ((equal arg '(4)) ''occur)
9888 ((equal arg '(16)) ''org-occur))
9889 ,pos)))
9890 (condition-case nil (let ((org-link-search-inhibit-query t))
9891 (eval cmd))
9892 (error (progn (widen) (eval cmd))))))
9894 (t (browse-url-at-point)))))))
9895 (move-marker org-open-link-marker nil)
9896 (run-hook-with-args 'org-follow-link-hook)))
9898 (defun org-offer-links-in-entry (&optional nth zero)
9899 "Offer links in the current entry and follow the selected link.
9900 If there is only one link, follow it immediately as well.
9901 If NTH is an integer, immediately pick the NTH link found.
9902 If ZERO is a string, check also this string for a link, and if
9903 there is one, offer it as link number zero."
9904 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9905 "\\(" org-angle-link-re "\\)\\|"
9906 "\\(" org-plain-link-re "\\)"))
9907 (cnt ?0)
9908 (in-emacs (if (integerp nth) nil nth))
9909 have-zero end links link c)
9910 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9911 (push (match-string 0 zero) links)
9912 (setq cnt (1- cnt) have-zero t))
9913 (save-excursion
9914 (org-back-to-heading t)
9915 (setq end (save-excursion (outline-next-heading) (point)))
9916 (while (re-search-forward re end t)
9917 (push (match-string 0) links))
9918 (setq links (org-uniquify (reverse links))))
9920 (cond
9921 ((null links)
9922 (message "No links"))
9923 ((equal (length links) 1)
9924 (setq link (list (car links))))
9925 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9926 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9927 (t ; we have to select a link
9928 (save-excursion
9929 (save-window-excursion
9930 (delete-other-windows)
9931 (with-output-to-temp-buffer "*Select Link*"
9932 (mapc (lambda (l)
9933 (if (not (string-match org-bracket-link-regexp l))
9934 (princ (format "[%c] %s\n" (incf cnt)
9935 (org-remove-angle-brackets l)))
9936 (if (match-end 3)
9937 (princ (format "[%c] %s (%s)\n" (incf cnt)
9938 (match-string 3 l) (match-string 1 l)))
9939 (princ (format "[%c] %s\n" (incf cnt)
9940 (match-string 1 l))))))
9941 links))
9942 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9943 (message "Select link to open, RET to open all:")
9944 (setq c (read-char-exclusive))
9945 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9946 (when (equal c ?q) (error "Abort"))
9947 (if (equal c ?\C-m)
9948 (setq link links)
9949 (setq nth (- c ?0))
9950 (if have-zero (setq nth (1+ nth)))
9951 (unless (and (integerp nth) (>= (length links) nth))
9952 (error "Invalid link selection"))
9953 (setq link (list (nth (1- nth) links))))))
9954 (if link
9955 (let ((buf (current-buffer)))
9956 (dolist (l link)
9957 (org-open-link-from-string l in-emacs buf))
9959 nil)))
9961 ;; Add special file links that specify the way of opening
9963 (org-add-link-type "file+sys" 'org-open-file-with-system)
9964 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9965 (defun org-open-file-with-system (path)
9966 "Open file at PATH using the system way of opening it."
9967 (org-open-file path 'system))
9968 (defun org-open-file-with-emacs (path)
9969 "Open file at PATH in Emacs."
9970 (org-open-file path 'emacs))
9971 (defun org-remove-file-link-modifiers ()
9972 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9973 (goto-char (point-min))
9974 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9975 (org-if-unprotected
9976 (replace-match "file:" t t))))
9977 (eval-after-load "org-exp"
9978 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9979 'org-remove-file-link-modifiers))
9981 ;;;; Time estimates
9983 (defun org-get-effort (&optional pom)
9984 "Get the effort estimate for the current entry."
9985 (org-entry-get pom org-effort-property))
9987 ;;; File search
9989 (defvar org-create-file-search-functions nil
9990 "List of functions to construct the right search string for a file link.
9991 These functions are called in turn with point at the location to
9992 which the link should point.
9994 A function in the hook should first test if it would like to
9995 handle this file type, for example by checking the `major-mode'
9996 or the file extension. If it decides not to handle this file, it
9997 should just return nil to give other functions a chance. If it
9998 does handle the file, it must return the search string to be used
9999 when following the link. The search string will be part of the
10000 file link, given after a double colon, and `org-open-at-point'
10001 will automatically search for it. If special measures must be
10002 taken to make the search successful, another function should be
10003 added to the companion hook `org-execute-file-search-functions',
10004 which see.
10006 A function in this hook may also use `setq' to set the variable
10007 `description' to provide a suggestion for the descriptive text to
10008 be used for this link when it gets inserted into an Org-mode
10009 buffer with \\[org-insert-link].")
10011 (defvar org-execute-file-search-functions nil
10012 "List of functions to execute a file search triggered by a link.
10014 Functions added to this hook must accept a single argument, the
10015 search string that was part of the file link, the part after the
10016 double colon. The function must first check if it would like to
10017 handle this search, for example by checking the `major-mode' or
10018 the file extension. If it decides not to handle this search, it
10019 should just return nil to give other functions a chance. If it
10020 does handle the search, it must return a non-nil value to keep
10021 other functions from trying.
10023 Each function can access the current prefix argument through the
10024 variable `current-prefix-argument'. Note that a single prefix is
10025 used to force opening a link in Emacs, so it may be good to only
10026 use a numeric or double prefix to guide the search function.
10028 In case this is needed, a function in this hook can also restore
10029 the window configuration before `org-open-at-point' was called using:
10031 (set-window-configuration org-window-config-before-follow-link)")
10033 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10034 (defun org-link-search (s &optional type avoid-pos stealth)
10035 "Search for a link search option.
10036 If S is surrounded by forward slashes, it is interpreted as a
10037 regular expression. In org-mode files, this will create an `org-occur'
10038 sparse tree. In ordinary files, `occur' will be used to list matches.
10039 If the current buffer is in `dired-mode', grep will be used to search
10040 in all files. If AVOID-POS is given, ignore matches near that position.
10042 When optional argument STEALTH is non-nil, do not modify
10043 visibility around point, thus ignoring
10044 `org-show-hierarchy-above', `org-show-following-heading' and
10045 `org-show-siblings' variables."
10046 (let ((case-fold-search t)
10047 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10048 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10049 (append '(("") (" ") ("\t") ("\n"))
10050 org-emphasis-alist)
10051 "\\|") "\\)"))
10052 (pos (point))
10053 (pre nil) (post nil)
10054 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10055 (cond
10056 ;; First check if there are any special search functions
10057 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10058 ;; Now try the builtin stuff
10059 ((and (equal (string-to-char s0) ?#)
10060 (> (length s0) 1)
10061 (save-excursion
10062 (goto-char (point-min))
10063 (and
10064 (re-search-forward
10065 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10066 (setq type 'dedicated
10067 pos (match-beginning 0))))
10068 ;; There is an exact target for this
10069 (goto-char pos)
10070 (org-back-to-heading t)))
10071 ((save-excursion
10072 (goto-char (point-min))
10073 (and
10074 (re-search-forward
10075 (concat "<<" (regexp-quote s0) ">>") nil t)
10076 (setq type 'dedicated
10077 pos (match-beginning 0))))
10078 ;; There is an exact target for this
10079 (goto-char pos))
10080 ((save-excursion
10081 (goto-char (point-min))
10082 (and
10083 (re-search-forward
10084 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10085 (setq type 'dedicated pos (match-beginning 0))))
10086 ;; Found an invisible target.
10087 (goto-char pos))
10088 ((save-excursion
10089 (goto-char (point-min))
10090 (and
10091 (re-search-forward
10092 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10093 (setq type 'dedicated pos (match-beginning 0))))
10094 ;; Found an element with a matching #+name affiliated keyword.
10095 (goto-char pos))
10096 ((and (string-match "^(\\(.*\\))$" s0)
10097 (save-excursion
10098 (goto-char (point-min))
10099 (and
10100 (re-search-forward
10101 (concat "[^[]" (regexp-quote
10102 (format org-coderef-label-format
10103 (match-string 1 s0))))
10104 nil t)
10105 (setq type 'dedicated
10106 pos (1+ (match-beginning 0))))))
10107 ;; There is a coderef target for this
10108 (goto-char pos))
10109 ((string-match "^/\\(.*\\)/$" s)
10110 ;; A regular expression
10111 (cond
10112 ((derived-mode-p 'org-mode)
10113 (org-occur (match-string 1 s)))
10114 ;;((eq major-mode 'dired-mode)
10115 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10116 (t (org-do-occur (match-string 1 s)))))
10117 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10118 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10119 (goto-char (point-min))
10120 (cond
10121 ((let (case-fold-search)
10122 (re-search-forward (format org-complex-heading-regexp-format
10123 (regexp-quote s))
10124 nil t))
10125 ;; OK, found a match
10126 (setq type 'dedicated)
10127 (goto-char (match-beginning 0)))
10128 ((and (not org-link-search-inhibit-query)
10129 (eq org-link-search-must-match-exact-headline 'query-to-create)
10130 (y-or-n-p "No match - create this as a new heading? "))
10131 (goto-char (point-max))
10132 (or (bolp) (newline))
10133 (insert "* " s "\n")
10134 (beginning-of-line 0))
10136 (goto-char pos)
10137 (error "No match"))))
10139 ;; A normal search string
10140 (when (equal (string-to-char s) ?*)
10141 ;; Anchor on headlines, post may include tags.
10142 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10143 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10144 s (substring s 1)))
10145 (remove-text-properties
10146 0 (length s)
10147 '(face nil mouse-face nil keymap nil fontified nil) s)
10148 ;; Make a series of regular expressions to find a match
10149 (setq words (org-split-string s "[ \n\r\t]+")
10151 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10152 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10153 "\\)" markers)
10154 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10155 re2a (concat "[ \t\r\n]" re2a_)
10156 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10157 re4 (concat "[^a-zA-Z_]" re4_)
10159 re1 (concat pre re2 post)
10160 re3 (concat pre (if pre re4_ re4) post)
10161 re5 (concat pre ".*" re4)
10162 re2 (concat pre re2)
10163 re2a (concat pre (if pre re2a_ re2a))
10164 re4 (concat pre (if pre re4_ re4))
10165 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10166 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10167 re5 "\\)"
10169 (cond
10170 ((eq type 'org-occur) (org-occur reall))
10171 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10172 (t (goto-char (point-min))
10173 (setq type 'fuzzy)
10174 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10175 (org-search-not-self 1 re1 nil t)
10176 (org-search-not-self 1 re2 nil t)
10177 (org-search-not-self 1 re2a nil t)
10178 (org-search-not-self 1 re3 nil t)
10179 (org-search-not-self 1 re4 nil t)
10180 (org-search-not-self 1 re5 nil t)
10182 (goto-char (match-beginning 1))
10183 (goto-char pos)
10184 (error "No match"))))))
10185 (and (derived-mode-p 'org-mode)
10186 (not stealth)
10187 (org-show-context 'link-search))
10188 type))
10190 (defun org-search-not-self (group &rest args)
10191 "Execute `re-search-forward', but only accept matches that do not
10192 enclose the position of `org-open-link-marker'."
10193 (let ((m org-open-link-marker))
10194 (catch 'exit
10195 (while (apply 're-search-forward args)
10196 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10197 (goto-char (match-end group))
10198 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10199 (> (match-beginning 0) (marker-position m))
10200 (< (match-end 0) (marker-position m)))
10201 (save-match-data
10202 (or (not (org-in-regexp
10203 org-bracket-link-analytic-regexp 1))
10204 (not (match-end 4)) ; no description
10205 (and (<= (match-beginning 4) (point))
10206 (>= (match-end 4) (point))))))
10207 (throw 'exit (point))))))))
10209 (defun org-get-buffer-for-internal-link (buffer)
10210 "Return a buffer to be used for displaying the link target of internal links."
10211 (cond
10212 ((not org-display-internal-link-with-indirect-buffer)
10213 buffer)
10214 ((string-match "(Clone)$" (buffer-name buffer))
10215 (message "Buffer is already a clone, not making another one")
10216 ;; we also do not modify visibility in this case
10217 buffer)
10218 (t ; make a new indirect buffer for displaying the link
10219 (let* ((bn (buffer-name buffer))
10220 (ibn (concat bn "(Clone)"))
10221 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10222 (with-current-buffer ib (org-overview))
10223 ib))))
10225 (defun org-do-occur (regexp &optional cleanup)
10226 "Call the Emacs command `occur'.
10227 If CLEANUP is non-nil, remove the printout of the regular expression
10228 in the *Occur* buffer. This is useful if the regex is long and not useful
10229 to read."
10230 (occur regexp)
10231 (when cleanup
10232 (let ((cwin (selected-window)) win beg end)
10233 (when (setq win (get-buffer-window "*Occur*"))
10234 (select-window win))
10235 (goto-char (point-min))
10236 (when (re-search-forward "match[a-z]+" nil t)
10237 (setq beg (match-end 0))
10238 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10239 (setq end (1- (match-beginning 0)))))
10240 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10241 (goto-char (point-min))
10242 (select-window cwin))))
10244 ;;; The mark ring for links jumps
10246 (defvar org-mark-ring nil
10247 "Mark ring for positions before jumps in Org-mode.")
10248 (defvar org-mark-ring-last-goto nil
10249 "Last position in the mark ring used to go back.")
10250 ;; Fill and close the ring
10251 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10252 (loop for i from 1 to org-mark-ring-length do
10253 (push (make-marker) org-mark-ring))
10254 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10255 org-mark-ring)
10257 (defun org-mark-ring-push (&optional pos buffer)
10258 "Put the current position or POS into the mark ring and rotate it."
10259 (interactive)
10260 (setq pos (or pos (point)))
10261 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10262 (move-marker (car org-mark-ring)
10263 (or pos (point))
10264 (or buffer (current-buffer)))
10265 (message "%s"
10266 (substitute-command-keys
10267 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10269 (defun org-mark-ring-goto (&optional n)
10270 "Jump to the previous position in the mark ring.
10271 With prefix arg N, jump back that many stored positions. When
10272 called several times in succession, walk through the entire ring.
10273 Org-mode commands jumping to a different position in the current file,
10274 or to another Org-mode file, automatically push the old position
10275 onto the ring."
10276 (interactive "p")
10277 (let (p m)
10278 (if (eq last-command this-command)
10279 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10280 (setq p org-mark-ring))
10281 (setq org-mark-ring-last-goto p)
10282 (setq m (car p))
10283 (org-pop-to-buffer-same-window (marker-buffer m))
10284 (goto-char m)
10285 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10287 (defun org-remove-angle-brackets (s)
10288 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10289 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10291 (defun org-add-angle-brackets (s)
10292 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10293 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10295 (defun org-remove-double-quotes (s)
10296 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10297 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10300 ;;; Following specific links
10302 (defun org-follow-timestamp-link ()
10303 "Open an agenda view for the time-stamp date/range at point."
10304 (cond
10305 ((org-at-date-range-p t)
10306 (let ((org-agenda-start-on-weekday)
10307 (t1 (match-string 1))
10308 (t2 (match-string 2)) tt1 tt2)
10309 (setq tt1 (time-to-days (org-time-string-to-time t1))
10310 tt2 (time-to-days (org-time-string-to-time t2)))
10311 (let ((org-agenda-buffer-tmp-name
10312 (format "*Org Agenda(a:%s)"
10313 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10314 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10315 ((org-at-timestamp-p t)
10316 (let ((org-agenda-buffer-tmp-name
10317 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10318 (org-agenda-list nil (time-to-days (org-time-string-to-time
10319 (substring (match-string 1) 0 10)))
10320 1)))
10321 (t (error "This should not happen"))))
10324 ;;; Following file links
10325 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10326 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10327 (declare-function mailcap-mime-info
10328 "mailcap" (string &optional request no-decode))
10329 (defvar org-wait nil)
10330 (defun org-open-file (path &optional in-emacs line search)
10331 "Open the file at PATH.
10332 First, this expands any special file name abbreviations. Then the
10333 configuration variable `org-file-apps' is checked if it contains an
10334 entry for this file type, and if yes, the corresponding command is launched.
10336 If no application is found, Emacs simply visits the file.
10338 With optional prefix argument IN-EMACS, Emacs will visit the file.
10339 With a double \\[universal-argument] \\[universal-argument] \
10340 prefix arg, Org tries to avoid opening in Emacs
10341 and to use an external application to visit the file.
10343 Optional LINE specifies a line to go to, optional SEARCH a string
10344 to search for. If LINE or SEARCH is given, the file will be
10345 opened in Emacs, unless an entry from org-file-apps that makes
10346 use of groups in a regexp matches.
10348 If you want to change the way frames are used when following a
10349 link, please customize `org-link-frame-setup'.
10351 If the file does not exist, an error is thrown."
10352 (let* ((file (if (equal path "")
10353 buffer-file-name
10354 (substitute-in-file-name (expand-file-name path))))
10355 (file-apps (append org-file-apps (org-default-apps)))
10356 (apps (org-remove-if
10357 'org-file-apps-entry-match-against-dlink-p file-apps))
10358 (apps-dlink (org-remove-if-not
10359 'org-file-apps-entry-match-against-dlink-p file-apps))
10360 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10361 (dirp (if remp nil (file-directory-p file)))
10362 (file (if (and dirp org-open-directory-means-index-dot-org)
10363 (concat (file-name-as-directory file) "index.org")
10364 file))
10365 (a-m-a-p (assq 'auto-mode apps))
10366 (dfile (downcase file))
10367 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10368 (link (cond ((and (eq line nil)
10369 (eq search nil))
10370 file)
10371 (line
10372 (concat file "::" (number-to-string line)))
10373 (search
10374 (concat file "::" search))))
10375 (dlink (downcase link))
10376 (old-buffer (current-buffer))
10377 (old-pos (point))
10378 (old-mode major-mode)
10379 ext cmd link-match-data)
10380 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10381 (setq ext (match-string 1 dfile))
10382 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10383 (setq ext (match-string 1 dfile))))
10384 (cond
10385 ((member in-emacs '((16) system))
10386 (setq cmd (cdr (assoc 'system apps))))
10387 (in-emacs (setq cmd 'emacs))
10389 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10390 (and dirp (cdr (assoc 'directory apps)))
10391 ; first, try matching against apps-dlink
10392 ; if we get a match here, store the match data for later
10393 (let ((match (assoc-default dlink apps-dlink
10394 'string-match)))
10395 (if match
10396 (progn (setq link-match-data (match-data))
10397 match)
10398 (progn (setq in-emacs (or in-emacs line search))
10399 nil))) ; if we have no match in apps-dlink,
10400 ; always open the file in emacs if line or search
10401 ; is given (for backwards compatibility)
10402 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10403 'string-match)
10404 (cdr (assoc ext apps))
10405 (cdr (assoc t apps))))))
10406 (when (eq cmd 'system)
10407 (setq cmd (cdr (assoc 'system apps))))
10408 (when (eq cmd 'default)
10409 (setq cmd (cdr (assoc t apps))))
10410 (when (eq cmd 'mailcap)
10411 (require 'mailcap)
10412 (mailcap-parse-mailcaps)
10413 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10414 (command (mailcap-mime-info mime-type)))
10415 (if (stringp command)
10416 (setq cmd command)
10417 (setq cmd 'emacs))))
10418 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10419 (not (file-exists-p file))
10420 (not org-open-non-existing-files))
10421 (error "No such file: %s" file))
10422 (cond
10423 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10424 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10425 (while (string-match "['\"]%s['\"]" cmd)
10426 (setq cmd (replace-match "%s" t t cmd)))
10427 (while (string-match "%s" cmd)
10428 (setq cmd (replace-match
10429 (save-match-data
10430 (shell-quote-argument
10431 (convert-standard-filename file)))
10432 t t cmd)))
10434 ;; Replace "%1", "%2" etc. in command with group matches from regex
10435 (save-match-data
10436 (let ((match-index 1)
10437 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10438 (set-match-data link-match-data)
10439 (while (<= match-index number-of-groups)
10440 (let ((regex (concat "%" (number-to-string match-index)))
10441 (replace-with (match-string match-index dlink)))
10442 (while (string-match regex cmd)
10443 (setq cmd (replace-match replace-with t t cmd))))
10444 (setq match-index (+ match-index 1)))))
10446 (save-window-excursion
10447 (message "Running %s...done" cmd)
10448 (start-process-shell-command cmd nil cmd)
10449 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10450 ((or (stringp cmd)
10451 (eq cmd 'emacs))
10452 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10453 (widen)
10454 (if line (org-goto-line line)
10455 (if search (org-link-search search))))
10456 ((consp cmd)
10457 (let ((file (convert-standard-filename file)))
10458 (save-match-data
10459 (set-match-data link-match-data)
10460 (eval cmd))))
10461 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10462 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10463 (or (not (equal old-buffer (current-buffer)))
10464 (not (equal old-pos (point))))
10465 (org-mark-ring-push old-pos old-buffer))))
10467 (defun org-file-apps-entry-match-against-dlink-p (entry)
10468 "This function returns non-nil if `entry' uses a regular
10469 expression which should be matched against the whole link by
10470 org-open-file.
10472 It assumes that is the case when the entry uses a regular
10473 expression which has at least one grouping construct and the
10474 action is either a lisp form or a command string containing
10475 '%1', i.e. using at least one subexpression match as a
10476 parameter."
10477 (let ((selector (car entry))
10478 (action (cdr entry)))
10479 (if (stringp selector)
10480 (and (> (regexp-opt-depth selector) 0)
10481 (or (and (stringp action)
10482 (string-match "%[0-9]" action))
10483 (consp action)))
10484 nil)))
10486 (defun org-default-apps ()
10487 "Return the default applications for this operating system."
10488 (cond
10489 ((eq system-type 'darwin)
10490 org-file-apps-defaults-macosx)
10491 ((eq system-type 'windows-nt)
10492 org-file-apps-defaults-windowsnt)
10493 (t org-file-apps-defaults-gnu)))
10495 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10496 "Convert extensions to regular expressions in the cars of LIST.
10497 Also, weed out any non-string entries, because the return value is used
10498 only for regexp matching.
10499 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10500 point to the symbol `emacs', indicating that the file should
10501 be opened in Emacs."
10502 (append
10503 (delq nil
10504 (mapcar (lambda (x)
10505 (if (not (stringp (car x)))
10507 (if (string-match "\\W" (car x))
10509 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10510 list))
10511 (if add-auto-mode
10512 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10514 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10515 (defun org-file-remote-p (file)
10516 "Test whether FILE specifies a location on a remote system.
10517 Return non-nil if the location is indeed remote.
10519 For example, the filename \"/user@host:/foo\" specifies a location
10520 on the system \"/user@host:\"."
10521 (cond ((fboundp 'file-remote-p)
10522 (file-remote-p file))
10523 ((fboundp 'tramp-handle-file-remote-p)
10524 (tramp-handle-file-remote-p file))
10525 ((and (boundp 'ange-ftp-name-format)
10526 (string-match (car ange-ftp-name-format) file))
10527 t)))
10530 ;;;; Refiling
10532 (defun org-get-org-file ()
10533 "Read a filename, with default directory `org-directory'."
10534 (let ((default (or org-default-notes-file remember-data-file)))
10535 (read-file-name (format "File name [%s]: " default)
10536 (file-name-as-directory org-directory)
10537 default)))
10539 (defun org-notes-order-reversed-p ()
10540 "Check if the current file should receive notes in reversed order."
10541 (cond
10542 ((not org-reverse-note-order) nil)
10543 ((eq t org-reverse-note-order) t)
10544 ((not (listp org-reverse-note-order)) nil)
10545 (t (catch 'exit
10546 (let ((all org-reverse-note-order)
10547 entry)
10548 (while (setq entry (pop all))
10549 (if (string-match (car entry) buffer-file-name)
10550 (throw 'exit (cdr entry))))
10551 nil)))))
10553 (defvar org-refile-target-table nil
10554 "The list of refile targets, created by `org-refile'.")
10556 (defvar org-agenda-new-buffers nil
10557 "Buffers created to visit agenda files.")
10559 (defvar org-refile-cache nil
10560 "Cache for refile targets.")
10562 (defvar org-refile-markers nil
10563 "All the markers used for caching refile locations.")
10565 (defun org-refile-marker (pos)
10566 "Get a new refile marker, but only if caching is in use."
10567 (if (not org-refile-use-cache)
10569 (let ((m (make-marker)))
10570 (move-marker m pos)
10571 (push m org-refile-markers)
10572 m)))
10574 (defun org-refile-cache-clear ()
10575 "Clear the refile cache and disable all the markers."
10576 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10577 (setq org-refile-markers nil)
10578 (setq org-refile-cache nil)
10579 (message "Refile cache has been cleared"))
10581 (defun org-refile-cache-check-set (set)
10582 "Check if all the markers in the cache still have live buffers."
10583 (let (marker)
10584 (catch 'exit
10585 (while (and set (setq marker (nth 3 (pop set))))
10586 ;; if org-refile-use-outline-path is 'file, marker may be nil
10587 (when (and marker (null (marker-buffer marker)))
10588 (message "not found") (sit-for 3)
10589 (throw 'exit nil)))
10590 t)))
10592 (defun org-refile-cache-put (set &rest identifiers)
10593 "Push the refile targets SET into the cache, under IDENTIFIERS."
10594 (let* ((key (sha1 (prin1-to-string identifiers)))
10595 (entry (assoc key org-refile-cache)))
10596 (if entry
10597 (setcdr entry set)
10598 (push (cons key set) org-refile-cache))))
10600 (defun org-refile-cache-get (&rest identifiers)
10601 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10602 (cond
10603 ((not org-refile-cache) nil)
10604 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10606 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10607 org-refile-cache))))
10608 (and set (org-refile-cache-check-set set) set)))))
10610 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10611 "Produce a table with refile targets."
10612 (let ((case-fold-search nil)
10613 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10614 (entries (or org-refile-targets '((nil . (:level . 1)))))
10615 targets tgs txt re files f desc descre fast-path-p level pos0)
10616 (message "Getting targets...")
10617 (with-current-buffer (or default-buffer (current-buffer))
10618 (while (setq entry (pop entries))
10619 (setq files (car entry) desc (cdr entry))
10620 (setq fast-path-p nil)
10621 (cond
10622 ((null files) (setq files (list (current-buffer))))
10623 ((eq files 'org-agenda-files)
10624 (setq files (org-agenda-files 'unrestricted)))
10625 ((and (symbolp files) (fboundp files))
10626 (setq files (funcall files)))
10627 ((and (symbolp files) (boundp files))
10628 (setq files (symbol-value files))))
10629 (if (stringp files) (setq files (list files)))
10630 (cond
10631 ((eq (car desc) :tag)
10632 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10633 ((eq (car desc) :todo)
10634 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10635 ((eq (car desc) :regexp)
10636 (setq descre (cdr desc)))
10637 ((eq (car desc) :level)
10638 (setq descre (concat "^\\*\\{" (number-to-string
10639 (if org-odd-levels-only
10640 (1- (* 2 (cdr desc)))
10641 (cdr desc)))
10642 "\\}[ \t]")))
10643 ((eq (car desc) :maxlevel)
10644 (setq fast-path-p t)
10645 (setq descre (concat "^\\*\\{1," (number-to-string
10646 (if org-odd-levels-only
10647 (1- (* 2 (cdr desc)))
10648 (cdr desc)))
10649 "\\}[ \t]")))
10650 (t (error "Bad refiling target description %s" desc)))
10651 (while (setq f (pop files))
10652 (with-current-buffer
10653 (if (bufferp f) f (org-get-agenda-file-buffer f))
10655 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10656 (progn
10657 (if (bufferp f) (setq f (buffer-file-name
10658 (buffer-base-buffer f))))
10659 (setq f (and f (expand-file-name f)))
10660 (if (eq org-refile-use-outline-path 'file)
10661 (push (list (file-name-nondirectory f) f nil nil) tgs))
10662 (save-excursion
10663 (save-restriction
10664 (widen)
10665 (goto-char (point-min))
10666 (while (re-search-forward descre nil t)
10667 (goto-char (setq pos0 (point-at-bol)))
10668 (catch 'next
10669 (when org-refile-target-verify-function
10670 (save-match-data
10671 (or (funcall org-refile-target-verify-function)
10672 (throw 'next t))))
10673 (when (and (looking-at org-complex-heading-regexp)
10674 (not (member (match-string 4) excluded-entries))
10675 (match-string 4))
10676 (setq level (org-reduced-level
10677 (- (match-end 1) (match-beginning 1)))
10678 txt (org-link-display-format (match-string 4))
10679 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10680 re (format org-complex-heading-regexp-format
10681 (regexp-quote (match-string 4))))
10682 (when org-refile-use-outline-path
10683 (setq txt (mapconcat
10684 'org-protect-slash
10685 (append
10686 (if (eq org-refile-use-outline-path
10687 'file)
10688 (list (file-name-nondirectory
10689 (buffer-file-name
10690 (buffer-base-buffer))))
10691 (if (eq org-refile-use-outline-path
10692 'full-file-path)
10693 (list (buffer-file-name
10694 (buffer-base-buffer)))))
10695 (org-get-outline-path fast-path-p
10696 level txt)
10697 (list txt))
10698 "/")))
10699 (push (list txt f re (org-refile-marker (point)))
10700 tgs)))
10701 (when (= (point) pos0)
10702 ;; verification function has not moved point
10703 (goto-char (point-at-eol))))))))
10704 (when org-refile-use-cache
10705 (org-refile-cache-put tgs (buffer-file-name) descre))
10706 (setq targets (append tgs targets))
10707 ))))
10708 (message "Getting targets...done")
10709 (nreverse targets)))
10711 (defun org-protect-slash (s)
10712 (while (string-match "/" s)
10713 (setq s (replace-match "\\" t t s)))
10716 (defvar org-olpa (make-vector 20 nil))
10718 (defun org-get-outline-path (&optional fastp level heading)
10719 "Return the outline path to the current entry, as a list.
10721 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10722 routine which makes outline path derivations for an entire file,
10723 avoiding backtracing. Refile target collection makes use of that."
10724 (if fastp
10725 (progn
10726 (if (> level 19)
10727 (error "Outline path failure, more than 19 levels"))
10728 (loop for i from level upto 19 do
10729 (aset org-olpa i nil))
10730 (prog1
10731 (delq nil (append org-olpa nil))
10732 (aset org-olpa level heading)))
10733 (let (rtn case-fold-search)
10734 (save-excursion
10735 (save-restriction
10736 (widen)
10737 (while (org-up-heading-safe)
10738 (when (looking-at org-complex-heading-regexp)
10739 (push (org-match-string-no-properties 4) rtn)))
10740 rtn)))))
10742 (defun org-format-outline-path (path &optional width prefix separator)
10743 "Format the outline path PATH for display.
10744 WIDTH is the maximum number of characters that is available.
10745 PREFIX is a prefix to be included in the returned string,
10746 such as the file name.
10747 SEPARATOR is inserted between the different parts of the path,
10748 the default is \"/\"."
10749 (setq width (or width 79))
10750 (if prefix (setq width (- width (length prefix))))
10751 (if (not path)
10752 (or prefix "")
10753 (let* ((nsteps (length path))
10754 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10755 (maxwidth (if (<= total-width width)
10756 10000 ;; everything fits
10757 ;; we need to shorten the level headings
10758 (/ (- width nsteps) nsteps)))
10759 (org-odd-levels-only nil)
10760 (n 0)
10761 (total (1+ (length prefix))))
10762 (setq maxwidth (max maxwidth 10))
10763 (concat prefix
10764 (if prefix (or separator "/"))
10765 (mapconcat
10766 (lambda (h)
10767 (setq n (1+ n))
10768 (if (and (= n nsteps) (< maxwidth 10000))
10769 (setq maxwidth (- total-width total)))
10770 (if (< (length h) maxwidth)
10771 (progn (setq total (+ total (length h) 1)) h)
10772 (setq h (substring h 0 (- maxwidth 2))
10773 total (+ total maxwidth 1))
10774 (if (string-match "[ \t]+\\'" h)
10775 (setq h (substring h 0 (match-beginning 0))))
10776 (setq h (concat h "..")))
10777 (org-add-props h nil 'face
10778 (nth (% (1- n) org-n-level-faces)
10779 org-level-faces))
10781 path (or separator "/"))))))
10783 (defun org-display-outline-path (&optional file current separator just-return-string)
10784 "Display the current outline path in the echo area.
10786 If FILE is non-nil, prepend the output with the file name.
10787 If CURRENT is non-nil, append the current heading to the output.
10788 SEPARATOR is passed through to `org-format-outline-path'. It separates
10789 the different parts of the path and defaults to \"/\".
10790 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10791 (interactive "P")
10792 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10793 (case-fold-search nil)
10794 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10795 res)
10796 (if current (setq path (append path
10797 (save-excursion
10798 (org-back-to-heading t)
10799 (if (looking-at org-complex-heading-regexp)
10800 (list (match-string 4)))))))
10801 (setq res
10802 (org-format-outline-path
10803 path
10804 (1- (frame-width))
10805 (and file bfn (concat (file-name-nondirectory bfn) separator))
10806 separator))
10807 (if just-return-string
10808 (org-no-properties res)
10809 (message "%s" res))))
10811 (defvar org-refile-history nil
10812 "History for refiling operations.")
10814 (defvar org-after-refile-insert-hook nil
10815 "Hook run after `org-refile' has inserted its stuff at the new location.
10816 Note that this is still *before* the stuff will be removed from
10817 the *old* location.")
10819 (defvar org-capture-last-stored-marker)
10820 (defvar org-refile-keep nil
10821 "Non-nil means `org-refile' will copy instead of refile.")
10823 (defun org-copy ()
10824 "Like `org-refile', but copy."
10825 (interactive)
10826 (let ((org-refile-keep t))
10827 (funcall 'org-refile nil nil nil "Copy")))
10829 (defun org-refile (&optional goto default-buffer rfloc msg)
10830 "Move the entry or entries at point to another heading.
10831 The list of target headings is compiled using the information in
10832 `org-refile-targets', which see.
10834 At the target location, the entry is filed as a subitem of the target
10835 heading. Depending on `org-reverse-note-order', the new subitem will
10836 either be the first or the last subitem.
10838 If there is an active region, all entries in that region will be moved.
10839 However, the region must fulfill the requirement that the first heading
10840 is the first one sets the top-level of the moved text - at most siblings
10841 below it are allowed.
10843 With prefix arg GOTO, the command will only visit the target location
10844 and not actually move anything.
10846 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10847 go to the location where the last refiling operation has put the subtree.
10848 With a prefix argument of `2', refile to the running clock.
10850 RFLOC can be a refile location obtained in a different way.
10852 MSG is a string to replace \"Refile\" in the default prompt with
10853 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10855 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10857 If you are using target caching (see `org-refile-use-cache'),
10858 you have to clear the target cache in order to find new targets.
10859 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10860 prefix argument (`C-u C-u C-u C-c C-w')."
10862 (interactive "P")
10863 (if (member goto '(0 (64)))
10864 (org-refile-cache-clear)
10865 (let* ((actionmsg (or msg "Refile"))
10866 (cbuf (current-buffer))
10867 (regionp (org-region-active-p))
10868 (region-start (and regionp (region-beginning)))
10869 (region-end (and regionp (region-end)))
10870 (region-length (and regionp (- region-end region-start)))
10871 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10872 pos it nbuf file re level reversed)
10873 (setq last-command nil)
10874 (when regionp
10875 (goto-char region-start)
10876 (or (bolp) (goto-char (point-at-bol)))
10877 (setq region-start (point))
10878 (unless (or (org-kill-is-subtree-p
10879 (buffer-substring region-start region-end))
10880 (prog1 org-refile-active-region-within-subtree
10881 (org-toggle-heading)))
10882 (error "The region is not a (sequence of) subtree(s)")))
10883 (if (equal goto '(16))
10884 (org-refile-goto-last-stored)
10885 (when (or
10886 (and (equal goto 2)
10887 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10888 (prog1
10889 (setq it (list (or org-clock-heading "running clock")
10890 (buffer-file-name
10891 (marker-buffer org-clock-hd-marker))
10893 (marker-position org-clock-hd-marker)))
10894 (setq goto nil)))
10895 (setq it (or rfloc
10896 (let (heading-text)
10897 (save-excursion
10898 (unless goto
10899 (org-back-to-heading t)
10900 (setq heading-text
10901 (nth 4 (org-heading-components))))
10903 (org-refile-get-location
10904 (cond (goto "Goto")
10905 (regionp (concat actionmsg " region to"))
10906 (t (concat actionmsg " subtree \""
10907 heading-text "\" to")))
10908 default-buffer
10909 (and (not (equal '(4) goto))
10910 org-refile-allow-creating-parent-nodes)
10911 goto))))))
10912 (setq file (nth 1 it)
10913 re (nth 2 it)
10914 pos (nth 3 it))
10915 (if (and (not goto)
10917 (equal (buffer-file-name) file)
10918 (if regionp
10919 (and (>= pos region-start)
10920 (<= pos region-end))
10921 (and (>= pos (point))
10922 (< pos (save-excursion
10923 (org-end-of-subtree t t))))))
10924 (error "Cannot refile to position inside the tree or region"))
10926 (setq nbuf (or (find-buffer-visiting file)
10927 (find-file-noselect file)))
10928 (if goto
10929 (progn
10930 (org-pop-to-buffer-same-window nbuf)
10931 (goto-char pos)
10932 (org-show-context 'org-goto))
10933 (if regionp
10934 (progn
10935 (org-kill-new (buffer-substring region-start region-end))
10936 (org-save-markers-in-region region-start region-end))
10937 (org-copy-subtree 1 nil t))
10938 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10939 (find-file-noselect file)))
10940 (setq reversed (org-notes-order-reversed-p))
10941 (save-excursion
10942 (save-restriction
10943 (widen)
10944 (if pos
10945 (progn
10946 (goto-char pos)
10947 (looking-at org-outline-regexp)
10948 (setq level (org-get-valid-level (funcall outline-level) 1))
10949 (goto-char
10950 (if reversed
10951 (or (outline-next-heading) (point-max))
10952 (or (save-excursion (org-get-next-sibling))
10953 (org-end-of-subtree t t)
10954 (point-max)))))
10955 (setq level 1)
10956 (if (not reversed)
10957 (goto-char (point-max))
10958 (goto-char (point-min))
10959 (or (outline-next-heading) (goto-char (point-max)))))
10960 (if (not (bolp)) (newline))
10961 (org-paste-subtree level)
10962 (when org-log-refile
10963 (org-add-log-setup 'refile nil nil 'findpos
10964 org-log-refile)
10965 (unless (eq org-log-refile 'note)
10966 (save-excursion (org-add-log-note))))
10967 (and org-auto-align-tags
10968 (let ((org-loop-over-headlines-in-active-region nil))
10969 (org-set-tags nil t)))
10970 (bookmark-set "org-refile-last-stored")
10971 ;; If we are refiling for capture, make sure that the
10972 ;; last-capture pointers point here
10973 (when (org-bound-and-true-p org-refile-for-capture)
10974 (bookmark-set "org-capture-last-stored-marker")
10975 (move-marker org-capture-last-stored-marker (point)))
10976 (if (fboundp 'deactivate-mark) (deactivate-mark))
10977 (run-hooks 'org-after-refile-insert-hook))))
10978 (unless org-refile-keep
10979 (if regionp
10980 (delete-region (point) (+ (point) region-length))
10981 (org-cut-subtree)))
10982 (when (featurep 'org-inlinetask)
10983 (org-inlinetask-remove-END-maybe))
10984 (setq org-markers-to-move nil)
10985 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
10987 (defun org-refile-goto-last-stored ()
10988 "Go to the location where the last refile was stored."
10989 (interactive)
10990 (bookmark-jump "org-refile-last-stored")
10991 (message "This is the location of the last refile"))
10993 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10994 no-exclude)
10995 "Prompt the user for a refile location, using PROMPT.
10996 PROMPT should not be suffixed with a colon and a space, because
10997 this function appends the default value from
10998 `org-refile-history' automatically, if that is not empty.
10999 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11000 this is used for the GOTO interface."
11001 (let ((org-refile-targets org-refile-targets)
11002 (org-refile-use-outline-path org-refile-use-outline-path)
11003 excluded-entries)
11004 (when (and (derived-mode-p 'org-mode)
11005 (not org-refile-use-cache)
11006 (not no-exclude))
11007 (org-map-tree
11008 (lambda()
11009 (setq excluded-entries
11010 (append excluded-entries (list (org-get-heading t t)))))))
11011 (setq org-refile-target-table
11012 (org-refile-get-targets default-buffer excluded-entries)))
11013 (unless org-refile-target-table
11014 (error "No refile targets"))
11015 (let* ((cbuf (current-buffer))
11016 (partial-completion-mode nil)
11017 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11018 (cfunc (if (and org-refile-use-outline-path
11019 org-outline-path-complete-in-steps)
11020 'org-olpath-completing-read
11021 'org-icompleting-read))
11022 (extra (if org-refile-use-outline-path "/" ""))
11023 (cbnex (concat (buffer-name) extra))
11024 (filename (and cfn (expand-file-name cfn)))
11025 (tbl (mapcar
11026 (lambda (x)
11027 (if (and (not (member org-refile-use-outline-path
11028 '(file full-file-path)))
11029 (not (equal filename (nth 1 x))))
11030 (cons (concat (car x) extra " ("
11031 (file-name-nondirectory (nth 1 x)) ")")
11032 (cdr x))
11033 (cons (concat (car x) extra) (cdr x))))
11034 org-refile-target-table))
11035 (completion-ignore-case t)
11036 cdef
11037 (prompt (concat prompt
11038 (or (and (car org-refile-history)
11039 (concat " (default " (car org-refile-history) ")"))
11040 (and (assoc cbnex tbl) (setq cdef cbnex)
11041 (concat " (default " cbnex ")"))) ": "))
11042 pa answ parent-target child parent old-hist)
11043 (setq old-hist org-refile-history)
11044 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11045 nil 'org-refile-history (or cdef (car org-refile-history))))
11046 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11047 (org-refile-check-position pa)
11048 (if pa
11049 (progn
11050 (when (or (not org-refile-history)
11051 (not (eq old-hist org-refile-history))
11052 (not (equal (car pa) (car org-refile-history))))
11053 (setq org-refile-history
11054 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11055 org-refile-history
11056 (cdr org-refile-history))))
11057 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11058 (pop org-refile-history)))
11060 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11061 (progn
11062 (setq parent (match-string 1 answ)
11063 child (match-string 2 answ))
11064 (setq parent-target (or (assoc parent tbl)
11065 (assoc (concat parent "/") tbl)))
11066 (when (and parent-target
11067 (or (eq new-nodes t)
11068 (and (eq new-nodes 'confirm)
11069 (y-or-n-p (format "Create new node \"%s\"? "
11070 child)))))
11071 (org-refile-new-child parent-target child)))
11072 (error "Invalid target location")))))
11074 (declare-function org-string-nw-p "org-macs" (s))
11075 (defun org-refile-check-position (refile-pointer)
11076 "Check if the refile pointer matches the readline to which it points."
11077 (let* ((file (nth 1 refile-pointer))
11078 (re (nth 2 refile-pointer))
11079 (pos (nth 3 refile-pointer))
11080 buffer)
11081 (when (org-string-nw-p re)
11082 (setq buffer (if (markerp pos)
11083 (marker-buffer pos)
11084 (or (find-buffer-visiting file)
11085 (find-file-noselect file))))
11086 (with-current-buffer buffer
11087 (save-excursion
11088 (save-restriction
11089 (widen)
11090 (goto-char pos)
11091 (beginning-of-line 1)
11092 (unless (org-looking-at-p re)
11093 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11095 (defun org-refile-new-child (parent-target child)
11096 "Use refile target PARENT-TARGET to add new CHILD below it."
11097 (unless parent-target
11098 (error "Cannot find parent for new node"))
11099 (let ((file (nth 1 parent-target))
11100 (pos (nth 3 parent-target))
11101 level)
11102 (with-current-buffer (or (find-buffer-visiting file)
11103 (find-file-noselect file))
11104 (save-excursion
11105 (save-restriction
11106 (widen)
11107 (if pos
11108 (goto-char pos)
11109 (goto-char (point-max))
11110 (if (not (bolp)) (newline)))
11111 (when (looking-at org-outline-regexp)
11112 (setq level (funcall outline-level))
11113 (org-end-of-subtree t t))
11114 (org-back-over-empty-lines)
11115 (insert "\n" (make-string
11116 (if pos (org-get-valid-level level 1) 1) ?*)
11117 " " child "\n")
11118 (beginning-of-line 0)
11119 (list (concat (car parent-target) "/" child) file "" (point)))))))
11121 (defun org-olpath-completing-read (prompt collection &rest args)
11122 "Read an outline path like a file name."
11123 (let ((thetable collection)
11124 (org-completion-use-ido nil) ; does not work with ido.
11125 (org-completion-use-iswitchb nil)) ; or iswitchb
11126 (apply
11127 'org-icompleting-read prompt
11128 (lambda (string predicate &optional flag)
11129 (let (rtn r f (l (length string)))
11130 (cond
11131 ((eq flag nil)
11132 ;; try completion
11133 (try-completion string thetable))
11134 ((eq flag t)
11135 ;; all-completions
11136 (setq rtn (all-completions string thetable predicate))
11137 (mapcar
11138 (lambda (x)
11139 (setq r (substring x l))
11140 (if (string-match " ([^)]*)$" x)
11141 (setq f (match-string 0 x))
11142 (setq f ""))
11143 (if (string-match "/" r)
11144 (concat string (substring r 0 (match-end 0)) f)
11146 rtn))
11147 ((eq flag 'lambda)
11148 ;; exact match?
11149 (assoc string thetable)))))
11150 args)))
11152 ;;;; Dynamic blocks
11154 (defun org-find-dblock (name)
11155 "Find the first dynamic block with name NAME in the buffer.
11156 If not found, stay at current position and return nil."
11157 (let ((case-fold-search t) pos)
11158 (save-excursion
11159 (goto-char (point-min))
11160 (setq pos (and (re-search-forward
11161 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11162 (match-beginning 0))))
11163 (if pos (goto-char pos))
11164 pos))
11166 (defconst org-dblock-start-re
11167 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11168 "Matches the start line of a dynamic block, with parameters.")
11170 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11171 "Matches the end of a dynamic block.")
11173 (defun org-create-dblock (plist)
11174 "Create a dynamic block section, with parameters taken from PLIST.
11175 PLIST must contain a :name entry which is used as name of the block."
11176 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11177 (end-of-line 1)
11178 (newline))
11179 (let ((col (current-column))
11180 (name (plist-get plist :name)))
11181 (insert "#+BEGIN: " name)
11182 (while plist
11183 (if (eq (car plist) :name)
11184 (setq plist (cddr plist))
11185 (insert " " (prin1-to-string (pop plist)))))
11186 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11187 (beginning-of-line -2)))
11189 (defun org-prepare-dblock ()
11190 "Prepare dynamic block for refresh.
11191 This empties the block, puts the cursor at the insert position and returns
11192 the property list including an extra property :name with the block name."
11193 (unless (looking-at org-dblock-start-re)
11194 (error "Not at a dynamic block"))
11195 (let* ((begdel (1+ (match-end 0)))
11196 (name (org-no-properties (match-string 1)))
11197 (params (append (list :name name)
11198 (read (concat "(" (match-string 3) ")")))))
11199 (save-excursion
11200 (beginning-of-line 1)
11201 (skip-chars-forward " \t")
11202 (setq params (plist-put params :indentation-column (current-column))))
11203 (unless (re-search-forward org-dblock-end-re nil t)
11204 (error "Dynamic block not terminated"))
11205 (setq params
11206 (append params
11207 (list :content (buffer-substring
11208 begdel (match-beginning 0)))))
11209 (delete-region begdel (match-beginning 0))
11210 (goto-char begdel)
11211 (open-line 1)
11212 params))
11214 (defun org-map-dblocks (&optional command)
11215 "Apply COMMAND to all dynamic blocks in the current buffer.
11216 If COMMAND is not given, use `org-update-dblock'."
11217 (let ((cmd (or command 'org-update-dblock)))
11218 (save-excursion
11219 (goto-char (point-min))
11220 (while (re-search-forward org-dblock-start-re nil t)
11221 (goto-char (match-beginning 0))
11222 (save-excursion
11223 (condition-case nil
11224 (funcall cmd)
11225 (error (message "Error during update of dynamic block"))))
11226 (unless (re-search-forward org-dblock-end-re nil t)
11227 (error "Dynamic block not terminated"))))))
11229 (defun org-dblock-update (&optional arg)
11230 "User command for updating dynamic blocks.
11231 Update the dynamic block at point. With prefix ARG, update all dynamic
11232 blocks in the buffer."
11233 (interactive "P")
11234 (if arg
11235 (org-update-all-dblocks)
11236 (or (looking-at org-dblock-start-re)
11237 (org-beginning-of-dblock))
11238 (org-update-dblock)))
11240 (defun org-update-dblock ()
11241 "Update the dynamic block at point.
11242 This means to empty the block, parse for parameters and then call
11243 the correct writing function."
11244 (interactive)
11245 (save-window-excursion
11246 (let* ((pos (point))
11247 (line (org-current-line))
11248 (params (org-prepare-dblock))
11249 (name (plist-get params :name))
11250 (indent (plist-get params :indentation-column))
11251 (cmd (intern (concat "org-dblock-write:" name))))
11252 (message "Updating dynamic block `%s' at line %d..." name line)
11253 (funcall cmd params)
11254 (message "Updating dynamic block `%s' at line %d...done" name line)
11255 (goto-char pos)
11256 (when (and indent (> indent 0))
11257 (setq indent (make-string indent ?\ ))
11258 (save-excursion
11259 (org-beginning-of-dblock)
11260 (forward-line 1)
11261 (while (not (looking-at org-dblock-end-re))
11262 (insert indent)
11263 (beginning-of-line 2))
11264 (when (looking-at org-dblock-end-re)
11265 (and (looking-at "[ \t]+")
11266 (replace-match ""))
11267 (insert indent)))))))
11269 (defun org-beginning-of-dblock ()
11270 "Find the beginning of the dynamic block at point.
11271 Error if there is no such block at point."
11272 (let ((pos (point))
11273 beg)
11274 (end-of-line 1)
11275 (if (and (re-search-backward org-dblock-start-re nil t)
11276 (setq beg (match-beginning 0))
11277 (re-search-forward org-dblock-end-re nil t)
11278 (> (match-end 0) pos))
11279 (goto-char beg)
11280 (goto-char pos)
11281 (error "Not in a dynamic block"))))
11283 (defun org-update-all-dblocks ()
11284 "Update all dynamic blocks in the buffer.
11285 This function can be used in a hook."
11286 (interactive)
11287 (when (derived-mode-p 'org-mode)
11288 (org-map-dblocks 'org-update-dblock)))
11291 ;;;; Completion
11293 (defconst org-additional-option-like-keywords
11294 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11295 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11296 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11297 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11298 "BEGIN:" "END:"
11299 "ORGTBL" "TBLFM:" "TBLNAME:"
11300 "BEGIN_EXAMPLE" "END_EXAMPLE"
11301 "BEGIN_VERBATIM" "END_VERBATIM"
11302 "BEGIN_QUOTE" "END_QUOTE"
11303 "BEGIN_VERSE" "END_VERSE"
11304 "BEGIN_CENTER" "END_CENTER"
11305 "BEGIN_SRC" "END_SRC"
11306 "BEGIN_RESULT" "END_RESULT"
11307 "BEGIN_lstlisting" "END_lstlisting"
11308 "NAME:" "RESULTS:"
11309 "HEADER:" "HEADERS:"
11310 "COLUMNS:" "PROPERTY:"
11311 "CAPTION:" "LABEL:"
11312 "SETUPFILE:"
11313 "INCLUDE:"
11314 "BIND:"
11315 "MACRO:"))
11317 (defconst org-options-keywords
11318 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11319 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11320 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11321 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11322 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11323 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11324 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11326 (defconst org-additional-option-like-keywords-for-flyspell
11327 (delete-dups
11328 (split-string
11329 (mapconcat (lambda(k)
11330 (replace-regexp-in-string
11331 "_\\|:" " "
11332 (concat k " " (downcase k) " " (upcase k))))
11333 (append org-options-keywords org-additional-option-like-keywords)
11334 " ")
11335 " +" t)))
11337 (defcustom org-structure-template-alist
11339 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11340 "<src lang=\"?\">\n\n</src>")
11341 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11342 "<example>\n?\n</example>")
11343 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11344 "<quote>\n?\n</quote>")
11345 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11346 "<verse>\n?\n</verse>")
11347 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11348 "<center>\n?\n</center>")
11349 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11350 "<literal style=\"latex\">\n?\n</literal>")
11351 ("L" "#+LaTeX: "
11352 "<literal style=\"latex\">?</literal>")
11353 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11354 "<literal style=\"html\">\n?\n</literal>")
11355 ("H" "#+HTML: "
11356 "<literal style=\"html\">?</literal>")
11357 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11358 ("A" "#+ASCII: ")
11359 ("i" "#+INDEX: ?"
11360 "#+INDEX: ?")
11361 ("I" "#+INCLUDE: %file ?"
11362 "<include file=%file markup=\"?\">")
11364 "Structure completion elements.
11365 This is a list of abbreviation keys and values. The value gets inserted
11366 if you type `<' followed by the key and then press the completion key,
11367 usually `M-TAB'. %file will be replaced by a file name after prompting
11368 for the file using completion. The cursor will be placed at the position
11369 of the `?` in the template.
11370 There are two templates for each key, the first uses the original Org syntax,
11371 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11372 the default when the /org-mtags.el/ module has been loaded. See also the
11373 variable `org-mtags-prefer-muse-templates'."
11374 :group 'org-completion
11375 :type '(repeat
11376 (string :tag "Key")
11377 (string :tag "Template")
11378 (string :tag "Muse Template")))
11380 (defun org-try-structure-completion ()
11381 "Try to complete a structure template before point.
11382 This looks for strings like \"<e\" on an otherwise empty line and
11383 expands them."
11384 (let ((l (buffer-substring (point-at-bol) (point)))
11386 (when (and (looking-at "[ \t]*$")
11387 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11388 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11389 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11390 (match-beginning 1)) a)
11391 t)))
11393 (defun org-complete-expand-structure-template (start cell)
11394 "Expand a structure template."
11395 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11396 (rpl (nth (if musep 2 1) cell))
11397 (ind ""))
11398 (delete-region start (point))
11399 (when (string-match "\\`#\\+" rpl)
11400 (cond
11401 ((bolp))
11402 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11403 (setq ind (buffer-substring (point-at-bol) (point))))
11404 (t (newline))))
11405 (setq start (point))
11406 (if (string-match "%file" rpl)
11407 (setq rpl (replace-match
11408 (concat
11409 "\""
11410 (save-match-data
11411 (abbreviate-file-name (read-file-name "Include file: ")))
11412 "\"")
11413 t t rpl)))
11414 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11415 (concat "\n" ind)))
11416 (insert rpl)
11417 (if (re-search-backward "\\?" start t) (delete-char 1))))
11419 ;;;; TODO, DEADLINE, Comments
11421 (defun org-toggle-comment ()
11422 "Change the COMMENT state of an entry."
11423 (interactive)
11424 (save-excursion
11425 (org-back-to-heading)
11426 (let (case-fold-search)
11427 (cond
11428 ((looking-at (format org-heading-keyword-regexp-format
11429 org-comment-string))
11430 (goto-char (match-end 1))
11431 (looking-at (concat " +" org-comment-string))
11432 (replace-match "" t t)
11433 (when (eolp) (insert " ")))
11434 ((looking-at org-outline-regexp)
11435 (goto-char (match-end 0))
11436 (insert org-comment-string " "))))))
11438 (defvar org-last-todo-state-is-todo nil
11439 "This is non-nil when the last TODO state change led to a TODO state.
11440 If the last change removed the TODO tag or switched to DONE, then
11441 this is nil.")
11443 (defvar org-setting-tags nil) ; dynamically skipped
11445 (defvar org-todo-setup-filter-hook nil
11446 "Hook for functions that pre-filter todo specs.
11447 Each function takes a todo spec and returns either nil or the spec
11448 transformed into canonical form." )
11450 (defvar org-todo-get-default-hook nil
11451 "Hook for functions that get a default item for todo.
11452 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11453 nil or a string to be used for the todo mark." )
11455 (defvar org-agenda-headline-snapshot-before-repeat)
11457 (defun org-current-effective-time ()
11458 "Return current time adjusted for `org-extend-today-until' variable."
11459 (let* ((ct (org-current-time))
11460 (dct (decode-time ct))
11461 (ct1
11462 (cond
11463 (org-use-last-clock-out-time-as-effective-time
11464 (or (org-clock-get-last-clock-out-time) ct))
11465 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11466 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11467 (t ct))))
11468 ct1))
11470 (defun org-todo-yesterday (&optional arg)
11471 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11472 (interactive "P")
11473 (if (eq major-mode 'org-agenda-mode)
11474 (apply 'org-agenda-todo-yesterday arg)
11475 (let* ((hour (third (decode-time
11476 (org-current-time))))
11477 (org-extend-today-until (1+ hour)))
11478 (org-todo arg))))
11480 (defun org-todo (&optional arg)
11481 "Change the TODO state of an item.
11482 The state of an item is given by a keyword at the start of the heading,
11483 like
11484 *** TODO Write paper
11485 *** DONE Call mom
11487 The different keywords are specified in the variable `org-todo-keywords'.
11488 By default the available states are \"TODO\" and \"DONE\".
11489 So for this example: when the item starts with TODO, it is changed to DONE.
11490 When it starts with DONE, the DONE is removed. And when neither TODO nor
11491 DONE are present, add TODO at the beginning of the heading.
11493 With \\[universal-argument] prefix arg, use completion to determine the new \
11494 state.
11495 With numeric prefix arg, switch to that state.
11496 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11497 keywords (nextset).
11498 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11499 With a numeric prefix arg of 0, inhibit note taking for the change.
11501 For calling through lisp, arg is also interpreted in the following way:
11502 'none -> empty state
11503 \"\"(empty string) -> switch to empty state
11504 'done -> switch to DONE
11505 'nextset -> switch to the next set of keywords
11506 'previousset -> switch to the previous set of keywords
11507 \"WAITING\" -> switch to the specified keyword, but only if it
11508 really is a member of `org-todo-keywords'."
11509 (interactive "P")
11510 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11511 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11512 'region-start-level 'region))
11513 org-loop-over-headlines-in-active-region)
11514 (org-map-entries
11515 `(org-todo ,arg)
11516 org-loop-over-headlines-in-active-region
11517 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11518 (if (equal arg '(16)) (setq arg 'nextset))
11519 (let ((org-blocker-hook org-blocker-hook)
11520 (case-fold-search nil))
11521 (when (equal arg '(64))
11522 (setq arg nil org-blocker-hook nil))
11523 (when (and org-blocker-hook
11524 (or org-inhibit-blocking
11525 (org-entry-get nil "NOBLOCKING")))
11526 (setq org-blocker-hook nil))
11527 (save-excursion
11528 (catch 'exit
11529 (org-back-to-heading t)
11530 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11531 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11532 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11533 (let* ((match-data (match-data))
11534 (startpos (point-at-bol))
11535 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11536 (org-log-done org-log-done)
11537 (org-log-repeat org-log-repeat)
11538 (org-todo-log-states org-todo-log-states)
11539 (org-inhibit-logging
11540 (if (equal arg 0)
11541 (progn (setq arg nil) 'note) org-inhibit-logging))
11542 (this (match-string 1))
11543 (hl-pos (match-beginning 0))
11544 (head (org-get-todo-sequence-head this))
11545 (ass (assoc head org-todo-kwd-alist))
11546 (interpret (nth 1 ass))
11547 (done-word (nth 3 ass))
11548 (final-done-word (nth 4 ass))
11549 (org-last-state (or this ""))
11550 (completion-ignore-case t)
11551 (member (member this org-todo-keywords-1))
11552 (tail (cdr member))
11553 (org-state (cond
11554 ((and org-todo-key-trigger
11555 (or (and (equal arg '(4))
11556 (eq org-use-fast-todo-selection 'prefix))
11557 (and (not arg) org-use-fast-todo-selection
11558 (not (eq org-use-fast-todo-selection
11559 'prefix)))))
11560 ;; Use fast selection
11561 (org-fast-todo-selection))
11562 ((and (equal arg '(4))
11563 (or (not org-use-fast-todo-selection)
11564 (not org-todo-key-trigger)))
11565 ;; Read a state with completion
11566 (org-icompleting-read
11567 "State: " (mapcar (lambda(x) (list x))
11568 org-todo-keywords-1)
11569 nil t))
11570 ((eq arg 'right)
11571 (if this
11572 (if tail (car tail) nil)
11573 (car org-todo-keywords-1)))
11574 ((eq arg 'left)
11575 (if (equal member org-todo-keywords-1)
11577 (if this
11578 (nth (- (length org-todo-keywords-1)
11579 (length tail) 2)
11580 org-todo-keywords-1)
11581 (org-last org-todo-keywords-1))))
11582 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11583 (setq arg nil))) ; hack to fall back to cycling
11584 (arg
11585 ;; user or caller requests a specific state
11586 (cond
11587 ((equal arg "") nil)
11588 ((eq arg 'none) nil)
11589 ((eq arg 'done) (or done-word (car org-done-keywords)))
11590 ((eq arg 'nextset)
11591 (or (car (cdr (member head org-todo-heads)))
11592 (car org-todo-heads)))
11593 ((eq arg 'previousset)
11594 (let ((org-todo-heads (reverse org-todo-heads)))
11595 (or (car (cdr (member head org-todo-heads)))
11596 (car org-todo-heads))))
11597 ((car (member arg org-todo-keywords-1)))
11598 ((stringp arg)
11599 (error "State `%s' not valid in this file" arg))
11600 ((nth (1- (prefix-numeric-value arg))
11601 org-todo-keywords-1))))
11602 ((null member) (or head (car org-todo-keywords-1)))
11603 ((equal this final-done-word) nil) ;; -> make empty
11604 ((null tail) nil) ;; -> first entry
11605 ((memq interpret '(type priority))
11606 (if (eq this-command last-command)
11607 (car tail)
11608 (if (> (length tail) 0)
11609 (or done-word (car org-done-keywords))
11610 nil)))
11612 (car tail))))
11613 (org-state (or
11614 (run-hook-with-args-until-success
11615 'org-todo-get-default-hook org-state org-last-state)
11616 org-state))
11617 (next (if org-state (concat " " org-state " ") " "))
11618 (change-plist (list :type 'todo-state-change :from this :to org-state
11619 :position startpos))
11620 dolog now-done-p)
11621 (when org-blocker-hook
11622 (setq org-last-todo-state-is-todo
11623 (not (member this org-done-keywords)))
11624 (unless (save-excursion
11625 (save-match-data
11626 (org-with-wide-buffer
11627 (run-hook-with-args-until-failure
11628 'org-blocker-hook change-plist))))
11629 (if (org-called-interactively-p 'interactive)
11630 (error "TODO state change from %s to %s blocked" this org-state)
11631 ;; fail silently
11632 (message "TODO state change from %s to %s blocked" this org-state)
11633 (throw 'exit nil))))
11634 (store-match-data match-data)
11635 (replace-match next t t)
11636 (unless (pos-visible-in-window-p hl-pos)
11637 (message "TODO state changed to %s" (org-trim next)))
11638 (unless head
11639 (setq head (org-get-todo-sequence-head org-state)
11640 ass (assoc head org-todo-kwd-alist)
11641 interpret (nth 1 ass)
11642 done-word (nth 3 ass)
11643 final-done-word (nth 4 ass)))
11644 (when (memq arg '(nextset previousset))
11645 (message "Keyword-Set %d/%d: %s"
11646 (- (length org-todo-sets) -1
11647 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11648 (length org-todo-sets)
11649 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11650 (setq org-last-todo-state-is-todo
11651 (not (member org-state org-done-keywords)))
11652 (setq now-done-p (and (member org-state org-done-keywords)
11653 (not (member this org-done-keywords))))
11654 (and logging (org-local-logging logging))
11655 (when (and (or org-todo-log-states org-log-done)
11656 (not (eq org-inhibit-logging t))
11657 (not (memq arg '(nextset previousset))))
11658 ;; we need to look at recording a time and note
11659 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11660 (nth 2 (assoc this org-todo-log-states))))
11661 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11662 (setq dolog 'time))
11663 (when (and org-state
11664 (member org-state org-not-done-keywords)
11665 (not (member this org-not-done-keywords)))
11666 ;; This is now a todo state and was not one before
11667 ;; If there was a CLOSED time stamp, get rid of it.
11668 (org-add-planning-info nil nil 'closed))
11669 (when (and now-done-p org-log-done)
11670 ;; It is now done, and it was not done before
11671 (org-add-planning-info 'closed (org-current-effective-time))
11672 (if (and (not dolog) (eq 'note org-log-done))
11673 (org-add-log-setup 'done org-state this 'findpos 'note)))
11674 (when (and org-state dolog)
11675 ;; This is a non-nil state, and we need to log it
11676 (org-add-log-setup 'state org-state this 'findpos dolog)))
11677 ;; Fixup tag positioning
11678 (org-todo-trigger-tag-changes org-state)
11679 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11680 (when org-provide-todo-statistics
11681 (org-update-parent-todo-statistics))
11682 (run-hooks 'org-after-todo-state-change-hook)
11683 (if (and arg (not (member org-state org-done-keywords)))
11684 (setq head (org-get-todo-sequence-head org-state)))
11685 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11686 ;; Do we need to trigger a repeat?
11687 (when now-done-p
11688 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11689 ;; This is for the agenda, take a snapshot of the headline.
11690 (save-match-data
11691 (setq org-agenda-headline-snapshot-before-repeat
11692 (org-get-heading))))
11693 (org-auto-repeat-maybe org-state))
11694 ;; Fixup cursor location if close to the keyword
11695 (if (and (outline-on-heading-p)
11696 (not (bolp))
11697 (save-excursion (beginning-of-line 1)
11698 (looking-at org-todo-line-regexp))
11699 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11700 (progn
11701 (goto-char (or (match-end 2) (match-end 1)))
11702 (and (looking-at " ") (just-one-space))))
11703 (when org-trigger-hook
11704 (save-excursion
11705 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11707 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11708 "Block turning an entry into a TODO, using the hierarchy.
11709 This checks whether the current task should be blocked from state
11710 changes. Such blocking occurs when:
11712 1. The task has children which are not all in a completed state.
11714 2. A task has a parent with the property :ORDERED:, and there
11715 are siblings prior to the current task with incomplete
11716 status.
11718 3. The parent of the task is blocked because it has siblings that should
11719 be done first, or is child of a block grandparent TODO entry."
11721 (if (not org-enforce-todo-dependencies)
11722 t ; if locally turned off don't block
11723 (catch 'dont-block
11724 ;; If this is not a todo state change, or if this entry is already DONE,
11725 ;; do not block
11726 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11727 (member (plist-get change-plist :from)
11728 (cons 'done org-done-keywords))
11729 (member (plist-get change-plist :to)
11730 (cons 'todo org-not-done-keywords))
11731 (not (plist-get change-plist :to)))
11732 (throw 'dont-block t))
11733 ;; If this task has children, and any are undone, it's blocked
11734 (save-excursion
11735 (org-back-to-heading t)
11736 (let ((this-level (funcall outline-level)))
11737 (outline-next-heading)
11738 (let ((child-level (funcall outline-level)))
11739 (while (and (not (eobp))
11740 (> child-level this-level))
11741 ;; this todo has children, check whether they are all
11742 ;; completed
11743 (if (and (not (org-entry-is-done-p))
11744 (org-entry-is-todo-p))
11745 (throw 'dont-block nil))
11746 (outline-next-heading)
11747 (setq child-level (funcall outline-level))))))
11748 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11749 ;; any previous siblings are undone, it's blocked
11750 (save-excursion
11751 (org-back-to-heading t)
11752 (let* ((pos (point))
11753 (parent-pos (and (org-up-heading-safe) (point))))
11754 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11755 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11756 (forward-line 1)
11757 (re-search-forward org-not-done-heading-regexp pos t))
11758 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11759 ;; Search further up the hierarchy, to see if an ancestor is blocked
11760 (while t
11761 (goto-char parent-pos)
11762 (if (not (looking-at org-not-done-heading-regexp))
11763 (throw 'dont-block t)) ; do not block, parent is not a TODO
11764 (setq pos (point))
11765 (setq parent-pos (and (org-up-heading-safe) (point)))
11766 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11767 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11768 (forward-line 1)
11769 (re-search-forward org-not-done-heading-regexp pos t))
11770 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11772 (defcustom org-track-ordered-property-with-tag nil
11773 "Should the ORDERED property also be shown as a tag?
11774 The ORDERED property decides if an entry should require subtasks to be
11775 completed in sequence. Since a property is not very visible, setting
11776 this option means that toggling the ORDERED property with the command
11777 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11778 not relevant for the behavior, but it makes things more visible.
11780 Note that toggling the tag with tags commands will not change the property
11781 and therefore not influence behavior!
11783 This can be t, meaning the tag ORDERED should be used, It can also be a
11784 string to select a different tag for this task."
11785 :group 'org-todo
11786 :type '(choice
11787 (const :tag "No tracking" nil)
11788 (const :tag "Track with ORDERED tag" t)
11789 (string :tag "Use other tag")))
11791 (defun org-toggle-ordered-property ()
11792 "Toggle the ORDERED property of the current entry.
11793 For better visibility, you can track the value of this property with a tag.
11794 See variable `org-track-ordered-property-with-tag'."
11795 (interactive)
11796 (let* ((t1 org-track-ordered-property-with-tag)
11797 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11798 (save-excursion
11799 (org-back-to-heading)
11800 (if (org-entry-get nil "ORDERED")
11801 (progn
11802 (org-delete-property "ORDERED")
11803 (and tag (org-toggle-tag tag 'off))
11804 (message "Subtasks can be completed in arbitrary order"))
11805 (org-entry-put nil "ORDERED" "t")
11806 (and tag (org-toggle-tag tag 'on))
11807 (message "Subtasks must be completed in sequence")))))
11809 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11810 (defun org-block-todo-from-checkboxes (change-plist)
11811 "Block turning an entry into a TODO, using checkboxes.
11812 This checks whether the current task should be blocked from state
11813 changes because there are unchecked boxes in this entry."
11814 (if (not org-enforce-todo-checkbox-dependencies)
11815 t ; if locally turned off don't block
11816 (catch 'dont-block
11817 ;; If this is not a todo state change, or if this entry is already DONE,
11818 ;; do not block
11819 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11820 (member (plist-get change-plist :from)
11821 (cons 'done org-done-keywords))
11822 (member (plist-get change-plist :to)
11823 (cons 'todo org-not-done-keywords))
11824 (not (plist-get change-plist :to)))
11825 (throw 'dont-block t))
11826 ;; If this task has checkboxes that are not checked, it's blocked
11827 (save-excursion
11828 (org-back-to-heading t)
11829 (let ((beg (point)) end)
11830 (outline-next-heading)
11831 (setq end (point))
11832 (goto-char beg)
11833 (if (org-list-search-forward
11834 (concat (org-item-beginning-re)
11835 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11836 "\\[[- ]\\]")
11837 end t)
11838 (progn
11839 (if (boundp 'org-blocked-by-checkboxes)
11840 (setq org-blocked-by-checkboxes t))
11841 (throw 'dont-block nil)))))
11842 t))) ; do not block
11844 (defun org-entry-blocked-p ()
11845 "Is the current entry blocked?"
11846 (if (org-entry-get nil "NOBLOCKING")
11847 nil ;; Never block this entry
11848 (not
11849 (run-hook-with-args-until-failure
11850 'org-blocker-hook
11851 (list :type 'todo-state-change
11852 :position (point)
11853 :from 'todo
11854 :to 'done)))))
11856 (defun org-update-statistics-cookies (all)
11857 "Update the statistics cookie, either from TODO or from checkboxes.
11858 This should be called with the cursor in a line with a statistics cookie."
11859 (interactive "P")
11860 (if all
11861 (progn
11862 (org-update-checkbox-count 'all)
11863 (org-map-entries 'org-update-parent-todo-statistics))
11864 (if (not (org-at-heading-p))
11865 (org-update-checkbox-count)
11866 (let ((pos (move-marker (make-marker) (point)))
11867 end l1 l2)
11868 (ignore-errors (org-back-to-heading t))
11869 (if (not (org-at-heading-p))
11870 (org-update-checkbox-count)
11871 (setq l1 (org-outline-level))
11872 (setq end (save-excursion
11873 (outline-next-heading)
11874 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11875 (point)))
11876 (if (and (save-excursion
11877 (re-search-forward
11878 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11879 (not (save-excursion (re-search-forward
11880 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11881 (org-update-checkbox-count)
11882 (if (and l2 (> l2 l1))
11883 (progn
11884 (goto-char end)
11885 (org-update-parent-todo-statistics))
11886 (goto-char pos)
11887 (beginning-of-line 1)
11888 (while (re-search-forward
11889 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11890 (point-at-eol) t)
11891 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11892 (goto-char pos)
11893 (move-marker pos nil)))))
11895 (defvar org-entry-property-inherited-from) ;; defined below
11896 (defun org-update-parent-todo-statistics ()
11897 "Update any statistics cookie in the parent of the current headline.
11898 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11899 the entire subtree and this will travel up the hierarchy and update
11900 statistics everywhere."
11901 (let* ((prop (save-excursion (org-up-heading-safe)
11902 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11903 (recursive (or (not org-hierarchical-todo-statistics)
11904 (and prop (string-match "\\<recursive\\>" prop))))
11905 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11907 (first t)
11908 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11909 level ltoggle l1 new ndel
11910 (cnt-all 0) (cnt-done 0) is-percent kwd
11911 checkbox-beg ov ovs ove cookie-present)
11912 (catch 'exit
11913 (save-excursion
11914 (beginning-of-line 1)
11915 (setq ltoggle (funcall outline-level))
11916 ;; Three situations are to consider:
11918 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11919 ;; to the top-level ancestor on the headline;
11921 ;; 2. If parent has "recursive" property, repeat up to the
11922 ;; headline setting that property, taking inheritance into
11923 ;; account;
11925 ;; 3. Else, move up to direct parent and proceed only once.
11926 (while (and (setq level (org-up-heading-safe))
11927 (or recursive first)
11928 (>= (point) lim))
11929 (setq first nil cookie-present nil)
11930 (unless (and level
11931 (not (string-match
11932 "\\<checkbox\\>"
11933 (downcase (or (org-entry-get nil "COOKIE_DATA")
11934 "")))))
11935 (throw 'exit nil))
11936 (while (re-search-forward box-re (point-at-eol) t)
11937 (setq cnt-all 0 cnt-done 0 cookie-present t)
11938 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11939 (save-match-data
11940 (unless (outline-next-heading) (throw 'exit nil))
11941 (while (and (looking-at org-complex-heading-regexp)
11942 (> (setq l1 (length (match-string 1))) level))
11943 (setq kwd (and (or recursive (= l1 ltoggle))
11944 (match-string 2)))
11945 (if (or (eq org-provide-todo-statistics 'all-headlines)
11946 (and (listp org-provide-todo-statistics)
11947 (or (member kwd org-provide-todo-statistics)
11948 (member kwd org-done-keywords))))
11949 (setq cnt-all (1+ cnt-all))
11950 (if (eq org-provide-todo-statistics t)
11951 (and kwd (setq cnt-all (1+ cnt-all)))))
11952 (and (member kwd org-done-keywords)
11953 (setq cnt-done (1+ cnt-done)))
11954 (outline-next-heading)))
11955 (setq new
11956 (if is-percent
11957 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11958 (format "[%d/%d]" cnt-done cnt-all))
11959 ndel (- (match-end 0) checkbox-beg))
11960 ;; handle overlays when updating cookie from column view
11961 (when (setq ov (car (overlays-at checkbox-beg)))
11962 (setq ovs (overlay-start ov) ove (overlay-end ov))
11963 (delete-overlay ov))
11964 (goto-char checkbox-beg)
11965 (insert new)
11966 (delete-region (point) (+ (point) ndel))
11967 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11968 (when ov (move-overlay ov ovs ove)))
11969 (when cookie-present
11970 (run-hook-with-args 'org-after-todo-statistics-hook
11971 cnt-done (- cnt-all cnt-done))))))
11972 (run-hooks 'org-todo-statistics-hook)))
11974 (defvar org-after-todo-statistics-hook nil
11975 "Hook that is called after a TODO statistics cookie has been updated.
11976 Each function is called with two arguments: the number of not-done entries
11977 and the number of done entries.
11979 For example, the following function, when added to this hook, will switch
11980 an entry to DONE when all children are done, and back to TODO when new
11981 entries are set to a TODO status. Note that this hook is only called
11982 when there is a statistics cookie in the headline!
11984 (defun org-summary-todo (n-done n-not-done)
11985 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11986 (let (org-log-done org-log-states) ; turn off logging
11987 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11990 (defvar org-todo-statistics-hook nil
11991 "Hook that is run whenever Org thinks TODO statistics should be updated.
11992 This hook runs even if there is no statistics cookie present, in which case
11993 `org-after-todo-statistics-hook' would not run.")
11995 (defun org-todo-trigger-tag-changes (state)
11996 "Apply the changes defined in `org-todo-state-tags-triggers'."
11997 (let ((l org-todo-state-tags-triggers)
11998 changes)
11999 (when (or (not state) (equal state ""))
12000 (setq changes (append changes (cdr (assoc "" l)))))
12001 (when (and (stringp state) (> (length state) 0))
12002 (setq changes (append changes (cdr (assoc state l)))))
12003 (when (member state org-not-done-keywords)
12004 (setq changes (append changes (cdr (assoc 'todo l)))))
12005 (when (member state org-done-keywords)
12006 (setq changes (append changes (cdr (assoc 'done l)))))
12007 (dolist (c changes)
12008 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12010 (defun org-local-logging (value)
12011 "Get logging settings from a property VALUE."
12012 (let* (words w a)
12013 ;; directly set the variables, they are already local.
12014 (setq org-log-done nil
12015 org-log-repeat nil
12016 org-todo-log-states nil)
12017 (setq words (org-split-string value))
12018 (while (setq w (pop words))
12019 (cond
12020 ((setq a (assoc w org-startup-options))
12021 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12022 (set (nth 1 a) (nth 2 a))))
12023 ((setq a (org-extract-log-state-settings w))
12024 (and (member (car a) org-todo-keywords-1)
12025 (push a org-todo-log-states)))))))
12027 (defun org-get-todo-sequence-head (kwd)
12028 "Return the head of the TODO sequence to which KWD belongs.
12029 If KWD is not set, check if there is a text property remembering the
12030 right sequence."
12031 (let (p)
12032 (cond
12033 ((not kwd)
12034 (or (get-text-property (point-at-bol) 'org-todo-head)
12035 (progn
12036 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12037 nil (point-at-eol)))
12038 (get-text-property p 'org-todo-head))))
12039 ((not (member kwd org-todo-keywords-1))
12040 (car org-todo-keywords-1))
12041 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12043 (defun org-fast-todo-selection ()
12044 "Fast TODO keyword selection with single keys.
12045 Returns the new TODO keyword, or nil if no state change should occur."
12046 (let* ((fulltable org-todo-key-alist)
12047 (done-keywords org-done-keywords) ;; needed for the faces.
12048 (maxlen (apply 'max (mapcar
12049 (lambda (x)
12050 (if (stringp (car x)) (string-width (car x)) 0))
12051 fulltable)))
12052 (expert nil)
12053 (fwidth (+ maxlen 3 1 3))
12054 (ncol (/ (- (window-width) 4) fwidth))
12055 tg cnt e c tbl
12056 groups ingroup)
12057 (save-excursion
12058 (save-window-excursion
12059 (if expert
12060 (set-buffer (get-buffer-create " *Org todo*"))
12061 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12062 (erase-buffer)
12063 (org-set-local 'org-done-keywords done-keywords)
12064 (setq tbl fulltable cnt 0)
12065 (while (setq e (pop tbl))
12066 (cond
12067 ((equal e '(:startgroup))
12068 (push '() groups) (setq ingroup t)
12069 (when (not (= cnt 0))
12070 (setq cnt 0)
12071 (insert "\n"))
12072 (insert "{ "))
12073 ((equal e '(:endgroup))
12074 (setq ingroup nil cnt 0)
12075 (insert "}\n"))
12076 ((equal e '(:newline))
12077 (when (not (= cnt 0))
12078 (setq cnt 0)
12079 (insert "\n")
12080 (setq e (car tbl))
12081 (while (equal (car tbl) '(:newline))
12082 (insert "\n")
12083 (setq tbl (cdr tbl)))))
12085 (setq tg (car e) c (cdr e))
12086 (if ingroup (push tg (car groups)))
12087 (setq tg (org-add-props tg nil 'face
12088 (org-get-todo-face tg)))
12089 (if (and (= cnt 0) (not ingroup)) (insert " "))
12090 (insert "[" c "] " tg (make-string
12091 (- fwidth 4 (length tg)) ?\ ))
12092 (when (= (setq cnt (1+ cnt)) ncol)
12093 (insert "\n")
12094 (if ingroup (insert " "))
12095 (setq cnt 0)))))
12096 (insert "\n")
12097 (goto-char (point-min))
12098 (if (not expert) (org-fit-window-to-buffer))
12099 (message "[a-z..]:Set [SPC]:clear")
12100 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12101 (cond
12102 ((or (= c ?\C-g)
12103 (and (= c ?q) (not (rassoc c fulltable))))
12104 (setq quit-flag t))
12105 ((= c ?\ ) nil)
12106 ((setq e (rassoc c fulltable) tg (car e))
12108 (t (setq quit-flag t)))))))
12110 (defun org-entry-is-todo-p ()
12111 (member (org-get-todo-state) org-not-done-keywords))
12113 (defun org-entry-is-done-p ()
12114 (member (org-get-todo-state) org-done-keywords))
12116 (defun org-get-todo-state ()
12117 (save-excursion
12118 (org-back-to-heading t)
12119 (and (looking-at org-todo-line-regexp)
12120 (match-end 2)
12121 (match-string 2))))
12123 (defun org-at-date-range-p (&optional inactive-ok)
12124 "Is the cursor inside a date range?"
12125 (interactive)
12126 (save-excursion
12127 (catch 'exit
12128 (let ((pos (point)))
12129 (skip-chars-backward "^[<\r\n")
12130 (skip-chars-backward "<[")
12131 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12132 (>= (match-end 0) pos)
12133 (throw 'exit t))
12134 (skip-chars-backward "^<[\r\n")
12135 (skip-chars-backward "<[")
12136 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12137 (>= (match-end 0) pos)
12138 (throw 'exit t)))
12139 nil)))
12141 (defun org-get-repeat (&optional tagline)
12142 "Check if there is a deadline/schedule with repeater in this entry."
12143 (save-match-data
12144 (save-excursion
12145 (org-back-to-heading t)
12146 (and (re-search-forward (if tagline
12147 (concat tagline "\\s-*" org-repeat-re)
12148 org-repeat-re)
12149 (org-entry-end-position) t)
12150 (match-string-no-properties 1)))))
12152 (defvar org-last-changed-timestamp)
12153 (defvar org-last-inserted-timestamp)
12154 (defvar org-log-post-message)
12155 (defvar org-log-note-purpose)
12156 (defvar org-log-note-how)
12157 (defvar org-log-note-extra)
12158 (defun org-auto-repeat-maybe (done-word)
12159 "Check if the current headline contains a repeated deadline/schedule.
12160 If yes, set TODO state back to what it was and change the base date
12161 of repeating deadline/scheduled time stamps to new date.
12162 This function is run automatically after each state change to a DONE state."
12163 ;; last-state is dynamically scoped into this function
12164 (let* ((repeat (org-get-repeat))
12165 (aa (assoc org-last-state org-todo-kwd-alist))
12166 (interpret (nth 1 aa))
12167 (head (nth 2 aa))
12168 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12169 (msg "Entry repeats: ")
12170 (org-log-done nil)
12171 (org-todo-log-states nil)
12172 re type n what ts time to-state)
12173 (when repeat
12174 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12175 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12176 org-todo-repeat-to-state))
12177 (unless (and to-state (member to-state org-todo-keywords-1))
12178 (setq to-state (if (eq interpret 'type) org-last-state head)))
12179 (org-todo to-state)
12180 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12181 (org-entry-put nil "LAST_REPEAT" (format-time-string
12182 (org-time-stamp-format t t))))
12183 (when org-log-repeat
12184 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12185 (memq 'org-add-log-note post-command-hook))
12186 ;; OK, we are already setup for some record
12187 (if (eq org-log-repeat 'note)
12188 ;; make sure we take a note, not only a time stamp
12189 (setq org-log-note-how 'note))
12190 ;; Set up for taking a record
12191 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12192 org-last-state
12193 'findpos org-log-repeat)))
12194 (org-back-to-heading t)
12195 (org-add-planning-info nil nil 'closed)
12196 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12197 org-deadline-time-regexp "\\)\\|\\("
12198 org-ts-regexp "\\)"))
12199 (while (re-search-forward
12200 re (save-excursion (outline-next-heading) (point)) t)
12201 (setq type (if (match-end 1) org-scheduled-string
12202 (if (match-end 3) org-deadline-string "Plain:"))
12203 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12204 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12205 (setq n (string-to-number (match-string 2 ts))
12206 what (match-string 3 ts))
12207 (if (equal what "w") (setq n (* n 7) what "d"))
12208 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12209 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12210 ;; Preparation, see if we need to modify the start date for the change
12211 (when (match-end 1)
12212 (setq time (save-match-data (org-time-string-to-time ts)))
12213 (cond
12214 ((equal (match-string 1 ts) ".")
12215 ;; Shift starting date to today
12216 (org-timestamp-change
12217 (- (org-today) (time-to-days time))
12218 'day))
12219 ((equal (match-string 1 ts) "+")
12220 (let ((nshiftmax 10) (nshift 0))
12221 (while (or (= nshift 0)
12222 (<= (time-to-days time)
12223 (time-to-days (current-time))))
12224 (when (= (incf nshift) nshiftmax)
12225 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12226 (error "Abort")))
12227 (org-timestamp-change n (cdr (assoc what whata)))
12228 (org-at-timestamp-p t)
12229 (setq ts (match-string 1))
12230 (setq time (save-match-data (org-time-string-to-time ts)))))
12231 (org-timestamp-change (- n) (cdr (assoc what whata)))
12232 ;; rematch, so that we have everything in place for the real shift
12233 (org-at-timestamp-p t)
12234 (setq ts (match-string 1))
12235 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12236 (org-timestamp-change n (cdr (assoc what whata)))
12237 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12238 (setq org-log-post-message msg)
12239 (message "%s" msg))))
12241 (defun org-show-todo-tree (arg)
12242 "Make a compact tree which shows all headlines marked with TODO.
12243 The tree will show the lines where the regexp matches, and all higher
12244 headlines above the match.
12245 With a \\[universal-argument] prefix, prompt for a regexp to match.
12246 With a numeric prefix N, construct a sparse tree for the Nth element
12247 of `org-todo-keywords-1'."
12248 (interactive "P")
12249 (let ((case-fold-search nil)
12250 (kwd-re
12251 (cond ((null arg) org-not-done-regexp)
12252 ((equal arg '(4))
12253 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12254 (mapcar 'list org-todo-keywords-1))))
12255 (concat "\\("
12256 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12257 "\\)\\>")))
12258 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12259 (regexp-quote (nth (1- (prefix-numeric-value arg))
12260 org-todo-keywords-1)))
12261 (t (error "Invalid prefix argument: %s" arg)))))
12262 (message "%d TODO entries found"
12263 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12265 (defun org-deadline (&optional remove time)
12266 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12267 With argument REMOVE, remove any deadline from the item.
12268 With argument TIME, set the deadline at the corresponding date. TIME
12269 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12270 (interactive "P")
12271 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12272 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12273 'region-start-level 'region))
12274 org-loop-over-headlines-in-active-region)
12275 (org-map-entries
12276 `(org-deadline ',remove ,time)
12277 org-loop-over-headlines-in-active-region
12278 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12279 (let* ((old-date (org-entry-get nil "DEADLINE"))
12280 (repeater (and old-date
12281 (string-match
12282 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12283 old-date)
12284 (match-string 1 old-date))))
12285 (if remove
12286 (progn
12287 (when (and old-date org-log-redeadline)
12288 (org-add-log-setup 'deldeadline nil old-date 'findpos
12289 org-log-redeadline))
12290 (org-remove-timestamp-with-keyword org-deadline-string)
12291 (message "Item no longer has a deadline."))
12292 (org-add-planning-info 'deadline time 'closed)
12293 (when (and old-date org-log-redeadline
12294 (not (equal old-date
12295 (substring org-last-inserted-timestamp 1 -1))))
12296 (org-add-log-setup 'redeadline nil old-date 'findpos
12297 org-log-redeadline))
12298 (when repeater
12299 (save-excursion
12300 (org-back-to-heading t)
12301 (when (re-search-forward (concat org-deadline-string " "
12302 org-last-inserted-timestamp)
12303 (save-excursion
12304 (outline-next-heading) (point)) t)
12305 (goto-char (1- (match-end 0)))
12306 (insert " " repeater)
12307 (setq org-last-inserted-timestamp
12308 (concat (substring org-last-inserted-timestamp 0 -1)
12309 " " repeater
12310 (substring org-last-inserted-timestamp -1))))))
12311 (message "Deadline on %s" org-last-inserted-timestamp)))))
12313 (defun org-schedule (&optional remove time)
12314 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12315 With argument REMOVE, remove any scheduling date from the item.
12316 With argument TIME, scheduled at the corresponding date. TIME can
12317 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12318 (interactive "P")
12319 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12320 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12321 'region-start-level 'region))
12322 org-loop-over-headlines-in-active-region)
12323 (org-map-entries
12324 `(org-schedule ',remove ,time)
12325 org-loop-over-headlines-in-active-region
12326 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12327 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12328 (repeater (and old-date
12329 (string-match
12330 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12331 old-date)
12332 (match-string 1 old-date))))
12333 (if remove
12334 (progn
12335 (when (and old-date org-log-reschedule)
12336 (org-add-log-setup 'delschedule nil old-date 'findpos
12337 org-log-reschedule))
12338 (org-remove-timestamp-with-keyword org-scheduled-string)
12339 (message "Item is no longer scheduled."))
12340 (org-add-planning-info 'scheduled time 'closed)
12341 (when (and old-date org-log-reschedule
12342 (not (equal old-date
12343 (substring org-last-inserted-timestamp 1 -1))))
12344 (org-add-log-setup 'reschedule nil old-date 'findpos
12345 org-log-reschedule))
12346 (when repeater
12347 (save-excursion
12348 (org-back-to-heading t)
12349 (when (re-search-forward (concat org-scheduled-string " "
12350 org-last-inserted-timestamp)
12351 (save-excursion
12352 (outline-next-heading) (point)) t)
12353 (goto-char (1- (match-end 0)))
12354 (insert " " repeater)
12355 (setq org-last-inserted-timestamp
12356 (concat (substring org-last-inserted-timestamp 0 -1)
12357 " " repeater
12358 (substring org-last-inserted-timestamp -1))))))
12359 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12361 (defun org-get-scheduled-time (pom &optional inherit)
12362 "Get the scheduled time as a time tuple, of a format suitable
12363 for calling org-schedule with, or if there is no scheduling,
12364 returns nil."
12365 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12366 (when time
12367 (apply 'encode-time (org-parse-time-string time)))))
12369 (defun org-get-deadline-time (pom &optional inherit)
12370 "Get the deadline as a time tuple, of a format suitable for
12371 calling org-deadline with, or if there is no scheduling, returns
12372 nil."
12373 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12374 (when time
12375 (apply 'encode-time (org-parse-time-string time)))))
12377 (defun org-remove-timestamp-with-keyword (keyword)
12378 "Remove all time stamps with KEYWORD in the current entry."
12379 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12380 beg)
12381 (save-excursion
12382 (org-back-to-heading t)
12383 (setq beg (point))
12384 (outline-next-heading)
12385 (while (re-search-backward re beg t)
12386 (replace-match "")
12387 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12388 (equal (char-before) ?\ ))
12389 (backward-delete-char 1)
12390 (if (string-match "^[ \t]*$" (buffer-substring
12391 (point-at-bol) (point-at-eol)))
12392 (delete-region (point-at-bol)
12393 (min (point-max) (1+ (point-at-eol))))))))))
12395 (defun org-add-planning-info (what &optional time &rest remove)
12396 "Insert new timestamp with keyword in the line directly after the headline.
12397 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12398 If non is given, the user is prompted for a date.
12399 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12400 be removed."
12401 (interactive)
12402 (let (org-time-was-given org-end-time-was-given ts
12403 end default-time default-input)
12405 (catch 'exit
12406 (when (and (memq what '(scheduled deadline))
12407 (or (not time)
12408 (and (stringp time)
12409 (string-match "^[-+]+[0-9]" time))))
12410 ;; Try to get a default date/time from existing timestamp
12411 (save-excursion
12412 (org-back-to-heading t)
12413 (setq end (save-excursion (outline-next-heading) (point)))
12414 (when (re-search-forward (if (eq what 'scheduled)
12415 org-scheduled-time-regexp
12416 org-deadline-time-regexp)
12417 end t)
12418 (setq ts (match-string 1)
12419 default-time
12420 (apply 'encode-time (org-parse-time-string ts))
12421 default-input (and ts (org-get-compact-tod ts))))))
12422 (when what
12423 (setq time
12424 (if (stringp time)
12425 ;; This is a string (relative or absolute), set proper date
12426 (apply 'encode-time
12427 (org-read-date-analyze
12428 time default-time (decode-time default-time)))
12429 ;; If necessary, get the time from the user
12430 (or time (org-read-date nil 'to-time nil nil
12431 default-time default-input)))))
12433 (when (and org-insert-labeled-timestamps-at-point
12434 (member what '(scheduled deadline)))
12435 (insert
12436 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12437 (org-insert-time-stamp time org-time-was-given
12438 nil nil nil (list org-end-time-was-given))
12439 (setq what nil))
12440 (save-excursion
12441 (save-restriction
12442 (let (col list elt ts buffer-invisibility-spec)
12443 (org-back-to-heading t)
12444 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12445 (goto-char (match-end 1))
12446 (setq col (current-column))
12447 (goto-char (match-end 0))
12448 (if (eobp) (insert "\n") (forward-char 1))
12449 (when (and (not what)
12450 (not (looking-at
12451 (concat "[ \t]*"
12452 org-keyword-time-not-clock-regexp))))
12453 ;; Nothing to add, nothing to remove...... :-)
12454 (throw 'exit nil))
12455 (if (and (not (looking-at org-outline-regexp))
12456 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12457 "[^\r\n]*"))
12458 (not (equal (match-string 1) org-clock-string)))
12459 (narrow-to-region (match-beginning 0) (match-end 0))
12460 (insert-before-markers "\n")
12461 (backward-char 1)
12462 (narrow-to-region (point) (point))
12463 (and org-adapt-indentation (org-indent-to-column col)))
12464 ;; Check if we have to remove something.
12465 (setq list (cons what remove))
12466 (while list
12467 (setq elt (pop list))
12468 (when (or (and (eq elt 'scheduled)
12469 (re-search-forward org-scheduled-time-regexp nil t))
12470 (and (eq elt 'deadline)
12471 (re-search-forward org-deadline-time-regexp nil t))
12472 (and (eq elt 'closed)
12473 (re-search-forward org-closed-time-regexp nil t)))
12474 (replace-match "")
12475 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12476 (and (looking-at "[ \t]+") (replace-match ""))
12477 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12478 (when what
12479 (insert
12480 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12481 (cond ((eq what 'scheduled) org-scheduled-string)
12482 ((eq what 'deadline) org-deadline-string)
12483 ((eq what 'closed) org-closed-string))
12484 " ")
12485 (setq ts (org-insert-time-stamp
12486 time
12487 (or org-time-was-given
12488 (and (eq what 'closed) org-log-done-with-time))
12489 (eq what 'closed)
12490 nil nil (list org-end-time-was-given)))
12491 (insert
12492 (if (not (or (bolp) (eq (char-before) ?\ )
12493 (memq (char-after) '(32 10))
12494 (eobp))) " " ""))
12495 (end-of-line 1))
12496 (goto-char (point-min))
12497 (widen)
12498 (if (and (looking-at "[ \t]*\n")
12499 (equal (char-before) ?\n))
12500 (delete-region (1- (point)) (point-at-eol)))
12501 ts))))))
12503 (defvar org-log-note-marker (make-marker))
12504 (defvar org-log-note-purpose nil)
12505 (defvar org-log-note-state nil)
12506 (defvar org-log-note-previous-state nil)
12507 (defvar org-log-note-how nil)
12508 (defvar org-log-note-extra nil)
12509 (defvar org-log-note-window-configuration nil)
12510 (defvar org-log-note-return-to (make-marker))
12511 (defvar org-log-note-effective-time nil
12512 "Remembered current time so that dynamically scoped
12513 `org-extend-today-until' affects tha timestamps in state change
12514 log")
12516 (defvar org-log-post-message nil
12517 "Message to be displayed after a log note has been stored.
12518 The auto-repeater uses this.")
12520 (defun org-add-note ()
12521 "Add a note to the current entry.
12522 This is done in the same way as adding a state change note."
12523 (interactive)
12524 (org-add-log-setup 'note nil nil 'findpos nil))
12526 (defvar org-property-end-re)
12527 (defun org-add-log-setup (&optional purpose state prev-state
12528 findpos how extra)
12529 "Set up the post command hook to take a note.
12530 If this is about to TODO state change, the new state is expected in STATE.
12531 When FINDPOS is non-nil, find the correct position for the note in
12532 the current entry. If not, assume that it can be inserted at point.
12533 HOW is an indicator what kind of note should be created.
12534 EXTRA is additional text that will be inserted into the notes buffer."
12535 (let* ((org-log-into-drawer (org-log-into-drawer))
12536 (drawer (cond ((stringp org-log-into-drawer)
12537 org-log-into-drawer)
12538 (org-log-into-drawer "LOGBOOK"))))
12539 (save-restriction
12540 (save-excursion
12541 (when findpos
12542 (org-back-to-heading t)
12543 (narrow-to-region (point) (save-excursion
12544 (outline-next-heading) (point)))
12545 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12546 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12547 "[^\r\n]*\\)?"))
12548 (goto-char (match-end 0))
12549 (cond
12550 (drawer
12551 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12552 nil t)
12553 (progn
12554 (goto-char (match-end 0))
12555 (or org-log-states-order-reversed
12556 (and (re-search-forward org-property-end-re nil t)
12557 (goto-char (1- (match-beginning 0))))))
12558 (insert "\n:" drawer ":\n:END:")
12559 (beginning-of-line 0)
12560 (org-indent-line)
12561 (beginning-of-line 2)
12562 (org-indent-line)
12563 (end-of-line 0)))
12564 ((and org-log-state-notes-insert-after-drawers
12565 (save-excursion
12566 (forward-line) (looking-at org-drawer-regexp)))
12567 (forward-line)
12568 (while (looking-at org-drawer-regexp)
12569 (goto-char (match-end 0))
12570 (re-search-forward org-property-end-re (point-max) t)
12571 (forward-line))
12572 (forward-line -1)))
12573 (unless org-log-states-order-reversed
12574 (and (= (char-after) ?\n) (forward-char 1))
12575 (org-skip-over-state-notes)
12576 (skip-chars-backward " \t\n\r")))
12577 (move-marker org-log-note-marker (point))
12578 (setq org-log-note-purpose purpose
12579 org-log-note-state state
12580 org-log-note-previous-state prev-state
12581 org-log-note-how how
12582 org-log-note-extra extra
12583 org-log-note-effective-time (org-current-effective-time))
12584 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12586 (defun org-skip-over-state-notes ()
12587 "Skip past the list of State notes in an entry."
12588 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12589 (when (ignore-errors (goto-char (org-in-item-p)))
12590 (let* ((struct (org-list-struct))
12591 (prevs (org-list-prevs-alist struct)))
12592 (while (looking-at "[ \t]*- State")
12593 (goto-char (or (org-list-get-next-item (point) struct prevs)
12594 (org-list-get-item-end (point) struct)))))))
12596 (defun org-add-log-note (&optional purpose)
12597 "Pop up a window for taking a note, and add this note later at point."
12598 (remove-hook 'post-command-hook 'org-add-log-note)
12599 (setq org-log-note-window-configuration (current-window-configuration))
12600 (delete-other-windows)
12601 (move-marker org-log-note-return-to (point))
12602 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12603 (goto-char org-log-note-marker)
12604 (org-switch-to-buffer-other-window "*Org Note*")
12605 (erase-buffer)
12606 (if (memq org-log-note-how '(time state))
12607 (let (current-prefix-arg) (org-store-log-note))
12608 (let ((org-inhibit-startup t)) (org-mode))
12609 (insert (format "# Insert note for %s.
12610 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12611 (cond
12612 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12613 ((eq org-log-note-purpose 'done) "closed todo item")
12614 ((eq org-log-note-purpose 'state)
12615 (format "state change from \"%s\" to \"%s\""
12616 (or org-log-note-previous-state "")
12617 (or org-log-note-state "")))
12618 ((eq org-log-note-purpose 'reschedule)
12619 "rescheduling")
12620 ((eq org-log-note-purpose 'delschedule)
12621 "no longer scheduled")
12622 ((eq org-log-note-purpose 'redeadline)
12623 "changing deadline")
12624 ((eq org-log-note-purpose 'deldeadline)
12625 "removing deadline")
12626 ((eq org-log-note-purpose 'refile)
12627 "refiling")
12628 ((eq org-log-note-purpose 'note)
12629 "this entry")
12630 (t (error "This should not happen")))))
12631 (if org-log-note-extra (insert org-log-note-extra))
12632 (org-set-local 'org-finish-function 'org-store-log-note)
12633 (run-hooks 'org-log-buffer-setup-hook)))
12635 (defvar org-note-abort nil) ; dynamically scoped
12636 (defun org-store-log-note ()
12637 "Finish taking a log note, and insert it to where it belongs."
12638 (let ((txt (buffer-string))
12639 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12640 lines ind bul)
12641 (kill-buffer (current-buffer))
12642 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12643 (setq txt (replace-match "" t t txt)))
12644 (if (string-match "\\s-+\\'" txt)
12645 (setq txt (replace-match "" t t txt)))
12646 (setq lines (org-split-string txt "\n"))
12647 (when (and note (string-match "\\S-" note))
12648 (setq note
12649 (org-replace-escapes
12650 note
12651 (list (cons "%u" (user-login-name))
12652 (cons "%U" user-full-name)
12653 (cons "%t" (format-time-string
12654 (org-time-stamp-format 'long 'inactive)
12655 org-log-note-effective-time))
12656 (cons "%T" (format-time-string
12657 (org-time-stamp-format 'long nil)
12658 org-log-note-effective-time))
12659 (cons "%d" (format-time-string
12660 (org-time-stamp-format nil 'inactive)
12661 org-log-note-effective-time))
12662 (cons "%D" (format-time-string
12663 (org-time-stamp-format nil nil)
12664 org-log-note-effective-time))
12665 (cons "%s" (if org-log-note-state
12666 (concat "\"" org-log-note-state "\"")
12667 ""))
12668 (cons "%S" (if org-log-note-previous-state
12669 (concat "\"" org-log-note-previous-state "\"")
12670 "\"\"")))))
12671 (if lines (setq note (concat note " \\\\")))
12672 (push note lines))
12673 (when (or current-prefix-arg org-note-abort)
12674 (when org-log-into-drawer
12675 (org-remove-empty-drawer-at
12676 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12677 org-log-note-marker))
12678 (setq lines nil))
12679 (when lines
12680 (with-current-buffer (marker-buffer org-log-note-marker)
12681 (save-excursion
12682 (goto-char org-log-note-marker)
12683 (move-marker org-log-note-marker nil)
12684 (end-of-line 1)
12685 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12686 (setq ind (save-excursion
12687 (if (ignore-errors (goto-char (org-in-item-p)))
12688 (let ((struct (org-list-struct)))
12689 (org-list-get-ind
12690 (org-list-get-top-point struct) struct))
12691 (skip-chars-backward " \r\t\n")
12692 (cond
12693 ((and (org-at-heading-p)
12694 org-adapt-indentation)
12695 (1+ (org-current-level)))
12696 ((org-at-heading-p) 0)
12697 (t (org-get-indentation))))))
12698 (setq bul (org-list-bullet-string "-"))
12699 (org-indent-line-to ind)
12700 (insert bul (pop lines))
12701 (let ((ind-body (+ (length bul) ind)))
12702 (while lines
12703 (insert "\n")
12704 (org-indent-line-to ind-body)
12705 (insert (pop lines))))
12706 (message "Note stored")
12707 (org-back-to-heading t)
12708 (org-cycle-hide-drawers 'children)))))
12709 (set-window-configuration org-log-note-window-configuration)
12710 (with-current-buffer (marker-buffer org-log-note-return-to)
12711 (goto-char org-log-note-return-to))
12712 (move-marker org-log-note-return-to nil)
12713 (and org-log-post-message (message "%s" org-log-post-message)))
12715 (defun org-remove-empty-drawer-at (drawer pos)
12716 "Remove an empty drawer DRAWER at position POS.
12717 POS may also be a marker."
12718 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12719 (save-excursion
12720 (save-restriction
12721 (widen)
12722 (goto-char pos)
12723 (if (org-in-regexp
12724 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12725 (replace-match ""))))))
12727 (defvar org-ts-type nil)
12728 (defun org-sparse-tree (&optional arg type)
12729 "Create a sparse tree, prompt for the details.
12730 This command can create sparse trees. You first need to select the type
12731 of match used to create the tree:
12733 t Show all TODO entries.
12734 T Show entries with a specific TODO keyword.
12735 m Show entries selected by a tags/property match.
12736 p Enter a property name and its value (both with completion on existing
12737 names/values) and show entries with that property.
12738 r Show entries matching a regular expression (`/' can be used as well).
12739 b Show deadlines and scheduled items before a date.
12740 a Show deadlines and scheduled items after a date.
12741 d Show deadlines due within `org-deadline-warning-days'.
12742 D Show deadlines and scheduled items between a date range."
12743 (interactive "P")
12744 (let (ans kwd value ts-type)
12745 (setq type (or type org-sparse-tree-default-date-type))
12746 (setq org-ts-type type)
12747 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12748 (cond ((eq type 'all) "all timestamps")
12749 ((eq type 'scheduled) "only scheduled")
12750 ((eq type 'deadline) "only deadline")
12751 ((eq type 'active) "only active timestamps")
12752 ((eq type 'inactive) "only inactive timestamps")
12753 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12754 (t "scheduled/deadline")))
12755 (setq ans (read-char-exclusive))
12756 (cond
12757 ((equal ans ?c)
12758 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12759 ((equal ans ?d)
12760 (call-interactively 'org-check-deadlines))
12761 ((equal ans ?b)
12762 (call-interactively 'org-check-before-date))
12763 ((equal ans ?a)
12764 (call-interactively 'org-check-after-date))
12765 ((equal ans ?D)
12766 (call-interactively 'org-check-dates-range))
12767 ((equal ans ?t)
12768 (call-interactively 'org-show-todo-tree))
12769 ((equal ans ?T)
12770 (org-show-todo-tree '(4)))
12771 ((member ans '(?T ?m))
12772 (call-interactively 'org-match-sparse-tree))
12773 ((member ans '(?p ?P))
12774 (setq kwd (org-icompleting-read "Property: "
12775 (mapcar 'list (org-buffer-property-keys))))
12776 (setq value (org-icompleting-read "Value: "
12777 (mapcar 'list (org-property-values kwd))))
12778 (unless (string-match "\\`{.*}\\'" value)
12779 (setq value (concat "\"" value "\"")))
12780 (org-match-sparse-tree arg (concat kwd "=" value)))
12781 ((member ans '(?r ?R ?/))
12782 (call-interactively 'org-occur))
12783 (t (error "No such sparse tree command \"%c\"" ans)))))
12785 (defvar org-occur-highlights nil
12786 "List of overlays used for occur matches.")
12787 (make-variable-buffer-local 'org-occur-highlights)
12788 (defvar org-occur-parameters nil
12789 "Parameters of the active org-occur calls.
12790 This is a list, each call to org-occur pushes as cons cell,
12791 containing the regular expression and the callback, onto the list.
12792 The list can contain several entries if `org-occur' has been called
12793 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12794 will only contain one set of parameters. When the highlights are
12795 removed (for example with `C-c C-c', or with the next edit (depending
12796 on `org-remove-highlights-with-change'), this variable is emptied
12797 as well.")
12798 (make-variable-buffer-local 'org-occur-parameters)
12800 (defun org-occur (regexp &optional keep-previous callback)
12801 "Make a compact tree which shows all matches of REGEXP.
12802 The tree will show the lines where the regexp matches, and all higher
12803 headlines above the match. It will also show the heading after the match,
12804 to make sure editing the matching entry is easy.
12805 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12806 call to `org-occur' will be kept, to allow stacking of calls to this
12807 command.
12808 If CALLBACK is non-nil, it is a function which is called to confirm
12809 that the match should indeed be shown."
12810 (interactive "sRegexp: \nP")
12811 (when (equal regexp "")
12812 (error "Regexp cannot be empty"))
12813 (unless keep-previous
12814 (org-remove-occur-highlights nil nil t))
12815 (push (cons regexp callback) org-occur-parameters)
12816 (let ((cnt 0))
12817 (save-excursion
12818 (goto-char (point-min))
12819 (if (or (not keep-previous) ; do not want to keep
12820 (not org-occur-highlights)) ; no previous matches
12821 ;; hide everything
12822 (org-overview))
12823 (while (re-search-forward regexp nil t)
12824 (when (or (not callback)
12825 (save-match-data (funcall callback)))
12826 (setq cnt (1+ cnt))
12827 (when org-highlight-sparse-tree-matches
12828 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12829 (org-show-context 'occur-tree))))
12830 (when org-remove-highlights-with-change
12831 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12832 nil 'local))
12833 (unless org-sparse-tree-open-archived-trees
12834 (org-hide-archived-subtrees (point-min) (point-max)))
12835 (run-hooks 'org-occur-hook)
12836 (if (org-called-interactively-p 'interactive)
12837 (message "%d match(es) for regexp %s" cnt regexp))
12838 cnt))
12840 (defun org-occur-next-match (&optional n reset)
12841 "Function for `next-error-function' to find sparse tree matches.
12842 N is the number of matches to move, when negative move backwards.
12843 RESET is entirely ignored - this function always goes back to the
12844 starting point when no match is found."
12845 (let* ((limit (if (< n 0) (point-min) (point-max)))
12846 (search-func (if (< n 0)
12847 'previous-single-char-property-change
12848 'next-single-char-property-change))
12849 (n (abs n))
12850 (pos (point))
12852 (catch 'exit
12853 (while (setq p1 (funcall search-func (point) 'org-type))
12854 (when (equal p1 limit)
12855 (goto-char pos)
12856 (error "No more matches"))
12857 (when (equal (get-char-property p1 'org-type) 'org-occur)
12858 (setq n (1- n))
12859 (when (= n 0)
12860 (goto-char p1)
12861 (throw 'exit (point))))
12862 (goto-char p1))
12863 (goto-char p1)
12864 (error "No more matches"))))
12866 (defun org-show-context (&optional key)
12867 "Make sure point and context are visible.
12868 How much context is shown depends upon the variables
12869 `org-show-hierarchy-above', `org-show-following-heading',
12870 `org-show-entry-below' and `org-show-siblings'."
12871 (let ((heading-p (org-at-heading-p t))
12872 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12873 (following-p (org-get-alist-option org-show-following-heading key))
12874 (entry-p (org-get-alist-option org-show-entry-below key))
12875 (siblings-p (org-get-alist-option org-show-siblings key)))
12876 (catch 'exit
12877 ;; Show heading or entry text
12878 (if (and heading-p (not entry-p))
12879 (org-flag-heading nil) ; only show the heading
12880 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12881 (org-show-hidden-entry))) ; show entire entry
12882 (when following-p
12883 ;; Show next sibling, or heading below text
12884 (save-excursion
12885 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12886 (org-flag-heading nil))))
12887 (when siblings-p (org-show-siblings))
12888 (when hierarchy-p
12889 ;; show all higher headings, possibly with siblings
12890 (save-excursion
12891 (while (and (condition-case nil
12892 (progn (org-up-heading-all 1) t)
12893 (error nil))
12894 (not (bobp)))
12895 (org-flag-heading nil)
12896 (when siblings-p (org-show-siblings))))))))
12898 (defvar org-reveal-start-hook nil
12899 "Hook run before revealing a location.")
12901 (defun org-reveal (&optional siblings)
12902 "Show current entry, hierarchy above it, and the following headline.
12903 This can be used to show a consistent set of context around locations
12904 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12905 not t for the search context.
12907 With optional argument SIBLINGS, on each level of the hierarchy all
12908 siblings are shown. This repairs the tree structure to what it would
12909 look like when opened with hierarchical calls to `org-cycle'.
12910 With double optional argument \\[universal-argument] \\[universal-argument], \
12911 go to the parent and show the
12912 entire tree."
12913 (interactive "P")
12914 (run-hooks 'org-reveal-start-hook)
12915 (let ((org-show-hierarchy-above t)
12916 (org-show-following-heading t)
12917 (org-show-siblings (if siblings t org-show-siblings)))
12918 (org-show-context nil))
12919 (when (equal siblings '(16))
12920 (save-excursion
12921 (when (org-up-heading-safe)
12922 (org-show-subtree)
12923 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12925 (defun org-highlight-new-match (beg end)
12926 "Highlight from BEG to END and mark the highlight is an occur headline."
12927 (let ((ov (make-overlay beg end)))
12928 (overlay-put ov 'face 'secondary-selection)
12929 (overlay-put ov 'org-type 'org-occur)
12930 (push ov org-occur-highlights)))
12932 (defun org-remove-occur-highlights (&optional beg end noremove)
12933 "Remove the occur highlights from the buffer.
12934 BEG and END are ignored. If NOREMOVE is nil, remove this function
12935 from the `before-change-functions' in the current buffer."
12936 (interactive)
12937 (unless org-inhibit-highlight-removal
12938 (mapc 'delete-overlay org-occur-highlights)
12939 (setq org-occur-highlights nil)
12940 (setq org-occur-parameters nil)
12941 (unless noremove
12942 (remove-hook 'before-change-functions
12943 'org-remove-occur-highlights 'local))))
12945 ;;;; Priorities
12947 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12948 "Regular expression matching the priority indicator.")
12950 (defvar org-remove-priority-next-time nil)
12952 (defun org-priority-up ()
12953 "Increase the priority of the current item."
12954 (interactive)
12955 (org-priority 'up))
12957 (defun org-priority-down ()
12958 "Decrease the priority of the current item."
12959 (interactive)
12960 (org-priority 'down))
12962 (defun org-priority (&optional action show)
12963 "Change the priority of an item.
12964 ACTION can be `set', `up', `down', or a character."
12965 (interactive "P")
12966 (if (equal action '(4))
12967 (org-show-priority)
12968 (unless org-enable-priority-commands
12969 (error "Priority commands are disabled"))
12970 (setq action (or action 'set))
12971 (let (current new news have remove)
12972 (save-excursion
12973 (org-back-to-heading t)
12974 (if (looking-at org-priority-regexp)
12975 (setq current (string-to-char (match-string 2))
12976 have t))
12977 (cond
12978 ((eq action 'remove)
12979 (setq remove t new ?\ ))
12980 ((or (eq action 'set)
12981 (if (featurep 'xemacs) (characterp action) (integerp action)))
12982 (if (not (eq action 'set))
12983 (setq new action)
12984 (message "Priority %c-%c, SPC to remove: "
12985 org-highest-priority org-lowest-priority)
12986 (save-match-data
12987 (setq new (read-char-exclusive))))
12988 (if (and (= (upcase org-highest-priority) org-highest-priority)
12989 (= (upcase org-lowest-priority) org-lowest-priority))
12990 (setq new (upcase new)))
12991 (cond ((equal new ?\ ) (setq remove t))
12992 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12993 (error "Priority must be between `%c' and `%c'"
12994 org-highest-priority org-lowest-priority))))
12995 ((eq action 'up)
12996 (setq new (if have
12997 (1- current) ; normal cycling
12998 ;; last priority was empty
12999 (if (eq last-command this-command)
13000 org-lowest-priority ; wrap around empty to lowest
13001 ;; default
13002 (if org-priority-start-cycle-with-default
13003 org-default-priority
13004 (1- org-default-priority))))))
13005 ((eq action 'down)
13006 (setq new (if have
13007 (1+ current) ; normal cycling
13008 ;; last priority was empty
13009 (if (eq last-command this-command)
13010 org-highest-priority ; wrap around empty to highest
13011 ;; default
13012 (if org-priority-start-cycle-with-default
13013 org-default-priority
13014 (1+ org-default-priority))))))
13015 (t (error "Invalid action")))
13016 (if (or (< (upcase new) org-highest-priority)
13017 (> (upcase new) org-lowest-priority))
13018 (if (and (memq action '(up down))
13019 (not have) (not (eq last-command this-command)))
13020 ;; `new' is from default priority
13021 (error
13022 "The default can not be set, see `org-default-priority' why")
13023 ;; normal cycling: `new' is beyond highest/lowest priority
13024 ;; and is wrapped around to the empty priority
13025 (setq remove t)))
13026 (setq news (format "%c" new))
13027 (if have
13028 (if remove
13029 (replace-match "" t t nil 1)
13030 (replace-match news t t nil 2))
13031 (if remove
13032 (error "No priority cookie found in line")
13033 (let ((case-fold-search nil))
13034 (looking-at org-todo-line-regexp))
13035 (if (match-end 2)
13036 (progn
13037 (goto-char (match-end 2))
13038 (insert " [#" news "]"))
13039 (goto-char (match-beginning 3))
13040 (insert "[#" news "] "))))
13041 (org-preserve-lc (org-set-tags nil 'align)))
13042 (if remove
13043 (message "Priority removed")
13044 (message "Priority of current item set to %s" news)))))
13046 (defun org-show-priority ()
13047 "Show the priority of the current item.
13048 This priority is composed of the main priority given with the [#A] cookies,
13049 and by additional input from the age of a schedules or deadline entry."
13050 (interactive)
13051 (let ((pri (if (eq major-mode 'org-agenda-mode)
13052 (org-get-at-bol 'priority)
13053 (save-excursion
13054 (save-match-data
13055 (beginning-of-line)
13056 (and (looking-at org-heading-regexp)
13057 (org-get-priority (match-string 0))))))))
13058 (message "Priority is %d" (if pri pri -1000))))
13060 (defun org-get-priority (s)
13061 "Find priority cookie and return priority."
13062 (if (functionp org-get-priority-function)
13063 (funcall org-get-priority-function)
13064 (save-match-data
13065 (if (not (string-match org-priority-regexp s))
13066 (* 1000 (- org-lowest-priority org-default-priority))
13067 (* 1000 (- org-lowest-priority
13068 (string-to-char (match-string 2 s))))))))
13070 ;;;; Tags
13072 (defvar org-agenda-archives-mode)
13073 (defvar org-map-continue-from nil
13074 "Position from where mapping should continue.
13075 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13077 (defvar org-scanner-tags nil
13078 "The current tag list while the tags scanner is running.")
13079 (defvar org-trust-scanner-tags nil
13080 "Should `org-get-tags-at' use the tags for the scanner.
13081 This is for internal dynamical scoping only.
13082 When this is non-nil, the function `org-get-tags-at' will return the value
13083 of `org-scanner-tags' instead of building the list by itself. This
13084 can lead to large speed-ups when the tags scanner is used in a file with
13085 many entries, and when the list of tags is retrieved, for example to
13086 obtain a list of properties. Building the tags list for each entry in such
13087 a file becomes an N^2 operation - but with this variable set, it scales
13088 as N.")
13090 (defun org-scan-tags (action matcher todo-only &optional start-level)
13091 "Scan headline tags with inheritance and produce output ACTION.
13093 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13094 or `agenda' to produce an entry list for an agenda view. It can also be
13095 a Lisp form or a function that should be called at each matched headline, in
13096 this case the return value is a list of all return values from these calls.
13098 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13099 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13100 only lines with a not-done TODO keyword are included in the output.
13101 This should be the same variable that was scoped into
13102 and set by `org-make-tags-matcher' when it constructed MATCHER.
13104 START-LEVEL can be a string with asterisks, reducing the scope to
13105 headlines matching this string."
13106 (require 'org-agenda)
13107 (let* ((re (concat "^"
13108 (if start-level
13109 ;; Get the correct level to match
13110 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13111 org-outline-regexp)
13112 " *\\(\\<\\("
13113 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13114 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13115 (props (list 'face 'default
13116 'done-face 'org-agenda-done
13117 'undone-face 'default
13118 'mouse-face 'highlight
13119 'org-not-done-regexp org-not-done-regexp
13120 'org-todo-regexp org-todo-regexp
13121 'org-complex-heading-regexp org-complex-heading-regexp
13122 'help-echo
13123 (format "mouse-2 or RET jump to org file %s"
13124 (abbreviate-file-name
13125 (or (buffer-file-name (buffer-base-buffer))
13126 (buffer-name (buffer-base-buffer)))))))
13127 (case-fold-search nil)
13128 (org-map-continue-from nil)
13129 lspos tags tags-list
13130 (tags-alist (list (cons 0 org-file-tags)))
13131 (llast 0) rtn rtn1 level category i txt
13132 todo marker entry priority)
13133 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13134 (setq action (list 'lambda nil action)))
13135 (save-excursion
13136 (goto-char (point-min))
13137 (when (eq action 'sparse-tree)
13138 (org-overview)
13139 (org-remove-occur-highlights))
13140 (while (re-search-forward re nil t)
13141 (setq org-map-continue-from nil)
13142 (catch :skip
13143 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13144 tags (if (match-end 4) (org-match-string-no-properties 4)))
13145 (goto-char (setq lspos (match-beginning 0)))
13146 (setq level (org-reduced-level (org-outline-level))
13147 category (org-get-category))
13148 (setq i llast llast level)
13149 ;; remove tag lists from same and sublevels
13150 (while (>= i level)
13151 (when (setq entry (assoc i tags-alist))
13152 (setq tags-alist (delete entry tags-alist)))
13153 (setq i (1- i)))
13154 ;; add the next tags
13155 (when tags
13156 (setq tags (org-split-string tags ":")
13157 tags-alist
13158 (cons (cons level tags) tags-alist)))
13159 ;; compile tags for current headline
13160 (setq tags-list
13161 (if org-use-tag-inheritance
13162 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13163 tags)
13164 org-scanner-tags tags-list)
13165 (when org-use-tag-inheritance
13166 (setcdr (car tags-alist)
13167 (mapcar (lambda (x)
13168 (setq x (copy-sequence x))
13169 (org-add-prop-inherited x))
13170 (cdar tags-alist))))
13171 (when (and tags org-use-tag-inheritance
13172 (or (not (eq t org-use-tag-inheritance))
13173 org-tags-exclude-from-inheritance))
13174 ;; selective inheritance, remove uninherited ones
13175 (setcdr (car tags-alist)
13176 (org-remove-uninherited-tags (cdar tags-alist))))
13177 (when (and
13179 ;; eval matcher only when the todo condition is OK
13180 (and (or (not todo-only) (member todo org-not-done-keywords))
13181 (let ((case-fold-search t) (org-trust-scanner-tags t))
13182 (eval matcher)))
13184 ;; Call the skipper, but return t if it does not skip,
13185 ;; so that the `and' form continues evaluating
13186 (progn
13187 (unless (eq action 'sparse-tree) (org-agenda-skip))
13190 ;; Check if timestamps are deselecting this entry
13191 (or (not todo-only)
13192 (and (member todo org-not-done-keywords)
13193 (or (not org-agenda-tags-todo-honor-ignore-options)
13194 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13196 ;; Extra check for the archive tag
13197 ;; FIXME: Does the skipper already do this????
13199 (not (member org-archive-tag tags-list))
13200 ;; we have an archive tag, should we use this anyway?
13201 (or (not org-agenda-skip-archived-trees)
13202 (and (eq action 'agenda) org-agenda-archives-mode))))
13204 ;; select this headline
13205 (cond
13206 ((eq action 'sparse-tree)
13207 (and org-highlight-sparse-tree-matches
13208 (org-get-heading) (match-end 0)
13209 (org-highlight-new-match
13210 (match-beginning 1) (match-end 1)))
13211 (org-show-context 'tags-tree))
13212 ((eq action 'agenda)
13213 (setq txt (org-agenda-format-item
13215 (concat
13216 (if (eq org-tags-match-list-sublevels 'indented)
13217 (make-string (1- level) ?.) "")
13218 (org-get-heading))
13219 level category
13220 tags-list)
13221 priority (org-get-priority txt))
13222 (goto-char lspos)
13223 (setq marker (org-agenda-new-marker))
13224 (org-add-props txt props
13225 'org-marker marker 'org-hd-marker marker 'org-category category
13226 'todo-state todo
13227 'priority priority 'type "tagsmatch")
13228 (push txt rtn))
13229 ((functionp action)
13230 (setq org-map-continue-from nil)
13231 (save-excursion
13232 (setq rtn1 (funcall action))
13233 (push rtn1 rtn)))
13234 (t (error "Invalid action")))
13236 ;; if we are to skip sublevels, jump to end of subtree
13237 (unless org-tags-match-list-sublevels
13238 (org-end-of-subtree t)
13239 (backward-char 1))))
13240 ;; Get the correct position from where to continue
13241 (if org-map-continue-from
13242 (goto-char org-map-continue-from)
13243 (and (= (point) lspos) (end-of-line 1)))))
13244 (when (and (eq action 'sparse-tree)
13245 (not org-sparse-tree-open-archived-trees))
13246 (org-hide-archived-subtrees (point-min) (point-max)))
13247 (nreverse rtn)))
13249 (defun org-remove-uninherited-tags (tags)
13250 "Remove all tags that are not inherited from the list TAGS."
13251 (cond
13252 ((eq org-use-tag-inheritance t)
13253 (if org-tags-exclude-from-inheritance
13254 (org-delete-all org-tags-exclude-from-inheritance tags)
13255 tags))
13256 ((not org-use-tag-inheritance) nil)
13257 ((stringp org-use-tag-inheritance)
13258 (delq nil (mapcar
13259 (lambda (x)
13260 (if (and (string-match org-use-tag-inheritance x)
13261 (not (member x org-tags-exclude-from-inheritance)))
13262 x nil))
13263 tags)))
13264 ((listp org-use-tag-inheritance)
13265 (delq nil (mapcar
13266 (lambda (x)
13267 (if (member x org-use-tag-inheritance) x nil))
13268 tags)))))
13270 (defun org-match-sparse-tree (&optional todo-only match)
13271 "Create a sparse tree according to tags string MATCH.
13272 MATCH can contain positive and negative selection of tags, like
13273 \"+WORK+URGENT-WITHBOSS\".
13274 If optional argument TODO-ONLY is non-nil, only select lines that are
13275 also TODO lines."
13276 (interactive "P")
13277 (org-agenda-prepare-buffers (list (current-buffer)))
13278 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13280 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13282 (defvar org-cached-props nil)
13283 (defun org-cached-entry-get (pom property)
13284 (if (or (eq t org-use-property-inheritance)
13285 (and (stringp org-use-property-inheritance)
13286 (string-match org-use-property-inheritance property))
13287 (and (listp org-use-property-inheritance)
13288 (member property org-use-property-inheritance)))
13289 ;; Caching is not possible, check it directly
13290 (org-entry-get pom property 'inherit)
13291 ;; Get all properties, so that we can do complicated checks easily
13292 (cdr (assoc property (or org-cached-props
13293 (setq org-cached-props
13294 (org-entry-properties pom)))))))
13296 (defun org-global-tags-completion-table (&optional files)
13297 "Return the list of all tags in all agenda buffer/files.
13298 Optional FILES argument is a list of files which can be used
13299 instead of the agenda files."
13300 (save-excursion
13301 (org-uniquify
13302 (delq nil
13303 (apply 'append
13304 (mapcar
13305 (lambda (file)
13306 (set-buffer (find-file-noselect file))
13307 (append (org-get-buffer-tags)
13308 (mapcar (lambda (x) (if (stringp (car-safe x))
13309 (list (car-safe x)) nil))
13310 org-tag-alist)))
13311 (if (and files (car files))
13312 files
13313 (org-agenda-files))))))))
13315 (defun org-make-tags-matcher (match)
13316 "Create the TAGS/TODO matcher form for the selection string MATCH.
13318 The variable `todo-only' is scoped dynamically into this function.
13319 It will be set to t if the matcher restricts matching to TODO entries,
13320 otherwise will not be touched.
13322 Returns a cons of the selection string MATCH and the constructed
13323 lisp form implementing the matcher. The matcher is to be evaluated
13324 at an Org entry, with point on the headline, and returns t if the
13325 entry matches the selection string MATCH. The returned lisp form
13326 references two variables with information about the entry, which
13327 must be bound around the form's evaluation: todo, the TODO keyword
13328 at the entry (or nil of none); and tags-list, the list of all tags
13329 at the entry including inherited ones. Additionally, the category
13330 of the entry (if any) must be specified as the text property
13331 'org-category on the headline.
13333 See also `org-scan-tags'.
13335 (declare (special todo-only))
13336 (unless (boundp 'todo-only)
13337 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13338 (unless match
13339 ;; Get a new match request, with completion
13340 (let ((org-last-tags-completion-table
13341 (org-global-tags-completion-table)))
13342 (setq match (org-completing-read-no-i
13343 "Match: " 'org-tags-completion-function nil nil nil
13344 'org-tags-history))))
13346 ;; Parse the string and create a lisp form
13347 (let ((match0 match)
13348 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13349 minus tag mm
13350 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13351 orterms term orlist re-p str-p level-p level-op time-p
13352 prop-p pn pv po gv rest)
13353 (if (string-match "/+" match)
13354 ;; match contains also a todo-matching request
13355 (progn
13356 (setq tagsmatch (substring match 0 (match-beginning 0))
13357 todomatch (substring match (match-end 0)))
13358 (if (string-match "^!" todomatch)
13359 (setq todo-only t todomatch (substring todomatch 1)))
13360 (if (string-match "^\\s-*$" todomatch)
13361 (setq todomatch nil)))
13362 ;; only matching tags
13363 (setq tagsmatch match todomatch nil))
13365 ;; Make the tags matcher
13366 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13367 (setq tagsmatcher t)
13368 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13369 (while (setq term (pop orterms))
13370 (while (and (equal (substring term -1) "\\") orterms)
13371 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13372 (while (string-match re term)
13373 (setq rest (substring term (match-end 0))
13374 minus (and (match-end 1)
13375 (equal (match-string 1 term) "-"))
13376 tag (save-match-data (replace-regexp-in-string
13377 "\\\\-" "-"
13378 (match-string 2 term)))
13379 re-p (equal (string-to-char tag) ?{)
13380 level-p (match-end 4)
13381 prop-p (match-end 5)
13382 mm (cond
13383 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13384 (level-p
13385 (setq level-op (org-op-to-function (match-string 3 term)))
13386 `(,level-op level ,(string-to-number
13387 (match-string 4 term))))
13388 (prop-p
13389 (setq pn (match-string 5 term)
13390 po (match-string 6 term)
13391 pv (match-string 7 term)
13392 re-p (equal (string-to-char pv) ?{)
13393 str-p (equal (string-to-char pv) ?\")
13394 time-p (save-match-data
13395 (string-match "^\"[[<].*[]>]\"$" pv))
13396 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13397 (if time-p (setq pv (org-matcher-time pv)))
13398 (setq po (org-op-to-function po (if time-p 'time str-p)))
13399 (cond
13400 ((equal pn "CATEGORY")
13401 (setq gv '(get-text-property (point) 'org-category)))
13402 ((equal pn "TODO")
13403 (setq gv 'todo))
13405 (setq gv `(org-cached-entry-get nil ,pn))))
13406 (if re-p
13407 (if (eq po 'org<>)
13408 `(not (string-match ,pv (or ,gv "")))
13409 `(string-match ,pv (or ,gv "")))
13410 (if str-p
13411 `(,po (or ,gv "") ,pv)
13412 `(,po (string-to-number (or ,gv ""))
13413 ,(string-to-number pv) ))))
13414 (t `(member ,tag tags-list)))
13415 mm (if minus (list 'not mm) mm)
13416 term rest)
13417 (push mm tagsmatcher))
13418 (push (if (> (length tagsmatcher) 1)
13419 (cons 'and tagsmatcher)
13420 (car tagsmatcher))
13421 orlist)
13422 (setq tagsmatcher nil))
13423 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13424 (setq tagsmatcher
13425 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13426 ;; Make the todo matcher
13427 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13428 (setq todomatcher t)
13429 (setq orterms (org-split-string todomatch "|") orlist nil)
13430 (while (setq term (pop orterms))
13431 (while (string-match re term)
13432 (setq minus (and (match-end 1)
13433 (equal (match-string 1 term) "-"))
13434 kwd (match-string 2 term)
13435 re-p (equal (string-to-char kwd) ?{)
13436 term (substring term (match-end 0))
13437 mm (if re-p
13438 `(string-match ,(substring kwd 1 -1) todo)
13439 (list 'equal 'todo kwd))
13440 mm (if minus (list 'not mm) mm))
13441 (push mm todomatcher))
13442 (push (if (> (length todomatcher) 1)
13443 (cons 'and todomatcher)
13444 (car todomatcher))
13445 orlist)
13446 (setq todomatcher nil))
13447 (setq todomatcher (if (> (length orlist) 1)
13448 (cons 'or orlist) (car orlist))))
13450 ;; Return the string and lisp forms of the matcher
13451 (setq matcher (if todomatcher
13452 (list 'and tagsmatcher todomatcher)
13453 tagsmatcher))
13454 (when todo-only
13455 (setq matcher (list 'and '(member todo org-not-done-keywords)
13456 matcher)))
13457 (cons match0 matcher)))
13459 (defun org-op-to-function (op &optional stringp)
13460 "Turn an operator into the appropriate function."
13461 (setq op
13462 (cond
13463 ((equal op "<" ) '(< string< org-time<))
13464 ((equal op ">" ) '(> org-string> org-time>))
13465 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13466 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13467 ((member op '("=" "==")) '(= string= org-time=))
13468 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13469 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13471 (defun org<> (a b) (not (= a b)))
13472 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13473 (defun org-string>= (a b) (not (string< a b)))
13474 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13475 (defun org-string<> (a b) (not (string= a b)))
13476 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13477 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13478 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13479 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13480 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13481 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13482 (defun org-2ft (s)
13483 "Convert S to a floating point time.
13484 If S is already a number, just return it. If it is a string, parse
13485 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13486 (cond
13487 ((numberp s) s)
13488 ((stringp s)
13489 (condition-case nil
13490 (float-time (apply 'encode-time (org-parse-time-string s)))
13491 (error 0.)))
13492 (t 0.)))
13494 (defun org-time-today ()
13495 "Time in seconds today at 0:00.
13496 Returns the float number of seconds since the beginning of the
13497 epoch to the beginning of today (00:00)."
13498 (float-time (apply 'encode-time
13499 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13501 (defun org-matcher-time (s)
13502 "Interpret a time comparison value."
13503 (save-match-data
13504 (cond
13505 ((string= s "<now>") (float-time))
13506 ((string= s "<today>") (org-time-today))
13507 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13508 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13509 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13510 (+ (org-time-today)
13511 (* (string-to-number (match-string 1 s))
13512 (cdr (assoc (match-string 2 s)
13513 '(("d" . 86400.0) ("w" . 604800.0)
13514 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13515 (t (org-2ft s)))))
13517 (defun org-match-any-p (re list)
13518 "Does re match any element of list?"
13519 (setq list (mapcar (lambda (x) (string-match re x)) list))
13520 (delq nil list))
13522 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13523 (defvar org-tags-overlay (make-overlay 1 1))
13524 (org-detach-overlay org-tags-overlay)
13526 (defun org-get-local-tags-at (&optional pos)
13527 "Get a list of tags defined in the current headline."
13528 (org-get-tags-at pos 'local))
13530 (defun org-get-local-tags ()
13531 "Get a list of tags defined in the current headline."
13532 (org-get-tags-at nil 'local))
13534 (defun org-get-tags-at (&optional pos local)
13535 "Get a list of all headline tags applicable at POS.
13536 POS defaults to point. If tags are inherited, the list contains
13537 the targets in the same sequence as the headlines appear, i.e.
13538 the tags of the current headline come last.
13539 When LOCAL is non-nil, only return tags from the current headline,
13540 ignore inherited ones."
13541 (interactive)
13542 (if (and org-trust-scanner-tags
13543 (or (not pos) (equal pos (point)))
13544 (not local))
13545 org-scanner-tags
13546 (let (tags ltags lastpos parent)
13547 (save-excursion
13548 (save-restriction
13549 (widen)
13550 (goto-char (or pos (point)))
13551 (save-match-data
13552 (catch 'done
13553 (condition-case nil
13554 (progn
13555 (org-back-to-heading t)
13556 (while (not (equal lastpos (point)))
13557 (setq lastpos (point))
13558 (when (looking-at
13559 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13560 (setq ltags (org-split-string
13561 (org-match-string-no-properties 1) ":"))
13562 (when parent
13563 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13564 (setq tags (append
13565 (if parent
13566 (org-remove-uninherited-tags ltags)
13567 ltags)
13568 tags)))
13569 (or org-use-tag-inheritance (throw 'done t))
13570 (if local (throw 'done t))
13571 (or (org-up-heading-safe) (error nil))
13572 (setq parent t)))
13573 (error nil)))))
13574 (if local
13575 tags
13576 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13578 (defun org-add-prop-inherited (s)
13579 (add-text-properties 0 (length s) '(inherited t) s)
13582 (defun org-toggle-tag (tag &optional onoff)
13583 "Toggle the tag TAG for the current line.
13584 If ONOFF is `on' or `off', don't toggle but set to this state."
13585 (let (res current)
13586 (save-excursion
13587 (org-back-to-heading t)
13588 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13589 (point-at-eol) t)
13590 (progn
13591 (setq current (match-string 1))
13592 (replace-match ""))
13593 (setq current ""))
13594 (setq current (nreverse (org-split-string current ":")))
13595 (cond
13596 ((eq onoff 'on)
13597 (setq res t)
13598 (or (member tag current) (push tag current)))
13599 ((eq onoff 'off)
13600 (or (not (member tag current)) (setq current (delete tag current))))
13601 (t (if (member tag current)
13602 (setq current (delete tag current))
13603 (setq res t)
13604 (push tag current))))
13605 (end-of-line 1)
13606 (if current
13607 (progn
13608 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13609 (org-set-tags nil t))
13610 (delete-horizontal-space))
13611 (run-hooks 'org-after-tags-change-hook))
13612 res))
13614 (defun org-align-tags-here (to-col)
13615 ;; Assumes that this is a headline
13616 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13617 (beginning-of-line 1)
13618 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13619 (< pos (match-beginning 2)))
13620 (progn
13621 (setq tags-l (- (match-end 2) (match-beginning 2)))
13622 (goto-char (match-beginning 1))
13623 (insert " ")
13624 (delete-region (point) (1+ (match-beginning 2)))
13625 (setq ncol (max (current-column)
13626 (1+ col)
13627 (if (> to-col 0)
13628 to-col
13629 (- (abs to-col) tags-l))))
13630 (setq p (point))
13631 (insert (make-string (- ncol (current-column)) ?\ ))
13632 (setq ncol (current-column))
13633 (when indent-tabs-mode (tabify p (point-at-eol)))
13634 (org-move-to-column (min ncol col) t))
13635 (goto-char pos))))
13637 (defun org-set-tags-command (&optional arg just-align)
13638 "Call the set-tags command for the current entry."
13639 (interactive "P")
13640 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13641 (org-set-tags arg just-align)
13642 (save-excursion
13643 (org-back-to-heading t)
13644 (org-set-tags arg just-align))))
13646 (defun org-set-tags-to (data)
13647 "Set the tags of the current entry to DATA, replacing the current tags.
13648 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13649 If DATA is nil or the empty string, any tags will be removed."
13650 (interactive "sTags: ")
13651 (setq data
13652 (cond
13653 ((eq data nil) "")
13654 ((equal data "") "")
13655 ((stringp data)
13656 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13657 ":"))
13658 ((listp data)
13659 (concat ":" (mapconcat 'identity data ":") ":"))))
13660 (when data
13661 (save-excursion
13662 (org-back-to-heading t)
13663 (when (looking-at org-complex-heading-regexp)
13664 (if (match-end 5)
13665 (progn
13666 (goto-char (match-beginning 5))
13667 (insert data)
13668 (delete-region (point) (point-at-eol))
13669 (org-set-tags nil 'align))
13670 (goto-char (point-at-eol))
13671 (insert " " data)
13672 (org-set-tags nil 'align)))
13673 (beginning-of-line 1)
13674 (if (looking-at ".*?\\([ \t]+\\)$")
13675 (delete-region (match-beginning 1) (match-end 1))))))
13677 (defun org-align-all-tags ()
13678 "Align the tags i all headings."
13679 (interactive)
13680 (save-excursion
13681 (or (ignore-errors (org-back-to-heading t))
13682 (outline-next-heading))
13683 (if (org-at-heading-p)
13684 (org-set-tags t)
13685 (message "No headings"))))
13687 (defvar org-indent-indentation-per-level)
13688 (defun org-set-tags (&optional arg just-align)
13689 "Set the tags for the current headline.
13690 With prefix ARG, realign all tags in headings in the current buffer."
13691 (interactive "P")
13692 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13693 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13694 'region-start-level 'region))
13695 org-loop-over-headlines-in-active-region)
13696 (org-map-entries
13697 ;; We don't use ARG and JUST-ALIGN here these args are not
13698 ;; useful when looping over headlines
13699 `(org-set-tags)
13700 org-loop-over-headlines-in-active-region
13701 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13702 (let* ((re org-outline-regexp-bol)
13703 (current (unless arg (org-get-tags-string)))
13704 (col (current-column))
13705 (org-setting-tags t)
13706 table current-tags inherited-tags ; computed below when needed
13707 tags p0 c0 c1 rpl di tc level)
13708 (if arg
13709 (save-excursion
13710 (goto-char (point-min))
13711 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13712 (while (re-search-forward re nil t)
13713 (org-set-tags nil t)
13714 (end-of-line 1)))
13715 (message "All tags realigned to column %d" org-tags-column))
13716 (if just-align
13717 (setq tags current)
13718 ;; Get a new set of tags from the user
13719 (save-excursion
13720 (setq table (append org-tag-persistent-alist
13721 (or org-tag-alist (org-get-buffer-tags))
13722 (and
13723 org-complete-tags-always-offer-all-agenda-tags
13724 (org-global-tags-completion-table
13725 (org-agenda-files))))
13726 org-last-tags-completion-table table
13727 current-tags (org-split-string current ":")
13728 inherited-tags (nreverse
13729 (nthcdr (length current-tags)
13730 (nreverse (org-get-tags-at))))
13731 tags
13732 (if (or (eq t org-use-fast-tag-selection)
13733 (and org-use-fast-tag-selection
13734 (delq nil (mapcar 'cdr table))))
13735 (org-fast-tag-selection
13736 current-tags inherited-tags table
13737 (if org-fast-tag-selection-include-todo
13738 org-todo-key-alist))
13739 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13740 (org-trim
13741 (org-icompleting-read "Tags: "
13742 'org-tags-completion-function
13743 nil nil current 'org-tags-history))))))
13744 (while (string-match "[-+&]+" tags)
13745 ;; No boolean logic, just a list
13746 (setq tags (replace-match ":" t t tags))))
13748 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13750 (if org-tags-sort-function
13751 (setq tags (mapconcat 'identity
13752 (sort (org-split-string
13753 tags (org-re "[^[:alnum:]_@#%]+"))
13754 org-tags-sort-function) ":")))
13756 (if (string-match "\\`[\t ]*\\'" tags)
13757 (setq tags "")
13758 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13759 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13761 ;; Insert new tags at the correct column
13762 (beginning-of-line 1)
13763 (setq level (or (and (looking-at org-outline-regexp)
13764 (- (match-end 0) (point) 1))
13766 (cond
13767 ((and (equal current "") (equal tags "")))
13768 ((re-search-forward
13769 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13770 (point-at-eol) t)
13771 (if (equal tags "")
13772 (setq rpl "")
13773 (goto-char (match-beginning 0))
13774 (setq c0 (current-column)
13775 ;; compute offset for the case of org-indent-mode active
13776 di (if org-indent-mode
13777 (* (1- org-indent-indentation-per-level) (1- level))
13779 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13780 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13781 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13782 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13783 (replace-match rpl t t)
13784 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13785 tags)
13786 (t (error "Tags alignment failed")))
13787 (org-move-to-column col)
13788 (unless just-align
13789 (run-hooks 'org-after-tags-change-hook))))))
13791 (defun org-change-tag-in-region (beg end tag off)
13792 "Add or remove TAG for each entry in the region.
13793 This works in the agenda, and also in an org-mode buffer."
13794 (interactive
13795 (list (region-beginning) (region-end)
13796 (let ((org-last-tags-completion-table
13797 (if (derived-mode-p 'org-mode)
13798 (org-get-buffer-tags)
13799 (org-global-tags-completion-table))))
13800 (org-icompleting-read
13801 "Tag: " 'org-tags-completion-function nil nil nil
13802 'org-tags-history))
13803 (progn
13804 (message "[s]et or [r]emove? ")
13805 (equal (read-char-exclusive) ?r))))
13806 (if (fboundp 'deactivate-mark) (deactivate-mark))
13807 (let ((agendap (equal major-mode 'org-agenda-mode))
13808 l1 l2 m buf pos newhead (cnt 0))
13809 (goto-char end)
13810 (setq l2 (1- (org-current-line)))
13811 (goto-char beg)
13812 (setq l1 (org-current-line))
13813 (loop for l from l1 to l2 do
13814 (org-goto-line l)
13815 (setq m (get-text-property (point) 'org-hd-marker))
13816 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13817 (and agendap m))
13818 (setq buf (if agendap (marker-buffer m) (current-buffer))
13819 pos (if agendap m (point)))
13820 (with-current-buffer buf
13821 (save-excursion
13822 (save-restriction
13823 (goto-char pos)
13824 (setq cnt (1+ cnt))
13825 (org-toggle-tag tag (if off 'off 'on))
13826 (setq newhead (org-get-heading)))))
13827 (and agendap (org-agenda-change-all-lines newhead m))))
13828 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13830 (defun org-tags-completion-function (string predicate &optional flag)
13831 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13832 (confirm (lambda (x) (stringp (car x)))))
13833 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13834 (setq s1 (match-string 1 string)
13835 s2 (match-string 2 string))
13836 (setq s1 "" s2 string))
13837 (cond
13838 ((eq flag nil)
13839 ;; try completion
13840 (setq rtn (try-completion s2 ctable confirm))
13841 (if (stringp rtn)
13842 (setq rtn
13843 (concat s1 s2 (substring rtn (length s2))
13844 (if (and org-add-colon-after-tag-completion
13845 (assoc rtn ctable))
13846 ":" ""))))
13847 rtn)
13848 ((eq flag t)
13849 ;; all-completions
13850 (all-completions s2 ctable confirm)
13852 ((eq flag 'lambda)
13853 ;; exact match?
13854 (assoc s2 ctable)))
13857 (defun org-fast-tag-insert (kwd tags face &optional end)
13858 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13859 (insert (format "%-12s" (concat kwd ":"))
13860 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13861 (or end "")))
13863 (defun org-fast-tag-show-exit (flag)
13864 (save-excursion
13865 (org-goto-line 3)
13866 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13867 (replace-match ""))
13868 (when flag
13869 (end-of-line 1)
13870 (org-move-to-column (- (window-width) 19) t)
13871 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13873 (defun org-set-current-tags-overlay (current prefix)
13874 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13875 (if (featurep 'xemacs)
13876 (org-overlay-display org-tags-overlay (concat prefix s)
13877 'secondary-selection)
13878 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13879 (org-overlay-display org-tags-overlay (concat prefix s)))))
13881 (defvar org-last-tag-selection-key nil)
13882 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13883 "Fast tag selection with single keys.
13884 CURRENT is the current list of tags in the headline, INHERITED is the
13885 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13886 possibly with grouping information. TODO-TABLE is a similar table with
13887 TODO keywords, should these have keys assigned to them.
13888 If the keys are nil, a-z are automatically assigned.
13889 Returns the new tags string, or nil to not change the current settings."
13890 (let* ((fulltable (append table todo-table))
13891 (maxlen (apply 'max (mapcar
13892 (lambda (x)
13893 (if (stringp (car x)) (string-width (car x)) 0))
13894 fulltable)))
13895 (buf (current-buffer))
13896 (expert (eq org-fast-tag-selection-single-key 'expert))
13897 (buffer-tags nil)
13898 (fwidth (+ maxlen 3 1 3))
13899 (ncol (/ (- (window-width) 4) fwidth))
13900 (i-face 'org-done)
13901 (c-face 'org-todo)
13902 tg cnt e c char c1 c2 ntable tbl rtn
13903 ov-start ov-end ov-prefix
13904 (exit-after-next org-fast-tag-selection-single-key)
13905 (done-keywords org-done-keywords)
13906 groups ingroup)
13907 (save-excursion
13908 (beginning-of-line 1)
13909 (if (looking-at
13910 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13911 (setq ov-start (match-beginning 1)
13912 ov-end (match-end 1)
13913 ov-prefix "")
13914 (setq ov-start (1- (point-at-eol))
13915 ov-end (1+ ov-start))
13916 (skip-chars-forward "^\n\r")
13917 (setq ov-prefix
13918 (concat
13919 (buffer-substring (1- (point)) (point))
13920 (if (> (current-column) org-tags-column)
13922 (make-string (- org-tags-column (current-column)) ?\ ))))))
13923 (move-overlay org-tags-overlay ov-start ov-end)
13924 (save-window-excursion
13925 (if expert
13926 (set-buffer (get-buffer-create " *Org tags*"))
13927 (delete-other-windows)
13928 (split-window-vertically)
13929 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13930 (erase-buffer)
13931 (org-set-local 'org-done-keywords done-keywords)
13932 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13933 (org-fast-tag-insert "Current" current c-face "\n\n")
13934 (org-fast-tag-show-exit exit-after-next)
13935 (org-set-current-tags-overlay current ov-prefix)
13936 (setq tbl fulltable char ?a cnt 0)
13937 (while (setq e (pop tbl))
13938 (cond
13939 ((equal (car e) :startgroup)
13940 (push '() groups) (setq ingroup t)
13941 (when (not (= cnt 0))
13942 (setq cnt 0)
13943 (insert "\n"))
13944 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13945 ((equal (car e) :endgroup)
13946 (setq ingroup nil cnt 0)
13947 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13948 ((equal e '(:newline))
13949 (when (not (= cnt 0))
13950 (setq cnt 0)
13951 (insert "\n")
13952 (setq e (car tbl))
13953 (while (equal (car tbl) '(:newline))
13954 (insert "\n")
13955 (setq tbl (cdr tbl)))))
13957 (setq tg (copy-sequence (car e)) c2 nil)
13958 (if (cdr e)
13959 (setq c (cdr e))
13960 ;; automatically assign a character.
13961 (setq c1 (string-to-char
13962 (downcase (substring
13963 tg (if (= (string-to-char tg) ?@) 1 0)))))
13964 (if (or (rassoc c1 ntable) (rassoc c1 table))
13965 (while (or (rassoc char ntable) (rassoc char table))
13966 (setq char (1+ char)))
13967 (setq c2 c1))
13968 (setq c (or c2 char)))
13969 (if ingroup (push tg (car groups)))
13970 (setq tg (org-add-props tg nil 'face
13971 (cond
13972 ((not (assoc tg table))
13973 (org-get-todo-face tg))
13974 ((member tg current) c-face)
13975 ((member tg inherited) i-face))))
13976 (if (and (= cnt 0) (not ingroup)) (insert " "))
13977 (insert "[" c "] " tg (make-string
13978 (- fwidth 4 (length tg)) ?\ ))
13979 (push (cons tg c) ntable)
13980 (when (= (setq cnt (1+ cnt)) ncol)
13981 (insert "\n")
13982 (if ingroup (insert " "))
13983 (setq cnt 0)))))
13984 (setq ntable (nreverse ntable))
13985 (insert "\n")
13986 (goto-char (point-min))
13987 (if (not expert) (org-fit-window-to-buffer))
13988 (setq rtn
13989 (catch 'exit
13990 (while t
13991 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13992 (if (not groups) "no " "")
13993 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13994 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13995 (setq org-last-tag-selection-key c)
13996 (cond
13997 ((= c ?\r) (throw 'exit t))
13998 ((= c ?!)
13999 (setq groups (not groups))
14000 (goto-char (point-min))
14001 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14002 ((= c ?\C-c)
14003 (if (not expert)
14004 (org-fast-tag-show-exit
14005 (setq exit-after-next (not exit-after-next)))
14006 (setq expert nil)
14007 (delete-other-windows)
14008 (set-window-buffer (split-window-vertically) " *Org tags*")
14009 (org-switch-to-buffer-other-window " *Org tags*")
14010 (org-fit-window-to-buffer)))
14011 ((or (= c ?\C-g)
14012 (and (= c ?q) (not (rassoc c ntable))))
14013 (org-detach-overlay org-tags-overlay)
14014 (setq quit-flag t))
14015 ((= c ?\ )
14016 (setq current nil)
14017 (if exit-after-next (setq exit-after-next 'now)))
14018 ((= c ?\t)
14019 (condition-case nil
14020 (setq tg (org-icompleting-read
14021 "Tag: "
14022 (or buffer-tags
14023 (with-current-buffer buf
14024 (org-get-buffer-tags)))))
14025 (quit (setq tg "")))
14026 (when (string-match "\\S-" tg)
14027 (add-to-list 'buffer-tags (list tg))
14028 (if (member tg current)
14029 (setq current (delete tg current))
14030 (push tg current)))
14031 (if exit-after-next (setq exit-after-next 'now)))
14032 ((setq e (rassoc c todo-table) tg (car e))
14033 (with-current-buffer buf
14034 (save-excursion (org-todo tg)))
14035 (if exit-after-next (setq exit-after-next 'now)))
14036 ((setq e (rassoc c ntable) tg (car e))
14037 (if (member tg current)
14038 (setq current (delete tg current))
14039 (loop for g in groups do
14040 (if (member tg g)
14041 (mapc (lambda (x)
14042 (setq current (delete x current)))
14043 g)))
14044 (push tg current))
14045 (if exit-after-next (setq exit-after-next 'now))))
14047 ;; Create a sorted list
14048 (setq current
14049 (sort current
14050 (lambda (a b)
14051 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14052 (if (eq exit-after-next 'now) (throw 'exit t))
14053 (goto-char (point-min))
14054 (beginning-of-line 2)
14055 (delete-region (point) (point-at-eol))
14056 (org-fast-tag-insert "Current" current c-face)
14057 (org-set-current-tags-overlay current ov-prefix)
14058 (while (re-search-forward
14059 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14060 (setq tg (match-string 1))
14061 (add-text-properties
14062 (match-beginning 1) (match-end 1)
14063 (list 'face
14064 (cond
14065 ((member tg current) c-face)
14066 ((member tg inherited) i-face)
14067 (t (get-text-property (match-beginning 1) 'face))))))
14068 (goto-char (point-min)))))
14069 (org-detach-overlay org-tags-overlay)
14070 (if rtn
14071 (mapconcat 'identity current ":")
14072 nil))))
14074 (defun org-get-tags-string ()
14075 "Get the TAGS string in the current headline."
14076 (unless (org-at-heading-p t)
14077 (error "Not on a heading"))
14078 (save-excursion
14079 (beginning-of-line 1)
14080 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14081 (org-match-string-no-properties 1)
14082 "")))
14084 (defun org-get-tags ()
14085 "Get the list of tags specified in the current headline."
14086 (org-split-string (org-get-tags-string) ":"))
14088 (defun org-get-buffer-tags ()
14089 "Get a table of all tags used in the buffer, for completion."
14090 (let (tags)
14091 (save-excursion
14092 (goto-char (point-min))
14093 (while (re-search-forward
14094 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14095 (when (equal (char-after (point-at-bol 0)) ?*)
14096 (mapc (lambda (x) (add-to-list 'tags x))
14097 (org-split-string (org-match-string-no-properties 1) ":")))))
14098 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14099 (mapcar 'list tags)))
14101 ;;;; The mapping API
14103 (defun org-map-entries (func &optional match scope &rest skip)
14104 "Call FUNC at each headline selected by MATCH in SCOPE.
14106 FUNC is a function or a lisp form. The function will be called without
14107 arguments, with the cursor positioned at the beginning of the headline.
14108 The return values of all calls to the function will be collected and
14109 returned as a list.
14111 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14112 does not need to preserve point. After evaluation, the cursor will be
14113 moved to the end of the line (presumably of the headline of the
14114 processed entry) and search continues from there. Under some
14115 circumstances, this may not produce the wanted results. For example,
14116 if you have removed (e.g. archived) the current (sub)tree it could
14117 mean that the next entry will be skipped entirely. In such cases, you
14118 can specify the position from where search should continue by making
14119 FUNC set the variable `org-map-continue-from' to the desired buffer
14120 position.
14122 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14123 Only headlines that are matched by this query will be considered during
14124 the iteration. When MATCH is nil or t, all headlines will be
14125 visited by the iteration.
14127 SCOPE determines the scope of this command. It can be any of:
14129 nil The current buffer, respecting the restriction if any
14130 tree The subtree started with the entry at point
14131 region The entries within the active region, if any
14132 region-start-level
14133 The entries within the active region, but only those at
14134 the same level than the first one.
14135 file The current buffer, without restriction
14136 file-with-archives
14137 The current buffer, and any archives associated with it
14138 agenda All agenda files
14139 agenda-with-archives
14140 All agenda files with any archive files associated with them
14141 \(file1 file2 ...)
14142 If this is a list, all files in the list will be scanned
14144 The remaining args are treated as settings for the skipping facilities of
14145 the scanner. The following items can be given here:
14147 archive skip trees with the archive tag.
14148 comment skip trees with the COMMENT keyword
14149 function or Emacs Lisp form:
14150 will be used as value for `org-agenda-skip-function', so whenever
14151 the function returns t, FUNC will not be called for that
14152 entry and search will continue from the point where the
14153 function leaves it.
14155 If your function needs to retrieve the tags including inherited tags
14156 at the *current* entry, you can use the value of the variable
14157 `org-scanner-tags' which will be much faster than getting the value
14158 with `org-get-tags-at'. If your function gets properties with
14159 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14160 to t around the call to `org-entry-properties' to get the same speedup.
14161 Note that if your function moves around to retrieve tags and properties at
14162 a *different* entry, you cannot use these techniques."
14163 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14164 (not (org-region-active-p)))
14165 (let* ((org-agenda-archives-mode nil) ; just to make sure
14166 (org-agenda-skip-archived-trees (memq 'archive skip))
14167 (org-agenda-skip-comment-trees (memq 'comment skip))
14168 (org-agenda-skip-function
14169 (car (org-delete-all '(comment archive) skip)))
14170 (org-tags-match-list-sublevels t)
14171 (start-level (eq scope 'region-start-level))
14172 matcher file res
14173 org-todo-keywords-for-agenda
14174 org-done-keywords-for-agenda
14175 org-todo-keyword-alist-for-agenda
14176 org-drawers-for-agenda
14177 org-tag-alist-for-agenda
14178 todo-only)
14180 (cond
14181 ((eq match t) (setq matcher t))
14182 ((eq match nil) (setq matcher t))
14183 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14185 (save-excursion
14186 (save-restriction
14187 (cond ((eq scope 'tree)
14188 (org-back-to-heading t)
14189 (org-narrow-to-subtree)
14190 (setq scope nil))
14191 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14192 (org-region-active-p))
14193 ;; If needed, set start-level to a string like "2"
14194 (when start-level
14195 (save-excursion
14196 (goto-char (region-beginning))
14197 (unless (org-at-heading-p) (outline-next-heading))
14198 (setq start-level (org-current-level))))
14199 (narrow-to-region (region-beginning)
14200 (save-excursion
14201 (goto-char (region-end))
14202 (unless (and (bolp) (org-at-heading-p))
14203 (outline-next-heading))
14204 (point)))
14205 (setq scope nil)))
14207 (if (not scope)
14208 (progn
14209 (org-agenda-prepare-buffers
14210 (list (buffer-file-name (current-buffer))))
14211 (setq res (org-scan-tags func matcher todo-only start-level)))
14212 ;; Get the right scope
14213 (cond
14214 ((and scope (listp scope) (symbolp (car scope)))
14215 (setq scope (eval scope)))
14216 ((eq scope 'agenda)
14217 (setq scope (org-agenda-files t)))
14218 ((eq scope 'agenda-with-archives)
14219 (setq scope (org-agenda-files t))
14220 (setq scope (org-add-archive-files scope)))
14221 ((eq scope 'file)
14222 (setq scope (list (buffer-file-name))))
14223 ((eq scope 'file-with-archives)
14224 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14225 (org-agenda-prepare-buffers scope)
14226 (while (setq file (pop scope))
14227 (with-current-buffer (org-find-base-buffer-visiting file)
14228 (save-excursion
14229 (save-restriction
14230 (widen)
14231 (goto-char (point-min))
14232 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14233 res)))
14235 ;;;; Properties
14237 ;;; Setting and retrieving properties
14239 (defconst org-special-properties
14240 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14241 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14242 "The special properties valid in Org-mode.
14244 These are properties that are not defined in the property drawer,
14245 but in some other way.")
14247 (defconst org-default-properties
14248 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14249 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14250 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14251 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14252 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14253 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14254 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14255 "Some properties that are used by Org-mode for various purposes.
14256 Being in this list makes sure that they are offered for completion.")
14258 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14259 "Regular expression matching the first line of a property drawer.")
14261 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14262 "Regular expression matching the last line of a property drawer.")
14264 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14265 "Regular expression matching the first line of a property drawer.")
14267 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14268 "Regular expression matching the first line of a property drawer.")
14270 (defconst org-property-drawer-re
14271 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14272 org-property-end-re "\\)\n?")
14273 "Matches an entire property drawer.")
14275 (defconst org-clock-drawer-re
14276 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14277 org-property-end-re "\\)\n?")
14278 "Matches an entire clock drawer.")
14280 (defsubst org-re-property (property)
14281 "Return a regexp matching a PROPERTY line.
14282 Match group 1 will be set to the value."
14283 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14285 (defsubst org-re-property-keyword (property)
14286 "Return a regexp matching a PROPERTY line, possibly with no
14287 value for the property."
14288 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14290 (defun org-property-action ()
14291 "Do an action on properties."
14292 (interactive)
14293 (let (c)
14294 (org-at-property-p)
14295 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14296 (setq c (read-char-exclusive))
14297 (cond
14298 ((equal c ?s)
14299 (call-interactively 'org-set-property))
14300 ((equal c ?d)
14301 (call-interactively 'org-delete-property))
14302 ((equal c ?D)
14303 (call-interactively 'org-delete-property-globally))
14304 ((equal c ?c)
14305 (call-interactively 'org-compute-property-at-point))
14306 (t (error "No such property action %c" c)))))
14308 (defun org-inc-effort ()
14309 "Increment the value of the effort property in the current entry."
14310 (interactive)
14311 (org-set-effort nil t))
14313 (defun org-set-effort (&optional value increment)
14314 "Set the effort property of the current entry.
14315 With numerical prefix arg, use the nth allowed value, 0 stands for the
14316 10th allowed value.
14318 When INCREMENT is non-nil, set the property to the next allowed value."
14319 (interactive "P")
14320 (if (equal value 0) (setq value 10))
14321 (let* ((completion-ignore-case t)
14322 (prop org-effort-property)
14323 (cur (org-entry-get nil prop))
14324 (allowed (org-property-get-allowed-values nil prop 'table))
14325 (existing (mapcar 'list (org-property-values prop)))
14327 (val (cond
14328 ((stringp value) value)
14329 ((and allowed (integerp value))
14330 (or (car (nth (1- value) allowed))
14331 (car (org-last allowed))))
14332 ((and allowed increment)
14333 (or (caadr (member (list cur) allowed))
14334 (error "Allowed effort values are not set")))
14335 (allowed
14336 (message "Select 1-9,0, [RET%s]: %s"
14337 (if cur (concat "=" cur) "")
14338 (mapconcat 'car allowed " "))
14339 (setq rpl (read-char-exclusive))
14340 (if (equal rpl ?\r)
14342 (setq rpl (- rpl ?0))
14343 (if (equal rpl 0) (setq rpl 10))
14344 (if (and (> rpl 0) (<= rpl (length allowed)))
14345 (car (nth (1- rpl) allowed))
14346 (org-completing-read "Effort: " allowed nil))))
14348 (let (org-completion-use-ido org-completion-use-iswitchb)
14349 (org-completing-read
14350 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14351 (concat "[" cur "]") "")
14352 ": ")
14353 existing nil nil "" nil cur))))))
14354 (unless (equal (org-entry-get nil prop) val)
14355 (org-entry-put nil prop val))
14356 (message "%s is now %s" prop val)))
14358 (defun org-at-property-p ()
14359 "Is cursor inside a property drawer?"
14360 (save-excursion
14361 (beginning-of-line 1)
14362 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14363 (save-match-data ;; Used by calling procedures
14364 (let ((p (point))
14365 (range (unless (org-before-first-heading-p)
14366 (org-get-property-block))))
14367 (and range (<= (car range) p) (< p (cdr range))))))))
14369 (defun org-get-property-block (&optional beg end force)
14370 "Return the (beg . end) range of the body of the property drawer.
14371 BEG and END are the beginning and end of the current subtree, or of
14372 the part before the first headline. If they are not given, they will
14373 be found. If the drawer does not exist and FORCE is non-nil, create
14374 the drawer."
14375 (catch 'exit
14376 (save-excursion
14377 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14378 (progn (org-back-to-heading t) (point))))
14379 (end (or end (and (not (outline-next-heading)) (point-max))
14380 (point))))
14381 (goto-char beg)
14382 (if (re-search-forward org-property-start-re end t)
14383 (setq beg (1+ (match-end 0)))
14384 (if force
14385 (save-excursion
14386 (org-insert-property-drawer)
14387 (setq end (progn (outline-next-heading) (point))))
14388 (throw 'exit nil))
14389 (goto-char beg)
14390 (if (re-search-forward org-property-start-re end t)
14391 (setq beg (1+ (match-end 0)))))
14392 (if (re-search-forward org-property-end-re end t)
14393 (setq end (match-beginning 0))
14394 (or force (throw 'exit nil))
14395 (goto-char beg)
14396 (setq end beg)
14397 (org-indent-line)
14398 (insert ":END:\n"))
14399 (cons beg end)))))
14401 (defun org-entry-properties (&optional pom which specific)
14402 "Get all properties of the entry at point-or-marker POM.
14403 This includes the TODO keyword, the tags, time strings for deadline,
14404 scheduled, and clocking, and any additional properties defined in the
14405 entry. The return value is an alist, keys may occur multiple times
14406 if the property key was used several times.
14407 POM may also be nil, in which case the current entry is used.
14408 If WHICH is nil or `all', get all properties. If WHICH is
14409 `special' or `standard', only get that subclass. If WHICH
14410 is a string only get exactly this property. SPECIFIC can be a string, the
14411 specific property we are interested in. Specifying it can speed
14412 things up because then unnecessary parsing is avoided."
14413 (setq which (or which 'all))
14414 (org-with-point-at pom
14415 (let ((clockstr (substring org-clock-string 0 -1))
14416 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14417 (case-fold-search nil)
14418 beg end range props sum-props key key1 value string clocksum clocksumt)
14419 (save-excursion
14420 (when (condition-case nil
14421 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14422 (error nil))
14423 (setq beg (point))
14424 (setq sum-props (get-text-property (point) 'org-summaries))
14425 (setq clocksum (get-text-property (point) :org-clock-minutes)
14426 clocksumt (get-text-property (point) :org-clock-minutes-today))
14427 (outline-next-heading)
14428 (setq end (point))
14429 (when (memq which '(all special))
14430 ;; Get the special properties, like TODO and tags
14431 (goto-char beg)
14432 (when (and (or (not specific) (string= specific "TODO"))
14433 (looking-at org-todo-line-regexp) (match-end 2))
14434 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14435 (when (and (or (not specific) (string= specific "PRIORITY"))
14436 (looking-at org-priority-regexp))
14437 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14438 (when (or (not specific) (string= specific "FILE"))
14439 (push (cons "FILE" buffer-file-name) props))
14440 (when (and (or (not specific) (string= specific "TAGS"))
14441 (setq value (org-get-tags-string))
14442 (string-match "\\S-" value))
14443 (push (cons "TAGS" value) props))
14444 (when (and (or (not specific) (string= specific "ALLTAGS"))
14445 (setq value (org-get-tags-at)))
14446 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14447 ":"))
14448 props))
14449 (when (or (not specific) (string= specific "BLOCKED"))
14450 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14451 (when (or (not specific)
14452 (member specific
14453 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14454 "TIMESTAMP" "TIMESTAMP_IA")))
14455 (catch 'match
14456 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14457 (setq key (if (match-end 1)
14458 (substring (org-match-string-no-properties 1)
14459 0 -1))
14460 string (if (equal key clockstr)
14461 (org-trim
14462 (buffer-substring-no-properties
14463 (match-beginning 3) (goto-char
14464 (point-at-eol))))
14465 (substring (org-match-string-no-properties 3)
14466 1 -1)))
14467 ;; Get the correct property name from the key. This is
14468 ;; necessary if the user has configured time keywords.
14469 (setq key1 (concat key ":"))
14470 (cond
14471 ((not key)
14472 (setq key
14473 (if (= (char-after (match-beginning 3)) ?\[)
14474 "TIMESTAMP_IA" "TIMESTAMP")))
14475 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14476 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14477 ((equal key1 org-closed-string) (setq key "CLOSED"))
14478 ((equal key1 org-clock-string) (setq key "CLOCK")))
14479 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14480 (progn
14481 (push (cons key string) props)
14482 ;; no need to search further if match is found
14483 (throw 'match t))
14484 (when (or (equal key "CLOCK") (not (assoc key props)))
14485 (push (cons key string) props)))))))
14487 (when (memq which '(all standard))
14488 ;; Get the standard properties, like :PROP: ...
14489 (setq range (org-get-property-block beg end))
14490 (when range
14491 (goto-char (car range))
14492 (while (re-search-forward
14493 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14494 (cdr range) t)
14495 (setq key (org-match-string-no-properties 1)
14496 value (org-trim (or (org-match-string-no-properties 2) "")))
14497 (unless (member key excluded)
14498 (push (cons key (or value "")) props)))))
14499 (if clocksum
14500 (push (cons "CLOCKSUM"
14501 (org-columns-number-to-string (/ (float clocksum) 60.)
14502 'add_times))
14503 props))
14504 (if clocksumt
14505 (push (cons "CLOCKSUM_T"
14506 (org-columns-number-to-string (/ (float clocksumt) 60.)
14507 'add_times))
14508 props))
14509 (unless (assoc "CATEGORY" props)
14510 (push (cons "CATEGORY" (org-get-category)) props))
14511 (append sum-props (nreverse props)))))))
14513 (defun org-entry-get (pom property &optional inherit literal-nil)
14514 "Get value of PROPERTY for entry or content at point-or-marker POM.
14515 If INHERIT is non-nil and the entry does not have the property,
14516 then also check higher levels of the hierarchy.
14517 If INHERIT is the symbol `selective', use inheritance only if the setting
14518 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14519 If the property is present but empty, the return value is the empty string.
14520 If the property is not present at all, nil is returned.
14522 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14523 do not interpret it as the list atom nil. This is used for inheritance
14524 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14525 (org-with-point-at pom
14526 (if (and inherit (if (eq inherit 'selective)
14527 (org-property-inherit-p property)
14529 (org-entry-get-with-inheritance property literal-nil)
14530 (if (member property org-special-properties)
14531 ;; We need a special property. Use `org-entry-properties' to
14532 ;; retrieve it, but specify the wanted property
14533 (cdr (assoc property (org-entry-properties nil 'special property)))
14534 (let* ((range (org-get-property-block))
14535 (props (list (or (assoc property org-file-properties)
14536 (assoc property org-global-properties)
14537 (assoc property org-global-properties-fixed))))
14538 (ap (lambda (key)
14539 (when (re-search-forward
14540 (org-re-property key) (cdr range) t)
14541 (setq props
14542 (org-update-property-plist
14544 (if (match-end 1)
14545 (org-match-string-no-properties 1) "")
14546 props)))))
14547 val)
14548 (when (and range (goto-char (car range)))
14549 (funcall ap property)
14550 (goto-char (car range))
14551 (while (funcall ap (concat property "+")))
14552 (setq val (cdr (assoc property props)))
14553 (when val (if literal-nil val (org-not-nil val)))))))))
14555 (defun org-property-or-variable-value (var &optional inherit)
14556 "Check if there is a property fixing the value of VAR.
14557 If yes, return this value. If not, return the current value of the variable."
14558 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14559 (if (and prop (stringp prop) (string-match "\\S-" prop))
14560 (read prop)
14561 (symbol-value var))))
14563 (defun org-entry-delete (pom property)
14564 "Delete the property PROPERTY from entry at point-or-marker POM."
14565 (org-with-point-at pom
14566 (if (member property org-special-properties)
14567 nil ; cannot delete these properties.
14568 (let ((range (org-get-property-block)))
14569 (if (and range
14570 (goto-char (car range))
14571 (re-search-forward
14572 (org-re-property property)
14573 (cdr range) t))
14574 (progn
14575 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14577 nil)))))
14579 ;; Multi-values properties are properties that contain multiple values
14580 ;; These values are assumed to be single words, separated by whitespace.
14581 (defun org-entry-add-to-multivalued-property (pom property value)
14582 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14583 (let* ((old (org-entry-get pom property))
14584 (values (and old (org-split-string old "[ \t]"))))
14585 (setq value (org-entry-protect-space value))
14586 (unless (member value values)
14587 (setq values (cons value values))
14588 (org-entry-put pom property
14589 (mapconcat 'identity values " ")))))
14591 (defun org-entry-remove-from-multivalued-property (pom property value)
14592 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14593 (let* ((old (org-entry-get pom property))
14594 (values (and old (org-split-string old "[ \t]"))))
14595 (setq value (org-entry-protect-space value))
14596 (when (member value values)
14597 (setq values (delete value values))
14598 (org-entry-put pom property
14599 (mapconcat 'identity values " ")))))
14601 (defun org-entry-member-in-multivalued-property (pom property value)
14602 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14603 (let* ((old (org-entry-get pom property))
14604 (values (and old (org-split-string old "[ \t]"))))
14605 (setq value (org-entry-protect-space value))
14606 (member value values)))
14608 (defun org-entry-get-multivalued-property (pom property)
14609 "Return a list of values in a multivalued property."
14610 (let* ((value (org-entry-get pom property))
14611 (values (and value (org-split-string value "[ \t]"))))
14612 (mapcar 'org-entry-restore-space values)))
14614 (defun org-entry-put-multivalued-property (pom property &rest values)
14615 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14616 VALUES should be a list of strings. Spaces will be protected."
14617 (org-entry-put pom property
14618 (mapconcat 'org-entry-protect-space values " "))
14619 (let* ((value (org-entry-get pom property))
14620 (values (and value (org-split-string value "[ \t]"))))
14621 (mapcar 'org-entry-restore-space values)))
14623 (defun org-entry-protect-space (s)
14624 "Protect spaces and newline in string S."
14625 (while (string-match " " s)
14626 (setq s (replace-match "%20" t t s)))
14627 (while (string-match "\n" s)
14628 (setq s (replace-match "%0A" t t s)))
14631 (defun org-entry-restore-space (s)
14632 "Restore spaces and newline in string S."
14633 (while (string-match "%20" s)
14634 (setq s (replace-match " " t t s)))
14635 (while (string-match "%0A" s)
14636 (setq s (replace-match "\n" t t s)))
14639 (defvar org-entry-property-inherited-from (make-marker)
14640 "Marker pointing to the entry from where a property was inherited.
14641 Each call to `org-entry-get-with-inheritance' will set this marker to the
14642 location of the entry where the inheritance search matched. If there was
14643 no match, the marker will point nowhere.
14644 Note that also `org-entry-get' calls this function, if the INHERIT flag
14645 is set.")
14647 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14648 "Get PROPERTY of entry or content at point, search higher levels if needed.
14649 The search will stop at the first ancestor which has the property defined.
14650 If the value found is \"nil\", return nil to show that the property
14651 should be considered as undefined (this is the meaning of nil here).
14652 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14653 (move-marker org-entry-property-inherited-from nil)
14654 (let (tmp)
14655 (save-excursion
14656 (save-restriction
14657 (widen)
14658 (catch 'ex
14659 (while t
14660 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14661 (or (ignore-errors (org-back-to-heading t))
14662 (goto-char (point-min)))
14663 (move-marker org-entry-property-inherited-from (point))
14664 (throw 'ex tmp))
14665 (or (ignore-errors (org-up-heading-safe))
14666 (throw 'ex nil))))))
14667 (setq tmp (or tmp
14668 (cdr (assoc property org-file-properties))
14669 (cdr (assoc property org-global-properties))
14670 (cdr (assoc property org-global-properties-fixed))))
14671 (if literal-nil tmp (org-not-nil tmp))))
14673 (defvar org-property-changed-functions nil
14674 "Hook called when the value of a property has changed.
14675 Each hook function should accept two arguments, the name of the property
14676 and the new value.")
14678 (defun org-entry-put (pom property value)
14679 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14680 (org-with-point-at pom
14681 (org-back-to-heading t)
14682 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14683 range)
14684 (cond
14685 ((equal property "TODO")
14686 (when (and (stringp value) (string-match "\\S-" value)
14687 (not (member value org-todo-keywords-1)))
14688 (error "\"%s\" is not a valid TODO state" value))
14689 (if (or (not value)
14690 (not (string-match "\\S-" value)))
14691 (setq value 'none))
14692 (org-todo value)
14693 (org-set-tags nil 'align))
14694 ((equal property "PRIORITY")
14695 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14696 (string-to-char value) ?\ ))
14697 (org-set-tags nil 'align))
14698 ((equal property "CLOCKSUM")
14699 (if (not (re-search-forward
14700 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14701 (error "Cannot find a clock log")
14702 (goto-char (- (match-end 1) 2))
14703 (cond
14704 ((eq value 'earlier) (org-timestamp-down))
14705 ((eq value 'later) (org-timestamp-up)))
14706 (org-clock-sum-current-item)))
14707 ((equal property "SCHEDULED")
14708 (if (re-search-forward org-scheduled-time-regexp end t)
14709 (cond
14710 ((eq value 'earlier) (org-timestamp-change -1 'day))
14711 ((eq value 'later) (org-timestamp-change 1 'day))
14712 (t (call-interactively 'org-schedule)))
14713 (call-interactively 'org-schedule)))
14714 ((equal property "DEADLINE")
14715 (if (re-search-forward org-deadline-time-regexp end t)
14716 (cond
14717 ((eq value 'earlier) (org-timestamp-change -1 'day))
14718 ((eq value 'later) (org-timestamp-change 1 'day))
14719 (t (call-interactively 'org-deadline)))
14720 (call-interactively 'org-deadline)))
14721 ((member property org-special-properties)
14722 (error "The %s property can not yet be set with `org-entry-put'"
14723 property))
14724 (t ; a non-special property
14725 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14726 (setq range (org-get-property-block beg end 'force))
14727 (goto-char (car range))
14728 (if (re-search-forward
14729 (org-re-property-keyword property) (cdr range) t)
14730 (progn
14731 (delete-region (match-beginning 0) (match-end 0))
14732 (goto-char (match-beginning 0)))
14733 (goto-char (cdr range))
14734 (insert "\n")
14735 (backward-char 1)
14736 (org-indent-line))
14737 (insert ":" property ":")
14738 (and value (insert " " value))
14739 (org-indent-line)))))
14740 (run-hook-with-args 'org-property-changed-functions property value)))
14742 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14743 "Get all property keys in the current buffer.
14744 With INCLUDE-SPECIALS, also list the special properties that reflect things
14745 like tags and TODO state.
14746 With INCLUDE-DEFAULTS, also include properties that has special meaning
14747 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14748 and others.
14749 With INCLUDE-COLUMNS, also include property names given in COLUMN
14750 formats in the current buffer."
14751 (let (rtn range cfmt s p)
14752 (save-excursion
14753 (save-restriction
14754 (widen)
14755 (goto-char (point-min))
14756 (while (re-search-forward org-property-start-re nil t)
14757 (setq range (org-get-property-block))
14758 (goto-char (car range))
14759 (while (re-search-forward
14760 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14761 (cdr range) t)
14762 (add-to-list 'rtn (org-match-string-no-properties 1)))
14763 (outline-next-heading))))
14765 (when include-specials
14766 (setq rtn (append org-special-properties rtn)))
14768 (when include-defaults
14769 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14770 (add-to-list 'rtn org-effort-property))
14772 (when include-columns
14773 (save-excursion
14774 (save-restriction
14775 (widen)
14776 (goto-char (point-min))
14777 (while (re-search-forward
14778 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14779 nil t)
14780 (setq cfmt (match-string 2) s 0)
14781 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14782 cfmt s)
14783 (setq s (match-end 0)
14784 p (match-string 1 cfmt))
14785 (unless (or (equal p "ITEM")
14786 (member p org-special-properties))
14787 (add-to-list 'rtn (match-string 1 cfmt))))))))
14789 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14791 (defun org-property-values (key)
14792 "Return a list of all values of property KEY in the current buffer."
14793 (save-excursion
14794 (save-restriction
14795 (widen)
14796 (goto-char (point-min))
14797 (let ((re (org-re-property key))
14798 values)
14799 (while (re-search-forward re nil t)
14800 (add-to-list 'values (org-trim (match-string 1))))
14801 (delete "" values)))))
14803 (defun org-insert-property-drawer ()
14804 "Insert a property drawer into the current entry."
14805 (org-back-to-heading t)
14806 (looking-at org-outline-regexp)
14807 (let ((indent (if org-adapt-indentation
14808 (- (match-end 0) (match-beginning 0))
14810 (beg (point))
14811 (re (concat "^[ \t]*" org-keyword-time-regexp))
14812 end hiddenp)
14813 (outline-next-heading)
14814 (setq end (point))
14815 (goto-char beg)
14816 (while (re-search-forward re end t))
14817 (setq hiddenp (outline-invisible-p))
14818 (end-of-line 1)
14819 (and (equal (char-after) ?\n) (forward-char 1))
14820 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14821 (if (member (match-string 1) '("CLOCK:" ":END:"))
14822 ;; just skip this line
14823 (beginning-of-line 2)
14824 ;; Drawer start, find the end
14825 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14826 (beginning-of-line 1)))
14827 (org-skip-over-state-notes)
14828 (skip-chars-backward " \t\n\r")
14829 (if (eq (char-before) ?*) (forward-char 1))
14830 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14831 (beginning-of-line 0)
14832 (org-indent-to-column indent)
14833 (beginning-of-line 2)
14834 (org-indent-to-column indent)
14835 (beginning-of-line 0)
14836 (if hiddenp
14837 (save-excursion
14838 (org-back-to-heading t)
14839 (hide-entry))
14840 (org-flag-drawer t))))
14842 (defun org-insert-drawer (&optional arg drawer)
14843 "Insert a drawer at point.
14845 Optional argument DRAWER, when non-nil, is a string representing
14846 drawer's name. Otherwise, the user is prompted for a name.
14848 If a region is active, insert the drawer around that region
14849 instead.
14851 Point is left between drawer's boundaries."
14852 (interactive "P")
14853 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14854 "LOGBOOK"))
14855 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14856 ;; internally by Org. They are meant to be inserted
14857 ;; automatically.
14858 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14859 ;; Remove system drawers from list. Note: For some reason,
14860 ;; `org-completing-read' ignores the predicate while
14861 ;; `completing-read' handles it fine.
14862 (drawer (if arg "PROPERTIES"
14863 (or drawer
14864 (completing-read
14865 "Drawer: " org-drawers
14866 (lambda (d) (not (member d system-drawers))))))))
14867 (cond
14868 ;; With C-u, fall back on `org-insert-property-drawer'
14869 (arg (org-insert-property-drawer))
14870 ;; With an active region, insert a drawer at point.
14871 ((not (org-region-active-p))
14872 (progn
14873 (unless (bolp) (insert "\n"))
14874 (insert (format ":%s:\n\n:END:\n" drawer))
14875 (forward-line -2)))
14876 ;; Otherwise, insert the drawer at point
14878 (let ((rbeg (region-beginning))
14879 (rend (copy-marker (region-end))))
14880 (unwind-protect
14881 (progn
14882 (goto-char rbeg)
14883 (beginning-of-line)
14884 (when (save-excursion
14885 (re-search-forward org-outline-regexp-bol rend t))
14886 (error "Drawers cannot contain headlines"))
14887 ;; Position point at the beginning of the first
14888 ;; non-blank line in region. Insert drawer's opening
14889 ;; there, then indent it.
14890 (org-skip-whitespace)
14891 (beginning-of-line)
14892 (insert ":" drawer ":\n")
14893 (forward-line -1)
14894 (indent-for-tab-command)
14895 ;; Move point to the beginning of the first blank line
14896 ;; after the last non-blank line in region. Insert
14897 ;; drawer's closing, then indent it.
14898 (goto-char rend)
14899 (skip-chars-backward " \r\t\n")
14900 (insert "\n:END:")
14901 (deactivate-mark t)
14902 (indent-for-tab-command)
14903 (unless (eolp) (insert "\n")))
14904 ;; Clear marker, whatever the outcome of insertion is.
14905 (set-marker rend nil)))))))
14907 (defvar org-property-set-functions-alist nil
14908 "Property set function alist.
14909 Each entry should have the following format:
14911 (PROPERTY . READ-FUNCTION)
14913 The read function will be called with the same argument as
14914 `org-completing-read'.")
14916 (defun org-set-property-function (property)
14917 "Get the function that should be used to set PROPERTY.
14918 This is computed according to `org-property-set-functions-alist'."
14919 (or (cdr (assoc property org-property-set-functions-alist))
14920 'org-completing-read))
14922 (defun org-read-property-value (property)
14923 "Read PROPERTY value from user."
14924 (let* ((completion-ignore-case t)
14925 (allowed (org-property-get-allowed-values nil property 'table))
14926 (cur (org-entry-get nil property))
14927 (prompt (concat property " value"
14928 (if (and cur (string-match "\\S-" cur))
14929 (concat " [" cur "]") "") ": "))
14930 (set-function (org-set-property-function property))
14931 (val (if allowed
14932 (funcall set-function prompt allowed nil
14933 (not (get-text-property 0 'org-unrestricted
14934 (caar allowed))))
14935 (let (org-completion-use-ido org-completion-use-iswitchb)
14936 (funcall set-function prompt
14937 (mapcar 'list (org-property-values property))
14938 nil nil "" nil cur)))))
14939 (if (equal val "")
14941 val)))
14943 (defvar org-last-set-property nil)
14944 (defun org-read-property-name ()
14945 "Read a property name."
14946 (let* ((completion-ignore-case t)
14947 (keys (org-buffer-property-keys nil t t))
14948 (default-prop (or (save-excursion
14949 (save-match-data
14950 (beginning-of-line)
14951 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14952 (null (string= (match-string 1) "END"))
14953 (match-string 1))))
14954 org-last-set-property))
14955 (property (org-icompleting-read
14956 (concat "Property"
14957 (if default-prop (concat " [" default-prop "]") "")
14958 ": ")
14959 (mapcar 'list keys)
14960 nil nil nil nil
14961 default-prop
14963 (if (member property keys)
14964 property
14965 (or (cdr (assoc (downcase property)
14966 (mapcar (lambda (x) (cons (downcase x) x))
14967 keys)))
14968 property))))
14970 (defun org-set-property (property value)
14971 "In the current entry, set PROPERTY to VALUE.
14972 When called interactively, this will prompt for a property name, offering
14973 completion on existing and default properties. And then it will prompt
14974 for a value, offering completion either on allowed values (via an inherited
14975 xxx_ALL property) or on existing values in other instances of this property
14976 in the current file."
14977 (interactive (list nil nil))
14978 (let* ((property (or property (org-read-property-name)))
14979 (value (or value (org-read-property-value property)))
14980 (fn (cdr (assoc property org-properties-postprocess-alist))))
14981 (setq org-last-set-property property)
14982 ;; Possibly postprocess the inserted value:
14983 (when fn (setq value (funcall fn value)))
14984 (unless (equal (org-entry-get nil property) value)
14985 (org-entry-put nil property value))))
14987 (defun org-delete-property (property)
14988 "In the current entry, delete PROPERTY."
14989 (interactive
14990 (let* ((completion-ignore-case t)
14991 (prop (org-icompleting-read "Property: "
14992 (org-entry-properties nil 'standard))))
14993 (list prop)))
14994 (message "Property %s %s" property
14995 (if (org-entry-delete nil property)
14996 "deleted"
14997 "was not present in the entry")))
14999 (defun org-delete-property-globally (property)
15000 "Remove PROPERTY globally, from all entries."
15001 (interactive
15002 (let* ((completion-ignore-case t)
15003 (prop (org-icompleting-read
15004 "Globally remove property: "
15005 (mapcar 'list (org-buffer-property-keys)))))
15006 (list prop)))
15007 (save-excursion
15008 (save-restriction
15009 (widen)
15010 (goto-char (point-min))
15011 (let ((cnt 0))
15012 (while (re-search-forward
15013 (org-re-property property)
15014 nil t)
15015 (setq cnt (1+ cnt))
15016 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15017 (message "Property \"%s\" removed from %d entries" property cnt)))))
15019 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15021 (defun org-compute-property-at-point ()
15022 "Compute the property at point.
15023 This looks for an enclosing column format, extracts the operator and
15024 then applies it to the property in the column format's scope."
15025 (interactive)
15026 (unless (org-at-property-p)
15027 (error "Not at a property"))
15028 (let ((prop (org-match-string-no-properties 2)))
15029 (org-columns-get-format-and-top-level)
15030 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15031 (error "No operator defined for property %s" prop))
15032 (org-columns-compute prop)))
15034 (defvar org-property-allowed-value-functions nil
15035 "Hook for functions supplying allowed values for a specific property.
15036 The functions must take a single argument, the name of the property, and
15037 return a flat list of allowed values. If \":ETC\" is one of
15038 the values, this means that these values are intended as defaults for
15039 completion, but that other values should be allowed too.
15040 The functions must return nil if they are not responsible for this
15041 property.")
15043 (defun org-property-get-allowed-values (pom property &optional table)
15044 "Get allowed values for the property PROPERTY.
15045 When TABLE is non-nil, return an alist that can directly be used for
15046 completion."
15047 (let (vals)
15048 (cond
15049 ((equal property "TODO")
15050 (setq vals (org-with-point-at pom
15051 (append org-todo-keywords-1 '("")))))
15052 ((equal property "PRIORITY")
15053 (let ((n org-lowest-priority))
15054 (while (>= n org-highest-priority)
15055 (push (char-to-string n) vals)
15056 (setq n (1- n)))))
15057 ((member property org-special-properties))
15058 ((setq vals (run-hook-with-args-until-success
15059 'org-property-allowed-value-functions property)))
15061 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15062 (when (and vals (string-match "\\S-" vals))
15063 (setq vals (car (read-from-string (concat "(" vals ")"))))
15064 (setq vals (mapcar (lambda (x)
15065 (cond ((stringp x) x)
15066 ((numberp x) (number-to-string x))
15067 ((symbolp x) (symbol-name x))
15068 (t "???")))
15069 vals)))))
15070 (when (member ":ETC" vals)
15071 (setq vals (remove ":ETC" vals))
15072 (org-add-props (car vals) '(org-unrestricted t)))
15073 (if table (mapcar 'list vals) vals)))
15075 (defun org-property-previous-allowed-value (&optional previous)
15076 "Switch to the next allowed value for this property."
15077 (interactive)
15078 (org-property-next-allowed-value t))
15080 (defun org-property-next-allowed-value (&optional previous)
15081 "Switch to the next allowed value for this property."
15082 (interactive)
15083 (unless (org-at-property-p)
15084 (error "Not at a property"))
15085 (let* ((key (match-string 2))
15086 (value (match-string 3))
15087 (allowed (or (org-property-get-allowed-values (point) key)
15088 (and (member value '("[ ]" "[-]" "[X]"))
15089 '("[ ]" "[X]"))))
15090 nval)
15091 (unless allowed
15092 (error "Allowed values for this property have not been defined"))
15093 (if previous (setq allowed (reverse allowed)))
15094 (if (member value allowed)
15095 (setq nval (car (cdr (member value allowed)))))
15096 (setq nval (or nval (car allowed)))
15097 (if (equal nval value)
15098 (error "Only one allowed value for this property"))
15099 (org-at-property-p)
15100 (replace-match (concat " :" key ": " nval) t t)
15101 (org-indent-line)
15102 (beginning-of-line 1)
15103 (skip-chars-forward " \t")
15104 (run-hook-with-args 'org-property-changed-functions key nval)))
15106 (defun org-find-olp (path &optional this-buffer)
15107 "Return a marker pointing to the entry at outline path OLP.
15108 If anything goes wrong, throw an error.
15109 You can wrap this call to catch the error like this:
15111 (condition-case msg
15112 (org-mobile-locate-entry (match-string 4))
15113 (error (nth 1 msg)))
15115 The return value will then be either a string with the error message,
15116 or a marker if everything is OK.
15118 If THIS-BUFFER is set, the outline path does not contain a file,
15119 only headings."
15120 (let* ((file (if this-buffer buffer-file-name (pop path)))
15121 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15122 (level 1)
15123 (lmin 1)
15124 (lmax 1)
15125 limit re end found pos heading cnt flevel)
15126 (unless buffer (error "File not found :%s" file))
15127 (with-current-buffer buffer
15128 (save-excursion
15129 (save-restriction
15130 (widen)
15131 (setq limit (point-max))
15132 (goto-char (point-min))
15133 (while (setq heading (pop path))
15134 (setq re (format org-complex-heading-regexp-format
15135 (regexp-quote heading)))
15136 (setq cnt 0 pos (point))
15137 (while (re-search-forward re end t)
15138 (setq level (- (match-end 1) (match-beginning 1)))
15139 (if (and (>= level lmin) (<= level lmax))
15140 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15141 (when (= cnt 0) (error "Heading not found on level %d: %s"
15142 lmax heading))
15143 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15144 lmax heading))
15145 (goto-char found)
15146 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15147 (setq end (save-excursion (org-end-of-subtree t t))))
15148 (when (org-at-heading-p)
15149 (move-marker (make-marker) (point))))))))
15151 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15152 "Find node HEADING in BUFFER.
15153 Return a marker to the heading if it was found, or nil if not.
15154 If POS-ONLY is set, return just the position instead of a marker.
15156 The heading text must match exact, but it may have a TODO keyword,
15157 a priority cookie and tags in the standard locations."
15158 (with-current-buffer (or buffer (current-buffer))
15159 (save-excursion
15160 (save-restriction
15161 (widen)
15162 (goto-char (point-min))
15163 (let (case-fold-search)
15164 (if (re-search-forward
15165 (format org-complex-heading-regexp-format
15166 (regexp-quote heading)) nil t)
15167 (if pos-only
15168 (match-beginning 0)
15169 (move-marker (make-marker) (match-beginning 0)))))))))
15171 (defun org-find-exact-heading-in-directory (heading &optional dir)
15172 "Find Org node headline HEADING in all .org files in directory DIR.
15173 When the target headline is found, return a marker to this location."
15174 (let ((files (directory-files (or dir default-directory)
15175 nil "\\`[^.#].*\\.org\\'"))
15176 file visiting m buffer)
15177 (catch 'found
15178 (while (setq file (pop files))
15179 (message "trying %s" file)
15180 (setq visiting (org-find-base-buffer-visiting file))
15181 (setq buffer (or visiting (find-file-noselect file)))
15182 (setq m (org-find-exact-headline-in-buffer
15183 heading buffer))
15184 (when (and (not m) (not visiting)) (kill-buffer buffer))
15185 (and m (throw 'found m))))))
15187 (defun org-find-entry-with-id (ident)
15188 "Locate the entry that contains the ID property with exact value IDENT.
15189 IDENT can be a string, a symbol or a number, this function will search for
15190 the string representation of it.
15191 Return the position where this entry starts, or nil if there is no such entry."
15192 (interactive "sID: ")
15193 (let ((id (cond
15194 ((stringp ident) ident)
15195 ((symbol-name ident) (symbol-name ident))
15196 ((numberp ident) (number-to-string ident))
15197 (t (error "IDENT %s must be a string, symbol or number" ident))))
15198 (case-fold-search nil))
15199 (save-excursion
15200 (save-restriction
15201 (widen)
15202 (goto-char (point-min))
15203 (when (re-search-forward
15204 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15205 nil t)
15206 (org-back-to-heading t)
15207 (point))))))
15209 ;;;; Timestamps
15211 (defvar org-last-changed-timestamp nil)
15212 (defvar org-last-inserted-timestamp nil
15213 "The last time stamp inserted with `org-insert-time-stamp'.")
15214 (defvar org-time-was-given) ; dynamically scoped parameter
15215 (defvar org-end-time-was-given) ; dynamically scoped parameter
15216 (defvar org-ts-what) ; dynamically scoped parameter
15218 (defun org-time-stamp (arg &optional inactive)
15219 "Prompt for a date/time and insert a time stamp.
15220 If the user specifies a time like HH:MM or if this command is
15221 called with at least one prefix argument, the time stamp contains
15222 the date and the time. Otherwise, only the date is be included.
15224 All parts of a date not specified by the user is filled in from
15225 the current date/time. So if you just press return without
15226 typing anything, the time stamp will represent the current
15227 date/time.
15229 If there is already a timestamp at the cursor, it will be
15230 modified.
15232 With two universal prefix arguments, insert an active timestamp
15233 with the current time without prompting the user."
15234 (interactive "P")
15235 (let* ((ts nil)
15236 (default-time
15237 ;; Default time is either today, or, when entering a range,
15238 ;; the range start.
15239 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15240 (save-excursion
15241 (re-search-backward
15242 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15243 (- (point) 20) t)))
15244 (apply 'encode-time (org-parse-time-string (match-string 1)))
15245 (current-time)))
15246 (default-input (and ts (org-get-compact-tod ts)))
15247 (repeater (save-excursion
15248 (save-match-data
15249 (beginning-of-line)
15250 (when (re-search-forward
15251 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15252 (save-excursion (progn (end-of-line) (point))) t)
15253 (match-string 0)))))
15254 org-time-was-given org-end-time-was-given time)
15255 (cond
15256 ((and (org-at-timestamp-p t)
15257 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15258 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15259 (insert "--")
15260 (setq time (let ((this-command this-command))
15261 (org-read-date arg 'totime nil nil
15262 default-time default-input inactive)))
15263 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15264 ((org-at-timestamp-p t)
15265 (setq time (let ((this-command this-command))
15266 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15267 (when (org-at-timestamp-p t) ; just to get the match data
15268 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15269 (replace-match "")
15270 (setq org-last-changed-timestamp
15271 (org-insert-time-stamp
15272 time (or org-time-was-given arg)
15273 inactive nil nil (list org-end-time-was-given)))
15274 (when repeater (goto-char (1- (point))) (insert " " repeater)
15275 (setq org-last-changed-timestamp
15276 (concat (substring org-last-inserted-timestamp 0 -1)
15277 " " repeater ">"))))
15278 (message "Timestamp updated"))
15279 ((equal arg '(16))
15280 (org-insert-time-stamp (current-time) t))
15282 (setq time (let ((this-command this-command))
15283 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15284 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15285 nil nil (list org-end-time-was-given))))))
15287 ;; FIXME: can we use this for something else, like computing time differences?
15288 (defun org-get-compact-tod (s)
15289 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15290 (let* ((t1 (match-string 1 s))
15291 (h1 (string-to-number (match-string 2 s)))
15292 (m1 (string-to-number (match-string 3 s)))
15293 (t2 (and (match-end 4) (match-string 5 s)))
15294 (h2 (and t2 (string-to-number (match-string 6 s))))
15295 (m2 (and t2 (string-to-number (match-string 7 s))))
15296 dh dm)
15297 (if (not t2)
15299 (setq dh (- h2 h1) dm (- m2 m1))
15300 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15301 (concat t1 "+" (number-to-string dh)
15302 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15304 (defun org-time-stamp-inactive (&optional arg)
15305 "Insert an inactive time stamp.
15306 An inactive time stamp is enclosed in square brackets instead of angle
15307 brackets. It is inactive in the sense that it does not trigger agenda entries,
15308 does not link to the calendar and cannot be changed with the S-cursor keys.
15309 So these are more for recording a certain time/date."
15310 (interactive "P")
15311 (org-time-stamp arg 'inactive))
15313 (defvar org-date-ovl (make-overlay 1 1))
15314 (overlay-put org-date-ovl 'face 'org-date-selected)
15315 (org-detach-overlay org-date-ovl)
15317 (defvar org-ans1) ; dynamically scoped parameter
15318 (defvar org-ans2) ; dynamically scoped parameter
15320 (defvar org-plain-time-of-day-regexp) ; defined below
15322 (defvar org-overriding-default-time nil) ; dynamically scoped
15323 (defvar org-read-date-overlay nil)
15324 (defvar org-dcst nil) ; dynamically scoped
15325 (defvar org-read-date-history nil)
15326 (defvar org-read-date-final-answer nil)
15327 (defvar org-read-date-analyze-futurep nil)
15328 (defvar org-read-date-analyze-forced-year nil)
15329 (defvar org-read-date-inactive)
15331 (defun org-read-date (&optional org-with-time to-time from-string prompt
15332 default-time default-input inactive)
15333 "Read a date, possibly a time, and make things smooth for the user.
15334 The prompt will suggest to enter an ISO date, but you can also enter anything
15335 which will at least partially be understood by `parse-time-string'.
15336 Unrecognized parts of the date will default to the current day, month, year,
15337 hour and minute. If this command is called to replace a timestamp at point,
15338 or to enter the second timestamp of a range, the default time is taken
15339 from the existing stamp. Furthermore, the command prefers the future,
15340 so if you are giving a date where the year is not given, and the day-month
15341 combination is already past in the current year, it will assume you
15342 mean next year. For details, see the manual. A few examples:
15344 3-2-5 --> 2003-02-05
15345 feb 15 --> currentyear-02-15
15346 2/15 --> currentyear-02-15
15347 sep 12 9 --> 2009-09-12
15348 12:45 --> today 12:45
15349 22 sept 0:34 --> currentyear-09-22 0:34
15350 12 --> currentyear-currentmonth-12
15351 Fri --> nearest Friday (today or later)
15352 etc.
15354 Furthermore you can specify a relative date by giving, as the *first* thing
15355 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15356 change in days weeks, months, years.
15357 With a single plus or minus, the date is relative to today. With a double
15358 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15359 +4d --> four days from today
15360 +4 --> same as above
15361 +2w --> two weeks from today
15362 ++5 --> five days from default date
15364 The function understands only English month and weekday abbreviations.
15366 While prompting, a calendar is popped up - you can also select the
15367 date with the mouse (button 1). The calendar shows a period of three
15368 months. To scroll it to other months, use the keys `>' and `<'.
15369 If you don't like the calendar, turn it off with
15370 \(setq org-read-date-popup-calendar nil)
15372 With optional argument TO-TIME, the date will immediately be converted
15373 to an internal time.
15374 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15375 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15376 still enter a time, and this function will inform the calling routine
15377 about this change. The calling routine may then choose to change the
15378 format used to insert the time stamp into the buffer to include the time.
15379 With optional argument FROM-STRING, read from this string instead from
15380 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15381 the time/date that is used for everything that is not specified by the
15382 user."
15383 (require 'parse-time)
15384 (let* ((org-time-stamp-rounding-minutes
15385 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15386 (org-dcst org-display-custom-times)
15387 (ct (org-current-time))
15388 (org-def (or org-overriding-default-time default-time ct))
15389 (org-defdecode (decode-time org-def))
15390 (dummy (progn
15391 (when (< (nth 2 org-defdecode) org-extend-today-until)
15392 (setcar (nthcdr 2 org-defdecode) -1)
15393 (setcar (nthcdr 1 org-defdecode) 59)
15394 (setq org-def (apply 'encode-time org-defdecode)
15395 org-defdecode (decode-time org-def)))))
15396 (calendar-frame-setup nil)
15397 (calendar-setup nil)
15398 (calendar-move-hook nil)
15399 (calendar-view-diary-initially-flag nil)
15400 (calendar-view-holidays-initially-flag nil)
15401 (timestr (format-time-string
15402 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15403 (prompt (concat (if prompt (concat prompt " ") "")
15404 (format "Date+time [%s]: " timestr)))
15405 ans (org-ans0 "") org-ans1 org-ans2 final)
15407 (cond
15408 (from-string (setq ans from-string))
15409 (org-read-date-popup-calendar
15410 (save-excursion
15411 (save-window-excursion
15412 (calendar)
15413 (org-eval-in-calendar '(setq cursor-type nil) t)
15414 (unwind-protect
15415 (progn
15416 (calendar-forward-day (- (time-to-days org-def)
15417 (calendar-absolute-from-gregorian
15418 (calendar-current-date))))
15419 (org-eval-in-calendar nil t)
15420 (let* ((old-map (current-local-map))
15421 (map (copy-keymap calendar-mode-map))
15422 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15423 (org-defkey map (kbd "RET") 'org-calendar-select)
15424 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15425 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15426 (org-defkey minibuffer-local-map [(meta shift left)]
15427 (lambda () (interactive)
15428 (org-eval-in-calendar '(calendar-backward-month 1))))
15429 (org-defkey minibuffer-local-map [(meta shift right)]
15430 (lambda () (interactive)
15431 (org-eval-in-calendar '(calendar-forward-month 1))))
15432 (org-defkey minibuffer-local-map [(meta shift up)]
15433 (lambda () (interactive)
15434 (org-eval-in-calendar '(calendar-backward-year 1))))
15435 (org-defkey minibuffer-local-map [(meta shift down)]
15436 (lambda () (interactive)
15437 (org-eval-in-calendar '(calendar-forward-year 1))))
15438 (org-defkey minibuffer-local-map [?\e (shift left)]
15439 (lambda () (interactive)
15440 (org-eval-in-calendar '(calendar-backward-month 1))))
15441 (org-defkey minibuffer-local-map [?\e (shift right)]
15442 (lambda () (interactive)
15443 (org-eval-in-calendar '(calendar-forward-month 1))))
15444 (org-defkey minibuffer-local-map [?\e (shift up)]
15445 (lambda () (interactive)
15446 (org-eval-in-calendar '(calendar-backward-year 1))))
15447 (org-defkey minibuffer-local-map [?\e (shift down)]
15448 (lambda () (interactive)
15449 (org-eval-in-calendar '(calendar-forward-year 1))))
15450 (org-defkey minibuffer-local-map [(shift up)]
15451 (lambda () (interactive)
15452 (org-eval-in-calendar '(calendar-backward-week 1))))
15453 (org-defkey minibuffer-local-map [(shift down)]
15454 (lambda () (interactive)
15455 (org-eval-in-calendar '(calendar-forward-week 1))))
15456 (org-defkey minibuffer-local-map [(shift left)]
15457 (lambda () (interactive)
15458 (org-eval-in-calendar '(calendar-backward-day 1))))
15459 (org-defkey minibuffer-local-map [(shift right)]
15460 (lambda () (interactive)
15461 (org-eval-in-calendar '(calendar-forward-day 1))))
15462 (org-defkey minibuffer-local-map ">"
15463 (lambda () (interactive)
15464 (org-eval-in-calendar '(scroll-calendar-left 1))))
15465 (org-defkey minibuffer-local-map "<"
15466 (lambda () (interactive)
15467 (org-eval-in-calendar '(scroll-calendar-right 1))))
15468 (org-defkey minibuffer-local-map "\C-v"
15469 (lambda () (interactive)
15470 (org-eval-in-calendar
15471 '(calendar-scroll-left-three-months 1))))
15472 (org-defkey minibuffer-local-map "\M-v"
15473 (lambda () (interactive)
15474 (org-eval-in-calendar
15475 '(calendar-scroll-right-three-months 1))))
15476 (run-hooks 'org-read-date-minibuffer-setup-hook)
15477 (unwind-protect
15478 (progn
15479 (use-local-map map)
15480 (setq org-read-date-inactive inactive)
15481 (add-hook 'post-command-hook 'org-read-date-display)
15482 (setq org-ans0 (read-string prompt default-input
15483 'org-read-date-history nil))
15484 ;; org-ans0: from prompt
15485 ;; org-ans1: from mouse click
15486 ;; org-ans2: from calendar motion
15487 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15488 (remove-hook 'post-command-hook 'org-read-date-display)
15489 (use-local-map old-map)
15490 (when org-read-date-overlay
15491 (delete-overlay org-read-date-overlay)
15492 (setq org-read-date-overlay nil)))))
15493 (bury-buffer "*Calendar*")))))
15495 (t ; Naked prompt only
15496 (unwind-protect
15497 (setq ans (read-string prompt default-input
15498 'org-read-date-history timestr))
15499 (when org-read-date-overlay
15500 (delete-overlay org-read-date-overlay)
15501 (setq org-read-date-overlay nil)))))
15503 (setq final (org-read-date-analyze ans org-def org-defdecode))
15505 (when org-read-date-analyze-forced-year
15506 (message "Year was forced into %s"
15507 (if org-read-date-force-compatible-dates
15508 "compatible range (1970-2037)"
15509 "range representable on this machine"))
15510 (ding))
15512 ;; One round trip to get rid of 34th of August and stuff like that....
15513 (setq final (decode-time (apply 'encode-time final)))
15515 (setq org-read-date-final-answer ans)
15517 (if to-time
15518 (apply 'encode-time final)
15519 (if (and (boundp 'org-time-was-given) org-time-was-given)
15520 (format "%04d-%02d-%02d %02d:%02d"
15521 (nth 5 final) (nth 4 final) (nth 3 final)
15522 (nth 2 final) (nth 1 final))
15523 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15525 (defvar org-def)
15526 (defvar org-defdecode)
15527 (defvar org-with-time)
15528 (defun org-read-date-display ()
15529 "Display the current date prompt interpretation in the minibuffer."
15530 (when org-read-date-display-live
15531 (when org-read-date-overlay
15532 (delete-overlay org-read-date-overlay))
15533 (when (minibufferp (current-buffer))
15534 (save-excursion
15535 (end-of-line 1)
15536 (while (not (equal (buffer-substring
15537 (max (point-min) (- (point) 4)) (point))
15538 " "))
15539 (insert " ")))
15540 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15541 " " (or org-ans1 org-ans2)))
15542 (org-end-time-was-given nil)
15543 (f (org-read-date-analyze ans org-def org-defdecode))
15544 (fmts (if org-dcst
15545 org-time-stamp-custom-formats
15546 org-time-stamp-formats))
15547 (fmt (if (or org-with-time
15548 (and (boundp 'org-time-was-given) org-time-was-given))
15549 (cdr fmts)
15550 (car fmts)))
15551 (txt (format-time-string fmt (apply 'encode-time f)))
15552 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15553 (txt (concat "=> " txt)))
15554 (when (and org-end-time-was-given
15555 (string-match org-plain-time-of-day-regexp txt))
15556 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15557 org-end-time-was-given
15558 (substring txt (match-end 0)))))
15559 (when org-read-date-analyze-futurep
15560 (setq txt (concat txt " (=>F)")))
15561 (setq org-read-date-overlay
15562 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15563 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15565 (defun org-read-date-analyze (ans org-def org-defdecode)
15566 "Analyze the combined answer of the date prompt."
15567 ;; FIXME: cleanup and comment
15568 (let ((nowdecode (decode-time (current-time)))
15569 delta deltan deltaw deltadef year month day
15570 hour minute second wday pm h2 m2 tl wday1
15571 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15572 (setq org-read-date-analyze-futurep nil
15573 org-read-date-analyze-forced-year nil)
15574 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15575 (setq ans "+0"))
15577 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15578 (setq ans (replace-match "" t t ans)
15579 deltan (car delta)
15580 deltaw (nth 1 delta)
15581 deltadef (nth 2 delta)))
15583 ;; Check if there is an iso week date in there. If yes, store the
15584 ;; info and postpone interpreting it until the rest of the parsing
15585 ;; is done.
15586 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15587 (setq iso-year (if (match-end 1)
15588 (org-small-year-to-year
15589 (string-to-number (match-string 1 ans))))
15590 iso-weekday (if (match-end 3)
15591 (string-to-number (match-string 3 ans)))
15592 iso-week (string-to-number (match-string 2 ans)))
15593 (setq ans (replace-match "" t t ans)))
15595 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15596 (when (string-match
15597 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15598 (setq year (if (match-end 2)
15599 (string-to-number (match-string 2 ans))
15600 (progn (setq kill-year t)
15601 (string-to-number (format-time-string "%Y"))))
15602 month (string-to-number (match-string 3 ans))
15603 day (string-to-number (match-string 4 ans)))
15604 (if (< year 100) (setq year (+ 2000 year)))
15605 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15606 t nil ans)))
15608 ;; Help matching dotted european dates
15609 (when (string-match
15610 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15611 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15612 (setq kill-year t)
15613 (string-to-number (format-time-string "%Y")))
15614 day (string-to-number (match-string 1 ans))
15615 month (string-to-number (match-string 2 ans))
15616 ans (replace-match (format "%04d-%02d-%02d" year month day)
15617 t nil ans)))
15619 ;; Help matching american dates, like 5/30 or 5/30/7
15620 (when (string-match
15621 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15622 (setq year (if (match-end 4)
15623 (string-to-number (match-string 4 ans))
15624 (progn (setq kill-year t)
15625 (string-to-number (format-time-string "%Y"))))
15626 month (string-to-number (match-string 1 ans))
15627 day (string-to-number (match-string 2 ans)))
15628 (if (< year 100) (setq year (+ 2000 year)))
15629 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15630 t nil ans)))
15631 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15632 ;; If there is a time with am/pm, and *no* time without it, we convert
15633 ;; so that matching will be successful.
15634 (loop for i from 1 to 2 do ; twice, for end time as well
15635 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15636 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15637 (setq hour (string-to-number (match-string 1 ans))
15638 minute (if (match-end 3)
15639 (string-to-number (match-string 3 ans))
15641 pm (equal ?p
15642 (string-to-char (downcase (match-string 4 ans)))))
15643 (if (and (= hour 12) (not pm))
15644 (setq hour 0)
15645 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15646 (setq ans (replace-match (format "%02d:%02d" hour minute)
15647 t t ans))))
15649 ;; Check if a time range is given as a duration
15650 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15651 (setq hour (string-to-number (match-string 1 ans))
15652 h2 (+ hour (string-to-number (match-string 3 ans)))
15653 minute (string-to-number (match-string 2 ans))
15654 m2 (+ minute (if (match-end 5) (string-to-number
15655 (match-string 5 ans))0)))
15656 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15657 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15658 t t ans)))
15660 ;; Check if there is a time range
15661 (when (boundp 'org-end-time-was-given)
15662 (setq org-time-was-given nil)
15663 (when (and (string-match org-plain-time-of-day-regexp ans)
15664 (match-end 8))
15665 (setq org-end-time-was-given (match-string 8 ans))
15666 (setq ans (concat (substring ans 0 (match-beginning 7))
15667 (substring ans (match-end 7))))))
15669 (setq tl (parse-time-string ans)
15670 day (or (nth 3 tl) (nth 3 org-defdecode))
15671 month (or (nth 4 tl)
15672 (if (and org-read-date-prefer-future
15673 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15674 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15675 (nth 4 org-defdecode)))
15676 year (or (and (not kill-year) (nth 5 tl))
15677 (if (and org-read-date-prefer-future
15678 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15679 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15680 (nth 5 org-defdecode)))
15681 hour (or (nth 2 tl) (nth 2 org-defdecode))
15682 minute (or (nth 1 tl) (nth 1 org-defdecode))
15683 second (or (nth 0 tl) 0)
15684 wday (nth 6 tl))
15686 (when (and (eq org-read-date-prefer-future 'time)
15687 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15688 (equal day (nth 3 nowdecode))
15689 (equal month (nth 4 nowdecode))
15690 (equal year (nth 5 nowdecode))
15691 (nth 2 tl)
15692 (or (< (nth 2 tl) (nth 2 nowdecode))
15693 (and (= (nth 2 tl) (nth 2 nowdecode))
15694 (nth 1 tl)
15695 (< (nth 1 tl) (nth 1 nowdecode)))))
15696 (setq day (1+ day)
15697 futurep t))
15699 ;; Special date definitions below
15700 (cond
15701 (iso-week
15702 ;; There was an iso week
15703 (require 'cal-iso)
15704 (setq futurep nil)
15705 (setq year (or iso-year year)
15706 day (or iso-weekday wday 1)
15707 wday nil ; to make sure that the trigger below does not match
15708 iso-date (calendar-gregorian-from-absolute
15709 (calendar-absolute-from-iso
15710 (list iso-week day year))))
15711 ; FIXME: Should we also push ISO weeks into the future?
15712 ; (when (and org-read-date-prefer-future
15713 ; (not iso-year)
15714 ; (< (calendar-absolute-from-gregorian iso-date)
15715 ; (time-to-days (current-time))))
15716 ; (setq year (1+ year)
15717 ; iso-date (calendar-gregorian-from-absolute
15718 ; (calendar-absolute-from-iso
15719 ; (list iso-week day year)))))
15720 (setq month (car iso-date)
15721 year (nth 2 iso-date)
15722 day (nth 1 iso-date)))
15723 (deltan
15724 (setq futurep nil)
15725 (unless deltadef
15726 (let ((now (decode-time (current-time))))
15727 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15728 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15729 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15730 ((equal deltaw "m") (setq month (+ month deltan)))
15731 ((equal deltaw "y") (setq year (+ year deltan)))))
15732 ((and wday (not (nth 3 tl)))
15733 ;; Weekday was given, but no day, so pick that day in the week
15734 ;; on or after the derived date.
15735 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15736 (unless (equal wday wday1)
15737 (setq day (+ day (% (- wday wday1 -7) 7))))))
15738 (if (and (boundp 'org-time-was-given)
15739 (nth 2 tl))
15740 (setq org-time-was-given t))
15741 (if (< year 100) (setq year (+ 2000 year)))
15742 ;; Check of the date is representable
15743 (if org-read-date-force-compatible-dates
15744 (progn
15745 (if (< year 1970)
15746 (setq year 1970 org-read-date-analyze-forced-year t))
15747 (if (> year 2037)
15748 (setq year 2037 org-read-date-analyze-forced-year t)))
15749 (condition-case nil
15750 (ignore (encode-time second minute hour day month year))
15751 (error
15752 (setq year (nth 5 org-defdecode))
15753 (setq org-read-date-analyze-forced-year t))))
15754 (setq org-read-date-analyze-futurep futurep)
15755 (list second minute hour day month year)))
15757 (defvar parse-time-weekdays)
15758 (defun org-read-date-get-relative (s today default)
15759 "Check string S for special relative date string.
15760 TODAY and DEFAULT are internal times, for today and for a default.
15761 Return shift list (N what def-flag)
15762 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15763 N is the number of WHATs to shift.
15764 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15765 the DEFAULT date rather than TODAY."
15766 (require 'parse-time)
15767 (when (and
15768 (string-match
15769 (concat
15770 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15771 "\\([0-9]+\\)?"
15772 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15773 "\\([ \t]\\|$\\)") s)
15774 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15775 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15776 (string-to-char (substring (match-string 1 s) -1))
15777 ?+))
15778 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15779 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15780 (what (if (match-end 3) (match-string 3 s) "d"))
15781 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15782 (date (if rel default today))
15783 (wday (nth 6 (decode-time date)))
15784 delta)
15785 (if wday1
15786 (progn
15787 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15788 (if (= dir ?-) (setq delta (- delta 7)))
15789 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15790 (list delta "d" rel))
15791 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15793 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15794 "Turn a user-specified date into the internal representation.
15795 The internal representation needed by the calendar is (month day year).
15796 This is a wrapper to handle the brain-dead convention in calendar that
15797 user function argument order change dependent on argument order."
15798 (if (boundp 'calendar-date-style)
15799 (cond
15800 ((eq calendar-date-style 'american)
15801 (list arg1 arg2 arg3))
15802 ((eq calendar-date-style 'european)
15803 (list arg2 arg1 arg3))
15804 ((eq calendar-date-style 'iso)
15805 (list arg2 arg3 arg1)))
15806 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15807 (if (org-bound-and-true-p european-calendar-style)
15808 (list arg2 arg1 arg3)
15809 (list arg1 arg2 arg3)))))
15811 (defun org-eval-in-calendar (form &optional keepdate)
15812 "Eval FORM in the calendar window and return to current window.
15813 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15814 otherwise stick to the current value of `org-ans2'."
15815 (let ((sf (selected-frame))
15816 (sw (selected-window)))
15817 (select-window (get-buffer-window "*Calendar*" t))
15818 (eval form)
15819 (when (and (not keepdate) (calendar-cursor-to-date))
15820 (let* ((date (calendar-cursor-to-date))
15821 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15822 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15823 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15824 (select-window sw)
15825 (org-select-frame-set-input-focus sf)))
15827 (defun org-calendar-select ()
15828 "Return to `org-read-date' with the date currently selected.
15829 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15830 (interactive)
15831 (when (calendar-cursor-to-date)
15832 (let* ((date (calendar-cursor-to-date))
15833 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15834 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15835 (if (active-minibuffer-window) (exit-minibuffer))))
15837 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15838 "Insert a date stamp for the date given by the internal TIME.
15839 WITH-HM means use the stamp format that includes the time of the day.
15840 INACTIVE means use square brackets instead of angular ones, so that the
15841 stamp will not contribute to the agenda.
15842 PRE and POST are optional strings to be inserted before and after the
15843 stamp.
15844 The command returns the inserted time stamp."
15845 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15846 stamp)
15847 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15848 (insert-before-markers (or pre ""))
15849 (when (listp extra)
15850 (setq extra (car extra))
15851 (if (and (stringp extra)
15852 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15853 (setq extra (format "-%02d:%02d"
15854 (string-to-number (match-string 1 extra))
15855 (string-to-number (match-string 2 extra))))
15856 (setq extra nil)))
15857 (when extra
15858 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15859 (insert-before-markers (setq stamp (format-time-string fmt time)))
15860 (insert-before-markers (or post ""))
15861 (setq org-last-inserted-timestamp stamp)))
15863 (defun org-toggle-time-stamp-overlays ()
15864 "Toggle the use of custom time stamp formats."
15865 (interactive)
15866 (setq org-display-custom-times (not org-display-custom-times))
15867 (unless org-display-custom-times
15868 (let ((p (point-min)) (bmp (buffer-modified-p)))
15869 (while (setq p (next-single-property-change p 'display))
15870 (if (and (get-text-property p 'display)
15871 (eq (get-text-property p 'face) 'org-date))
15872 (remove-text-properties
15873 p (setq p (next-single-property-change p 'display))
15874 '(display t))))
15875 (set-buffer-modified-p bmp)))
15876 (if (featurep 'xemacs)
15877 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15878 (org-restart-font-lock)
15879 (setq org-table-may-need-update t)
15880 (if org-display-custom-times
15881 (message "Time stamps are overlaid with custom format")
15882 (message "Time stamp overlays removed")))
15884 (defun org-display-custom-time (beg end)
15885 "Overlay modified time stamp format over timestamp between BEG and END."
15886 (let* ((ts (buffer-substring beg end))
15887 t1 w1 with-hm tf time str w2 (off 0))
15888 (save-match-data
15889 (setq t1 (org-parse-time-string ts t))
15890 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15891 (setq off (- (match-end 0) (match-beginning 0)))))
15892 (setq end (- end off))
15893 (setq w1 (- end beg)
15894 with-hm (and (nth 1 t1) (nth 2 t1))
15895 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15896 time (org-fix-decoded-time t1)
15897 str (org-add-props
15898 (format-time-string
15899 (substring tf 1 -1) (apply 'encode-time time))
15900 nil 'mouse-face 'highlight)
15901 w2 (length str))
15902 (if (not (= w2 w1))
15903 (add-text-properties (1+ beg) (+ 2 beg)
15904 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15905 (if (featurep 'xemacs)
15906 (progn
15907 (put-text-property beg end 'invisible t)
15908 (put-text-property beg end 'end-glyph (make-glyph str)))
15909 (put-text-property beg end 'display str))))
15911 (defun org-translate-time (string)
15912 "Translate all timestamps in STRING to custom format.
15913 But do this only if the variable `org-display-custom-times' is set."
15914 (when org-display-custom-times
15915 (save-match-data
15916 (let* ((start 0)
15917 (re org-ts-regexp-both)
15918 t1 with-hm inactive tf time str beg end)
15919 (while (setq start (string-match re string start))
15920 (setq beg (match-beginning 0)
15921 end (match-end 0)
15922 t1 (save-match-data
15923 (org-parse-time-string (substring string beg end) t))
15924 with-hm (and (nth 1 t1) (nth 2 t1))
15925 inactive (equal (substring string beg (1+ beg)) "[")
15926 tf (funcall (if with-hm 'cdr 'car)
15927 org-time-stamp-custom-formats)
15928 time (org-fix-decoded-time t1)
15929 str (format-time-string
15930 (concat
15931 (if inactive "[" "<") (substring tf 1 -1)
15932 (if inactive "]" ">"))
15933 (apply 'encode-time time))
15934 string (replace-match str t t string)
15935 start (+ start (length str)))))))
15936 string)
15938 (defun org-fix-decoded-time (time)
15939 "Set 0 instead of nil for the first 6 elements of time.
15940 Don't touch the rest."
15941 (let ((n 0))
15942 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15944 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
15946 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
15947 "Difference between TIMESTAMP-STRING and now in days.
15948 If SECONDS is non-nil, return the difference in seconds."
15949 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
15950 (- (funcall fdiff (org-time-string-to-time timestamp-string))
15951 (funcall fdiff (current-time)))))
15953 (defun org-deadline-close (timestamp-string &optional ndays)
15954 "Is the time in TIMESTAMP-STRING close to the current date?"
15955 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15956 (and (< (org-time-stamp-to-now timestamp-string) ndays)
15957 (not (org-entry-is-done-p))))
15959 (defun org-get-wdays (ts)
15960 "Get the deadline lead time appropriate for timestring TS."
15961 (cond
15962 ((<= org-deadline-warning-days 0)
15963 ;; 0 or negative, enforce this value no matter what
15964 (- org-deadline-warning-days))
15965 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15966 ;; lead time is specified.
15967 (floor (* (string-to-number (match-string 1 ts))
15968 (cdr (assoc (match-string 2 ts)
15969 '(("d" . 1) ("w" . 7)
15970 ("m" . 30.4) ("y" . 365.25)))))))
15971 ;; go for the default.
15972 (t org-deadline-warning-days)))
15974 (defun org-calendar-select-mouse (ev)
15975 "Return to `org-read-date' with the date currently selected.
15976 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15977 (interactive "e")
15978 (mouse-set-point ev)
15979 (when (calendar-cursor-to-date)
15980 (let* ((date (calendar-cursor-to-date))
15981 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15982 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15983 (if (active-minibuffer-window) (exit-minibuffer))))
15985 (defun org-check-deadlines (ndays)
15986 "Check if there are any deadlines due or past due.
15987 A deadline is considered due if it happens within `org-deadline-warning-days'
15988 days from today's date. If the deadline appears in an entry marked DONE,
15989 it is not shown. The prefix arg NDAYS can be used to test that many
15990 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15991 (interactive "P")
15992 (let* ((org-warn-days
15993 (cond
15994 ((equal ndays '(4)) 100000)
15995 (ndays (prefix-numeric-value ndays))
15996 (t (abs org-deadline-warning-days))))
15997 (case-fold-search nil)
15998 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15999 (callback
16000 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16002 (message "%d deadlines past-due or due within %d days"
16003 (org-occur regexp nil callback)
16004 org-warn-days)))
16006 (defsubst org-re-timestamp (type)
16007 "Return a regexp for timestamp TYPE.
16008 Allowed values for TYPE are:
16010 all: all timestamps
16011 active: only active timestamps (<...>)
16012 inactive: only inactive timestamps ([...])
16013 scheduled: only scheduled timestamps
16014 deadline: only deadline timestamps
16016 When TYPE is nil, fall back on returning a regexp that matches
16017 both scheduled and deadline timestamps."
16018 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16019 ((eq type 'active) org-ts-regexp)
16020 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16021 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16022 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16023 ((eq type 'scheduled-or-deadline)
16024 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16026 (defun org-check-before-date (date)
16027 "Check if there are deadlines or scheduled entries before DATE."
16028 (interactive (list (org-read-date)))
16029 (let ((case-fold-search nil)
16030 (regexp (org-re-timestamp org-ts-type))
16031 (callback
16032 (lambda () (time-less-p
16033 (org-time-string-to-time (match-string 1))
16034 (org-time-string-to-time date)))))
16035 (message "%d entries before %s"
16036 (org-occur regexp nil callback) date)))
16038 (defun org-check-after-date (date)
16039 "Check if there are deadlines or scheduled entries after DATE."
16040 (interactive (list (org-read-date)))
16041 (let ((case-fold-search nil)
16042 (regexp (org-re-timestamp org-ts-type))
16043 (callback
16044 (lambda () (not
16045 (time-less-p
16046 (org-time-string-to-time (match-string 1))
16047 (org-time-string-to-time date))))))
16048 (message "%d entries after %s"
16049 (org-occur regexp nil callback) date)))
16051 (defun org-check-dates-range (start-date end-date)
16052 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16053 (interactive (list (org-read-date nil nil nil "Range starts")
16054 (org-read-date nil nil nil "Range end")))
16055 (let ((case-fold-search nil)
16056 (regexp (org-re-timestamp org-ts-type))
16057 (callback
16058 (lambda ()
16059 (let ((match (match-string 1)))
16060 (and
16061 (not (time-less-p
16062 (org-time-string-to-time match)
16063 (org-time-string-to-time start-date)))
16064 (time-less-p
16065 (org-time-string-to-time match)
16066 (org-time-string-to-time end-date)))))))
16067 (message "%d entries between %s and %s"
16068 (org-occur regexp nil callback) start-date end-date)))
16070 (defun org-evaluate-time-range (&optional to-buffer)
16071 "Evaluate a time range by computing the difference between start and end.
16072 Normally the result is just printed in the echo area, but with prefix arg
16073 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16074 If the time range is actually in a table, the result is inserted into the
16075 next column.
16076 For time difference computation, a year is assumed to be exactly 365
16077 days in order to avoid rounding problems."
16078 (interactive "P")
16080 (org-clock-update-time-maybe)
16081 (save-excursion
16082 (unless (org-at-date-range-p t)
16083 (goto-char (point-at-bol))
16084 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16085 (if (not (org-at-date-range-p t))
16086 (error "Not at a time-stamp range, and none found in current line")))
16087 (let* ((ts1 (match-string 1))
16088 (ts2 (match-string 2))
16089 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16090 (match-end (match-end 0))
16091 (time1 (org-time-string-to-time ts1))
16092 (time2 (org-time-string-to-time ts2))
16093 (t1 (org-float-time time1))
16094 (t2 (org-float-time time2))
16095 (diff (abs (- t2 t1)))
16096 (negative (< (- t2 t1) 0))
16097 ;; (ys (floor (* 365 24 60 60)))
16098 (ds (* 24 60 60))
16099 (hs (* 60 60))
16100 (fy "%dy %dd %02d:%02d")
16101 (fy1 "%dy %dd")
16102 (fd "%dd %02d:%02d")
16103 (fd1 "%dd")
16104 (fh "%02d:%02d")
16105 y d h m align)
16106 (if havetime
16107 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16109 d (floor (/ diff ds)) diff (mod diff ds)
16110 h (floor (/ diff hs)) diff (mod diff hs)
16111 m (floor (/ diff 60)))
16112 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16114 d (floor (+ (/ diff ds) 0.5))
16115 h 0 m 0))
16116 (if (not to-buffer)
16117 (message "%s" (org-make-tdiff-string y d h m))
16118 (if (org-at-table-p)
16119 (progn
16120 (goto-char match-end)
16121 (setq align t)
16122 (and (looking-at " *|") (goto-char (match-end 0))))
16123 (goto-char match-end))
16124 (if (looking-at
16125 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16126 (replace-match ""))
16127 (if negative (insert " -"))
16128 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16129 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16130 (insert " " (format fh h m))))
16131 (if align (org-table-align))
16132 (message "Time difference inserted")))))
16134 (defun org-make-tdiff-string (y d h m)
16135 (let ((fmt "")
16136 (l nil))
16137 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16138 l (push y l)))
16139 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16140 l (push d l)))
16141 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16142 l (push h l)))
16143 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16144 l (push m l)))
16145 (apply 'format fmt (nreverse l))))
16147 (defun org-time-string-to-time (s &optional buffer pos)
16148 "Convert a timestamp string into internal time."
16149 (condition-case errdata
16150 (apply 'encode-time (org-parse-time-string s))
16151 (error (error "Bad timestamp `%s'%s\nError was: %s"
16152 s (if (not (and buffer pos))
16154 (format " at %d in buffer `%s'" pos buffer))
16155 (cdr errdata)))))
16157 (defun org-time-string-to-seconds (s)
16158 "Convert a timestamp string to a number of seconds."
16159 (org-float-time (org-time-string-to-time s)))
16161 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16162 "Convert a time stamp to an absolute day number.
16163 If there is a specifier for a cyclic time stamp, get the closest date to
16164 DAYNR.
16165 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16166 The variable date is bound by the calendar when this is called."
16167 (cond
16168 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16169 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16170 daynr
16171 (+ daynr 1000)))
16172 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16173 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16174 (time-to-days (current-time))) (match-string 0 s)
16175 prefer show-all))
16176 (t (time-to-days
16177 (condition-case errdata
16178 (apply 'encode-time (org-parse-time-string s))
16179 (error (error "Bad timestamp `%s'%s\nError was: %s"
16180 s (if (not (and buffer pos))
16182 (format " at %d in buffer `%s'" pos buffer))
16183 (cdr errdata))))))))
16185 (defun org-days-to-iso-week (days)
16186 "Return the iso week number."
16187 (require 'cal-iso)
16188 (car (calendar-iso-from-absolute days)))
16190 (defun org-small-year-to-year (year)
16191 "Convert 2-digit years into 4-digit years.
16192 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16193 The year 2000 cannot be abbreviated. Any year larger than 99
16194 is returned unchanged."
16195 (if (< year 38)
16196 (setq year (+ 2000 year))
16197 (if (< year 100)
16198 (setq year (+ 1900 year))))
16199 year)
16201 (defun org-time-from-absolute (d)
16202 "Return the time corresponding to date D.
16203 D may be an absolute day number, or a calendar-type list (month day year)."
16204 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16205 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16207 (defun org-calendar-holiday ()
16208 "List of holidays, for Diary display in Org-mode."
16209 (require 'holidays)
16210 (let ((hl (funcall
16211 (if (fboundp 'calendar-check-holidays)
16212 'calendar-check-holidays 'check-calendar-holidays) date)))
16213 (if hl (mapconcat 'identity hl "; "))))
16215 (defun org-diary-sexp-entry (sexp entry date)
16216 "Process a SEXP diary ENTRY for DATE."
16217 (require 'diary-lib)
16218 (let ((result (if calendar-debug-sexp
16219 (let ((stack-trace-on-error t))
16220 (eval (car (read-from-string sexp))))
16221 (condition-case nil
16222 (eval (car (read-from-string sexp)))
16223 (error
16224 (beep)
16225 (message "Bad sexp at line %d in %s: %s"
16226 (org-current-line)
16227 (buffer-file-name) sexp)
16228 (sleep-for 2))))))
16229 (cond ((stringp result) (split-string result "; "))
16230 ((and (consp result)
16231 (not (consp (cdr result)))
16232 (stringp (cdr result))) (cdr result))
16233 ((and (consp result)
16234 (stringp (car result))) result)
16235 (result entry))))
16237 (defun org-diary-to-ical-string (frombuf)
16238 "Get iCalendar entries from diary entries in buffer FROMBUF.
16239 This uses the icalendar.el library."
16240 (let* ((tmpdir (if (featurep 'xemacs)
16241 (temp-directory)
16242 temporary-file-directory))
16243 (tmpfile (make-temp-name
16244 (expand-file-name "orgics" tmpdir)))
16245 buf rtn b e)
16246 (with-current-buffer frombuf
16247 (icalendar-export-region (point-min) (point-max) tmpfile)
16248 (setq buf (find-buffer-visiting tmpfile))
16249 (set-buffer buf)
16250 (goto-char (point-min))
16251 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16252 (setq b (match-beginning 0)))
16253 (goto-char (point-max))
16254 (if (re-search-backward "^END:VEVENT" nil t)
16255 (setq e (match-end 0)))
16256 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16257 (kill-buffer buf)
16258 (delete-file tmpfile)
16259 rtn))
16261 (defun org-closest-date (start current change prefer show-all)
16262 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16263 When PREFER is `past', return a date that is either CURRENT or past.
16264 When PREFER is `future', return a date that is either CURRENT or future.
16265 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16266 ;; Make the proper lists from the dates
16267 (catch 'exit
16268 (let ((a1 '(("h" . hour)
16269 ("d" . day)
16270 ("w" . week)
16271 ("m" . month)
16272 ("y" . year)))
16273 (shour (nth 2 (org-parse-time-string start)))
16274 dn dw sday cday n1 n2 n0
16275 d m y y1 y2 date1 date2 nmonths nm ny m2)
16277 (setq start (org-date-to-gregorian start)
16278 current (org-date-to-gregorian
16279 (if show-all
16280 current
16281 (time-to-days (current-time))))
16282 sday (calendar-absolute-from-gregorian start)
16283 cday (calendar-absolute-from-gregorian current))
16285 (if (<= cday sday) (throw 'exit sday))
16287 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16288 (setq dn (string-to-number (match-string 1 change))
16289 dw (cdr (assoc (match-string 2 change) a1)))
16290 (error "Invalid change specifier: %s" change))
16291 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16292 (cond
16293 ((eq dw 'hour)
16294 (let ((missing-hours
16295 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16296 dn)))
16297 (setq n1 (if (zerop missing-hours) cday
16298 (- cday (1+ (floor (/ missing-hours 24)))))
16299 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16300 ((eq dw 'day)
16301 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16302 n2 (+ n1 dn)))
16303 ((eq dw 'year)
16304 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16305 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16306 (setq date1 (list m d y1)
16307 n1 (calendar-absolute-from-gregorian date1)
16308 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16309 n2 (calendar-absolute-from-gregorian date2)))
16310 ((eq dw 'month)
16311 ;; approx number of month between the two dates
16312 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16313 ;; How often does dn fit in there?
16314 (setq d (nth 1 start) m (car start) y (nth 2 start)
16315 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16316 m (+ m nm)
16317 ny (floor (/ m 12))
16318 y (+ y ny)
16319 m (- m (* ny 12)))
16320 (while (> m 12) (setq m (- m 12) y (1+ y)))
16321 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16322 (setq m2 (+ m dn) y2 y)
16323 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16324 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16325 (while (<= n2 cday)
16326 (setq n1 n2 m m2 y y2)
16327 (setq m2 (+ m dn) y2 y)
16328 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16329 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16330 ;; Make sure n1 is the earlier date
16331 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16332 (if show-all
16333 (cond
16334 ((eq prefer 'past) (if (= cday n2) n2 n1))
16335 ((eq prefer 'future) (if (= cday n1) n1 n2))
16336 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16337 (cond
16338 ((eq prefer 'past) (if (= cday n2) n2 n1))
16339 ((eq prefer 'future) (if (= cday n1) n1 n2))
16340 (t (if (= cday n1) n1 n2)))))))
16342 (defun org-date-to-gregorian (date)
16343 "Turn any specification of DATE into a Gregorian date for the calendar."
16344 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16345 ((and (listp date) (= (length date) 3)) date)
16346 ((stringp date)
16347 (setq date (org-parse-time-string date))
16348 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16349 ((listp date)
16350 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16352 (defun org-parse-time-string (s &optional nodefault)
16353 "Parse the standard Org-mode time string.
16354 This should be a lot faster than the normal `parse-time-string'.
16355 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16356 hour and minute fields will be nil if not given."
16357 (if (string-match org-ts-regexp0 s)
16358 (list 0
16359 (if (or (match-beginning 8) (not nodefault))
16360 (string-to-number (or (match-string 8 s) "0")))
16361 (if (or (match-beginning 7) (not nodefault))
16362 (string-to-number (or (match-string 7 s) "0")))
16363 (string-to-number (match-string 4 s))
16364 (string-to-number (match-string 3 s))
16365 (string-to-number (match-string 2 s))
16366 nil nil nil)
16367 (error "Not a standard Org-mode time string: %s" s)))
16369 (defun org-timestamp-up (&optional arg)
16370 "Increase the date item at the cursor by one.
16371 If the cursor is on the year, change the year. If it is on the month,
16372 the day or the time, change that.
16373 With prefix ARG, change by that many units."
16374 (interactive "p")
16375 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16377 (defun org-timestamp-down (&optional arg)
16378 "Decrease the date item at the cursor by one.
16379 If the cursor is on the year, change the year. If it is on the month,
16380 the day or the time, change that.
16381 With prefix ARG, change by that many units."
16382 (interactive "p")
16383 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16385 (defun org-timestamp-up-day (&optional arg)
16386 "Increase the date in the time stamp by one day.
16387 With prefix ARG, change that many days."
16388 (interactive "p")
16389 (if (and (not (org-at-timestamp-p t))
16390 (org-at-heading-p))
16391 (org-todo 'up)
16392 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16394 (defun org-timestamp-down-day (&optional arg)
16395 "Decrease the date in the time stamp by one day.
16396 With prefix ARG, change that many days."
16397 (interactive "p")
16398 (if (and (not (org-at-timestamp-p t))
16399 (org-at-heading-p))
16400 (org-todo 'down)
16401 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16403 (defun org-at-timestamp-p (&optional inactive-ok)
16404 "Determine if the cursor is in or at a timestamp."
16405 (interactive)
16406 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16407 (pos (point))
16408 (ans (or (looking-at tsr)
16409 (save-excursion
16410 (skip-chars-backward "^[<\n\r\t")
16411 (if (> (point) (point-min)) (backward-char 1))
16412 (and (looking-at tsr)
16413 (> (- (match-end 0) pos) -1))))))
16414 (and ans
16415 (boundp 'org-ts-what)
16416 (setq org-ts-what
16417 (cond
16418 ((= pos (match-beginning 0)) 'bracket)
16419 ;; Point is considered to be "on the bracket" whether
16420 ;; it's really on it or right after it.
16421 ((= pos (1- (match-end 0))) 'bracket)
16422 ((= pos (match-end 0)) 'after)
16423 ((org-pos-in-match-range pos 2) 'year)
16424 ((org-pos-in-match-range pos 3) 'month)
16425 ((org-pos-in-match-range pos 7) 'hour)
16426 ((org-pos-in-match-range pos 8) 'minute)
16427 ((or (org-pos-in-match-range pos 4)
16428 (org-pos-in-match-range pos 5)) 'day)
16429 ((and (> pos (or (match-end 8) (match-end 5)))
16430 (< pos (match-end 0)))
16431 (- pos (or (match-end 8) (match-end 5))))
16432 (t 'day))))
16433 ans))
16435 (defun org-toggle-timestamp-type ()
16436 "Toggle the type (<active> or [inactive]) of a time stamp."
16437 (interactive)
16438 (when (org-at-timestamp-p t)
16439 (let ((beg (match-beginning 0)) (end (match-end 0))
16440 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16441 (save-excursion
16442 (goto-char beg)
16443 (while (re-search-forward "[][<>]" end t)
16444 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16445 t t)))
16446 (message "Timestamp is now %sactive"
16447 (if (equal (char-after beg) ?<) "" "in")))))
16449 (defvar org-clock-history) ; defined in org-clock.el
16450 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16451 (defun org-timestamp-change (n &optional what updown)
16452 "Change the date in the time stamp at point.
16453 The date will be changed by N times WHAT. WHAT can be `day', `month',
16454 `year', `minute', `second'. If WHAT is not given, the cursor position
16455 in the timestamp determines what will be changed."
16456 (let ((origin (point)) origin-cat
16457 with-hm inactive
16458 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16459 org-ts-what
16460 extra rem
16461 ts time time0 fixnext clrgx)
16462 (if (not (org-at-timestamp-p t))
16463 (error "Not at a timestamp"))
16464 (if (and (not what) (eq org-ts-what 'bracket))
16465 (org-toggle-timestamp-type)
16466 ;; Point isn't on brackets. Remember the part of the time-stamp
16467 ;; the point was in. Indeed, size of time-stamps may change,
16468 ;; but point must be kept in the same category nonetheless.
16469 (setq origin-cat org-ts-what)
16470 (if (and (not what) (not (eq org-ts-what 'day))
16471 org-display-custom-times
16472 (get-text-property (point) 'display)
16473 (not (get-text-property (1- (point)) 'display)))
16474 (setq org-ts-what 'day))
16475 (setq org-ts-what (or what org-ts-what)
16476 inactive (= (char-after (match-beginning 0)) ?\[)
16477 ts (match-string 0))
16478 (replace-match "")
16479 (if (string-match
16480 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16482 (setq extra (match-string 1 ts)))
16483 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16484 (setq with-hm t))
16485 (setq time0 (org-parse-time-string ts))
16486 (when (and updown
16487 (eq org-ts-what 'minute)
16488 (not current-prefix-arg))
16489 ;; This looks like s-up and s-down. Change by one rounding step.
16490 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16491 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16492 (setcar (cdr time0) (+ (nth 1 time0)
16493 (if (> n 0) (- rem) (- dm rem))))))
16494 (setq time
16495 (encode-time (or (car time0) 0)
16496 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16497 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16498 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16499 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16500 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16501 (nthcdr 6 time0)))
16502 (when (and (member org-ts-what '(hour minute))
16503 extra
16504 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16505 (setq extra (org-modify-ts-extra
16506 extra
16507 (if (eq org-ts-what 'hour) 2 5)
16508 n dm)))
16509 (when (integerp org-ts-what)
16510 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16511 (if (eq what 'calendar)
16512 (let ((cal-date (org-get-date-from-calendar)))
16513 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16514 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16515 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16516 (setcar time0 (or (car time0) 0))
16517 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16518 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16519 (setq time (apply 'encode-time time0))))
16520 ;; Insert the new time-stamp, and ensure point stays in the same
16521 ;; category as before (i.e. not after the last position in that
16522 ;; category).
16523 (let ((pos (point)))
16524 ;; Stay before inserted string. `save-excursion' is of no use.
16525 (setq org-last-changed-timestamp
16526 (org-insert-time-stamp time with-hm inactive nil nil extra))
16527 (goto-char pos))
16528 (save-match-data
16529 (looking-at org-ts-regexp3)
16530 (goto-char (cond
16531 ;; `day' category ends before `hour' if any, or at
16532 ;; the end of the day name.
16533 ((eq origin-cat 'day)
16534 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16535 ((eq origin-cat 'hour) (min (match-end 7) origin))
16536 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16537 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16538 ;; `year' and `month' have both fixed size: point
16539 ;; couldn't have moved into another part.
16540 (t origin))))
16541 ;; Update clock if on a CLOCK line.
16542 (org-clock-update-time-maybe)
16543 ;; Maybe adjust the closest clock in `org-clock-history'
16544 (when org-clock-adjust-closest
16545 (if (not (and (org-at-clock-log-p)
16546 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16547 org-clock-history))))))
16548 (message "No clock to adjust")
16549 (cond ((save-excursion ; fix previous clock?
16550 (re-search-backward org-ts-regexp0 nil t)
16551 (org-looking-back (concat org-clock-string " \\[")))
16552 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16553 ((save-excursion ; fix next clock?
16554 (re-search-backward org-ts-regexp0 nil t)
16555 (looking-at (concat org-ts-regexp0 "\\] =>")))
16556 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16557 (save-window-excursion
16558 ;; Find closest clock to point, adjust the previous/next one in history
16559 (let* ((p (save-excursion (org-back-to-heading t)))
16560 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16561 (clfixnth
16562 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16563 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16564 (if (not clfixpos)
16565 (message "No clock to adjust")
16566 (save-excursion
16567 (org-goto-marker-or-bmk clfixpos)
16568 (org-show-subtree)
16569 (when (re-search-forward clrgx nil t)
16570 (goto-char (match-beginning 1))
16571 (let (org-clock-adjust-closest)
16572 (org-timestamp-change n org-ts-what updown))
16573 (message "Clock adjusted in %s for heading: %s"
16574 (file-name-nondirectory (buffer-file-name))
16575 (org-get-heading t t)))))))))
16576 ;; Try to recenter the calendar window, if any.
16577 (if (and org-calendar-follow-timestamp-change
16578 (get-buffer-window "*Calendar*" t)
16579 (memq org-ts-what '(day month year)))
16580 (org-recenter-calendar (time-to-days time))))))
16582 (defun org-modify-ts-extra (s pos n dm)
16583 "Change the different parts of the lead-time and repeat fields in timestamp."
16584 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16585 ng h m new rem)
16586 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16587 (cond
16588 ((or (org-pos-in-match-range pos 2)
16589 (org-pos-in-match-range pos 3))
16590 (setq m (string-to-number (match-string 3 s))
16591 h (string-to-number (match-string 2 s)))
16592 (if (org-pos-in-match-range pos 2)
16593 (setq h (+ h n))
16594 (setq n (* dm (org-no-warnings (signum n))))
16595 (when (not (= 0 (setq rem (% m dm))))
16596 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16597 (setq m (+ m n)))
16598 (if (< m 0) (setq m (+ m 60) h (1- h)))
16599 (if (> m 59) (setq m (- m 60) h (1+ h)))
16600 (setq h (min 24 (max 0 h)))
16601 (setq ng 1 new (format "-%02d:%02d" h m)))
16602 ((org-pos-in-match-range pos 6)
16603 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16604 ((org-pos-in-match-range pos 5)
16605 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16607 ((org-pos-in-match-range pos 9)
16608 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16609 ((org-pos-in-match-range pos 8)
16610 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16612 (when ng
16613 (setq s (concat
16614 (substring s 0 (match-beginning ng))
16616 (substring s (match-end ng))))))
16619 (defun org-recenter-calendar (date)
16620 "If the calendar is visible, recenter it to DATE."
16621 (let ((cwin (get-buffer-window "*Calendar*" t)))
16622 (when cwin
16623 (let ((calendar-move-hook nil))
16624 (with-selected-window cwin
16625 (calendar-goto-date (if (listp date) date
16626 (calendar-gregorian-from-absolute date))))))))
16628 (defun org-goto-calendar (&optional arg)
16629 "Go to the Emacs calendar at the current date.
16630 If there is a time stamp in the current line, go to that date.
16631 A prefix ARG can be used to force the current date."
16632 (interactive "P")
16633 (let ((tsr org-ts-regexp) diff
16634 (calendar-move-hook nil)
16635 (calendar-view-holidays-initially-flag nil)
16636 (calendar-view-diary-initially-flag nil))
16637 (if (or (org-at-timestamp-p)
16638 (save-excursion
16639 (beginning-of-line 1)
16640 (looking-at (concat ".*" tsr))))
16641 (let ((d1 (time-to-days (current-time)))
16642 (d2 (time-to-days
16643 (org-time-string-to-time (match-string 1)))))
16644 (setq diff (- d2 d1))))
16645 (calendar)
16646 (calendar-goto-today)
16647 (if (and diff (not arg)) (calendar-forward-day diff))))
16649 (defun org-get-date-from-calendar ()
16650 "Return a list (month day year) of date at point in calendar."
16651 (with-current-buffer "*Calendar*"
16652 (save-match-data
16653 (calendar-cursor-to-date))))
16655 (defun org-date-from-calendar ()
16656 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16657 If there is already a time stamp at the cursor position, update it."
16658 (interactive)
16659 (if (org-at-timestamp-p t)
16660 (org-timestamp-change 0 'calendar)
16661 (let ((cal-date (org-get-date-from-calendar)))
16662 (org-insert-time-stamp
16663 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16665 (defun org-minutes-to-hh:mm-string (m)
16666 "Compute H:MM from a number of minutes."
16667 (let ((h (/ m 60)))
16668 (setq m (- m (* 60 h)))
16669 (format org-time-clocksum-format h m)))
16671 (defun org-hh:mm-string-to-minutes (s)
16672 "Convert a string H:MM to a number of minutes.
16673 If the string is just a number, interpret it as minutes.
16674 In fact, the first hh:mm or number in the string will be taken,
16675 there can be extra stuff in the string.
16676 If no number is found, the return value is 0."
16677 (cond
16678 ((integerp s) s)
16679 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16680 (+ (* (string-to-number (match-string 1 s)) 60)
16681 (string-to-number (match-string 2 s))))
16682 ((string-match "\\([0-9]+\\)" s)
16683 (string-to-number (match-string 1 s)))
16684 (t 0)))
16686 (defcustom org-effort-durations
16687 `(("h" . 60)
16688 ("d" . ,(* 60 8))
16689 ("w" . ,(* 60 8 5))
16690 ("m" . ,(* 60 8 5 4))
16691 ("y" . ,(* 60 8 5 40)))
16692 "Conversion factor to minutes for an effort modifier.
16694 Each entry has the form (MODIFIER . MINUTES).
16696 In an effort string, a number followed by MODIFIER is multiplied
16697 by the specified number of MINUTES to obtain an effort in
16698 minutes.
16700 For example, if the value of this variable is ((\"hours\" . 60)), then an
16701 effort string \"2hours\" is equivalent to 120 minutes."
16702 :group 'org-agenda
16703 :version "24.1"
16704 :type '(alist :key-type (string :tag "Modifier")
16705 :value-type (number :tag "Minutes")))
16707 (defcustom org-image-actual-width t
16708 "Should we use the actual width of images when inlining them?
16710 When set to `t', always use the image width.
16712 When set to a number, use imagemagick (when available) to set
16713 the image's width to this value.
16715 When set to a number in a list, try to get the width from the
16716 #+ATTR.* keyword if it matches a width specification like
16717 width=\"[0-9]+\", and fall back on that number if none is found.
16719 When set to nil, try to get the width from an #+ATTR.* keyword
16720 and fall back on the original width if none is found.
16722 This requires Emacs >= 24.1, build with imagemagick support."
16723 :group 'org-appearance
16724 :version "24.3"
16725 :type '(choice
16726 (const :tag "Use the image width" t)
16727 (integer :tag "Use a number of pixels")
16728 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16729 (const :tag "Use #+ATTR* or don't resize" nil)))
16731 (defun org-duration-string-to-minutes (s &optional output-to-string)
16732 "Convert a duration string S to minutes.
16734 A bare number is interpreted as minutes, modifiers can be set by
16735 customizing `org-effort-durations' (which see).
16737 Entries containing a colon are interpreted as H:MM by
16738 `org-hh:mm-string-to-minutes'."
16739 (let ((result 0)
16740 (re (concat "\\([0-9.]+\\) *\\("
16741 (regexp-opt (mapcar 'car org-effort-durations))
16742 "\\)")))
16743 (while (string-match re s)
16744 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16745 (string-to-number (match-string 1 s))))
16746 (setq s (replace-match "" nil t s)))
16747 (setq result (floor result))
16748 (incf result (org-hh:mm-string-to-minutes s))
16749 (if output-to-string (number-to-string result) result)))
16751 ;;;; Files
16753 (defun org-save-all-org-buffers ()
16754 "Save all Org-mode buffers without user confirmation."
16755 (interactive)
16756 (message "Saving all Org-mode buffers...")
16757 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16758 (when (featurep 'org-id) (org-id-locations-save))
16759 (message "Saving all Org-mode buffers... done"))
16761 (defun org-revert-all-org-buffers ()
16762 "Revert all Org-mode buffers.
16763 Prompt for confirmation when there are unsaved changes.
16764 Be sure you know what you are doing before letting this function
16765 overwrite your changes.
16767 This function is useful in a setup where one tracks org files
16768 with a version control system, to revert on one machine after pulling
16769 changes from another. I believe the procedure must be like this:
16771 1. M-x org-save-all-org-buffers
16772 2. Pull changes from the other machine, resolve conflicts
16773 3. M-x org-revert-all-org-buffers"
16774 (interactive)
16775 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16776 (error "Abort"))
16777 (save-excursion
16778 (save-window-excursion
16779 (mapc
16780 (lambda (b)
16781 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16782 (with-current-buffer b buffer-file-name))
16783 (org-pop-to-buffer-same-window b)
16784 (revert-buffer t 'no-confirm)))
16785 (buffer-list))
16786 (when (and (featurep 'org-id) org-id-track-globally)
16787 (org-id-locations-load)))))
16789 ;;;; Agenda files
16791 ;;;###autoload
16792 (defun org-switchb (&optional arg)
16793 "Switch between Org buffers.
16794 With one prefix argument, restrict available buffers to files.
16795 With two prefix arguments, restrict available buffers to agenda files.
16797 Defaults to `iswitchb' for buffer name completion.
16798 Set `org-completion-use-ido' to make it use ido instead."
16799 (interactive "P")
16800 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16801 ((equal arg '(16)) (org-buffer-list 'agenda))
16802 (t (org-buffer-list))))
16803 (org-completion-use-iswitchb org-completion-use-iswitchb)
16804 (org-completion-use-ido org-completion-use-ido))
16805 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16806 (setq org-completion-use-iswitchb t))
16807 (org-pop-to-buffer-same-window
16808 (org-icompleting-read "Org buffer: "
16809 (mapcar 'list (mapcar 'buffer-name blist))
16810 nil t))))
16812 ;;; Define some older names previously used for this functionality
16813 ;;;###autoload
16814 (defalias 'org-ido-switchb 'org-switchb)
16815 ;;;###autoload
16816 (defalias 'org-iswitchb 'org-switchb)
16818 (defun org-buffer-list (&optional predicate exclude-tmp)
16819 "Return a list of Org buffers.
16820 PREDICATE can be `export', `files' or `agenda'.
16822 export restrict the list to Export buffers.
16823 files restrict the list to buffers visiting Org files.
16824 agenda restrict the list to buffers visiting agenda files.
16826 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16827 (let* ((bfn nil)
16828 (agenda-files (and (eq predicate 'agenda)
16829 (mapcar 'file-truename (org-agenda-files t))))
16830 (filter
16831 (cond
16832 ((eq predicate 'files)
16833 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16834 ((eq predicate 'export)
16835 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16836 ((eq predicate 'agenda)
16837 (lambda (b)
16838 (with-current-buffer b
16839 (and (derived-mode-p 'org-mode)
16840 (setq bfn (buffer-file-name b))
16841 (member (file-truename bfn) agenda-files)))))
16842 (t (lambda (b) (with-current-buffer b
16843 (or (derived-mode-p 'org-mode)
16844 (string-match "\*Org .*Export"
16845 (buffer-name b)))))))))
16846 (delq nil
16847 (mapcar
16848 (lambda(b)
16849 (if (and (funcall filter b)
16850 (or (not exclude-tmp)
16851 (not (string-match "tmp" (buffer-name b)))))
16853 nil))
16854 (buffer-list)))))
16856 (defun org-agenda-files (&optional unrestricted archives)
16857 "Get the list of agenda files.
16858 Optional UNRESTRICTED means return the full list even if a restriction
16859 is currently in place.
16860 When ARCHIVES is t, include all archive files that are really being
16861 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16862 `org-agenda-archives-mode' is t."
16863 (let ((files
16864 (cond
16865 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16866 ((stringp org-agenda-files) (org-read-agenda-file-list))
16867 ((listp org-agenda-files) org-agenda-files)
16868 (t (error "Invalid value of `org-agenda-files'")))))
16869 (setq files (apply 'append
16870 (mapcar (lambda (f)
16871 (if (file-directory-p f)
16872 (directory-files
16873 f t org-agenda-file-regexp)
16874 (list f)))
16875 files)))
16876 (when org-agenda-skip-unavailable-files
16877 (setq files (delq nil
16878 (mapcar (function
16879 (lambda (file)
16880 (and (file-readable-p file) file)))
16881 files))))
16882 (when (or (eq archives t)
16883 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16884 (setq files (org-add-archive-files files)))
16885 files))
16887 (defun org-agenda-file-p (&optional file)
16888 "Return non-nil, if FILE is an agenda file.
16889 If FILE is omitted, use the file associated with the current
16890 buffer."
16891 (member (or file (buffer-file-name))
16892 (org-agenda-files t)))
16894 (defun org-edit-agenda-file-list ()
16895 "Edit the list of agenda files.
16896 Depending on setup, this either uses customize to edit the variable
16897 `org-agenda-files', or it visits the file that is holding the list. In the
16898 latter case, the buffer is set up in a way that saving it automatically kills
16899 the buffer and restores the previous window configuration."
16900 (interactive)
16901 (if (stringp org-agenda-files)
16902 (let ((cw (current-window-configuration)))
16903 (find-file org-agenda-files)
16904 (org-set-local 'org-window-configuration cw)
16905 (org-add-hook 'after-save-hook
16906 (lambda ()
16907 (set-window-configuration
16908 (prog1 org-window-configuration
16909 (kill-buffer (current-buffer))))
16910 (org-install-agenda-files-menu)
16911 (message "New agenda file list installed"))
16912 nil 'local)
16913 (message "%s" (substitute-command-keys
16914 "Edit list and finish with \\[save-buffer]")))
16915 (customize-variable 'org-agenda-files)))
16917 (defun org-store-new-agenda-file-list (list)
16918 "Set new value for the agenda file list and save it correctly."
16919 (if (stringp org-agenda-files)
16920 (let ((fe (org-read-agenda-file-list t)) b u)
16921 (while (setq b (find-buffer-visiting org-agenda-files))
16922 (kill-buffer b))
16923 (with-temp-file org-agenda-files
16924 (insert
16925 (mapconcat
16926 (lambda (f) ;; Keep un-expanded entries.
16927 (if (setq u (assoc f fe))
16928 (cdr u)
16930 list "\n")
16931 "\n")))
16932 (let ((org-mode-hook nil) (org-inhibit-startup t)
16933 (org-insert-mode-line-in-empty-file nil))
16934 (setq org-agenda-files list)
16935 (customize-save-variable 'org-agenda-files org-agenda-files))))
16937 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16938 "Read the list of agenda files from a file.
16939 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16940 filenames, used by `org-store-new-agenda-file-list' to write back
16941 un-expanded file names."
16942 (when (file-directory-p org-agenda-files)
16943 (error "`org-agenda-files' cannot be a single directory"))
16944 (when (stringp org-agenda-files)
16945 (with-temp-buffer
16946 (insert-file-contents org-agenda-files)
16947 (mapcar
16948 (lambda (f)
16949 (let ((e (expand-file-name (substitute-in-file-name f)
16950 org-directory)))
16951 (if pair-with-expansion
16952 (cons e f)
16953 e)))
16954 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16956 ;;;###autoload
16957 (defun org-cycle-agenda-files ()
16958 "Cycle through the files in `org-agenda-files'.
16959 If the current buffer visits an agenda file, find the next one in the list.
16960 If the current buffer does not, find the first agenda file."
16961 (interactive)
16962 (let* ((fs (org-agenda-files t))
16963 (files (append fs (list (car fs))))
16964 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16965 file)
16966 (unless files (error "No agenda files"))
16967 (catch 'exit
16968 (while (setq file (pop files))
16969 (if (equal (file-truename file) tcf)
16970 (when (car files)
16971 (find-file (car files))
16972 (throw 'exit t))))
16973 (find-file (car fs)))
16974 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16976 (defun org-agenda-file-to-front (&optional to-end)
16977 "Move/add the current file to the top of the agenda file list.
16978 If the file is not present in the list, it is added to the front. If it is
16979 present, it is moved there. With optional argument TO-END, add/move to the
16980 end of the list."
16981 (interactive "P")
16982 (let ((org-agenda-skip-unavailable-files nil)
16983 (file-alist (mapcar (lambda (x)
16984 (cons (file-truename x) x))
16985 (org-agenda-files t)))
16986 (ctf (file-truename buffer-file-name))
16987 x had)
16988 (setq x (assoc ctf file-alist) had x)
16990 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16991 (if to-end
16992 (setq file-alist (append (delq x file-alist) (list x)))
16993 (setq file-alist (cons x (delq x file-alist))))
16994 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16995 (org-install-agenda-files-menu)
16996 (message "File %s to %s of agenda file list"
16997 (if had "moved" "added") (if to-end "end" "front"))))
16999 (defun org-remove-file (&optional file)
17000 "Remove current file from the list of files in variable `org-agenda-files'.
17001 These are the files which are being checked for agenda entries.
17002 Optional argument FILE means use this file instead of the current."
17003 (interactive)
17004 (let* ((org-agenda-skip-unavailable-files nil)
17005 (file (or file buffer-file-name))
17006 (true-file (file-truename file))
17007 (afile (abbreviate-file-name file))
17008 (files (delq nil (mapcar
17009 (lambda (x)
17010 (if (equal true-file
17011 (file-truename x))
17012 nil x))
17013 (org-agenda-files t)))))
17014 (if (not (= (length files) (length (org-agenda-files t))))
17015 (progn
17016 (org-store-new-agenda-file-list files)
17017 (org-install-agenda-files-menu)
17018 (message "Removed file: %s" afile))
17019 (message "File was not in list: %s (not removed)" afile))))
17021 (defun org-file-menu-entry (file)
17022 (vector file (list 'find-file file) t))
17024 (defun org-check-agenda-file (file)
17025 "Make sure FILE exists. If not, ask user what to do."
17026 (when (not (file-exists-p file))
17027 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17028 (abbreviate-file-name file))
17029 (let ((r (downcase (read-char-exclusive))))
17030 (cond
17031 ((equal r ?r)
17032 (org-remove-file file)
17033 (throw 'nextfile t))
17034 (t (error "Abort"))))))
17036 (defun org-get-agenda-file-buffer (file)
17037 "Get a buffer visiting FILE. If the buffer needs to be created, add
17038 it to the list of buffers which might be released later."
17039 (let ((buf (org-find-base-buffer-visiting file)))
17040 (if buf
17041 buf ; just return it
17042 ;; Make a new buffer and remember it
17043 (setq buf (find-file-noselect file))
17044 (if buf (push buf org-agenda-new-buffers))
17045 buf)))
17047 (defun org-release-buffers (blist)
17048 "Release all buffers in list, asking the user for confirmation when needed.
17049 When a buffer is unmodified, it is just killed. When modified, it is saved
17050 \(if the user agrees) and then killed."
17051 (let (buf file)
17052 (while (setq buf (pop blist))
17053 (setq file (buffer-file-name buf))
17054 (when (and (buffer-modified-p buf)
17055 file
17056 (y-or-n-p (format "Save file %s? " file)))
17057 (with-current-buffer buf (save-buffer)))
17058 (kill-buffer buf))))
17060 (defun org-agenda-prepare-buffers (files)
17061 "Create buffers for all agenda files, protect archived trees and comments."
17062 (interactive)
17063 (let ((pa '(:org-archived t))
17064 (pc '(:org-comment t))
17065 (pall '(:org-archived t :org-comment t))
17066 (inhibit-read-only t)
17067 (rea (concat ":" org-archive-tag ":"))
17068 bmp file re)
17069 (save-excursion
17070 (save-restriction
17071 (while (setq file (pop files))
17072 (catch 'nextfile
17073 (if (bufferp file)
17074 (set-buffer file)
17075 (org-check-agenda-file file)
17076 (set-buffer (org-get-agenda-file-buffer file)))
17077 (widen)
17078 (setq bmp (buffer-modified-p))
17079 (org-refresh-category-properties)
17080 (setq org-todo-keywords-for-agenda
17081 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17082 (setq org-done-keywords-for-agenda
17083 (append org-done-keywords-for-agenda org-done-keywords))
17084 (setq org-todo-keyword-alist-for-agenda
17085 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17086 (setq org-drawers-for-agenda
17087 (append org-drawers-for-agenda org-drawers))
17088 (setq org-tag-alist-for-agenda
17089 (append org-tag-alist-for-agenda org-tag-alist))
17091 (save-excursion
17092 (remove-text-properties (point-min) (point-max) pall)
17093 (when org-agenda-skip-archived-trees
17094 (goto-char (point-min))
17095 (while (re-search-forward rea nil t)
17096 (if (org-at-heading-p t)
17097 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17098 (goto-char (point-min))
17099 (setq re (format org-heading-keyword-regexp-format
17100 org-comment-string))
17101 (while (re-search-forward re nil t)
17102 (add-text-properties
17103 (match-beginning 0) (org-end-of-subtree t) pc)))
17104 (set-buffer-modified-p bmp)))))
17105 (setq org-todo-keywords-for-agenda
17106 (org-uniquify org-todo-keywords-for-agenda))
17107 (setq org-todo-keyword-alist-for-agenda
17108 (org-uniquify org-todo-keyword-alist-for-agenda)
17109 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17111 ;;;; Embedded LaTeX
17113 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17114 "Keymap for the minor `org-cdlatex-mode'.")
17116 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17117 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17118 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17119 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17120 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17122 (defvar org-cdlatex-texmathp-advice-is-done nil
17123 "Flag remembering if we have applied the advice to texmathp already.")
17125 (define-minor-mode org-cdlatex-mode
17126 "Toggle the minor `org-cdlatex-mode'.
17127 This mode supports entering LaTeX environment and math in LaTeX fragments
17128 in Org-mode.
17129 \\{org-cdlatex-mode-map}"
17130 nil " OCDL" nil
17131 (when org-cdlatex-mode
17132 (require 'cdlatex)
17133 (run-hooks 'cdlatex-mode-hook)
17134 (cdlatex-compute-tables))
17135 (unless org-cdlatex-texmathp-advice-is-done
17136 (setq org-cdlatex-texmathp-advice-is-done t)
17137 (defadvice texmathp (around org-math-always-on activate)
17138 "Always return t in org-mode buffers.
17139 This is because we want to insert math symbols without dollars even outside
17140 the LaTeX math segments. If Orgmode thinks that point is actually inside
17141 an embedded LaTeX fragment, let texmathp do its job.
17142 \\[org-cdlatex-mode-map]"
17143 (interactive)
17144 (let (p)
17145 (cond
17146 ((not (derived-mode-p 'org-mode)) ad-do-it)
17147 ((eq this-command 'cdlatex-math-symbol)
17148 (setq ad-return-value t
17149 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17151 (let ((p (org-inside-LaTeX-fragment-p)))
17152 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17153 (setq ad-return-value t
17154 texmathp-why '("Org-mode embedded math" . 0))
17155 (if p ad-do-it)))))))))
17157 (defun turn-on-org-cdlatex ()
17158 "Unconditionally turn on `org-cdlatex-mode'."
17159 (org-cdlatex-mode 1))
17161 (defun org-inside-LaTeX-fragment-p ()
17162 "Test if point is inside a LaTeX fragment.
17163 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17164 sequence appearing also before point.
17165 Even though the matchers for math are configurable, this function assumes
17166 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17167 delimiters are skipped when they have been removed by customization.
17168 The return value is nil, or a cons cell with the delimiter and the
17169 position of this delimiter.
17171 This function does a reasonably good job, but can locally be fooled by
17172 for example currency specifications. For example it will assume being in
17173 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17174 fragments that are properly closed, but during editing, we have to live
17175 with the uncertainty caused by missing closing delimiters. This function
17176 looks only before point, not after."
17177 (catch 'exit
17178 (let ((pos (point))
17179 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17180 (lim (progn
17181 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17182 (point)))
17183 dd-on str (start 0) m re)
17184 (goto-char pos)
17185 (when dodollar
17186 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17187 re (nth 1 (assoc "$" org-latex-regexps)))
17188 (while (string-match re str start)
17189 (cond
17190 ((= (match-end 0) (length str))
17191 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17192 ((= (match-end 0) (- (length str) 5))
17193 (throw 'exit nil))
17194 (t (setq start (match-end 0))))))
17195 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17196 (goto-char pos)
17197 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17198 (and (match-beginning 2) (throw 'exit nil))
17199 ;; count $$
17200 (while (re-search-backward "\\$\\$" lim t)
17201 (setq dd-on (not dd-on)))
17202 (goto-char pos)
17203 (if dd-on (cons "$$" m))))))
17205 (defun org-inside-latex-macro-p ()
17206 "Is point inside a LaTeX macro or its arguments?"
17207 (save-match-data
17208 (org-in-regexp
17209 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17211 (defun org-try-cdlatex-tab ()
17212 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17213 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17214 - inside a LaTeX fragment, or
17215 - after the first word in a line, where an abbreviation expansion could
17216 insert a LaTeX environment."
17217 (when org-cdlatex-mode
17218 (cond
17219 ;; Before any word on the line: No expansion possible.
17220 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17221 ;; Just after first word on the line: Expand it. Make sure it
17222 ;; cannot happen on headlines, though.
17223 ((save-excursion
17224 (skip-chars-backward "a-zA-Z0-9*")
17225 (skip-chars-backward " \t")
17226 (and (bolp) (not (org-at-heading-p))))
17227 (cdlatex-tab) t)
17228 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17230 (defun org-cdlatex-underscore-caret (&optional arg)
17231 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17232 Revert to the normal definition outside of these fragments."
17233 (interactive "P")
17234 (if (org-inside-LaTeX-fragment-p)
17235 (call-interactively 'cdlatex-sub-superscript)
17236 (let (org-cdlatex-mode)
17237 (call-interactively (key-binding (vector last-input-event))))))
17239 (defun org-cdlatex-math-modify (&optional arg)
17240 "Execute `cdlatex-math-modify' in LaTeX fragments.
17241 Revert to the normal definition outside of these fragments."
17242 (interactive "P")
17243 (if (org-inside-LaTeX-fragment-p)
17244 (call-interactively 'cdlatex-math-modify)
17245 (let (org-cdlatex-mode)
17246 (call-interactively (key-binding (vector last-input-event))))))
17248 (defvar org-latex-fragment-image-overlays nil
17249 "List of overlays carrying the images of latex fragments.")
17250 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17252 (defun org-remove-latex-fragment-image-overlays ()
17253 "Remove all overlays with LaTeX fragment images in current buffer."
17254 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17255 (setq org-latex-fragment-image-overlays nil))
17257 (defun org-preview-latex-fragment (&optional subtree)
17258 "Preview the LaTeX fragment at point, or all locally or globally.
17259 If the cursor is in a LaTeX fragment, create the image and overlay
17260 it over the source code. If there is no fragment at point, display
17261 all fragments in the current text, from one headline to the next. With
17262 prefix SUBTREE, display all fragments in the current subtree. With a
17263 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17264 the cursor is before the first headline,
17265 display all fragments in the buffer.
17266 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17267 (interactive "P")
17268 (unless buffer-file-name
17269 (error "Can't preview LaTeX fragment in a non-file buffer"))
17270 (org-remove-latex-fragment-image-overlays)
17271 (save-excursion
17272 (save-restriction
17273 (let (beg end at msg)
17274 (cond
17275 ((or (equal subtree '(16))
17276 (not (save-excursion
17277 (re-search-backward org-outline-regexp-bol nil t))))
17278 (setq beg (point-min) end (point-max)
17279 msg "Creating images for buffer...%s"))
17280 ((equal subtree '(4))
17281 (org-back-to-heading)
17282 (setq beg (point) end (org-end-of-subtree t)
17283 msg "Creating images for subtree...%s"))
17285 (if (setq at (org-inside-LaTeX-fragment-p))
17286 (goto-char (max (point-min) (- (cdr at) 2)))
17287 (org-back-to-heading))
17288 (setq beg (point) end (progn (outline-next-heading) (point))
17289 msg (if at "Creating image...%s"
17290 "Creating images for entry...%s"))))
17291 (message msg "")
17292 (narrow-to-region beg end)
17293 (goto-char beg)
17294 (org-format-latex
17295 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17296 (file-name-nondirectory
17297 buffer-file-name)))
17298 default-directory 'overlays msg at 'forbuffer
17299 org-latex-create-formula-image-program)
17300 (message msg "done. Use `C-c C-c' to remove images.")))))
17302 (defvar org-latex-regexps
17303 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17304 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17305 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17306 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17307 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17308 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17309 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17310 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17311 "Regular expressions for matching embedded LaTeX.")
17313 (defvar org-export-have-math nil) ;; dynamic scoping
17314 (defun org-format-latex (prefix &optional dir overlays msg at
17315 forbuffer processing-type)
17316 "Replace LaTeX fragments with links to an image, and produce images.
17317 Some of the options can be changed using the variable
17318 `org-format-latex-options'."
17319 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17320 (let* ((prefixnodir (file-name-nondirectory prefix))
17321 (absprefix (expand-file-name prefix dir))
17322 (todir (file-name-directory absprefix))
17323 (opt org-format-latex-options)
17324 (optnew org-format-latex-options)
17325 (matchers (plist-get opt :matchers))
17326 (re-list org-latex-regexps)
17327 (org-format-latex-header-extra
17328 (plist-get (org-infile-export-plist) :latex-header-extra))
17329 (cnt 0) txt hash link beg end re e checkdir
17330 string
17331 m n block-type block linkfile movefile ov)
17332 ;; Check the different regular expressions
17333 (while (setq e (pop re-list))
17334 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17335 block (if block-type "\n\n" ""))
17336 (when (member m matchers)
17337 (goto-char (point-min))
17338 (while (re-search-forward re nil t)
17339 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17340 (not (get-text-property (match-beginning n)
17341 'org-protected))
17342 (or (not overlays)
17343 (not (eq (get-char-property (match-beginning n)
17344 'org-overlay-type)
17345 'org-latex-overlay))))
17346 (setq org-export-have-math t)
17347 (cond
17348 ((eq processing-type 'verbatim)
17349 ;; Leave the text verbatim, just protect it
17350 (add-text-properties (match-beginning n) (match-end n)
17351 '(org-protected t)))
17352 ((eq processing-type 'mathjax)
17353 ;; Prepare for MathJax processing
17354 (setq string (match-string n))
17355 (if (member m '("$" "$1"))
17356 (save-excursion
17357 (delete-region (match-beginning n) (match-end n))
17358 (goto-char (match-beginning n))
17359 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17360 "\\)")
17361 '(org-protected t))))
17362 (add-text-properties (match-beginning n) (match-end n)
17363 '(org-protected t))))
17364 ((or (eq processing-type 'dvipng)
17365 (eq processing-type 'imagemagick))
17366 ;; Process to an image
17367 (setq txt (match-string n)
17368 beg (match-beginning n) end (match-end n)
17369 cnt (1+ cnt))
17370 (let ((face (face-at-point))
17371 (fg (plist-get opt :foreground))
17372 (bg (plist-get opt :background))
17373 print-length print-level) ; make sure full list is printed
17374 (when forbuffer
17375 ; Get the colors from the face at point
17376 (goto-char beg)
17377 (when (eq fg 'auto)
17378 (setq fg (face-attribute face :foreground nil 'default)))
17379 (when (eq bg 'auto)
17380 (setq bg (face-attribute face :background nil 'default)))
17381 (setq optnew (copy-sequence opt))
17382 (plist-put optnew :foreground fg)
17383 (plist-put optnew :background bg))
17384 (setq hash (sha1 (prin1-to-string
17385 (list org-format-latex-header
17386 org-format-latex-header-extra
17387 org-export-latex-default-packages-alist
17388 org-export-latex-packages-alist
17389 org-format-latex-options
17390 forbuffer txt fg bg)))
17391 linkfile (format "%s_%s.png" prefix hash)
17392 movefile (format "%s_%s.png" absprefix hash)))
17393 (setq link (concat block "[[file:" linkfile "]]" block))
17394 (if msg (message msg cnt))
17395 (goto-char beg)
17396 (unless checkdir ; make sure the directory exists
17397 (setq checkdir t)
17398 (or (file-directory-p todir) (make-directory todir t)))
17399 (org-create-formula-image
17400 txt movefile optnew forbuffer processing-type)
17401 (if overlays
17402 (progn
17403 (mapc (lambda (o)
17404 (if (eq (overlay-get o 'org-overlay-type)
17405 'org-latex-overlay)
17406 (delete-overlay o)))
17407 (overlays-in beg end))
17408 (setq ov (make-overlay beg end))
17409 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17410 (if (featurep 'xemacs)
17411 (progn
17412 (overlay-put ov 'invisible t)
17413 (overlay-put
17414 ov 'end-glyph
17415 (make-glyph (vector 'png :file movefile))))
17416 (overlay-put
17417 ov 'display
17418 (list 'image :type 'png :file movefile :ascent 'center)))
17419 (push ov org-latex-fragment-image-overlays)
17420 (goto-char end))
17421 (delete-region beg end)
17422 (insert (org-add-props link
17423 (list 'org-latex-src
17424 (replace-regexp-in-string
17425 "\"" "" txt)
17426 'org-latex-src-embed-type
17427 (if block-type 'paragraph 'character))))))
17428 ((eq processing-type 'mathml)
17429 ;; Process to MathML
17430 (unless (save-match-data (org-format-latex-mathml-available-p))
17431 (error "LaTeX to MathML converter not configured"))
17432 (setq txt (match-string n)
17433 beg (match-beginning n) end (match-end n)
17434 cnt (1+ cnt))
17435 (if msg (message msg cnt))
17436 (goto-char beg)
17437 (delete-region beg end)
17438 (insert (org-format-latex-as-mathml
17439 txt block-type prefix dir)))
17441 (error "Unknown conversion type %s for latex fragments"
17442 processing-type)))))))))
17444 (defun org-create-math-formula (latex-frag &optional mathml-file)
17445 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17446 Use `org-latex-to-mathml-convert-command'. If the conversion is
17447 sucessful, return the portion between \"<math...> </math>\"
17448 elements otherwise return nil. When MATHML-FILE is specified,
17449 write the results in to that file. When invoked as an
17450 interactive command, prompt for LATEX-FRAG, with initial value
17451 set to the current active region and echo the results for user
17452 inspection."
17453 (interactive (list (let ((frag (when (org-region-active-p)
17454 (buffer-substring-no-properties
17455 (region-beginning) (region-end)))))
17456 (read-string "LaTeX Fragment: " frag nil frag))))
17457 (unless latex-frag (error "Invalid latex-frag"))
17458 (let* ((tmp-in-file (file-relative-name
17459 (make-temp-name (expand-file-name "ltxmathml-in"))))
17460 (ignore (write-region latex-frag nil tmp-in-file))
17461 (tmp-out-file (file-relative-name
17462 (make-temp-name (expand-file-name "ltxmathml-out"))))
17463 (cmd (format-spec
17464 org-latex-to-mathml-convert-command
17465 `((?j . ,(shell-quote-argument
17466 (expand-file-name org-latex-to-mathml-jar-file)))
17467 (?I . ,(shell-quote-argument tmp-in-file))
17468 (?o . ,(shell-quote-argument tmp-out-file)))))
17469 mathml shell-command-output)
17470 (when (org-called-interactively-p 'any)
17471 (unless (org-format-latex-mathml-available-p)
17472 (error "LaTeX to MathML converter not configured")))
17473 (message "Running %s" cmd)
17474 (setq shell-command-output (shell-command-to-string cmd))
17475 (setq mathml
17476 (when (file-readable-p tmp-out-file)
17477 (with-current-buffer (find-file-noselect tmp-out-file t)
17478 (goto-char (point-min))
17479 (when (re-search-forward
17480 (concat
17481 (regexp-quote
17482 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17483 "\\(.\\|\n\\)*"
17484 (regexp-quote "</math>")) nil t)
17485 (prog1 (match-string 0) (kill-buffer))))))
17486 (cond
17487 (mathml
17488 (setq mathml
17489 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17490 (when mathml-file
17491 (write-region mathml nil mathml-file))
17492 (when (org-called-interactively-p 'any)
17493 (message mathml)))
17494 ((message "LaTeX to MathML conversion failed")
17495 (message shell-command-output)))
17496 (delete-file tmp-in-file)
17497 (when (file-exists-p tmp-out-file)
17498 (delete-file tmp-out-file))
17499 mathml))
17501 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17502 prefix &optional dir)
17503 "Use `org-create-math-formula' but check local cache first."
17504 (let* ((absprefix (expand-file-name prefix dir))
17505 (print-length nil) (print-level nil)
17506 (formula-id (concat
17507 "formula-"
17508 (sha1
17509 (prin1-to-string
17510 (list latex-frag
17511 org-latex-to-mathml-convert-command)))))
17512 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17513 (formula-cache-dir (file-name-directory formula-cache)))
17515 (unless (file-directory-p formula-cache-dir)
17516 (make-directory formula-cache-dir t))
17518 (unless (file-exists-p formula-cache)
17519 (org-create-math-formula latex-frag formula-cache))
17521 (if (file-exists-p formula-cache)
17522 ;; Successful conversion. Return the link to MathML file.
17523 (org-add-props
17524 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17525 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17526 'org-latex-src-embed-type (if latex-frag-type
17527 'paragraph 'character)))
17528 ;; Failed conversion. Return the LaTeX fragment verbatim
17529 (add-text-properties
17530 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17531 latex-frag)))
17533 (defun org-create-formula-image (string tofile options buffer &optional type)
17534 "Create an image from LaTeX source using dvipng or convert.
17535 This function calls either `org-create-formula-image-with-dvipng'
17536 or `org-create-formula-image-with-imagemagick' depending on the
17537 value of `org-latex-create-formula-image-program' or on the value
17538 of the optional TYPE variable.
17540 Note: ultimately these two function should be combined as they
17541 share a good deal of logic."
17542 (org-check-external-command
17543 "latex" "needed to convert LaTeX fragments to images")
17544 (funcall
17545 (case (or type org-latex-create-formula-image-program)
17546 ('dvipng
17547 (org-check-external-command
17548 "dvipng" "needed to convert LaTeX fragments to images")
17549 #'org-create-formula-image-with-dvipng)
17550 ('imagemagick
17551 (org-check-external-command
17552 "convert" "you need to install imagemagick")
17553 #'org-create-formula-image-with-imagemagick)
17554 (t (error
17555 "invalid value of `org-latex-create-formula-image-program'")))
17556 string tofile options buffer))
17558 ;; This function borrows from Ganesh Swami's latex2png.el
17559 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17560 "This calls dvipng."
17561 (require 'org-latex)
17562 (let* ((tmpdir (if (featurep 'xemacs)
17563 (temp-directory)
17564 temporary-file-directory))
17565 (texfilebase (make-temp-name
17566 (expand-file-name "orgtex" tmpdir)))
17567 (texfile (concat texfilebase ".tex"))
17568 (dvifile (concat texfilebase ".dvi"))
17569 (pngfile (concat texfilebase ".png"))
17570 (fnh (if (featurep 'xemacs)
17571 (font-height (face-font 'default))
17572 (face-attribute 'default :height nil)))
17573 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17574 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17575 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17576 "Black"))
17577 (bg (or (plist-get options (if buffer :background :html-background))
17578 "Transparent")))
17579 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17580 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17581 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17582 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17583 (with-temp-file texfile
17584 (insert (org-splice-latex-header
17585 org-format-latex-header
17586 org-export-latex-default-packages-alist
17587 org-export-latex-packages-alist t
17588 org-format-latex-header-extra))
17589 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17590 (require 'org-latex)
17591 (org-export-latex-fix-inputenc))
17592 (let ((dir default-directory))
17593 (condition-case nil
17594 (progn
17595 (cd tmpdir)
17596 (call-process "latex" nil nil nil texfile))
17597 (error nil))
17598 (cd dir))
17599 (if (not (file-exists-p dvifile))
17600 (progn (message "Failed to create dvi file from %s" texfile) nil)
17601 (condition-case nil
17602 (if (featurep 'xemacs)
17603 (call-process "dvipng" nil nil nil
17604 "-fg" fg "-bg" bg
17605 "-T" "tight"
17606 "-o" pngfile
17607 dvifile)
17608 (call-process "dvipng" nil nil nil
17609 "-fg" fg "-bg" bg
17610 "-D" dpi
17611 ;;"-x" scale "-y" scale
17612 "-T" "tight"
17613 "-o" pngfile
17614 dvifile))
17615 (error nil))
17616 (if (not (file-exists-p pngfile))
17617 (if org-format-latex-signal-error
17618 (error "Failed to create png file from %s" texfile)
17619 (message "Failed to create png file from %s" texfile)
17620 nil)
17621 ;; Use the requested file name and clean up
17622 (copy-file pngfile tofile 'replace)
17623 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17624 (if (file-exists-p (concat texfilebase e))
17625 (delete-file (concat texfilebase e))))
17626 pngfile))))
17628 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17629 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17630 "This calls convert, which is included into imagemagick."
17631 (require 'org-latex)
17632 (let* ((tmpdir (if (featurep 'xemacs)
17633 (temp-directory)
17634 temporary-file-directory))
17635 (texfilebase (make-temp-name
17636 (expand-file-name "orgtex" tmpdir)))
17637 (texfile (concat texfilebase ".tex"))
17638 (pdffile (concat texfilebase ".pdf"))
17639 (pngfile (concat texfilebase ".png"))
17640 (fnh (if (featurep 'xemacs)
17641 (font-height (face-font 'default))
17642 (face-attribute 'default :height nil)))
17643 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17644 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17645 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17646 "black"))
17647 (bg (or (plist-get options (if buffer :background :html-background))
17648 "white")))
17649 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17650 (setq fg (org-latex-color-format fg)))
17651 (if (eq bg 'default) (setq bg (org-latex-color :background))
17652 (setq bg (org-latex-color-format
17653 (if (string= bg "Transparent") "white" bg))))
17654 (with-temp-file texfile
17655 (insert (org-splice-latex-header
17656 org-format-latex-header
17657 org-export-latex-default-packages-alist
17658 org-export-latex-packages-alist t
17659 org-format-latex-header-extra))
17660 (insert "\n\\begin{document}\n"
17661 "\\definecolor{fg}{rgb}{" fg "}\n"
17662 "\\definecolor{bg}{rgb}{" bg "}\n"
17663 "\n\\pagecolor{bg}\n"
17664 "\n{\\color{fg}\n"
17665 string
17666 "\n}\n"
17667 "\n\\end{document}\n" )
17668 (require 'org-latex)
17669 (org-export-latex-fix-inputenc))
17670 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17671 (condition-case nil
17672 (progn
17673 (cd tmpdir)
17674 (setq cmds org-latex-to-pdf-process)
17675 (while cmds
17676 (setq latex-frags-cmds (pop cmds))
17677 (if (listp latex-frags-cmds)
17678 (setq cmds nil)
17679 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17680 (while latex-frags-cmds
17681 (setq cmd (pop latex-frags-cmds))
17682 (while (string-match "%b" cmd)
17683 (setq cmd (replace-match
17684 (save-match-data
17685 (shell-quote-argument texfile))
17686 t t cmd)))
17687 (while (string-match "%f" cmd)
17688 (setq cmd (replace-match
17689 (save-match-data
17690 (shell-quote-argument (file-name-nondirectory texfile)))
17691 t t cmd)))
17692 (while (string-match "%o" cmd)
17693 (setq cmd (replace-match
17694 (save-match-data
17695 (shell-quote-argument (file-name-directory texfile)))
17696 t t cmd)))
17697 (setq cmd (split-string cmd))
17698 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17699 (error nil))
17700 (cd dir))
17701 (if (not (file-exists-p pdffile))
17702 (progn (message "Failed to create pdf file from %s" texfile) nil)
17703 (condition-case nil
17704 (if (featurep 'xemacs)
17705 (call-process "convert" nil nil nil
17706 "-density" "96"
17707 "-trim"
17708 "-antialias"
17709 pdffile
17710 "-quality" "100"
17711 ;; "-sharpen" "0x1.0"
17712 pngfile)
17713 (call-process "convert" nil nil nil
17714 "-density" dpi
17715 "-trim"
17716 "-antialias"
17717 pdffile
17718 "-quality" "100"
17719 ; "-sharpen" "0x1.0"
17720 pngfile))
17721 (error nil))
17722 (if (not (file-exists-p pngfile))
17723 (if org-format-latex-signal-error
17724 (error "Failed to create png file from %s" texfile)
17725 (message "Failed to create png file from %s" texfile)
17726 nil)
17727 ;; Use the requested file name and clean up
17728 (copy-file pngfile tofile 'replace)
17729 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17730 (if (file-exists-p (concat texfilebase e))
17731 (delete-file (concat texfilebase e))))
17732 pngfile))))
17734 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17735 "Fill a LaTeX header template TPL.
17736 In the template, the following place holders will be recognized:
17738 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17739 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17740 [PACKAGES] \\usepackage statements for PKG
17741 [NO-PACKAGES] do not include PKG
17742 [EXTRA] the string EXTRA
17743 [NO-EXTRA] do not include EXTRA
17745 For backward compatibility, if both the positive and the negative place
17746 holder is missing, the positive one (without the \"NO-\") will be
17747 assumed to be present at the end of the template.
17748 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17749 EXTRA is a string.
17750 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17751 (let (rpl (end ""))
17752 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17753 (setq rpl (if (or (match-end 1) (not def-pkg))
17754 "" (org-latex-packages-to-string def-pkg snippets-p t))
17755 tpl (replace-match rpl t t tpl))
17756 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17758 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17759 (setq rpl (if (or (match-end 1) (not pkg))
17760 "" (org-latex-packages-to-string pkg snippets-p t))
17761 tpl (replace-match rpl t t tpl))
17762 (if pkg (setq end
17763 (concat end "\n"
17764 (org-latex-packages-to-string pkg snippets-p)))))
17766 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17767 (setq rpl (if (or (match-end 1) (not extra))
17768 "" (concat extra "\n"))
17769 tpl (replace-match rpl t t tpl))
17770 (if (and extra (string-match "\\S-" extra))
17771 (setq end (concat end "\n" extra))))
17773 (if (string-match "\\S-" end)
17774 (concat tpl "\n" end)
17775 tpl)))
17777 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17778 "Turn an alist of packages into a string with the \\usepackage macros."
17779 (setq pkg (mapconcat (lambda(p)
17780 (cond
17781 ((stringp p) p)
17782 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17783 (format "%% Package %s omitted" (cadr p)))
17784 ((equal "" (car p))
17785 (format "\\usepackage{%s}" (cadr p)))
17787 (format "\\usepackage[%s]{%s}"
17788 (car p) (cadr p)))))
17790 "\n"))
17791 (if newline (concat pkg "\n") pkg))
17793 (defun org-dvipng-color (attr)
17794 "Return a RGB color specification for dvipng."
17795 (apply 'format "rgb %s %s %s"
17796 (mapcar 'org-normalize-color
17797 (if (featurep 'xemacs)
17798 (color-rgb-components
17799 (face-property 'default
17800 (cond ((eq attr :foreground) 'foreground)
17801 ((eq attr :background) 'background))))
17802 (color-values (face-attribute 'default attr nil))))))
17804 (defun org-dvipng-color-format (color-name)
17805 "Convert COLOR-NAME to a RGB color value for dvipng."
17806 (apply 'format "rgb %s %s %s"
17807 (mapcar 'org-normalize-color
17808 (color-values color-name))))
17810 (defun org-latex-color (attr)
17811 "Return a RGB color for the LaTeX color package."
17812 (apply 'format "%s,%s,%s"
17813 (mapcar 'org-normalize-color
17814 (if (featurep 'xemacs)
17815 (color-rgb-components
17816 (face-property 'default
17817 (cond ((eq attr :foreground) 'foreground)
17818 ((eq attr :background) 'background))))
17819 (color-values (face-attribute 'default attr nil))))))
17821 (defun org-latex-color-format (color-name)
17822 "Convert COLOR-NAME to a RGB color value."
17823 (apply 'format "%s,%s,%s"
17824 (mapcar 'org-normalize-color
17825 (color-values color-name))))
17827 (defun org-normalize-color (value)
17828 "Return string to be used as color value for an RGB component."
17829 (format "%g" (/ value 65535.0)))
17831 ;; Image display
17834 (defvar org-inline-image-overlays nil)
17835 (make-variable-buffer-local 'org-inline-image-overlays)
17837 (defun org-toggle-inline-images (&optional include-linked)
17838 "Toggle the display of inline images.
17839 INCLUDE-LINKED is passed to `org-display-inline-images'."
17840 (interactive "P")
17841 (if org-inline-image-overlays
17842 (progn
17843 (org-remove-inline-images)
17844 (message "Inline image display turned off"))
17845 (org-display-inline-images include-linked)
17846 (if (and (org-called-interactively-p)
17847 org-inline-image-overlays)
17848 (message "%d images displayed inline"
17849 (length org-inline-image-overlays))
17850 (message "No images to display inline"))))
17852 (defun org-redisplay-inline-images ()
17853 "Refresh the display of inline images."
17854 (interactive)
17855 (if (not org-inline-image-overlays)
17856 (org-toggle-inline-images)
17857 (org-toggle-inline-images)
17858 (org-toggle-inline-images)))
17860 (defun org-display-inline-images (&optional include-linked refresh beg end)
17861 "Display inline images.
17862 Normally only links without a description part are inlined, because this
17863 is how it will work for export. When INCLUDE-LINKED is set, also links
17864 with a description part will be inlined. This can be nice for a quick
17865 look at those images, but it does not reflect what exported files will look
17866 like.
17867 When REFRESH is set, refresh existing images between BEG and END.
17868 This will create new image displays only if necessary.
17869 BEG and END default to the buffer boundaries."
17870 (interactive "P")
17871 (unless refresh
17872 (org-remove-inline-images)
17873 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17874 (save-excursion
17875 (save-restriction
17876 (widen)
17877 (setq beg (or beg (point-min)) end (or end (point-max)))
17878 (goto-char beg)
17879 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17880 (substring (org-image-file-name-regexp) 0 -2)
17881 "\\)\\]" (if include-linked "" "\\]")))
17882 old file ov img type attrwidth width)
17883 (while (re-search-forward re end t)
17884 (setq old (get-char-property-and-overlay (match-beginning 1)
17885 'org-image-overlay)
17886 file (expand-file-name
17887 (concat (or (match-string 3) "") (match-string 4))))
17888 (when (image-type-available-p 'imagemagick)
17889 (setq attrwidth (if (or (listp org-image-actual-width)
17890 (null org-image-actual-width))
17891 (save-excursion
17892 (save-match-data
17893 (when (re-search-backward
17894 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
17895 (save-excursion
17896 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
17897 (string-to-number (match-string 1))))))
17898 width (cond ((eq org-image-actual-width t) nil)
17899 ((null org-image-actual-width) attrwidth)
17900 ((numberp org-image-actual-width)
17901 org-image-actual-width)
17902 ((listp org-image-actual-width)
17903 (or attrwidth (car org-image-actual-width))))
17904 type (if width 'imagemagick)))
17905 (when (file-exists-p file)
17906 (if (and (car-safe old) refresh)
17907 (image-refresh (overlay-get (cdr old) 'display))
17908 (setq img (save-match-data (create-image file type nil :width width)))
17909 (when img
17910 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17911 (overlay-put ov 'display img)
17912 (overlay-put ov 'face 'default)
17913 (overlay-put ov 'org-image-overlay t)
17914 (overlay-put ov 'modification-hooks
17915 (list 'org-display-inline-remove-overlay))
17916 (push ov org-inline-image-overlays)))))))))
17918 (define-obsolete-function-alias
17919 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17921 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17922 "Remove inline-display overlay if a corresponding region is modified."
17923 (let ((inhibit-modification-hooks t))
17924 (when (and ov after)
17925 (delete ov org-inline-image-overlays)
17926 (delete-overlay ov))))
17928 (defun org-remove-inline-images ()
17929 "Remove inline display of images."
17930 (interactive)
17931 (mapc 'delete-overlay org-inline-image-overlays)
17932 (setq org-inline-image-overlays nil))
17934 ;;;; Key bindings
17936 ;; Outline functions from `outline-mode-prefix-map'
17937 ;; that can be remapped in Org:
17938 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17939 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17940 (define-key org-mode-map [remap outline-forward-same-level]
17941 'org-forward-heading-same-level)
17942 (define-key org-mode-map [remap outline-backward-same-level]
17943 'org-backward-heading-same-level)
17944 (define-key org-mode-map [remap show-branches]
17945 'org-kill-note-or-show-branches)
17946 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17947 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17948 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17950 ;; Outline functions from `outline-mode-prefix-map' that can not
17951 ;; be remapped in Org:
17953 ;; - the column "key binding" shows whether the Outline function is still
17954 ;; available in Org mode on the same key that it has been bound to in
17955 ;; Outline mode:
17956 ;; - "overridden": key used for a different functionality in Org mode
17957 ;; - else: key still bound to the same Outline function in Org mode
17959 ;; | Outline function | key binding | Org replacement |
17960 ;; |------------------------------------+-------------+-----------------------|
17961 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17962 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17963 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17964 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17965 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17966 ;; | `show-entry' | overridden | no replacement |
17967 ;; | `show-children' | `C-c C-i' | visibility cycling |
17968 ;; | `show-branches' | `C-c C-k' | still same function |
17969 ;; | `show-subtree' | overridden | visibility cycling |
17970 ;; | `show-all' | overridden | no replacement |
17971 ;; | `hide-subtree' | overridden | visibility cycling |
17972 ;; | `hide-body' | overridden | no replacement |
17973 ;; | `hide-entry' | overridden | visibility cycling |
17974 ;; | `hide-leaves' | overridden | no replacement |
17975 ;; | `hide-sublevels' | overridden | no replacement |
17976 ;; | `hide-other' | overridden | no replacement |
17978 ;; Make `C-c C-x' a prefix key
17979 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17981 ;; TAB key with modifiers
17982 (org-defkey org-mode-map "\C-i" 'org-cycle)
17983 (org-defkey org-mode-map [(tab)] 'org-cycle)
17984 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17985 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17986 ;; The following line is necessary under Suse GNU/Linux
17987 (unless (featurep 'xemacs)
17988 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17989 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17990 (define-key org-mode-map [backtab] 'org-shifttab)
17992 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17993 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17994 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17996 ;; Cursor keys with modifiers
17997 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17998 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17999 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18000 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18002 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18003 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18004 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18005 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18007 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18008 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18009 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18010 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18012 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18013 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18014 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18015 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18017 ;; Babel keys
18018 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18019 (mapc (lambda (pair)
18020 (define-key org-babel-map (car pair) (cdr pair)))
18021 org-babel-key-bindings)
18023 ;;; Extra keys for tty access.
18024 ;; We only set them when really needed because otherwise the
18025 ;; menus don't show the simple keys
18027 (when (or org-use-extra-keys
18028 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18029 (not window-system))
18030 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18031 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18032 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18033 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18034 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18035 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18036 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18037 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18038 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18039 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18040 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18041 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18042 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18043 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18044 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18045 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18046 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18047 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18048 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18049 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18050 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18051 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18052 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18053 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18054 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18055 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18056 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18057 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18059 ;; All the other keys
18061 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18062 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18063 (if (boundp 'narrow-map)
18064 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18065 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18066 (if (boundp 'narrow-map)
18067 (org-defkey narrow-map "b" 'org-narrow-to-block)
18068 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18069 (if (boundp 'narrow-map)
18070 (org-defkey narrow-map "e" 'org-narrow-to-element)
18071 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18072 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18073 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18074 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18075 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18076 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18077 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18078 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18079 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18080 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18081 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18082 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18083 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18084 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18085 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18086 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18087 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18088 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18089 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18090 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18091 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18092 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18093 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18094 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18095 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18096 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18097 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18098 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18099 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18100 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18101 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18102 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18103 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18104 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18105 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18106 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18107 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18108 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18109 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18110 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18111 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18112 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18113 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18114 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18115 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18116 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18117 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18118 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18119 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18120 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18121 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18122 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18123 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18124 (org-defkey org-mode-map "\C-c^" 'org-sort)
18125 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18126 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18127 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18128 (org-defkey org-mode-map "\C-m" 'org-return)
18129 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18130 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18131 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18132 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18133 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18134 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18135 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18136 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18137 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18138 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18139 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18140 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18141 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18142 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18143 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18144 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18145 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18146 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18147 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18148 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18149 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18150 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18151 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18153 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18154 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18155 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18157 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18158 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18159 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18160 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18161 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18162 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18163 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18164 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18165 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18166 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18167 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18168 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18169 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18170 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18171 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18172 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18173 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18174 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18175 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18176 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18177 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18178 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18180 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18181 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18182 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18183 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18184 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18186 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18188 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18190 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18191 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18193 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18196 (when (featurep 'xemacs)
18197 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18200 (defconst org-speed-commands-default
18202 ("Outline Navigation")
18203 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18204 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18205 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18206 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18207 ("u" . (org-speed-move-safe 'outline-up-heading))
18208 ("j" . org-goto)
18209 ("g" . (org-refile t))
18210 ("Outline Visibility")
18211 ("c" . org-cycle)
18212 ("C" . org-shifttab)
18213 (" " . org-display-outline-path)
18214 (":" . org-columns)
18215 ("Outline Structure Editing")
18216 ("U" . org-shiftmetaup)
18217 ("D" . org-shiftmetadown)
18218 ("r" . org-metaright)
18219 ("l" . org-metaleft)
18220 ("R" . org-shiftmetaright)
18221 ("L" . org-shiftmetaleft)
18222 ("i" . (progn (forward-char 1) (call-interactively
18223 'org-insert-heading-respect-content)))
18224 ("^" . org-sort)
18225 ("w" . org-refile)
18226 ("a" . org-archive-subtree-default-with-confirmation)
18227 ("." . org-mark-subtree)
18228 ("#" . org-toggle-comment)
18229 ("Clock Commands")
18230 ("I" . org-clock-in)
18231 ("O" . org-clock-out)
18232 ("Meta Data Editing")
18233 ("t" . org-todo)
18234 ("," . (org-priority))
18235 ("0" . (org-priority ?\ ))
18236 ("1" . (org-priority ?A))
18237 ("2" . (org-priority ?B))
18238 ("3" . (org-priority ?C))
18239 (";" . org-set-tags-command)
18240 ("e" . org-set-effort)
18241 ("E" . org-inc-effort)
18242 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18243 (org-entry-put (point) "APPT_WARNTIME" m)))
18244 ("Agenda Views etc")
18245 ("v" . org-agenda)
18246 ("/" . org-sparse-tree)
18247 ("Misc")
18248 ("o" . org-open-at-point)
18249 ("?" . org-speed-command-help)
18250 ("<" . (org-agenda-set-restriction-lock 'subtree))
18251 (">" . (org-agenda-remove-restriction-lock))
18253 "The default speed commands.")
18255 (defun org-print-speed-command (e)
18256 (if (> (length (car e)) 1)
18257 (progn
18258 (princ "\n")
18259 (princ (car e))
18260 (princ "\n")
18261 (princ (make-string (length (car e)) ?-))
18262 (princ "\n"))
18263 (princ (car e))
18264 (princ " ")
18265 (if (symbolp (cdr e))
18266 (princ (symbol-name (cdr e)))
18267 (prin1 (cdr e)))
18268 (princ "\n")))
18270 (defun org-speed-command-help ()
18271 "Show the available speed commands."
18272 (interactive)
18273 (if (not org-use-speed-commands)
18274 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18275 (with-output-to-temp-buffer "*Help*"
18276 (princ "User-defined Speed commands\n===========================\n")
18277 (mapc 'org-print-speed-command org-speed-commands-user)
18278 (princ "\n")
18279 (princ "Built-in Speed commands\n=======================\n")
18280 (mapc 'org-print-speed-command org-speed-commands-default))
18281 (with-current-buffer "*Help*"
18282 (setq truncate-lines t))))
18284 (defun org-speed-move-safe (cmd)
18285 "Execute CMD, but make sure that the cursor always ends up in a headline.
18286 If not, return to the original position and throw an error."
18287 (interactive)
18288 (let ((pos (point)))
18289 (call-interactively cmd)
18290 (unless (and (bolp) (org-at-heading-p))
18291 (goto-char pos)
18292 (error "Boundary reached while executing %s" cmd))))
18294 (defvar org-self-insert-command-undo-counter 0)
18296 (defvar org-table-auto-blank-field) ; defined in org-table.el
18297 (defvar org-speed-command nil)
18299 (define-obsolete-function-alias
18300 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18302 (defun org-speed-command-activate (keys)
18303 "Hook for activating single-letter speed commands.
18304 `org-speed-commands-default' specifies a minimal command set.
18305 Use `org-speed-commands-user' for further customization."
18306 (when (or (and (bolp) (looking-at org-outline-regexp))
18307 (and (functionp org-use-speed-commands)
18308 (funcall org-use-speed-commands)))
18309 (cdr (assoc keys (append org-speed-commands-user
18310 org-speed-commands-default)))))
18312 (define-obsolete-function-alias
18313 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18315 (defun org-babel-speed-command-activate (keys)
18316 "Hook for activating single-letter code block commands."
18317 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18318 (cdr (assoc keys org-babel-key-bindings))))
18320 (defcustom org-speed-command-hook
18321 '(org-speed-command-default-hook org-babel-speed-command-hook)
18322 "Hook for activating speed commands at strategic locations.
18323 Hook functions are called in sequence until a valid handler is
18324 found.
18326 Each hook takes a single argument, a user-pressed command key
18327 which is also a `self-insert-command' from the global map.
18329 Within the hook, examine the cursor position and the command key
18330 and return nil or a valid handler as appropriate. Handler could
18331 be one of an interactive command, a function, or a form.
18333 Set `org-use-speed-commands' to non-nil value to enable this
18334 hook. The default setting is `org-speed-command-activate'."
18335 :group 'org-structure
18336 :version "24.1"
18337 :type 'hook)
18339 (defun org-self-insert-command (N)
18340 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18341 If the cursor is in a table looking at whitespace, the whitespace is
18342 overwritten, and the table is not marked as requiring realignment."
18343 (interactive "p")
18344 (org-check-before-invisible-edit 'insert)
18345 (cond
18346 ((and org-use-speed-commands
18347 (setq org-speed-command
18348 (run-hook-with-args-until-success
18349 'org-speed-command-hook (this-command-keys))))
18350 (cond
18351 ((commandp org-speed-command)
18352 (setq this-command org-speed-command)
18353 (call-interactively org-speed-command))
18354 ((functionp org-speed-command)
18355 (funcall org-speed-command))
18356 ((and org-speed-command (listp org-speed-command))
18357 (eval org-speed-command))
18358 (t (let (org-use-speed-commands)
18359 (call-interactively 'org-self-insert-command)))))
18360 ((and
18361 (org-table-p)
18362 (progn
18363 ;; check if we blank the field, and if that triggers align
18364 (and (featurep 'org-table) org-table-auto-blank-field
18365 (member last-command
18366 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18367 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18368 ;; got extra space, this field does not determine column width
18369 (let (org-table-may-need-update) (org-table-blank-field))
18370 ;; no extra space, this field may determine column width
18371 (org-table-blank-field)))
18373 (eq N 1)
18374 (looking-at "[^|\n]* |"))
18375 (let (org-table-may-need-update)
18376 (goto-char (1- (match-end 0)))
18377 (backward-delete-char 1)
18378 (goto-char (match-beginning 0))
18379 (self-insert-command N)))
18381 (setq org-table-may-need-update t)
18382 (self-insert-command N)
18383 (org-fix-tags-on-the-fly)
18384 (if org-self-insert-cluster-for-undo
18385 (if (not (eq last-command 'org-self-insert-command))
18386 (setq org-self-insert-command-undo-counter 1)
18387 (if (>= org-self-insert-command-undo-counter 20)
18388 (setq org-self-insert-command-undo-counter 1)
18389 (and (> org-self-insert-command-undo-counter 0)
18390 buffer-undo-list (listp buffer-undo-list)
18391 (not (cadr buffer-undo-list)) ; remove nil entry
18392 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18393 (setq org-self-insert-command-undo-counter
18394 (1+ org-self-insert-command-undo-counter))))))))
18396 (defun org-check-before-invisible-edit (kind)
18397 "Check is editing if kind KIND would be dangerous with invisible text around.
18398 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18399 ;; First, try to get out of here as quickly as possible, to reduce overhead
18400 (if (and org-catch-invisible-edits
18401 (or (not (boundp 'visible-mode)) (not visible-mode))
18402 (or (get-char-property (point) 'invisible)
18403 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18404 ;; OK, we need to take a closer look
18405 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18406 (invisible-before-point (if (bobp) nil (get-char-property
18407 (1- (point)) 'invisible)))
18408 (border-and-ok-direction
18410 ;; Check if we are acting predictably before invisible text
18411 (and invisible-at-point (not invisible-before-point)
18412 (memq kind '(insert delete-backward)))
18413 ;; Check if we are acting predictably after invisible text
18414 ;; This works not well, and I have turned it off. It seems
18415 ;; better to always show and stop after invisible text.
18416 ;; (and (not invisible-at-point) invisible-before-point
18417 ;; (memq kind '(insert delete)))
18419 (when (or (memq invisible-at-point '(outline org-hide-block t))
18420 (memq invisible-before-point '(outline org-hide-block t)))
18421 (if (eq org-catch-invisible-edits 'error)
18422 (error "Editing in invisible areas is prohibited - make visible first"))
18423 (if (and org-custom-properties-overlays
18424 (y-or-n-p "Display invisible properties in this buffer? "))
18425 (org-toggle-custom-properties-visibility)
18426 ;; Make the area visible
18427 (save-excursion
18428 (if invisible-before-point
18429 (goto-char (previous-single-char-property-change
18430 (point) 'invisible)))
18431 (org-cycle))
18432 (cond
18433 ((eq org-catch-invisible-edits 'show)
18434 ;; That's it, we do the edit after showing
18435 (message
18436 "Unfolding invisible region around point before editing")
18437 (sit-for 1))
18438 ((and (eq org-catch-invisible-edits 'smart)
18439 border-and-ok-direction)
18440 (message "Unfolding invisible region around point before editing"))
18442 ;; Don't do the edit, make the user repeat it in full visibility
18443 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18445 (defun org-fix-tags-on-the-fly ()
18446 (when (and (equal (char-after (point-at-bol)) ?*)
18447 (org-at-heading-p))
18448 (org-align-tags-here org-tags-column)))
18450 (defun org-delete-backward-char (N)
18451 "Like `delete-backward-char', insert whitespace at field end in tables.
18452 When deleting backwards, in tables this function will insert whitespace in
18453 front of the next \"|\" separator, to keep the table aligned. The table will
18454 still be marked for re-alignment if the field did fill the entire column,
18455 because, in this case the deletion might narrow the column."
18456 (interactive "p")
18457 (org-check-before-invisible-edit 'delete-backward)
18458 (if (and (org-table-p)
18459 (eq N 1)
18460 (string-match "|" (buffer-substring (point-at-bol) (point)))
18461 (looking-at ".*?|"))
18462 (let ((pos (point))
18463 (noalign (looking-at "[^|\n\r]* |"))
18464 (c org-table-may-need-update))
18465 (backward-delete-char N)
18466 (if (not overwrite-mode)
18467 (progn
18468 (skip-chars-forward "^|")
18469 (insert " ")
18470 (goto-char (1- pos))))
18471 ;; noalign: if there were two spaces at the end, this field
18472 ;; does not determine the width of the column.
18473 (if noalign (setq org-table-may-need-update c)))
18474 (backward-delete-char N)
18475 (org-fix-tags-on-the-fly)))
18477 (defun org-delete-char (N)
18478 "Like `delete-char', but insert whitespace at field end in tables.
18479 When deleting characters, in tables this function will insert whitespace in
18480 front of the next \"|\" separator, to keep the table aligned. The table will
18481 still be marked for re-alignment if the field did fill the entire column,
18482 because, in this case the deletion might narrow the column."
18483 (interactive "p")
18484 (org-check-before-invisible-edit 'delete)
18485 (if (and (org-table-p)
18486 (not (bolp))
18487 (not (= (char-after) ?|))
18488 (eq N 1))
18489 (if (looking-at ".*?|")
18490 (let ((pos (point))
18491 (noalign (looking-at "[^|\n\r]* |"))
18492 (c org-table-may-need-update))
18493 (replace-match (concat
18494 (substring (match-string 0) 1 -1)
18495 " |"))
18496 (goto-char pos)
18497 ;; noalign: if there were two spaces at the end, this field
18498 ;; does not determine the width of the column.
18499 (if noalign (setq org-table-may-need-update c)))
18500 (delete-char N))
18501 (delete-char N)
18502 (org-fix-tags-on-the-fly)))
18504 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18505 (put 'org-self-insert-command 'delete-selection t)
18506 (put 'orgtbl-self-insert-command 'delete-selection t)
18507 (put 'org-delete-char 'delete-selection 'supersede)
18508 (put 'org-delete-backward-char 'delete-selection 'supersede)
18509 (put 'org-yank 'delete-selection 'yank)
18511 ;; Make `flyspell-mode' delay after some commands
18512 (put 'org-self-insert-command 'flyspell-delayed t)
18513 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18514 (put 'org-delete-char 'flyspell-delayed t)
18515 (put 'org-delete-backward-char 'flyspell-delayed t)
18517 ;; Make pabbrev-mode expand after org-mode commands
18518 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18519 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18521 ;; How to do this: Measure non-white length of current string
18522 ;; If equal to column width, we should realign.
18524 (defun org-remap (map &rest commands)
18525 "In MAP, remap the functions given in COMMANDS.
18526 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18527 (let (new old)
18528 (while commands
18529 (setq old (pop commands) new (pop commands))
18530 (if (fboundp 'command-remapping)
18531 (org-defkey map (vector 'remap old) new)
18532 (substitute-key-definition old new map global-map)))))
18534 (when (eq org-enable-table-editor 'optimized)
18535 ;; If the user wants maximum table support, we need to hijack
18536 ;; some standard editing functions
18537 (org-remap org-mode-map
18538 'self-insert-command 'org-self-insert-command
18539 'delete-char 'org-delete-char
18540 'delete-backward-char 'org-delete-backward-char)
18541 (org-defkey org-mode-map "|" 'org-force-self-insert))
18543 (defvar org-ctrl-c-ctrl-c-hook nil
18544 "Hook for functions attaching themselves to `C-c C-c'.
18546 This can be used to add additional functionality to the C-c C-c
18547 key which executes context-dependent commands. This hook is run
18548 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18549 run after the last test.
18551 Each function will be called with no arguments. The function
18552 must check if the context is appropriate for it to act. If yes,
18553 it should do its thing and then return a non-nil value. If the
18554 context is wrong, just do nothing and return nil.")
18556 (defvar org-ctrl-c-ctrl-c-final-hook nil
18557 "Hook for functions attaching themselves to `C-c C-c'.
18559 This can be used to add additional functionality to the C-c C-c
18560 key which executes context-dependent commands. This hook is run
18561 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18562 before the first test.
18564 Each function will be called with no arguments. The function
18565 must check if the context is appropriate for it to act. If yes,
18566 it should do its thing and then return a non-nil value. If the
18567 context is wrong, just do nothing and return nil.")
18569 (defvar org-tab-first-hook nil
18570 "Hook for functions to attach themselves to TAB.
18571 See `org-ctrl-c-ctrl-c-hook' for more information.
18572 This hook runs as the first action when TAB is pressed, even before
18573 `org-cycle' messes around with the `outline-regexp' to cater for
18574 inline tasks and plain list item folding.
18575 If any function in this hook returns t, any other actions that
18576 would have been caused by TAB (such as table field motion or visibility
18577 cycling) will not occur.")
18579 (defvar org-tab-after-check-for-table-hook nil
18580 "Hook for functions to attach themselves to TAB.
18581 See `org-ctrl-c-ctrl-c-hook' for more information.
18582 This hook runs after it has been established that the cursor is not in a
18583 table, but before checking if the cursor is in a headline or if global cycling
18584 should be done.
18585 If any function in this hook returns t, not other actions like visibility
18586 cycling will be done.")
18588 (defvar org-tab-after-check-for-cycling-hook nil
18589 "Hook for functions to attach themselves to TAB.
18590 See `org-ctrl-c-ctrl-c-hook' for more information.
18591 This hook runs after it has been established that not table field motion and
18592 not visibility should be done because of current context. This is probably
18593 the place where a package like yasnippets can hook in.")
18595 (defvar org-tab-before-tab-emulation-hook nil
18596 "Hook for functions to attach themselves to TAB.
18597 See `org-ctrl-c-ctrl-c-hook' for more information.
18598 This hook runs after every other options for TAB have been exhausted, but
18599 before indentation and \t insertion takes place.")
18601 (defvar org-metaleft-hook nil
18602 "Hook for functions attaching themselves to `M-left'.
18603 See `org-ctrl-c-ctrl-c-hook' for more information.")
18604 (defvar org-metaright-hook nil
18605 "Hook for functions attaching themselves to `M-right'.
18606 See `org-ctrl-c-ctrl-c-hook' for more information.")
18607 (defvar org-metaup-hook nil
18608 "Hook for functions attaching themselves to `M-up'.
18609 See `org-ctrl-c-ctrl-c-hook' for more information.")
18610 (defvar org-metadown-hook nil
18611 "Hook for functions attaching themselves to `M-down'.
18612 See `org-ctrl-c-ctrl-c-hook' for more information.")
18613 (defvar org-shiftmetaleft-hook nil
18614 "Hook for functions attaching themselves to `M-S-left'.
18615 See `org-ctrl-c-ctrl-c-hook' for more information.")
18616 (defvar org-shiftmetaright-hook nil
18617 "Hook for functions attaching themselves to `M-S-right'.
18618 See `org-ctrl-c-ctrl-c-hook' for more information.")
18619 (defvar org-shiftmetaup-hook nil
18620 "Hook for functions attaching themselves to `M-S-up'.
18621 See `org-ctrl-c-ctrl-c-hook' for more information.")
18622 (defvar org-shiftmetadown-hook nil
18623 "Hook for functions attaching themselves to `M-S-down'.
18624 See `org-ctrl-c-ctrl-c-hook' for more information.")
18625 (defvar org-metareturn-hook nil
18626 "Hook for functions attaching themselves to `M-RET'.
18627 See `org-ctrl-c-ctrl-c-hook' for more information.")
18628 (defvar org-shiftup-hook nil
18629 "Hook for functions attaching themselves to `S-up'.
18630 See `org-ctrl-c-ctrl-c-hook' for more information.")
18631 (defvar org-shiftup-final-hook nil
18632 "Hook for functions attaching themselves to `S-up'.
18633 This one runs after all other options except shift-select have been excluded.
18634 See `org-ctrl-c-ctrl-c-hook' for more information.")
18635 (defvar org-shiftdown-hook nil
18636 "Hook for functions attaching themselves to `S-down'.
18637 See `org-ctrl-c-ctrl-c-hook' for more information.")
18638 (defvar org-shiftdown-final-hook nil
18639 "Hook for functions attaching themselves to `S-down'.
18640 This one runs after all other options except shift-select have been excluded.
18641 See `org-ctrl-c-ctrl-c-hook' for more information.")
18642 (defvar org-shiftleft-hook nil
18643 "Hook for functions attaching themselves to `S-left'.
18644 See `org-ctrl-c-ctrl-c-hook' for more information.")
18645 (defvar org-shiftleft-final-hook nil
18646 "Hook for functions attaching themselves to `S-left'.
18647 This one runs after all other options except shift-select have been excluded.
18648 See `org-ctrl-c-ctrl-c-hook' for more information.")
18649 (defvar org-shiftright-hook nil
18650 "Hook for functions attaching themselves to `S-right'.
18651 See `org-ctrl-c-ctrl-c-hook' for more information.")
18652 (defvar org-shiftright-final-hook nil
18653 "Hook for functions attaching themselves to `S-right'.
18654 This one runs after all other options except shift-select have been excluded.
18655 See `org-ctrl-c-ctrl-c-hook' for more information.")
18657 (defun org-modifier-cursor-error ()
18658 "Throw an error, a modified cursor command was applied in wrong context."
18659 (error "This command is active in special context like tables, headlines or items"))
18661 (defun org-shiftselect-error ()
18662 "Throw an error because Shift-Cursor command was applied in wrong context."
18663 (if (and (boundp 'shift-select-mode) shift-select-mode)
18664 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18665 (error "This command works only in special context like headlines or timestamps")))
18667 (defun org-call-for-shift-select (cmd)
18668 (let ((this-command-keys-shift-translated t))
18669 (call-interactively cmd)))
18671 (defun org-shifttab (&optional arg)
18672 "Global visibility cycling or move to previous table field.
18673 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18674 on context.
18675 See the individual commands for more information."
18676 (interactive "P")
18677 (cond
18678 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18679 ((integerp arg)
18680 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18681 (message "Content view to level: %d" arg)
18682 (org-content (prefix-numeric-value arg2))
18683 (setq org-cycle-global-status 'overview)))
18684 (t (call-interactively 'org-global-cycle))))
18686 (defun org-shiftmetaleft ()
18687 "Promote subtree or delete table column.
18688 Calls `org-promote-subtree', `org-outdent-item-tree', or
18689 `org-table-delete-column', depending on context. See the
18690 individual commands for more information."
18691 (interactive)
18692 (cond
18693 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18694 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18695 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18696 ((if (not (org-region-active-p)) (org-at-item-p)
18697 (save-excursion (goto-char (region-beginning))
18698 (org-at-item-p)))
18699 (call-interactively 'org-outdent-item-tree))
18700 (t (org-modifier-cursor-error))))
18702 (defun org-shiftmetaright ()
18703 "Demote subtree or insert table column.
18704 Calls `org-demote-subtree', `org-indent-item-tree', or
18705 `org-table-insert-column', depending on context. See the
18706 individual commands for more information."
18707 (interactive)
18708 (cond
18709 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18710 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18711 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18712 ((if (not (org-region-active-p)) (org-at-item-p)
18713 (save-excursion (goto-char (region-beginning))
18714 (org-at-item-p)))
18715 (call-interactively 'org-indent-item-tree))
18716 (t (org-modifier-cursor-error))))
18718 (defun org-shiftmetaup (&optional arg)
18719 "Move subtree up or kill table row.
18720 Calls `org-move-subtree-up' or `org-table-kill-row' or
18721 `org-move-item-up' or `org-timestamp-up', depending on context.
18722 See the individual commands for more information."
18723 (interactive "P")
18724 (cond
18725 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18726 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18727 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18728 ((org-at-item-p) (call-interactively 'org-move-item-up))
18729 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18730 (call-interactively 'org-timestamp-up)))
18731 (t (org-modifier-cursor-error))))
18733 (defun org-shiftmetadown (&optional arg)
18734 "Move subtree down or insert table row.
18735 Calls `org-move-subtree-down' or `org-table-insert-row' or
18736 `org-move-item-down' or `org-timestamp-up', depending on context.
18737 See the individual commands for more information."
18738 (interactive "P")
18739 (cond
18740 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18741 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18742 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18743 ((org-at-item-p) (call-interactively 'org-move-item-down))
18744 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18745 (call-interactively 'org-timestamp-down)))
18746 (t (org-modifier-cursor-error))))
18748 (defsubst org-hidden-tree-error ()
18749 (error
18750 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18752 (defun org-metaleft (&optional arg)
18753 "Promote heading or move table column to left.
18754 Calls `org-do-promote' or `org-table-move-column', depending on context.
18755 With no specific context, calls the Emacs default `backward-word'.
18756 See the individual commands for more information."
18757 (interactive "P")
18758 (cond
18759 ((run-hook-with-args-until-success 'org-metaleft-hook))
18760 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18761 ((org-with-limited-levels
18762 (or (org-at-heading-p)
18763 (and (org-region-active-p)
18764 (save-excursion
18765 (goto-char (region-beginning))
18766 (org-at-heading-p)))))
18767 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18768 (call-interactively 'org-do-promote))
18769 ;; At an inline task.
18770 ((org-at-heading-p)
18771 (call-interactively 'org-inlinetask-promote))
18772 ((or (org-at-item-p)
18773 (and (org-region-active-p)
18774 (save-excursion
18775 (goto-char (region-beginning))
18776 (org-at-item-p))))
18777 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18778 (call-interactively 'org-outdent-item))
18779 (t (call-interactively 'backward-word))))
18781 (defun org-metaright (&optional arg)
18782 "Demote a subtree, a list item or move table column to right.
18783 In front of a drawer or a block keyword, indent it correctly.
18784 With no specific context, calls the Emacs default `forward-word'.
18785 See the individual commands for more information."
18786 (interactive "P")
18787 (cond
18788 ((run-hook-with-args-until-success 'org-metaright-hook))
18789 ((org-at-table-p) (call-interactively 'org-table-move-column))
18790 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18791 ((org-at-block-p) (call-interactively 'org-indent-block))
18792 ((org-with-limited-levels
18793 (or (org-at-heading-p)
18794 (and (org-region-active-p)
18795 (save-excursion
18796 (goto-char (region-beginning))
18797 (org-at-heading-p)))))
18798 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18799 (call-interactively 'org-do-demote))
18800 ;; At an inline task.
18801 ((org-at-heading-p)
18802 (call-interactively 'org-inlinetask-demote))
18803 ((or (org-at-item-p)
18804 (and (org-region-active-p)
18805 (save-excursion
18806 (goto-char (region-beginning))
18807 (org-at-item-p))))
18808 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18809 (call-interactively 'org-indent-item))
18810 (t (call-interactively 'forward-word))))
18812 (defun org-check-for-hidden (what)
18813 "Check if there are hidden headlines/items in the current visual line.
18814 WHAT can be either `headlines' or `items'. If the current line is
18815 an outline or item heading and it has a folded subtree below it,
18816 this function returns t, nil otherwise."
18817 (let ((re (cond
18818 ((eq what 'headlines) org-outline-regexp-bol)
18819 ((eq what 'items) (org-item-beginning-re))
18820 (t (error "This should not happen"))))
18821 beg end)
18822 (save-excursion
18823 (catch 'exit
18824 (unless (org-region-active-p)
18825 (setq beg (point-at-bol))
18826 (beginning-of-line 2)
18827 (while (and (not (eobp)) ;; this is like `next-line'
18828 (get-char-property (1- (point)) 'invisible))
18829 (beginning-of-line 2))
18830 (setq end (point))
18831 (goto-char beg)
18832 (goto-char (point-at-eol))
18833 (setq end (max end (point)))
18834 (while (re-search-forward re end t)
18835 (if (get-char-property (match-beginning 0) 'invisible)
18836 (throw 'exit t))))
18837 nil))))
18839 (defun org-metaup (&optional arg)
18840 "Move subtree up or move table row up.
18841 Calls `org-move-subtree-up' or `org-table-move-row' or
18842 `org-move-item-up', depending on context. See the individual commands
18843 for more information."
18844 (interactive "P")
18845 (cond
18846 ((run-hook-with-args-until-success 'org-metaup-hook))
18847 ((org-region-active-p)
18848 (let* ((a (min (region-beginning) (region-end)))
18849 (b (1- (max (region-beginning) (region-end))))
18850 (c (save-excursion (goto-char a)
18851 (move-beginning-of-line 0)))
18852 (d (save-excursion (goto-char a)
18853 (move-end-of-line 0) (point))))
18854 (transpose-regions a b c d)
18855 (goto-char c)))
18856 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18857 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18858 ((org-at-item-p) (call-interactively 'org-move-item-up))
18859 (t (org-drag-element-backward))))
18861 (defun org-metadown (&optional arg)
18862 "Move subtree down or move table row down.
18863 Calls `org-move-subtree-down' or `org-table-move-row' or
18864 `org-move-item-down', depending on context. See the individual
18865 commands for more information."
18866 (interactive "P")
18867 (cond
18868 ((run-hook-with-args-until-success 'org-metadown-hook))
18869 ((org-region-active-p)
18870 (let* ((a (min (region-beginning) (region-end)))
18871 (b (max (region-beginning) (region-end)))
18872 (c (save-excursion (goto-char b)
18873 (move-beginning-of-line 1)))
18874 (d (save-excursion (goto-char b)
18875 (move-end-of-line 1) (1+ (point)))))
18876 (transpose-regions a b c d)
18877 (goto-char d)))
18878 ((org-at-table-p) (call-interactively 'org-table-move-row))
18879 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18880 ((org-at-item-p) (call-interactively 'org-move-item-down))
18881 (t (org-drag-element-forward))))
18883 (defun org-shiftup (&optional arg)
18884 "Increase item in timestamp or increase priority of current headline.
18885 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18886 depending on context. See the individual commands for more information."
18887 (interactive "P")
18888 (cond
18889 ((run-hook-with-args-until-success 'org-shiftup-hook))
18890 ((and org-support-shift-select (org-region-active-p))
18891 (org-call-for-shift-select 'previous-line))
18892 ((org-at-timestamp-p t)
18893 (call-interactively (if org-edit-timestamp-down-means-later
18894 'org-timestamp-down 'org-timestamp-up)))
18895 ((and (not (eq org-support-shift-select 'always))
18896 org-enable-priority-commands
18897 (org-at-heading-p))
18898 (call-interactively 'org-priority-up))
18899 ((and (not org-support-shift-select) (org-at-item-p))
18900 (call-interactively 'org-previous-item))
18901 ((org-clocktable-try-shift 'up arg))
18902 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18903 (org-support-shift-select
18904 (org-call-for-shift-select 'previous-line))
18905 (t (org-shiftselect-error))))
18907 (defun org-shiftdown (&optional arg)
18908 "Decrease item in timestamp or decrease priority of current headline.
18909 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18910 depending on context. See the individual commands for more information."
18911 (interactive "P")
18912 (cond
18913 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18914 ((and org-support-shift-select (org-region-active-p))
18915 (org-call-for-shift-select 'next-line))
18916 ((org-at-timestamp-p t)
18917 (call-interactively (if org-edit-timestamp-down-means-later
18918 'org-timestamp-up 'org-timestamp-down)))
18919 ((and (not (eq org-support-shift-select 'always))
18920 org-enable-priority-commands
18921 (org-at-heading-p))
18922 (call-interactively 'org-priority-down))
18923 ((and (not org-support-shift-select) (org-at-item-p))
18924 (call-interactively 'org-next-item))
18925 ((org-clocktable-try-shift 'down arg))
18926 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18927 (org-support-shift-select
18928 (org-call-for-shift-select 'next-line))
18929 (t (org-shiftselect-error))))
18931 (defun org-shiftright (&optional arg)
18932 "Cycle the thing at point or in the current line, depending on context.
18933 Depending on context, this does one of the following:
18935 - switch a timestamp at point one day into the future
18936 - on a headline, switch to the next TODO keyword.
18937 - on an item, switch entire list to the next bullet type
18938 - on a property line, switch to the next allowed value
18939 - on a clocktable definition line, move time block into the future"
18940 (interactive "P")
18941 (cond
18942 ((run-hook-with-args-until-success 'org-shiftright-hook))
18943 ((and org-support-shift-select (org-region-active-p))
18944 (org-call-for-shift-select 'forward-char))
18945 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18946 ((and (not (eq org-support-shift-select 'always))
18947 (org-at-heading-p))
18948 (let ((org-inhibit-logging
18949 (not org-treat-S-cursor-todo-selection-as-state-change))
18950 (org-inhibit-blocking
18951 (not org-treat-S-cursor-todo-selection-as-state-change)))
18952 (org-call-with-arg 'org-todo 'right)))
18953 ((or (and org-support-shift-select
18954 (not (eq org-support-shift-select 'always))
18955 (org-at-item-bullet-p))
18956 (and (not org-support-shift-select) (org-at-item-p)))
18957 (org-call-with-arg 'org-cycle-list-bullet nil))
18958 ((and (not (eq org-support-shift-select 'always))
18959 (org-at-property-p))
18960 (call-interactively 'org-property-next-allowed-value))
18961 ((org-clocktable-try-shift 'right arg))
18962 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18963 (org-support-shift-select
18964 (org-call-for-shift-select 'forward-char))
18965 (t (org-shiftselect-error))))
18967 (defun org-shiftleft (&optional arg)
18968 "Cycle the thing at point or in the current line, depending on context.
18969 Depending on context, this does one of the following:
18971 - switch a timestamp at point one day into the past
18972 - on a headline, switch to the previous TODO keyword.
18973 - on an item, switch entire list to the previous bullet type
18974 - on a property line, switch to the previous allowed value
18975 - on a clocktable definition line, move time block into the past"
18976 (interactive "P")
18977 (cond
18978 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18979 ((and org-support-shift-select (org-region-active-p))
18980 (org-call-for-shift-select 'backward-char))
18981 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18982 ((and (not (eq org-support-shift-select 'always))
18983 (org-at-heading-p))
18984 (let ((org-inhibit-logging
18985 (not org-treat-S-cursor-todo-selection-as-state-change))
18986 (org-inhibit-blocking
18987 (not org-treat-S-cursor-todo-selection-as-state-change)))
18988 (org-call-with-arg 'org-todo 'left)))
18989 ((or (and org-support-shift-select
18990 (not (eq org-support-shift-select 'always))
18991 (org-at-item-bullet-p))
18992 (and (not org-support-shift-select) (org-at-item-p)))
18993 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18994 ((and (not (eq org-support-shift-select 'always))
18995 (org-at-property-p))
18996 (call-interactively 'org-property-previous-allowed-value))
18997 ((org-clocktable-try-shift 'left arg))
18998 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18999 (org-support-shift-select
19000 (org-call-for-shift-select 'backward-char))
19001 (t (org-shiftselect-error))))
19003 (defun org-shiftcontrolright ()
19004 "Switch to next TODO set."
19005 (interactive)
19006 (cond
19007 ((and org-support-shift-select (org-region-active-p))
19008 (org-call-for-shift-select 'forward-word))
19009 ((and (not (eq org-support-shift-select 'always))
19010 (org-at-heading-p))
19011 (org-call-with-arg 'org-todo 'nextset))
19012 (org-support-shift-select
19013 (org-call-for-shift-select 'forward-word))
19014 (t (org-shiftselect-error))))
19016 (defun org-shiftcontrolleft ()
19017 "Switch to previous TODO set."
19018 (interactive)
19019 (cond
19020 ((and org-support-shift-select (org-region-active-p))
19021 (org-call-for-shift-select 'backward-word))
19022 ((and (not (eq org-support-shift-select 'always))
19023 (org-at-heading-p))
19024 (org-call-with-arg 'org-todo 'previousset))
19025 (org-support-shift-select
19026 (org-call-for-shift-select 'backward-word))
19027 (t (org-shiftselect-error))))
19029 (defun org-shiftcontrolup ()
19030 "Change timestamps synchronously up in CLOCK log lines."
19031 (interactive)
19032 (cond ((and (not org-support-shift-select)
19033 (org-at-clock-log-p)
19034 (org-at-timestamp-p t))
19035 (org-clock-timestamps-up))
19036 (t (org-shiftselect-error))))
19038 (defun org-shiftcontroldown ()
19039 "Change timestamps synchronously down in CLOCK log lines."
19040 (interactive)
19041 (cond ((and (not org-support-shift-select)
19042 (org-at-clock-log-p)
19043 (org-at-timestamp-p t))
19044 (org-clock-timestamps-down))
19045 (t (org-shiftselect-error))))
19047 (defun org-ctrl-c-ret ()
19048 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19049 (interactive)
19050 (cond
19051 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19052 (t (call-interactively 'org-insert-heading))))
19054 (defun org-find-visible ()
19055 (let ((s (point)))
19056 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19057 (get-char-property s 'invisible)))
19059 (defun org-find-invisible ()
19060 (let ((s (point)))
19061 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19062 (not (get-char-property s 'invisible))))
19065 (defun org-copy-visible (beg end)
19066 "Copy the visible parts of the region."
19067 (interactive "r")
19068 (let (snippets s)
19069 (save-excursion
19070 (save-restriction
19071 (narrow-to-region beg end)
19072 (setq s (goto-char (point-min)))
19073 (while (not (= (point) (point-max)))
19074 (goto-char (org-find-invisible))
19075 (push (buffer-substring s (point)) snippets)
19076 (setq s (goto-char (org-find-visible))))))
19077 (kill-new (apply 'concat (nreverse snippets)))))
19079 (defun org-copy-special ()
19080 "Copy region in table or copy current subtree.
19081 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19082 See the individual commands for more information."
19083 (interactive)
19084 (call-interactively
19085 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19087 (defun org-cut-special ()
19088 "Cut region in table or cut current subtree.
19089 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19090 See the individual commands for more information."
19091 (interactive)
19092 (call-interactively
19093 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19095 (defun org-paste-special (arg)
19096 "Paste rectangular region into table, or past subtree relative to level.
19097 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19098 See the individual commands for more information."
19099 (interactive "P")
19100 (if (org-at-table-p)
19101 (org-table-paste-rectangle)
19102 (org-paste-subtree arg)))
19104 (defun org-edit-special (&optional arg)
19105 "Call a special editor for the stuff at point.
19106 When at a table, call the formula editor with `org-table-edit-formulas'.
19107 When at the first line of an src example, call `org-edit-src-code'.
19108 When in an #+include line, visit the include file. Otherwise call
19109 `ffap' to visit the file at point."
19110 (interactive)
19111 ;; possibly prep session before editing source
19112 (when arg
19113 (let* ((info (org-babel-get-src-block-info))
19114 (lang (nth 0 info))
19115 (params (nth 2 info))
19116 (session (cdr (assoc :session params))))
19117 (when (and info session) ;; we are in a source-code block with a session
19118 (funcall
19119 (intern (concat "org-babel-prep-session:" lang)) session params))))
19120 (cond ;; proceed with `org-edit-special'
19121 ((save-excursion
19122 (beginning-of-line 1)
19123 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19124 (find-file (org-trim (match-string 1))))
19125 ((org-edit-src-code))
19126 ((org-edit-fixed-width-region))
19127 ((org-at-table.el-p)
19128 (org-edit-src-code))
19129 ((or (org-at-table-p)
19130 (save-excursion
19131 (beginning-of-line 1)
19132 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19133 (call-interactively 'org-table-edit-formulas))
19134 (t (call-interactively 'ffap))))
19136 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19137 (defun org-ctrl-c-ctrl-c (&optional arg)
19138 "Set tags in headline, or update according to changed information at point.
19140 This command does many different things, depending on context:
19142 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19143 this is what we do.
19145 - If the cursor is on a statistics cookie, update it.
19147 - If the cursor is in a headline, prompt for tags and insert them
19148 into the current line, aligned to `org-tags-column'. When called
19149 with prefix arg, realign all tags in the current buffer.
19151 - If the cursor is in one of the special #+KEYWORD lines, this
19152 triggers scanning the buffer for these lines and updating the
19153 information.
19155 - If the cursor is inside a table, realign the table. This command
19156 works even if the automatic table editor has been turned off.
19158 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19159 the entire table.
19161 - If the cursor is at a footnote reference or definition, jump to
19162 the corresponding definition or references, respectively.
19164 - If the cursor is a the beginning of a dynamic block, update it.
19166 - If the current buffer is a capture buffer, close note and file it.
19168 - If the cursor is on a <<<target>>>, update radio targets and
19169 corresponding links in this buffer.
19171 - If the cursor is on a numbered item in a plain list, renumber the
19172 ordered list.
19174 - If the cursor is on a checkbox, toggle it.
19176 - If the cursor is on a code block, evaluate it. The variable
19177 `org-confirm-babel-evaluate' can be used to control prompting
19178 before code block evaluation, by default every code block
19179 evaluation requires confirmation. Code block evaluation can be
19180 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19181 (interactive "P")
19182 (let ((org-enable-table-editor t))
19183 (cond
19184 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19185 org-occur-highlights
19186 org-latex-fragment-image-overlays)
19187 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19188 (org-remove-occur-highlights)
19189 (org-remove-latex-fragment-image-overlays)
19190 (message "Temporary highlights/overlays removed from current buffer"))
19191 ((and (local-variable-p 'org-finish-function (current-buffer))
19192 (fboundp org-finish-function))
19193 (funcall org-finish-function))
19194 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19195 ((org-in-regexp org-ts-regexp-both)
19196 (org-timestamp-change 0 'day))
19197 ((or (looking-at org-property-start-re)
19198 (org-at-property-p))
19199 (call-interactively 'org-property-action))
19200 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19201 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19202 (or (org-at-heading-p) (org-at-item-p)))
19203 (call-interactively 'org-update-statistics-cookies))
19204 ((org-at-heading-p) (call-interactively 'org-set-tags))
19205 ((org-at-table.el-p)
19206 (message "Use C-c ' to edit table.el tables"))
19207 ((org-at-table-p)
19208 (org-table-maybe-eval-formula)
19209 (if arg
19210 (call-interactively 'org-table-recalculate)
19211 (org-table-maybe-recalculate-line))
19212 (call-interactively 'org-table-align)
19213 (orgtbl-send-table 'maybe))
19214 ((or (org-footnote-at-reference-p)
19215 (org-footnote-at-definition-p))
19216 (call-interactively 'org-footnote-action))
19217 ((org-at-item-checkbox-p)
19218 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19219 ;; list only if at top item.
19220 (let* ((cbox (match-string 1))
19221 (struct (org-list-struct))
19222 (old-struct (copy-tree struct))
19223 (parents (org-list-parents-alist struct))
19224 (orderedp (org-entry-get nil "ORDERED"))
19225 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19226 block-item)
19227 ;; Use a light version of `org-toggle-checkbox' to avoid
19228 ;; computing list structure twice.
19229 (let ((new-box (cond
19230 ((equal arg '(16)) "[-]")
19231 ((equal arg '(4)) nil)
19232 ((equal "[X]" cbox) "[ ]")
19233 (t "[X]"))))
19234 (if (and firstp arg)
19235 ;; If at first item of sub-list, remove check-box from
19236 ;; every item at the same level.
19237 (mapc
19238 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19239 (org-list-get-all-items
19240 (point-at-bol) struct (org-list-prevs-alist struct)))
19241 (org-list-set-checkbox (point-at-bol) struct new-box)))
19242 ;; Replicate `org-list-write-struct', while grabbing a return
19243 ;; value from `org-list-struct-fix-box'.
19244 (org-list-struct-fix-ind struct parents 2)
19245 (org-list-struct-fix-item-end struct)
19246 (let ((prevs (org-list-prevs-alist struct)))
19247 (org-list-struct-fix-bul struct prevs)
19248 (org-list-struct-fix-ind struct parents)
19249 (setq block-item
19250 (org-list-struct-fix-box struct parents prevs orderedp)))
19251 (org-list-struct-apply-struct struct old-struct)
19252 (org-update-checkbox-count-maybe)
19253 (when block-item
19254 (message
19255 "Checkboxes were removed due to unchecked box at line %d"
19256 (org-current-line block-item)))
19257 (when firstp (org-list-send-list 'maybe))))
19258 ((org-at-item-p)
19259 ;; Cursor at an item: repair list. Do checkbox related actions
19260 ;; only if function was called with an argument. Send list only
19261 ;; if at top item.
19262 (let* ((struct (org-list-struct))
19263 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19264 old-struct)
19265 (when arg
19266 (setq old-struct (copy-tree struct))
19267 (if firstp
19268 ;; If at first item of sub-list, add check-box to every
19269 ;; item at the same level.
19270 (mapc
19271 (lambda (pos)
19272 (unless (org-list-get-checkbox pos struct)
19273 (org-list-set-checkbox pos struct "[ ]")))
19274 (org-list-get-all-items
19275 (point-at-bol) struct (org-list-prevs-alist struct)))
19276 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19277 (org-list-write-struct
19278 struct (org-list-parents-alist struct) old-struct)
19279 (when arg (org-update-checkbox-count-maybe))
19280 (when firstp (org-list-send-list 'maybe))))
19281 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19282 ;; Dynamic block
19283 (beginning-of-line 1)
19284 (save-excursion (org-update-dblock)))
19285 ((save-excursion
19286 (let ((case-fold-search t))
19287 (beginning-of-line 1)
19288 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19289 (cond
19290 ((or (equal (match-string 1) "TBLFM")
19291 (equal (match-string 1) "tblfm"))
19292 ;; Recalculate the table before this line
19293 (save-excursion
19294 (beginning-of-line 1)
19295 (skip-chars-backward " \r\n\t")
19296 (if (org-at-table-p)
19297 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19299 (let ((org-inhibit-startup-visibility-stuff t)
19300 (org-startup-align-all-tables nil))
19301 (when (boundp 'org-table-coordinate-overlays)
19302 (mapc 'delete-overlay org-table-coordinate-overlays)
19303 (setq org-table-coordinate-overlays nil))
19304 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19305 (message "Local setup has been refreshed"))))
19306 ((org-clock-update-time-maybe))
19308 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19309 (error "C-c C-c can do nothing useful at this location"))))))
19311 (defun org-mode-restart ()
19312 "Restart Org-mode, to scan again for special lines.
19313 Also updates the keyword regular expressions."
19314 (interactive)
19315 (org-mode)
19316 (message "Org-mode restarted"))
19318 (defun org-kill-note-or-show-branches ()
19319 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19320 (interactive)
19321 (if (not org-finish-function)
19322 (progn
19323 (hide-subtree)
19324 (call-interactively 'show-branches))
19325 (let ((org-note-abort t))
19326 (funcall org-finish-function))))
19328 (defun org-return (&optional indent)
19329 "Goto next table row or insert a newline.
19330 Calls `org-table-next-row' or `newline', depending on context.
19331 See the individual commands for more information."
19332 (interactive)
19333 (let (org-ts-what)
19334 (cond
19335 ((or (bobp) (org-in-src-block-p))
19336 (if indent (newline-and-indent) (newline)))
19337 ((org-at-table-p)
19338 (org-table-justify-field-maybe)
19339 (call-interactively 'org-table-next-row))
19340 ;; when `newline-and-indent' is called within a list, make sure
19341 ;; text moved stays inside the item.
19342 ((and (org-in-item-p) indent)
19343 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19344 (progn
19345 (save-match-data (newline))
19346 (org-indent-line-to (length (match-string 0))))
19347 (let ((ind (org-get-indentation)))
19348 (newline)
19349 (if (org-looking-back org-list-end-re)
19350 (org-indent-line)
19351 (org-indent-line-to ind)))))
19352 ((and org-return-follows-link
19353 (org-at-timestamp-p t)
19354 (not (eq org-ts-what 'after)))
19355 (org-follow-timestamp-link))
19356 ((and org-return-follows-link
19357 (let ((tprop (get-text-property (point) 'face)))
19358 (or (eq tprop 'org-link)
19359 (and (listp tprop) (memq 'org-link tprop)))))
19360 (call-interactively 'org-open-at-point))
19361 ((and (org-at-heading-p)
19362 (looking-at
19363 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19364 (org-show-entry)
19365 (end-of-line 1)
19366 (newline))
19367 (t (if indent (newline-and-indent) (newline))))))
19369 (defun org-return-indent ()
19370 "Goto next table row or insert a newline and indent.
19371 Calls `org-table-next-row' or `newline-and-indent', depending on
19372 context. See the individual commands for more information."
19373 (interactive)
19374 (org-return t))
19376 (defun org-ctrl-c-star ()
19377 "Compute table, or change heading status of lines.
19378 Calls `org-table-recalculate' or `org-toggle-heading',
19379 depending on context."
19380 (interactive)
19381 (cond
19382 ((org-at-table-p)
19383 (call-interactively 'org-table-recalculate))
19385 ;; Convert all lines in region to list items
19386 (call-interactively 'org-toggle-heading))))
19388 (defun org-ctrl-c-minus ()
19389 "Insert separator line in table or modify bullet status of line.
19390 Also turns a plain line or a region of lines into list items.
19391 Calls `org-table-insert-hline', `org-toggle-item', or
19392 `org-cycle-list-bullet', depending on context."
19393 (interactive)
19394 (cond
19395 ((org-at-table-p)
19396 (call-interactively 'org-table-insert-hline))
19397 ((org-region-active-p)
19398 (call-interactively 'org-toggle-item))
19399 ((org-in-item-p)
19400 (call-interactively 'org-cycle-list-bullet))
19402 (call-interactively 'org-toggle-item))))
19404 (defun org-toggle-item (arg)
19405 "Convert headings or normal lines to items, items to normal lines.
19406 If there is no active region, only the current line is considered.
19408 If the first non blank line in the region is an headline, convert
19409 all headlines to items, shifting text accordingly.
19411 If it is an item, convert all items to normal lines.
19413 If it is normal text, change region into an item. With a prefix
19414 argument ARG, change each line in region into an item."
19415 (interactive "P")
19416 (let ((shift-text
19417 (function
19418 ;; Shift text in current section to IND, from point to END.
19419 ;; The function leaves point to END line.
19420 (lambda (ind end)
19421 (let ((min-i 1000) (end (copy-marker end)))
19422 ;; First determine the minimum indentation (MIN-I) of
19423 ;; the text.
19424 (save-excursion
19425 (catch 'exit
19426 (while (< (point) end)
19427 (let ((i (org-get-indentation)))
19428 (cond
19429 ;; Skip blank lines and inline tasks.
19430 ((looking-at "^[ \t]*$"))
19431 ((looking-at org-outline-regexp-bol))
19432 ;; We can't find less than 0 indentation.
19433 ((zerop i) (throw 'exit (setq min-i 0)))
19434 ((< i min-i) (setq min-i i))))
19435 (forward-line))))
19436 ;; Then indent each line so that a line indented to
19437 ;; MIN-I becomes indented to IND. Ignore blank lines
19438 ;; and inline tasks in the process.
19439 (let ((delta (- ind min-i)))
19440 (while (< (point) end)
19441 (unless (or (looking-at "^[ \t]*$")
19442 (looking-at org-outline-regexp-bol))
19443 (org-indent-line-to (+ (org-get-indentation) delta)))
19444 (forward-line)))))))
19445 (skip-blanks
19446 (function
19447 ;; Return beginning of first non-blank line, starting from
19448 ;; line at POS.
19449 (lambda (pos)
19450 (save-excursion
19451 (goto-char pos)
19452 (skip-chars-forward " \r\t\n")
19453 (point-at-bol)))))
19454 beg end)
19455 ;; Determine boundaries of changes.
19456 (if (org-region-active-p)
19457 (setq beg (funcall skip-blanks (region-beginning))
19458 end (copy-marker (region-end)))
19459 (setq beg (funcall skip-blanks (point-at-bol))
19460 end (copy-marker (point-at-eol))))
19461 ;; Depending on the starting line, choose an action on the text
19462 ;; between BEG and END.
19463 (org-with-limited-levels
19464 (save-excursion
19465 (goto-char beg)
19466 (cond
19467 ;; Case 1. Start at an item: de-itemize. Note that it only
19468 ;; happens when a region is active: `org-ctrl-c-minus'
19469 ;; would call `org-cycle-list-bullet' otherwise.
19470 ((org-at-item-p)
19471 (while (< (point) end)
19472 (when (org-at-item-p)
19473 (skip-chars-forward " \t")
19474 (delete-region (point) (match-end 0)))
19475 (forward-line)))
19476 ;; Case 2. Start at an heading: convert to items.
19477 ((org-at-heading-p)
19478 (let* ((bul (org-list-bullet-string "-"))
19479 (bul-len (length bul))
19480 ;; Indentation of the first heading. It should be
19481 ;; relative to the indentation of its parent, if any.
19482 (start-ind (save-excursion
19483 (cond
19484 ((not org-adapt-indentation) 0)
19485 ((not (outline-previous-heading)) 0)
19486 (t (length (match-string 0))))))
19487 ;; Level of first heading. Further headings will be
19488 ;; compared to it to determine hierarchy in the list.
19489 (ref-level (org-reduced-level (org-outline-level))))
19490 (while (< (point) end)
19491 (let* ((level (org-reduced-level (org-outline-level)))
19492 (delta (max 0 (- level ref-level))))
19493 ;; If current headline is less indented than the first
19494 ;; one, set it as reference, in order to preserve
19495 ;; subtrees.
19496 (when (< level ref-level) (setq ref-level level))
19497 (replace-match bul t t)
19498 (org-indent-line-to (+ start-ind (* delta bul-len)))
19499 ;; Ensure all text down to END (or SECTION-END) belongs
19500 ;; to the newly created item.
19501 (let ((section-end (save-excursion
19502 (or (outline-next-heading) (point)))))
19503 (forward-line)
19504 (funcall shift-text
19505 (+ start-ind (* (1+ delta) bul-len))
19506 (min end section-end)))))))
19507 ;; Case 3. Normal line with ARG: turn each non-item line into
19508 ;; an item.
19509 (arg
19510 (while (< (point) end)
19511 (unless (or (org-at-heading-p) (org-at-item-p))
19512 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19513 (replace-match
19514 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19515 (forward-line)))
19516 ;; Case 4. Normal line without ARG: make the first line of
19517 ;; region an item, and shift indentation of others
19518 ;; lines to set them as item's body.
19519 (t (let* ((bul (org-list-bullet-string "-"))
19520 (bul-len (length bul))
19521 (ref-ind (org-get-indentation)))
19522 (skip-chars-forward " \t")
19523 (insert bul)
19524 (forward-line)
19525 (while (< (point) end)
19526 ;; Ensure that lines less indented than first one
19527 ;; still get included in item body.
19528 (funcall shift-text
19529 (+ ref-ind bul-len)
19530 (min end (save-excursion (or (outline-next-heading)
19531 (point)))))
19532 (forward-line)))))))))
19534 (defun org-toggle-heading (&optional nstars)
19535 "Convert headings to normal text, or items or text to headings.
19536 If there is no active region, only the current line is considered.
19538 With a \\[universal-argument] prefix, convert the whole list at
19539 point into heading.
19541 In a region:
19543 - If the first non blank line is an headline, remove the stars
19544 from all headlines in the region.
19546 - If it is a normal line turn each and every normal line (i.e. not an
19547 heading or an item) in the region into a heading.
19549 - If it is a plain list item, turn all plain list items into headings.
19551 When converting a line into a heading, the number of stars is chosen
19552 such that the lines become children of the current entry. However,
19553 when a prefix argument is given, its value determines the number of
19554 stars to add."
19555 (interactive "P")
19556 (let ((skip-blanks
19557 (function
19558 ;; Return beginning of first non-blank line, starting from
19559 ;; line at POS.
19560 (lambda (pos)
19561 (save-excursion
19562 (goto-char pos)
19563 (while (org-at-comment-p) (forward-line))
19564 (skip-chars-forward " \r\t\n")
19565 (point-at-bol)))))
19566 beg end toggled)
19567 ;; Determine boundaries of changes. If a universal prefix has
19568 ;; been given, put the list in a region. If region ends at a bol,
19569 ;; do not consider the last line to be in the region.
19571 (when (and current-prefix-arg (org-at-item-p))
19572 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19573 (org-mark-element))
19575 (if (org-region-active-p)
19576 (setq beg (funcall skip-blanks (region-beginning))
19577 end (copy-marker (save-excursion
19578 (goto-char (region-end))
19579 (if (bolp) (point) (point-at-eol)))))
19580 (setq beg (funcall skip-blanks (point-at-bol))
19581 end (copy-marker (point-at-eol))))
19582 ;; Ensure inline tasks don't count as headings.
19583 (org-with-limited-levels
19584 (save-excursion
19585 (goto-char beg)
19586 (cond
19587 ;; Case 1. Started at an heading: de-star headings.
19588 ((org-at-heading-p)
19589 (while (< (point) end)
19590 (when (org-at-heading-p t)
19591 (looking-at org-outline-regexp) (replace-match "")
19592 (setq toggled t))
19593 (forward-line)))
19594 ;; Case 2. Started at an item: change items into headlines.
19595 ;; One star will be added by `org-list-to-subtree'.
19596 ((org-at-item-p)
19597 (let* ((stars (make-string
19598 (if nstars
19599 ;; subtract the star that will be added again by
19600 ;; `org-list-to-subtree'
19601 (1- (prefix-numeric-value current-prefix-arg))
19602 (or (org-current-level) 0))
19603 ?*))
19604 (add-stars
19605 (cond (nstars "") ; stars from prefix only
19606 ((equal stars "") "") ; before first heading
19607 (org-odd-levels-only "*") ; inside heading, odd
19608 (t "")))) ; inside heading, oddeven
19609 (while (< (point) end)
19610 (when (org-at-item-p)
19611 ;; Pay attention to cases when region ends before list.
19612 (let* ((struct (org-list-struct))
19613 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19614 (save-restriction
19615 (narrow-to-region (point) list-end)
19616 (insert
19617 (org-list-to-subtree
19618 (org-list-parse-list t)
19619 '(:istart (concat stars add-stars (funcall get-stars depth))
19620 :icount (concat stars add-stars (funcall get-stars depth)))))))
19621 (setq toggled t))
19622 (forward-line))))
19623 ;; Case 3. Started at normal text: make every line an heading,
19624 ;; skipping headlines and items.
19625 (t (let* ((stars (make-string
19626 (if nstars
19627 (prefix-numeric-value current-prefix-arg)
19628 (or (org-current-level) 0))
19629 ?*))
19630 (add-stars
19631 (cond (nstars "") ; stars from prefix only
19632 ((equal stars "") "*") ; before first heading
19633 (org-odd-levels-only "**") ; inside heading, odd
19634 (t "*"))) ; inside heading, oddeven
19635 (rpl (concat stars add-stars " ")))
19636 (while (< (point) end)
19637 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19638 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19639 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19640 (forward-line)))))))
19641 (unless toggled (message "Cannot toggle heading from here"))))
19643 (defun org-meta-return (&optional arg)
19644 "Insert a new heading or wrap a region in a table.
19645 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19646 See the individual commands for more information."
19647 (interactive "P")
19648 (cond
19649 ((run-hook-with-args-until-success 'org-metareturn-hook))
19650 ((or (org-at-drawer-p) (org-at-property-p))
19651 (newline-and-indent))
19652 ((org-at-table-p)
19653 (call-interactively 'org-table-wrap-region))
19654 (t (call-interactively 'org-insert-heading))))
19656 ;;; Menu entries
19658 (defsubst org-in-subtree-not-table-p ()
19659 "Are we in a subtree and not in a table?"
19660 (and (not (org-before-first-heading-p))
19661 (not (org-at-table-p))))
19663 ;; Define the Org-mode menus
19664 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19665 '("Tbl"
19666 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19667 ["Next Field" org-cycle (org-at-table-p)]
19668 ["Previous Field" org-shifttab (org-at-table-p)]
19669 ["Next Row" org-return (org-at-table-p)]
19670 "--"
19671 ["Blank Field" org-table-blank-field (org-at-table-p)]
19672 ["Edit Field" org-table-edit-field (org-at-table-p)]
19673 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19674 "--"
19675 ("Column"
19676 ["Move Column Left" org-metaleft (org-at-table-p)]
19677 ["Move Column Right" org-metaright (org-at-table-p)]
19678 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19679 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19680 ("Row"
19681 ["Move Row Up" org-metaup (org-at-table-p)]
19682 ["Move Row Down" org-metadown (org-at-table-p)]
19683 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19684 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19685 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19686 "--"
19687 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19688 ("Rectangle"
19689 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19690 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19691 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19692 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19693 "--"
19694 ("Calculate"
19695 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19696 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19697 ["Edit Formulas" org-edit-special (org-at-table-p)]
19698 "--"
19699 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19700 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19701 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19702 "--"
19703 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19704 "--"
19705 ["Sum Column/Rectangle" org-table-sum
19706 (or (org-at-table-p) (org-region-active-p))]
19707 ["Which Column?" org-table-current-column (org-at-table-p)])
19708 ["Debug Formulas"
19709 org-table-toggle-formula-debugger
19710 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19711 ["Show Col/Row Numbers"
19712 org-table-toggle-coordinate-overlays
19713 :style toggle
19714 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19715 "--"
19716 ["Create" org-table-create (and (not (org-at-table-p))
19717 org-enable-table-editor)]
19718 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19719 ["Import from File" org-table-import (not (org-at-table-p))]
19720 ["Export to File" org-table-export (org-at-table-p)]
19721 "--"
19722 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19724 (easy-menu-define org-org-menu org-mode-map "Org menu"
19725 '("Org"
19726 ("Show/Hide"
19727 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19728 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19729 ["Sparse Tree..." org-sparse-tree t]
19730 ["Reveal Context" org-reveal t]
19731 ["Show All" show-all t]
19732 "--"
19733 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19734 "--"
19735 ["New Heading" org-insert-heading t]
19736 ("Navigate Headings"
19737 ["Up" outline-up-heading t]
19738 ["Next" outline-next-visible-heading t]
19739 ["Previous" outline-previous-visible-heading t]
19740 ["Next Same Level" outline-forward-same-level t]
19741 ["Previous Same Level" outline-backward-same-level t]
19742 "--"
19743 ["Jump" org-goto t])
19744 ("Edit Structure"
19745 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19746 "--"
19747 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19748 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19749 "--"
19750 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19751 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19752 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19753 "--"
19754 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19755 "--"
19756 ["Copy visible text" org-copy-visible t]
19757 "--"
19758 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19759 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19760 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19761 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19762 "--"
19763 ["Sort Region/Children" org-sort t]
19764 "--"
19765 ["Convert to odd levels" org-convert-to-odd-levels t]
19766 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19767 ("Editing"
19768 ["Emphasis..." org-emphasize t]
19769 ["Edit Source Example" org-edit-special t]
19770 "--"
19771 ["Footnote new/jump" org-footnote-action t]
19772 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19773 ("Archive"
19774 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19775 "--"
19776 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19777 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19778 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19780 "--"
19781 ("Hyperlinks"
19782 ["Store Link (Global)" org-store-link t]
19783 ["Find existing link to here" org-occur-link-in-agenda-files t]
19784 ["Insert Link" org-insert-link t]
19785 ["Follow Link" org-open-at-point t]
19786 "--"
19787 ["Next link" org-next-link t]
19788 ["Previous link" org-previous-link t]
19789 "--"
19790 ["Descriptive Links"
19791 org-toggle-link-display
19792 :style radio
19793 :selected org-descriptive-links
19795 ["Literal Links"
19796 org-toggle-link-display
19797 :style radio
19798 :selected (not org-descriptive-links)])
19799 "--"
19800 ("TODO Lists"
19801 ["TODO/DONE/-" org-todo t]
19802 ("Select keyword"
19803 ["Next keyword" org-shiftright (org-at-heading-p)]
19804 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19805 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19806 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19807 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19808 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19809 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19810 "--"
19811 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19812 :selected org-enforce-todo-dependencies :style toggle :active t]
19813 "Settings for tree at point"
19814 ["Do Children sequentially" org-toggle-ordered-property :style radio
19815 :selected (org-entry-get nil "ORDERED")
19816 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19817 ["Do Children parallel" org-toggle-ordered-property :style radio
19818 :selected (not (org-entry-get nil "ORDERED"))
19819 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19820 "--"
19821 ["Set Priority" org-priority t]
19822 ["Priority Up" org-shiftup t]
19823 ["Priority Down" org-shiftdown t]
19824 "--"
19825 ["Get news from all feeds" org-feed-update-all t]
19826 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19827 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19828 ("TAGS and Properties"
19829 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19830 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19831 "--"
19832 ["Set property" org-set-property (not (org-before-first-heading-p))]
19833 ["Column view of properties" org-columns t]
19834 ["Insert Column View DBlock" org-insert-columns-dblock t])
19835 ("Dates and Scheduling"
19836 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19837 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19838 ("Change Date"
19839 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19840 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19841 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19842 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19843 ["Compute Time Range" org-evaluate-time-range t]
19844 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19845 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19846 "--"
19847 ["Custom time format" org-toggle-time-stamp-overlays
19848 :style radio :selected org-display-custom-times]
19849 "--"
19850 ["Goto Calendar" org-goto-calendar t]
19851 ["Date from Calendar" org-date-from-calendar t]
19852 "--"
19853 ["Start/Restart Timer" org-timer-start t]
19854 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19855 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19856 ["Insert Timer String" org-timer t]
19857 ["Insert Timer Item" org-timer-item t])
19858 ("Logging work"
19859 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19860 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19861 ["Clock out" org-clock-out t]
19862 ["Clock cancel" org-clock-cancel t]
19863 "--"
19864 ["Mark as default task" org-clock-mark-default-task t]
19865 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19866 ["Goto running clock" org-clock-goto t]
19867 "--"
19868 ["Display times" org-clock-display t]
19869 ["Create clock table" org-clock-report t]
19870 "--"
19871 ["Record DONE time"
19872 (progn (setq org-log-done (not org-log-done))
19873 (message "Switching to %s will %s record a timestamp"
19874 (car org-done-keywords)
19875 (if org-log-done "automatically" "not")))
19876 :style toggle :selected org-log-done])
19877 "--"
19878 ["Agenda Command..." org-agenda t]
19879 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19880 ("File List for Agenda")
19881 ("Special views current file"
19882 ["TODO Tree" org-show-todo-tree t]
19883 ["Check Deadlines" org-check-deadlines t]
19884 ["Timeline" org-timeline t]
19885 ["Tags/Property tree" org-match-sparse-tree t])
19886 "--"
19887 ["Export/Publish..." org-export t]
19888 ("LaTeX"
19889 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19890 :selected org-cdlatex-mode]
19891 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19892 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19893 ["Modify math symbol" org-cdlatex-math-modify
19894 (org-inside-LaTeX-fragment-p)]
19895 ["Insert citation" org-reftex-citation t]
19896 "--"
19897 ["Template for BEAMER" (progn (require 'org-beamer)
19898 (org-insert-beamer-options-template)) t])
19899 "--"
19900 ("MobileOrg"
19901 ["Push Files and Views" org-mobile-push t]
19902 ["Get Captured and Flagged" org-mobile-pull t]
19903 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19904 "--"
19905 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19906 "--"
19907 ("Documentation"
19908 ["Show Version" org-version t]
19909 ["Info Documentation" org-info t])
19910 ("Customize"
19911 ["Browse Org Group" org-customize t]
19912 "--"
19913 ["Expand This Menu" org-create-customize-menu
19914 (fboundp 'customize-menu-create)])
19915 ["Send bug report" org-submit-bug-report t]
19916 "--"
19917 ("Refresh/Reload"
19918 ["Refresh setup current buffer" org-mode-restart t]
19919 ["Reload Org (after update)" org-reload t]
19920 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19923 (defun org-info (&optional node)
19924 "Read documentation for Org-mode in the info system.
19925 With optional NODE, go directly to that node."
19926 (interactive)
19927 (info (format "(org)%s" (or node ""))))
19929 ;;;###autoload
19930 (defun org-submit-bug-report ()
19931 "Submit a bug report on Org-mode via mail.
19933 Don't hesitate to report any problems or inaccurate documentation.
19935 If you don't have setup sending mail from (X)Emacs, please copy the
19936 output buffer into your mail program, as it gives us important
19937 information about your Org-mode version and configuration."
19938 (interactive)
19939 (require 'reporter)
19940 (org-load-modules-maybe)
19941 (org-require-autoloaded-modules)
19942 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19943 (reporter-submit-bug-report
19944 "emacs-orgmode@gnu.org"
19945 (org-version nil 'full)
19946 (let (list)
19947 (save-window-excursion
19948 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19949 (delete-other-windows)
19950 (erase-buffer)
19951 (insert "You are about to submit a bug report to the Org-mode mailing list.
19953 We would like to add your full Org-mode and Outline configuration to the
19954 bug report. This greatly simplifies the work of the maintainer and
19955 other experts on the mailing list.
19957 HOWEVER, some variables you have customized may contain private
19958 information. The names of customers, colleagues, or friends, might
19959 appear in the form of file names, tags, todo states, or search strings.
19960 If you answer yes to the prompt, you might want to check and remove
19961 such private information before sending the email.")
19962 (add-text-properties (point-min) (point-max) '(face org-warning))
19963 (when (yes-or-no-p "Include your Org-mode configuration ")
19964 (mapatoms
19965 (lambda (v)
19966 (and (boundp v)
19967 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19968 (or (and (symbol-value v)
19969 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19970 (and
19971 (get v 'custom-type) (get v 'standard-value)
19972 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19973 (push v list)))))
19974 (kill-buffer (get-buffer "*Warn about privacy*"))
19975 list))
19976 nil nil
19977 "Remember to cover the basics, that is, what you expected to happen and
19978 what in fact did happen. You don't know how to make a good report? See
19980 http://orgmode.org/manual/Feedback.html#Feedback
19982 Your bug report will be posted to the Org-mode mailing list.
19983 ------------------------------------------------------------------------")
19984 (save-excursion
19985 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19986 (replace-match "\\1Bug: \\3 [\\2]")))))
19989 (defun org-install-agenda-files-menu ()
19990 (let ((bl (buffer-list)))
19991 (save-excursion
19992 (while bl
19993 (set-buffer (pop bl))
19994 (if (derived-mode-p 'org-mode) (setq bl nil)))
19995 (when (derived-mode-p 'org-mode)
19996 (easy-menu-change
19997 '("Org") "File List for Agenda"
19998 (append
19999 (list
20000 ["Edit File List" (org-edit-agenda-file-list) t]
20001 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20002 ["Remove Current File from List" org-remove-file t]
20003 ["Cycle through agenda files" org-cycle-agenda-files t]
20004 ["Occur in all agenda files" org-occur-in-agenda-files t]
20005 "--")
20006 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20008 ;;;; Documentation
20010 (defun org-require-autoloaded-modules ()
20011 (interactive)
20012 (mapc 'require
20013 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20014 org-docbook org-exp org-html org-icalendar
20015 org-id org-latex
20016 org-publish org-remember org-table
20017 org-timer org-xoxo)))
20019 ;;;###autoload
20020 (defun org-reload (&optional uncompiled)
20021 "Reload all org lisp files.
20022 With prefix arg UNCOMPILED, load the uncompiled versions."
20023 (interactive "P")
20024 (require 'loadhist)
20025 (let* ((org-dir (org-find-library-dir "org"))
20026 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20027 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20028 (remove-re (mapconcat 'identity
20029 (mapcar (lambda (f) (concat "^" f "$"))
20030 (list (if (featurep 'xemacs)
20031 "org-colview"
20032 "org-colview-xemacs")
20033 "org" "org-loaddefs" "org-version"))
20034 "\\|"))
20035 (feats (delete-dups
20036 (mapcar 'file-name-sans-extension
20037 (mapcar 'file-name-nondirectory
20038 (delq nil
20039 (mapcar 'feature-file
20040 features))))))
20041 (lfeat (append
20042 (sort
20043 (setq feats
20044 (delq nil (mapcar
20045 (lambda (f)
20046 (if (and (string-match feature-re f)
20047 (not (string-match remove-re f)))
20048 f nil))
20049 feats)))
20050 'string-lessp)
20051 (list "org-version" "org")))
20052 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20053 load-uncore load-misses)
20054 (setq load-misses
20055 (delq 't
20056 (mapcar (lambda (f)
20057 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20058 (and (string= org-dir contrib-dir)
20059 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20060 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20061 (add-to-list 'load-uncore f 'append)
20064 lfeat)))
20065 (if load-uncore
20066 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20067 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20068 (if load-misses
20069 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20070 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20071 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20073 ;;;###autoload
20074 (defun org-customize ()
20075 "Call the customize function with org as argument."
20076 (interactive)
20077 (org-load-modules-maybe)
20078 (org-require-autoloaded-modules)
20079 (customize-browse 'org))
20081 (defun org-create-customize-menu ()
20082 "Create a full customization menu for Org-mode, insert it into the menu."
20083 (interactive)
20084 (org-load-modules-maybe)
20085 (org-require-autoloaded-modules)
20086 (if (fboundp 'customize-menu-create)
20087 (progn
20088 (easy-menu-change
20089 '("Org") "Customize"
20090 `(["Browse Org group" org-customize t]
20091 "--"
20092 ,(customize-menu-create 'org)
20093 ["Set" Custom-set t]
20094 ["Save" Custom-save t]
20095 ["Reset to Current" Custom-reset-current t]
20096 ["Reset to Saved" Custom-reset-saved t]
20097 ["Reset to Standard Settings" Custom-reset-standard t]))
20098 (message "\"Org\"-menu now contains full customization menu"))
20099 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20101 ;;;; Miscellaneous stuff
20103 ;;; Generally useful functions
20105 (defun org-get-at-bol (property)
20106 "Get text property PROPERTY at beginning of line."
20107 (get-text-property (point-at-bol) property))
20109 (defun org-find-text-property-in-string (prop s)
20110 "Return the first non-nil value of property PROP in string S."
20111 (or (get-text-property 0 prop s)
20112 (get-text-property (or (next-single-property-change 0 prop s) 0)
20113 prop s)))
20115 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20116 "Display the given MESSAGE as a warning."
20117 (if (fboundp 'display-warning)
20118 (display-warning 'org message
20119 (if (featurep 'xemacs) 'warning :warning))
20120 (let ((buf (get-buffer-create "*Org warnings*")))
20121 (with-current-buffer buf
20122 (goto-char (point-max))
20123 (insert "Warning (Org): " message)
20124 (unless (bolp)
20125 (newline)))
20126 (display-buffer buf)
20127 (sit-for 0))))
20129 (defun org-eval (form)
20130 "Eval FORM and return result."
20131 (condition-case error
20132 (eval form)
20133 (error (format "%%![Error: %s]" error))))
20135 (defun org-in-clocktable-p ()
20136 "Check if the cursor is in a clocktable."
20137 (let ((pos (point)) start)
20138 (save-excursion
20139 (end-of-line 1)
20140 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20141 (setq start (match-beginning 0))
20142 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20143 (>= (match-end 0) pos)
20144 start))))
20146 (defun org-in-commented-line ()
20147 "Is point in a line starting with `#'?"
20148 (equal (char-after (point-at-bol)) ?#))
20150 (defun org-in-indented-comment-line ()
20151 "Is point in a line starting with `#' after some white space?"
20152 (save-excursion
20153 (save-match-data
20154 (goto-char (point-at-bol))
20155 (looking-at "[ \t]*#"))))
20157 (defun org-in-verbatim-emphasis ()
20158 (save-match-data
20159 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20161 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20162 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20163 (if (and marker (marker-buffer marker)
20164 (buffer-live-p (marker-buffer marker)))
20165 (progn
20166 (org-pop-to-buffer-same-window (marker-buffer marker))
20167 (if (or (> marker (point-max)) (< marker (point-min)))
20168 (widen))
20169 (goto-char marker)
20170 (org-show-context 'org-goto))
20171 (if bookmark
20172 (bookmark-jump bookmark)
20173 (error "Cannot find location"))))
20175 (defun org-quote-csv-field (s)
20176 "Quote field for inclusion in CSV material."
20177 (if (string-match "[\",]" s)
20178 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20181 (defun org-force-self-insert (N)
20182 "Needed to enforce self-insert under remapping."
20183 (interactive "p")
20184 (self-insert-command N))
20186 (defun org-string-width (s)
20187 "Compute width of string, ignoring invisible characters.
20188 This ignores character with invisibility property `org-link', and also
20189 characters with property `org-cwidth', because these will become invisible
20190 upon the next fontification round."
20191 (let (b l)
20192 (when (or (eq t buffer-invisibility-spec)
20193 (assq 'org-link buffer-invisibility-spec))
20194 (while (setq b (text-property-any 0 (length s)
20195 'invisible 'org-link s))
20196 (setq s (concat (substring s 0 b)
20197 (substring s (or (next-single-property-change
20198 b 'invisible s) (length s)))))))
20199 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20200 (setq s (concat (substring s 0 b)
20201 (substring s (or (next-single-property-change
20202 b 'org-cwidth s) (length s))))))
20203 (setq l (string-width s) b -1)
20204 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20205 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20208 (defun org-shorten-string (s maxlength)
20209 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20210 If the string is shorter or has length MAXLENGTH, just return the
20211 original string. If it is longer, the functions finds a space in the
20212 string, breaks this string off at that locations and adds three dots
20213 as ellipsis. Including the ellipsis, the string will not be longer
20214 than MAXLENGTH. If finding a good breaking point in the string does
20215 not work, the string is just chopped off in the middle of a word
20216 if necessary."
20217 (if (<= (length s) maxlength)
20219 (let* ((n (max (- maxlength 4) 1))
20220 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20221 (if (string-match re s)
20222 (concat (match-string 1 s) "...")
20223 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20225 (defun org-get-indentation (&optional line)
20226 "Get the indentation of the current line, interpreting tabs.
20227 When LINE is given, assume it represents a line and compute its indentation."
20228 (if line
20229 (if (string-match "^ *" (org-remove-tabs line))
20230 (match-end 0))
20231 (save-excursion
20232 (beginning-of-line 1)
20233 (skip-chars-forward " \t")
20234 (current-column))))
20236 (defun org-get-string-indentation (s)
20237 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20238 (let ((n -1) (i 0) (w tab-width) c)
20239 (catch 'exit
20240 (while (< (setq n (1+ n)) (length s))
20241 (setq c (aref s n))
20242 (cond ((= c ?\ ) (setq i (1+ i)))
20243 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20244 (t (throw 'exit t)))))
20247 (defun org-remove-tabs (s &optional width)
20248 "Replace tabulators in S with spaces.
20249 Assumes that s is a single line, starting in column 0."
20250 (setq width (or width tab-width))
20251 (while (string-match "\t" s)
20252 (setq s (replace-match
20253 (make-string
20254 (- (* width (/ (+ (match-beginning 0) width) width))
20255 (match-beginning 0)) ?\ )
20256 t t s)))
20259 (defun org-fix-indentation (line ind)
20260 "Fix indentation in LINE.
20261 IND is a cons cell with target and minimum indentation.
20262 If the current indentation in LINE is smaller than the minimum,
20263 leave it alone. If it is larger than ind, set it to the target."
20264 (let* ((l (org-remove-tabs line))
20265 (i (org-get-indentation l))
20266 (i1 (car ind)) (i2 (cdr ind)))
20267 (if (>= i i2) (setq l (substring line i2)))
20268 (if (> i1 0)
20269 (concat (make-string i1 ?\ ) l)
20270 l)))
20272 (defun org-remove-indentation (code &optional n)
20273 "Remove the maximum common indentation from the lines in CODE.
20274 N may optionally be the number of spaces to remove."
20275 (with-temp-buffer
20276 (insert code)
20277 (org-do-remove-indentation n)
20278 (buffer-string)))
20280 (defun org-do-remove-indentation (&optional n)
20281 "Remove the maximum common indentation from the buffer."
20282 (untabify (point-min) (point-max))
20283 (let ((min 10000) re)
20284 (if n
20285 (setq min n)
20286 (goto-char (point-min))
20287 (while (re-search-forward "^ *[^ \n]" nil t)
20288 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20289 (unless (or (= min 0) (= min 10000))
20290 (setq re (format "^ \\{%d\\}" min))
20291 (goto-char (point-min))
20292 (while (re-search-forward re nil t)
20293 (replace-match "")
20294 (end-of-line 1))
20295 min)))
20297 (defun org-fill-template (template alist)
20298 "Find each %key of ALIST in TEMPLATE and replace it."
20299 (let ((case-fold-search nil)
20300 entry key value)
20301 (setq alist (sort (copy-sequence alist)
20302 (lambda (a b) (< (length (car a)) (length (car b))))))
20303 (while (setq entry (pop alist))
20304 (setq template
20305 (replace-regexp-in-string
20306 (concat "%" (regexp-quote (car entry)))
20307 (or (cdr entry) "") template t t)))
20308 template))
20310 (defun org-base-buffer (buffer)
20311 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20312 (if (not buffer)
20313 buffer
20314 (or (buffer-base-buffer buffer)
20315 buffer)))
20317 (defun org-trim (s)
20318 "Remove whitespace at beginning and end of string."
20319 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20320 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20323 (defun org-wrap (string &optional width lines)
20324 "Wrap string to either a number of lines, or a width in characters.
20325 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20326 that costs. If there is a word longer than WIDTH, the text is actually
20327 wrapped to the length of that word.
20328 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20329 many lines, whatever width that takes.
20330 The return value is a list of lines, without newlines at the end."
20331 (let* ((words (org-split-string string "[ \t\n]+"))
20332 (maxword (apply 'max (mapcar 'org-string-width words)))
20333 w ll)
20334 (cond (width
20335 (org-do-wrap words (max maxword width)))
20336 (lines
20337 (setq w maxword)
20338 (setq ll (org-do-wrap words maxword))
20339 (if (<= (length ll) lines)
20341 (setq ll words)
20342 (while (> (length ll) lines)
20343 (setq w (1+ w))
20344 (setq ll (org-do-wrap words w)))
20345 ll))
20346 (t (error "Cannot wrap this")))))
20348 (defun org-do-wrap (words width)
20349 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20350 (let (lines line)
20351 (while words
20352 (setq line (pop words))
20353 (while (and words (< (+ (length line) (length (car words))) width))
20354 (setq line (concat line " " (pop words))))
20355 (setq lines (push line lines)))
20356 (nreverse lines)))
20358 (defun org-split-string (string &optional separators)
20359 "Splits STRING into substrings at SEPARATORS.
20360 No empty strings are returned if there are matches at the beginning
20361 and end of string."
20362 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20363 (start 0)
20364 notfirst
20365 (list nil))
20366 (while (and (string-match rexp string
20367 (if (and notfirst
20368 (= start (match-beginning 0))
20369 (< start (length string)))
20370 (1+ start) start))
20371 (< (match-beginning 0) (length string)))
20372 (setq notfirst t)
20373 (or (eq (match-beginning 0) 0)
20374 (and (eq (match-beginning 0) (match-end 0))
20375 (eq (match-beginning 0) start))
20376 (setq list
20377 (cons (substring string start (match-beginning 0))
20378 list)))
20379 (setq start (match-end 0)))
20380 (or (eq start (length string))
20381 (setq list
20382 (cons (substring string start)
20383 list)))
20384 (nreverse list)))
20386 (defun org-quote-vert (s)
20387 "Replace \"|\" with \"\\vert\"."
20388 (while (string-match "|" s)
20389 (setq s (replace-match "\\vert" t t s)))
20392 (defun org-uuidgen-p (s)
20393 "Is S an ID created by UUIDGEN?"
20394 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20396 (defun org-in-src-block-p nil
20397 "Whether point is in a code source block."
20398 (let (ov)
20399 (when (setq ov (overlays-at (point)))
20400 (memq 'org-block-background
20401 (overlay-properties
20402 (car ov))))))
20404 (defun org-context ()
20405 "Return a list of contexts of the current cursor position.
20406 If several contexts apply, all are returned.
20407 Each context entry is a list with a symbol naming the context, and
20408 two positions indicating start and end of the context. Possible
20409 contexts are:
20411 :headline anywhere in a headline
20412 :headline-stars on the leading stars in a headline
20413 :todo-keyword on a TODO keyword (including DONE) in a headline
20414 :tags on the TAGS in a headline
20415 :priority on the priority cookie in a headline
20416 :item on the first line of a plain list item
20417 :item-bullet on the bullet/number of a plain list item
20418 :checkbox on the checkbox in a plain list item
20419 :table in an org-mode table
20420 :table-special on a special filed in a table
20421 :table-table in a table.el table
20422 :clocktable in a clocktable
20423 :src-block in a source block
20424 :link on a hyperlink
20425 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20426 :target on a <<target>>
20427 :radio-target on a <<<radio-target>>>
20428 :latex-fragment on a LaTeX fragment
20429 :latex-preview on a LaTeX fragment with overlaid preview image
20431 This function expects the position to be visible because it uses font-lock
20432 faces as a help to recognize the following contexts: :table-special, :link,
20433 and :keyword."
20434 (let* ((f (get-text-property (point) 'face))
20435 (faces (if (listp f) f (list f)))
20436 (case-fold-search t)
20437 (p (point)) clist o)
20438 ;; First the large context
20439 (cond
20440 ((org-at-heading-p t)
20441 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20442 (when (progn
20443 (beginning-of-line 1)
20444 (looking-at org-todo-line-tags-regexp))
20445 (push (org-point-in-group p 1 :headline-stars) clist)
20446 (push (org-point-in-group p 2 :todo-keyword) clist)
20447 (push (org-point-in-group p 4 :tags) clist))
20448 (goto-char p)
20449 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20450 (if (looking-at "\\[#[A-Z0-9]\\]")
20451 (push (org-point-in-group p 0 :priority) clist)))
20453 ((org-at-item-p)
20454 (push (org-point-in-group p 2 :item-bullet) clist)
20455 (push (list :item (point-at-bol)
20456 (save-excursion (org-end-of-item) (point)))
20457 clist)
20458 (and (org-at-item-checkbox-p)
20459 (push (org-point-in-group p 0 :checkbox) clist)))
20461 ((org-at-table-p)
20462 (push (list :table (org-table-begin) (org-table-end)) clist)
20463 (if (memq 'org-formula faces)
20464 (push (list :table-special
20465 (previous-single-property-change p 'face)
20466 (next-single-property-change p 'face)) clist)))
20467 ((org-at-table-p 'any)
20468 (push (list :table-table) clist)))
20469 (goto-char p)
20471 (let ((case-fold-search t))
20472 ;; New the "medium" contexts: clocktables, source blocks
20473 (cond ((org-in-clocktable-p)
20474 (push (list :clocktable
20475 (and (or (looking-at "#\\+BEGIN: clocktable")
20476 (search-backward "#+BEGIN: clocktable" nil t))
20477 (match-beginning 0))
20478 (and (re-search-forward "#\\+END:?" nil t)
20479 (match-end 0))) clist))
20480 ((org-in-src-block-p)
20481 (push (list :src-block
20482 (and (or (looking-at "#\\+BEGIN_SRC")
20483 (search-backward "#+BEGIN_SRC" nil t))
20484 (match-beginning 0))
20485 (and (search-forward "#+END_SRC" nil t)
20486 (match-beginning 0))) clist))))
20487 (goto-char p)
20489 ;; Now the small context
20490 (cond
20491 ((org-at-timestamp-p)
20492 (push (org-point-in-group p 0 :timestamp) clist))
20493 ((memq 'org-link faces)
20494 (push (list :link
20495 (previous-single-property-change p 'face)
20496 (next-single-property-change p 'face)) clist))
20497 ((memq 'org-special-keyword faces)
20498 (push (list :keyword
20499 (previous-single-property-change p 'face)
20500 (next-single-property-change p 'face)) clist))
20501 ((org-at-target-p)
20502 (push (org-point-in-group p 0 :target) clist)
20503 (goto-char (1- (match-beginning 0)))
20504 (if (looking-at org-radio-target-regexp)
20505 (push (org-point-in-group p 0 :radio-target) clist))
20506 (goto-char p))
20507 ((setq o (car (delq nil
20508 (mapcar
20509 (lambda (x)
20510 (if (memq x org-latex-fragment-image-overlays) x))
20511 (overlays-at (point))))))
20512 (push (list :latex-fragment
20513 (overlay-start o) (overlay-end o)) clist)
20514 (push (list :latex-preview
20515 (overlay-start o) (overlay-end o)) clist))
20516 ((org-inside-LaTeX-fragment-p)
20517 ;; FIXME: positions wrong.
20518 (push (list :latex-fragment (point) (point)) clist)))
20520 (setq clist (nreverse (delq nil clist)))
20521 clist))
20523 ;; FIXME: Compare with at-regexp-p Do we need both?
20524 (defun org-in-regexp (re &optional nlines visually)
20525 "Check if point is inside a match of regexp.
20526 Normally only the current line is checked, but you can include NLINES extra
20527 lines both before and after point into the search.
20528 If VISUALLY is set, require that the cursor is not after the match but
20529 really on, so that the block visually is on the match."
20530 (catch 'exit
20531 (let ((pos (point))
20532 (eol (point-at-eol (+ 1 (or nlines 0))))
20533 (inc (if visually 1 0)))
20534 (save-excursion
20535 (beginning-of-line (- 1 (or nlines 0)))
20536 (while (re-search-forward re eol t)
20537 (if (and (<= (match-beginning 0) pos)
20538 (>= (+ inc (match-end 0)) pos))
20539 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20541 (defun org-at-regexp-p (regexp)
20542 "Is point inside a match of REGEXP in the current line?"
20543 (catch 'exit
20544 (save-excursion
20545 (let ((pos (point)) (end (point-at-eol)))
20546 (beginning-of-line 1)
20547 (while (re-search-forward regexp end t)
20548 (if (and (<= (match-beginning 0) pos)
20549 (>= (match-end 0) pos))
20550 (throw 'exit t)))
20551 nil))))
20553 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20554 "Non-nil when point is between matches of START-RE and END-RE.
20556 Also return a non-nil value when point is on one of the matches.
20558 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20559 buffer positions. Default values are the positions of headlines
20560 surrounding the point.
20562 The functions returns a cons cell whose car (resp. cdr) is the
20563 position before START-RE (resp. after END-RE)."
20564 (save-match-data
20565 (let ((pos (point))
20566 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20567 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20568 beg end)
20569 (save-excursion
20570 ;; Point is on a block when on START-RE or if START-RE can be
20571 ;; found before it...
20572 (and (or (org-at-regexp-p start-re)
20573 (re-search-backward start-re limit-up t))
20574 (setq beg (match-beginning 0))
20575 ;; ... and END-RE after it...
20576 (goto-char (match-end 0))
20577 (re-search-forward end-re limit-down t)
20578 (> (setq end (match-end 0)) pos)
20579 ;; ... without another START-RE in-between.
20580 (goto-char (match-beginning 0))
20581 (not (re-search-backward start-re (1+ beg) t))
20582 ;; Return value.
20583 (cons beg end))))))
20585 (defun org-in-block-p (names)
20586 "Non-nil when point belongs to a block whose name belongs to NAMES.
20588 NAMES is a list of strings containing names of blocks.
20590 Return first block name matched, or nil. Beware that in case of
20591 nested blocks, the returned name may not belong to the closest
20592 block from point."
20593 (save-match-data
20594 (catch 'exit
20595 (let ((case-fold-search t)
20596 (lim-up (save-excursion (outline-previous-heading)))
20597 (lim-down (save-excursion (outline-next-heading))))
20598 (mapc (lambda (name)
20599 (let ((n (regexp-quote name)))
20600 (when (org-between-regexps-p
20601 (concat "^[ \t]*#\\+begin_" n)
20602 (concat "^[ \t]*#\\+end_" n)
20603 lim-up lim-down)
20604 (throw 'exit n))))
20605 names))
20606 nil)))
20608 (defun org-occur-in-agenda-files (regexp &optional nlines)
20609 "Call `multi-occur' with buffers for all agenda files."
20610 (interactive "sOrg-files matching: \np")
20611 (let* ((files (org-agenda-files))
20612 (tnames (mapcar 'file-truename files))
20613 (extra org-agenda-text-search-extra-files)
20615 (when (eq (car extra) 'agenda-archives)
20616 (setq extra (cdr extra))
20617 (setq files (org-add-archive-files files)))
20618 (while (setq f (pop extra))
20619 (unless (member (file-truename f) tnames)
20620 (add-to-list 'files f 'append)
20621 (add-to-list 'tnames (file-truename f) 'append)))
20622 (multi-occur
20623 (mapcar (lambda (x)
20624 (with-current-buffer
20625 (or (get-file-buffer x) (find-file-noselect x))
20626 (widen)
20627 (current-buffer)))
20628 files)
20629 regexp)))
20631 (if (boundp 'occur-mode-find-occurrence-hook)
20632 ;; Emacs 23
20633 (add-hook 'occur-mode-find-occurrence-hook
20634 (lambda ()
20635 (when (derived-mode-p 'org-mode)
20636 (org-reveal))))
20637 ;; Emacs 22
20638 (defadvice occur-mode-goto-occurrence
20639 (after org-occur-reveal activate)
20640 (and (derived-mode-p 'org-mode) (org-reveal)))
20641 (defadvice occur-mode-goto-occurrence-other-window
20642 (after org-occur-reveal activate)
20643 (and (derived-mode-p 'org-mode) (org-reveal)))
20644 (defadvice occur-mode-display-occurrence
20645 (after org-occur-reveal activate)
20646 (when (derived-mode-p 'org-mode)
20647 (let ((pos (occur-mode-find-occurrence)))
20648 (with-current-buffer (marker-buffer pos)
20649 (save-excursion
20650 (goto-char pos)
20651 (org-reveal)))))))
20653 (defun org-occur-link-in-agenda-files ()
20654 "Create a link and search for it in the agendas.
20655 The link is not stored in `org-stored-links', it is just created
20656 for the search purpose."
20657 (interactive)
20658 (let ((link (condition-case nil
20659 (org-store-link nil)
20660 (error "Unable to create a link to here"))))
20661 (org-occur-in-agenda-files (regexp-quote link))))
20663 (defun org-uniquify (list)
20664 "Remove duplicate elements from LIST."
20665 (let (res)
20666 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20667 res))
20669 (defun org-delete-all (elts list)
20670 "Remove all elements in ELTS from LIST."
20671 (while elts
20672 (setq list (delete (pop elts) list)))
20673 list)
20675 (defun org-count (cl-item cl-seq)
20676 "Count the number of occurrences of ITEM in SEQ.
20677 Taken from `count' in cl-seq.el with all keyword arguments removed."
20678 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20679 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20680 (while (< cl-start cl-end)
20681 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20682 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20683 (setq cl-start (1+ cl-start)))
20684 cl-count))
20686 (defun org-remove-if (predicate seq)
20687 "Remove everything from SEQ that fulfills PREDICATE."
20688 (let (res e)
20689 (while seq
20690 (setq e (pop seq))
20691 (if (not (funcall predicate e)) (push e res)))
20692 (nreverse res)))
20694 (defun org-remove-if-not (predicate seq)
20695 "Remove everything from SEQ that does not fulfill PREDICATE."
20696 (let (res e)
20697 (while seq
20698 (setq e (pop seq))
20699 (if (funcall predicate e) (push e res)))
20700 (nreverse res)))
20702 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20703 "Reduce two-argument FUNCTION across SEQ.
20704 Taken from `reduce' in cl-seq.el with all keyword arguments but
20705 \":initial-value\" removed."
20706 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20707 (cadr (memq :initial-value cl-keys)))
20708 (cl-seq (pop cl-seq))
20709 (t (funcall cl-func)))))
20710 (while cl-seq
20711 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20712 cl-accum))
20714 (defun org-back-over-empty-lines ()
20715 "Move backwards over whitespace, to the beginning of the first empty line.
20716 Returns the number of empty lines passed."
20717 (let ((pos (point)))
20718 (if (cdr (assoc 'heading org-blank-before-new-entry))
20719 (skip-chars-backward " \t\n\r")
20720 (unless (eobp)
20721 (forward-line -1)))
20722 (beginning-of-line 2)
20723 (goto-char (min (point) pos))
20724 (count-lines (point) pos)))
20726 (defun org-skip-whitespace ()
20727 (skip-chars-forward " \t\n\r"))
20729 (defun org-point-in-group (point group &optional context)
20730 "Check if POINT is in match-group GROUP.
20731 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20732 match. If the match group does not exist or point is not inside it,
20733 return nil."
20734 (and (match-beginning group)
20735 (>= point (match-beginning group))
20736 (<= point (match-end group))
20737 (if context
20738 (list context (match-beginning group) (match-end group))
20739 t)))
20741 (defun org-switch-to-buffer-other-window (&rest args)
20742 "Switch to buffer in a second window on the current frame.
20743 In particular, do not allow pop-up frames.
20744 Returns the newly created buffer."
20745 (let (pop-up-frames special-display-buffer-names special-display-regexps
20746 special-display-function)
20747 (apply 'switch-to-buffer-other-window args)))
20749 (defun org-combine-plists (&rest plists)
20750 "Create a single property list from all plists in PLISTS.
20751 The process starts by copying the first list, and then setting properties
20752 from the other lists. Settings in the last list are the most significant
20753 ones and overrule settings in the other lists."
20754 (let ((rtn (copy-sequence (pop plists)))
20755 p v ls)
20756 (while plists
20757 (setq ls (pop plists))
20758 (while ls
20759 (setq p (pop ls) v (pop ls))
20760 (setq rtn (plist-put rtn p v))))
20761 rtn))
20763 (defun org-replace-escapes (string table)
20764 "Replace %-escapes in STRING with values in TABLE.
20765 TABLE is an association list with keys like \"%a\" and string values.
20766 The sequences in STRING may contain normal field width and padding information,
20767 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20768 so values can contain further %-escapes if they are define later in TABLE."
20769 (let ((tbl (copy-alist table))
20770 (case-fold-search nil)
20771 (pchg 0)
20772 e re rpl)
20773 (while (setq e (pop tbl))
20774 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20775 (when (and (cdr e) (string-match re (cdr e)))
20776 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20777 (safe "SREF"))
20778 (add-text-properties 0 3 (list 'sref sref) safe)
20779 (setcdr e (replace-match safe t t (cdr e)))))
20780 (while (string-match re string)
20781 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20782 (cdr e)))
20783 (setq string (replace-match rpl t t string))))
20784 (while (setq pchg (next-property-change pchg string))
20785 (let ((sref (get-text-property pchg 'sref string)))
20786 (when (and sref (string-match "SREF" string pchg))
20787 (setq string (replace-match sref t t string)))))
20788 string))
20790 (defun org-sublist (list start end)
20791 "Return a section of LIST, from START to END.
20792 Counting starts at 1."
20793 (let (rtn (c start))
20794 (setq list (nthcdr (1- start) list))
20795 (while (and list (<= c end))
20796 (push (pop list) rtn)
20797 (setq c (1+ c)))
20798 (nreverse rtn)))
20800 (defun org-find-base-buffer-visiting (file)
20801 "Like `find-buffer-visiting' but always return the base buffer and
20802 not an indirect buffer."
20803 (let ((buf (or (get-file-buffer file)
20804 (find-buffer-visiting file))))
20805 (if buf
20806 (or (buffer-base-buffer buf) buf)
20807 nil)))
20809 (defun org-image-file-name-regexp (&optional extensions)
20810 "Return regexp matching the file names of images.
20811 If EXTENSIONS is given, only match these."
20812 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20813 (image-file-name-regexp)
20814 (let ((image-file-name-extensions
20815 (or extensions
20816 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20817 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20818 (concat "\\."
20819 (regexp-opt (nconc (mapcar 'upcase
20820 image-file-name-extensions)
20821 image-file-name-extensions)
20823 "\\'"))))
20825 (defun org-file-image-p (file &optional extensions)
20826 "Return non-nil if FILE is an image."
20827 (save-match-data
20828 (string-match (org-image-file-name-regexp extensions) file)))
20830 (defun org-get-cursor-date ()
20831 "Return the date at cursor in as a time.
20832 This works in the calendar and in the agenda, anywhere else it just
20833 returns the current time."
20834 (let (date day defd)
20835 (cond
20836 ((eq major-mode 'calendar-mode)
20837 (setq date (calendar-cursor-to-date)
20838 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20839 ((eq major-mode 'org-agenda-mode)
20840 (setq day (get-text-property (point) 'day))
20841 (if day
20842 (setq date (calendar-gregorian-from-absolute day)
20843 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20844 (nth 2 date))))))
20845 (or defd (current-time))))
20847 (defun org-mark-subtree (&optional up)
20848 "Mark the current subtree.
20849 This puts point at the start of the current subtree, and mark at
20850 the end. If a numeric prefix UP is given, move up into the
20851 hierarchy of headlines by UP levels before marking the subtree."
20852 (interactive "P")
20853 (org-with-limited-levels
20854 (cond ((org-at-heading-p) (beginning-of-line))
20855 ((org-before-first-heading-p) (error "Not in a subtree"))
20856 (t (outline-previous-visible-heading 1))))
20857 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20858 (if (org-called-interactively-p 'any)
20859 (call-interactively 'org-mark-element)
20860 (org-mark-element)))
20863 ;;; Macros
20865 ;; Macros are expanded with `org-macro-replace-all', which relies
20866 ;; internally on `org-macro-expand'.
20868 ;; Default templates for expansion are stored in the buffer-local
20869 ;; variable `org-macro-templates'. This variable is updated by
20870 ;; `org-macro-initialize-templates'.
20872 ;; Along with macros defined through #+MACRO: keyword, default
20873 ;; templates include the following hard-coded macros:
20874 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
20875 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
20877 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
20878 ;; {{{title}}} will also be provided.
20881 (defvar org-macro-templates nil
20882 "Alist containing all macro templates in current buffer.
20883 Associations are in the shape of (NAME . TEMPLATE) where NAME
20884 stands for macro's name and template for its replacement value,
20885 both as strings. This is an internal variable. Do not set it
20886 directly, use instead:
20888 #+MACRO: name template")
20889 (make-variable-buffer-local 'org-macro-templates)
20891 (defun org-macro-expand (macro templates)
20892 "Return expanded MACRO, as a string.
20893 MACRO is an object, obtained, for example, with
20894 `org-element-context'. TEMPLATES is an alist of templates used
20895 for expansion. See `org-macro-templates' for a buffer-local
20896 default value. Return nil if no template was found."
20897 (let ((template
20898 ;; Macro names are case-insensitive.
20899 (cdr (assoc-string (org-element-property :key macro) templates t))))
20900 (when template
20901 (let ((value (replace-regexp-in-string
20902 "\\$[0-9]+"
20903 (lambda (arg)
20904 (or (nth (1- (string-to-number (substring arg 1)))
20905 (org-element-property :args macro))
20906 ;; No argument provided: remove
20907 ;; place-holder.
20908 ""))
20909 template)))
20910 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20911 (when (string-match "\\`(eval\\>" value)
20912 (setq value (eval (read value))))
20913 ;; Return string.
20914 (format "%s" (or value ""))))))
20916 (defun org-macro-replace-all (templates)
20917 "Replace all macros in current buffer by their expansion.
20918 TEMPLATES is an alist of templates used for expansion. See
20919 `org-macro-templates' for a buffer-local default value."
20920 (save-excursion
20921 (goto-char (point-min))
20922 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20923 (let ((object (org-element-context)))
20924 (when (eq (org-element-type object) 'macro)
20925 (let ((value (org-macro-expand object templates)))
20926 (when value
20927 (delete-region
20928 (org-element-property :begin object)
20929 ;; Preserve white spaces after the macro.
20930 (progn (goto-char (org-element-property :end object))
20931 (skip-chars-backward " \t")
20932 (point)))
20933 ;; Leave point before replacement in case of recursive
20934 ;; expansions.
20935 (save-excursion (insert value)))))))))
20937 (defun org-macro-initialize-templates ()
20938 "Collect macro templates defined in current buffer.
20939 Templates are stored in buffer-local variable
20940 `org-macro-templates'. In addition to buffer-defined macros, the
20941 function installs the following ones: \"property\", \"date\",
20942 \"time\". and, if appropriate, \"input-file\" and
20943 \"modification-time\"."
20944 (let ((case-fold-search t)
20945 (set-template
20946 (lambda (cell)
20947 ;; Add CELL to `org-macro-templates' if there's no
20948 ;; association matching its name already. Otherwise,
20949 ;; replace old association with the new one in that
20950 ;; variable.
20951 (let ((old-template (assoc (car cell) org-macro-templates)))
20952 (if old-template (setcdr old-template (cdr cell))
20953 (push cell org-macro-templates))))))
20954 ;; Install buffer-local macros.
20955 (org-with-wide-buffer
20956 (goto-char (point-min))
20957 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
20958 (let ((element (org-element-at-point)))
20959 (when (eq (org-element-type element) 'keyword)
20960 (let ((value (org-element-property :value element)))
20961 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
20962 (funcall set-template
20963 (cons (match-string 1 value)
20964 (or (match-string 2 value) "")))))))))
20965 ;; Install hard-coded macros.
20966 (mapc (lambda (cell) (funcall set-template cell))
20967 (list
20968 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
20969 (cons "time" "(eval (format-time-string \"$1\"))")))
20970 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
20971 (when (and visited-file (file-exists-p visited-file))
20972 (mapc (lambda (cell) (funcall set-template cell))
20973 (list
20974 (cons "input-file" (file-name-nondirectory visited-file))
20975 (cons "modification-time"
20976 (format "(eval (format-time-string \"$1\" '%s))"
20977 (prin1-to-string
20978 (nth 5 (file-attributes visited-file)))))))))))
20981 ;;; Indentation
20983 (defun org-indent-line ()
20984 "Indent line depending on context."
20985 (interactive)
20986 (let* ((pos (point))
20987 (itemp (org-at-item-p))
20988 (case-fold-search t)
20989 (org-drawer-regexp (or org-drawer-regexp "\000"))
20990 (inline-task-p (and (featurep 'org-inlinetask)
20991 (org-inlinetask-in-task-p)))
20992 (inline-re (and inline-task-p
20993 (org-inlinetask-outline-regexp)))
20994 column)
20995 (if (and orgstruct-is-++ (eq pos (point)))
20996 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20997 (indent-according-to-mode))
20998 (beginning-of-line 1)
20999 (cond
21000 ;; Headings
21001 ((looking-at org-outline-regexp) (setq column 0))
21002 ;; Included files
21003 ((looking-at "#\\+include:") (setq column 0))
21004 ;; Footnote definition
21005 ((looking-at org-footnote-definition-re) (setq column 0))
21006 ;; Literal examples
21007 ((looking-at "[ \t]*:\\( \\|$\\)")
21008 (setq column (org-get-indentation))) ; do nothing
21009 ;; Lists
21010 ((ignore-errors (goto-char (org-in-item-p)))
21011 (setq column (if itemp
21012 (org-get-indentation)
21013 (org-list-item-body-column (point))))
21014 (goto-char pos))
21015 ;; Drawers
21016 ((and (looking-at "[ \t]*:END:")
21017 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21018 (save-excursion
21019 (goto-char (1- (match-beginning 1)))
21020 (setq column (current-column))))
21021 ;; Special blocks
21022 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21023 (save-excursion
21024 (re-search-backward
21025 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21026 (setq column (org-get-indentation (match-string 0))))
21027 ((and (not (looking-at "[ \t]*#\\+begin_"))
21028 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21029 (save-excursion
21030 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21031 (setq column
21032 (cond ((equal (downcase (match-string 1)) "src")
21033 ;; src blocks: let `org-edit-src-exit' handle them
21034 (org-get-indentation))
21035 ((equal (downcase (match-string 1)) "example")
21036 (max (org-get-indentation)
21037 (org-get-indentation (match-string 0))))
21039 (org-get-indentation (match-string 0))))))
21040 ;; This line has nothing special, look at the previous relevant
21041 ;; line to compute indentation
21043 (beginning-of-line 0)
21044 (while (and (not (bobp))
21045 (not (looking-at org-drawer-regexp))
21046 ;; When point started in an inline task, do not move
21047 ;; above task starting line.
21048 (not (and inline-task-p (looking-at inline-re)))
21049 ;; Skip drawers, blocks, empty lines, verbatim,
21050 ;; comments, tables, footnotes definitions, lists,
21051 ;; inline tasks.
21052 (or (and (looking-at "[ \t]*:END:")
21053 (re-search-backward org-drawer-regexp nil t))
21054 (and (looking-at "[ \t]*#\\+end_")
21055 (re-search-backward "[ \t]*#\\+begin_"nil t))
21056 (looking-at "[ \t]*[\n:#|]")
21057 (looking-at org-footnote-definition-re)
21058 (and (ignore-errors (goto-char (org-in-item-p)))
21059 (goto-char
21060 (org-list-get-top-point (org-list-struct))))
21061 (and (not inline-task-p)
21062 (featurep 'org-inlinetask)
21063 (org-inlinetask-in-task-p)
21064 (or (org-inlinetask-goto-beginning) t))))
21065 (beginning-of-line 0))
21066 (cond
21067 ;; There was an heading above.
21068 ((looking-at "\\*+[ \t]+")
21069 (if (not org-adapt-indentation)
21070 (setq column 0)
21071 (goto-char (match-end 0))
21072 (setq column (current-column))))
21073 ;; A drawer had started and is unfinished
21074 ((looking-at org-drawer-regexp)
21075 (goto-char (1- (match-beginning 1)))
21076 (setq column (current-column)))
21077 ;; Else, nothing noticeable found: get indentation and go on.
21078 (t (setq column (org-get-indentation))))))
21079 ;; Now apply indentation and move cursor accordingly
21080 (goto-char pos)
21081 (if (<= (current-column) (current-indentation))
21082 (org-indent-line-to column)
21083 (save-excursion (org-indent-line-to column)))
21084 ;; Special polishing for properties, see `org-property-format'
21085 (setq column (current-column))
21086 (beginning-of-line 1)
21087 (if (looking-at
21088 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21089 (replace-match (concat (match-string 1)
21090 (format org-property-format
21091 (match-string 2) (match-string 3)))
21092 t t))
21093 (org-move-to-column column))))
21095 (defun org-indent-drawer ()
21096 "Indent the drawer at point."
21097 (interactive)
21098 (let ((p (point))
21099 (e (and (save-excursion (re-search-forward ":END:" nil t))
21100 (match-end 0)))
21101 (folded
21102 (save-excursion
21103 (end-of-line)
21104 (when (overlays-at (point))
21105 (member 'invisible (overlay-properties
21106 (car (overlays-at (point)))))))))
21107 (when folded (org-cycle))
21108 (indent-for-tab-command)
21109 (while (and (move-beginning-of-line 2) (< (point) e))
21110 (indent-for-tab-command))
21111 (goto-char p)
21112 (when folded (org-cycle)))
21113 (message "Drawer at point indented"))
21115 (defun org-indent-block ()
21116 "Indent the block at point."
21117 (interactive)
21118 (let ((p (point))
21119 (case-fold-search t)
21120 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21121 (match-end 0)))
21122 (folded
21123 (save-excursion
21124 (end-of-line)
21125 (when (overlays-at (point))
21126 (member 'invisible (overlay-properties
21127 (car (overlays-at (point)))))))))
21128 (when folded (org-cycle))
21129 (indent-for-tab-command)
21130 (while (and (move-beginning-of-line 2) (< (point) e))
21131 (indent-for-tab-command))
21132 (goto-char p)
21133 (when folded (org-cycle)))
21134 (message "Block at point indented"))
21136 (defun org-indent-region (start end)
21137 "Indent region."
21138 (interactive "r")
21139 (save-excursion
21140 (let ((line-end (org-current-line end)))
21141 (goto-char start)
21142 (while (< (org-current-line) line-end)
21143 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21144 (t (call-interactively 'org-indent-line)))
21145 (move-beginning-of-line 2)))))
21148 ;;; Filling
21150 ;; We use our own fill-paragraph and auto-fill functions.
21152 ;; `org-fill-paragraph' relies on adaptive filling and context
21153 ;; checking. Appropriate `fill-prefix' is computed with
21154 ;; `org-adaptive-fill-function'.
21156 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21157 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21158 ;; `org-adaptive-fill-function' value. Internally,
21159 ;; `org-comment-line-break-function' breaks the line.
21161 ;; `org-setup-filling' installs filling and auto-filling related
21162 ;; variables during `org-mode' initialization.
21164 (defun org-setup-filling ()
21165 (interactive)
21166 ;; Prevent auto-fill from inserting unwanted new items.
21167 (when (boundp 'fill-nobreak-predicate)
21168 (org-set-local
21169 'fill-nobreak-predicate
21170 (org-uniquify
21171 (append fill-nobreak-predicate
21172 '(org-fill-paragraph-separate-nobreak-p
21173 org-fill-line-break-nobreak-p)))))
21174 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21175 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21176 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21177 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21179 (defvar org-element-paragraph-separate) ; org-element.el
21180 (defun org-fill-paragraph-separate-nobreak-p ()
21181 "Non-nil when a line break at point would insert a new item."
21182 (looking-at (substring org-element-paragraph-separate 1)))
21184 (defun org-fill-line-break-nobreak-p ()
21185 "Non-nil when a line break at point would create an Org line break."
21186 (save-excursion
21187 (skip-chars-backward "[ \t]")
21188 (skip-chars-backward "\\\\")
21189 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21191 (declare-function message-in-body-p "message" ())
21192 (defvar org-element--affiliated-re) ; From org-element.el
21193 (defun org-adaptive-fill-function ()
21194 "Compute a fill prefix for the current line.
21195 Return fill prefix, as a string, or nil if current line isn't
21196 meant to be filled."
21197 (org-with-wide-buffer
21198 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21199 ;; FIXME: This is really the job of orgstruct++-mode
21200 (let* ((p (line-beginning-position))
21201 (element (save-excursion (beginning-of-line)
21202 (org-element-at-point)))
21203 (type (org-element-type element))
21204 (post-affiliated
21205 (save-excursion
21206 (goto-char (org-element-property :begin element))
21207 (while (looking-at org-element--affiliated-re) (forward-line))
21208 (point))))
21209 (unless (< p post-affiliated)
21210 (case type
21211 (comment (looking-at "[ \t]*# ?") (match-string 0))
21212 (footnote-definition "")
21213 ((item plain-list)
21214 (make-string (org-list-item-body-column post-affiliated) ? ))
21215 (paragraph
21216 ;; Fill prefix is usually the same as the current line,
21217 ;; except if the paragraph is at the beginning of an item.
21218 (let ((parent (org-element-property :parent element)))
21219 (cond ((eq (org-element-type parent) 'item)
21220 (make-string (org-list-item-body-column
21221 (org-element-property :begin parent))
21222 ? ))
21223 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21224 (match-string 0))
21225 (t ""))))
21226 (comment-block
21227 ;; Only fill contents if P is within block boundaries.
21228 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21229 (forward-line)
21230 (point)))
21231 (cend (save-excursion
21232 (goto-char (org-element-property :end element))
21233 (skip-chars-backward " \r\t\n")
21234 (line-beginning-position))))
21235 (when (and (>= p cbeg) (< p cend))
21236 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21237 (match-string 0)
21238 ""))))))))))
21240 (declare-function message-goto-body "message" ())
21241 (defvar message-cite-prefix-regexp) ; From message.el
21242 (defvar org-element-all-objects) ; From org-element.el
21243 (defun org-fill-paragraph (&optional justify)
21244 "Fill element at point, when applicable.
21246 This function only applies to comment blocks, comments, example
21247 blocks and paragraphs. Also, as a special case, re-align table
21248 when point is at one.
21250 If JUSTIFY is non-nil (interactively, with prefix argument),
21251 justify as well. If `sentence-end-double-space' is non-nil, then
21252 period followed by one space does not end a sentence, so don't
21253 break a line there. The variable `fill-column' controls the
21254 width for filling.
21256 For convenience, when point is at a plain list, an item or
21257 a footnote definition, try to fill the first paragraph within."
21258 ;; Falls back on message-fill-paragraph when necessary
21259 (interactive)
21260 (if (and (derived-mode-p 'message-mode)
21261 (or (not (message-in-body-p))
21262 (save-excursion (move-beginning-of-line 1)
21263 (looking-at message-cite-prefix-regexp))))
21264 (let ((fill-paragraph-function
21265 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21266 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21267 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21268 (paragraph-separate
21269 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21270 (fill-paragraph nil))
21271 (save-excursion
21272 ;; Move to end of line in order to get the first paragraph
21273 ;; within a plain list or a footnote definition.
21274 (end-of-line)
21275 (let ((element (org-element-at-point)))
21276 ;; First check if point is in a blank line at the beginning of
21277 ;; the buffer. In that case, ignore filling.
21278 (if (< (point) (org-element-property :begin element)) t
21279 (case (org-element-type element)
21280 ;; Align Org tables, leave table.el tables as-is.
21281 (table-row (org-table-align) t)
21282 (table
21283 (when (eq (org-element-property :type element) 'org)
21284 (org-table-align))
21286 (paragraph
21287 ;; Paragraphs may contain `line-break' type objects.
21288 (let ((beg (max (point-min)
21289 (org-element-property :contents-begin element)))
21290 (end (min (point-max)
21291 (org-element-property :contents-end element))))
21292 ;; Do nothing if point is at an affiliated keyword.
21293 (if (< (point) beg) t
21294 (when (derived-mode-p 'message-mode)
21295 ;; In `message-mode', do not fill following
21296 ;; citation in current paragraph nor text before
21297 ;; message body.
21298 (let ((body-start (save-excursion (message-goto-body))))
21299 (when body-start (setq beg (max body-start beg))))
21300 (when (save-excursion
21301 (re-search-forward
21302 (concat "^" message-cite-prefix-regexp) end t))
21303 (setq end (match-beginning 0))))
21304 ;; Fill paragraph, taking line breaks into
21305 ;; consideration. For that, slice the paragraph
21306 ;; using line breaks as separators, and fill the
21307 ;; parts in reverse order to avoid messing with
21308 ;; markers.
21309 (save-excursion
21310 (goto-char end)
21311 (mapc
21312 (lambda (pos)
21313 (fill-region-as-paragraph pos (point) justify)
21314 (goto-char pos))
21315 ;; Find the list of ending positions for line
21316 ;; breaks in the current paragraph. Add paragraph
21317 ;; beginning to include first slice.
21318 (nreverse
21319 (cons
21321 (org-element-map
21322 (org-element--parse-objects
21323 beg end nil org-element-all-objects)
21324 'line-break
21325 (lambda (lb) (org-element-property :end lb)))))))
21326 t)))
21327 ;; Contents of `comment-block' type elements should be
21328 ;; filled as plain text, but only if point is within block
21329 ;; markers.
21330 (comment-block
21331 (let* ((case-fold-search t)
21332 (beg (save-excursion
21333 (goto-char (org-element-property :begin element))
21334 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21335 (forward-line)
21336 (point)))
21337 (end (save-excursion
21338 (goto-char (org-element-property :end element))
21339 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21340 (line-beginning-position))))
21341 (when (and (>= (point) beg) (< (point) end))
21342 (fill-region-as-paragraph
21343 (save-excursion
21344 (end-of-line)
21345 (re-search-backward "^[ \t]*$" beg 'move)
21346 (line-beginning-position))
21347 (save-excursion
21348 (beginning-of-line)
21349 (re-search-forward "^[ \t]*$" end 'move)
21350 (line-beginning-position))
21351 justify)))
21353 ;; Fill comments.
21354 (comment (fill-comment-paragraph justify))
21355 ;; Ignore every other element.
21356 (otherwise t)))))))
21358 (defun org-auto-fill-function ()
21359 "Auto-fill function."
21360 ;; Check if auto-filling is meaningful.
21361 (let ((fc (current-fill-column)))
21362 (when (and fc (> (current-column) fc))
21363 (let* ((fill-prefix (org-adaptive-fill-function))
21364 ;; Enforce empty fill prefix, if required. Otherwise, it
21365 ;; will be computed again.
21366 (adaptive-fill-mode (not (equal fill-prefix ""))))
21367 (when fill-prefix (do-auto-fill))))))
21369 (defun org-comment-line-break-function (&optional soft)
21370 "Break line at point and indent, continuing comment if within one.
21371 The inserted newline is marked hard if variable
21372 `use-hard-newlines' is true, unless optional argument SOFT is
21373 non-nil."
21374 (if soft (insert-and-inherit ?\n) (newline 1))
21375 (save-excursion (forward-char -1) (delete-horizontal-space))
21376 (delete-horizontal-space)
21377 (indent-to-left-margin)
21378 (insert-before-markers-and-inherit fill-prefix))
21381 ;;; Comments
21383 ;; Org comments syntax is quite complex. It requires the entire line
21384 ;; to be just a comment. Also, even with the right syntax at the
21385 ;; beginning of line, some some elements (i.e. verse-block or
21386 ;; example-block) don't accept comments. Usual Emacs comment commands
21387 ;; cannot cope with those requirements. Therefore, Org replaces them.
21389 ;; Org still relies on `comment-dwim', but cannot trust
21390 ;; `comment-only-p'. So, `comment-region-function' and
21391 ;; `uncomment-region-function' both point
21392 ;; to`org-comment-or-uncomment-region'. Eventually,
21393 ;; `org-insert-comment' takes care of insertion of comments at the
21394 ;; beginning of line.
21396 ;; `org-setup-comments-handling' install comments related variables
21397 ;; during `org-mode' initialization.
21399 (defun org-setup-comments-handling ()
21400 (interactive)
21401 (org-set-local 'comment-use-syntax nil)
21402 (org-set-local 'comment-start "# ")
21403 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21404 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21405 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21406 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21408 (defun org-insert-comment ()
21409 "Insert an empty comment above current line.
21410 If the line is empty, insert comment at its beginning."
21411 (beginning-of-line)
21412 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21413 (org-indent-line)
21414 (insert "# "))
21416 (defvar comment-empty-lines) ; From newcomment.el.
21417 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21418 "Comment or uncomment each non-blank line in the region.
21419 Uncomment each non-blank line between BEG and END if it only
21420 contains commented lines. Otherwise, comment them."
21421 (save-restriction
21422 ;; Restrict region
21423 (narrow-to-region (save-excursion (goto-char beg)
21424 (skip-chars-forward " \r\t\n" end)
21425 (line-beginning-position))
21426 (save-excursion (goto-char end)
21427 (skip-chars-backward " \r\t\n" beg)
21428 (line-end-position)))
21429 (let ((uncommentp
21430 ;; UNCOMMENTP is non-nil when every non blank line between
21431 ;; BEG and END is a comment.
21432 (save-excursion
21433 (goto-char (point-min))
21434 (while (and (not (eobp))
21435 (let ((element (org-element-at-point)))
21436 (and (eq (org-element-type element) 'comment)
21437 (goto-char (min (point-max)
21438 (org-element-property
21439 :end element)))))))
21440 (eobp))))
21441 (if uncommentp
21442 ;; Only blank lines and comments in region: uncomment it.
21443 (save-excursion
21444 (goto-char (point-min))
21445 (while (not (eobp))
21446 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21447 (replace-match "" nil nil nil 1))
21448 (forward-line)))
21449 ;; Comment each line in region.
21450 (let ((min-indent (point-max)))
21451 ;; First find the minimum indentation across all lines.
21452 (save-excursion
21453 (goto-char (point-min))
21454 (while (and (not (eobp)) (not (zerop min-indent)))
21455 (unless (looking-at "[ \t]*$")
21456 (setq min-indent (min min-indent (current-indentation))))
21457 (forward-line)))
21458 ;; Then loop over all lines.
21459 (save-excursion
21460 (goto-char (point-min))
21461 (while (not (eobp))
21462 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21463 (org-move-to-column min-indent t)
21464 (insert comment-start))
21465 (forward-line))))))))
21468 ;;; Other stuff.
21470 (defun org-toggle-fixed-width-section (arg)
21471 "Toggle the fixed-width export.
21472 If there is no active region, the QUOTE keyword at the current headline is
21473 inserted or removed. When present, it causes the text between this headline
21474 and the next to be exported as fixed-width text, and unmodified.
21475 If there is an active region, this command adds or removes a colon as the
21476 first character of this line. If the first character of a line is a colon,
21477 this line is also exported in fixed-width font."
21478 (interactive "P")
21479 (let* ((cc 0)
21480 (regionp (org-region-active-p))
21481 (beg (if regionp (region-beginning) (point)))
21482 (end (if regionp (region-end)))
21483 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21484 (case-fold-search nil)
21485 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21486 off)
21487 (if regionp
21488 (save-excursion
21489 (goto-char beg)
21490 (setq cc (current-column))
21491 (beginning-of-line 1)
21492 (setq off (looking-at re))
21493 (while (> nlines 0)
21494 (setq nlines (1- nlines))
21495 (beginning-of-line 1)
21496 (cond
21497 (arg
21498 (org-move-to-column cc t)
21499 (insert ": \n")
21500 (forward-line -1))
21501 ((and off (looking-at re))
21502 (replace-match "" t t nil 1))
21503 ((not off) (org-move-to-column cc t) (insert ": ")))
21504 (forward-line 1)))
21505 (save-excursion
21506 (org-back-to-heading)
21507 (cond
21508 ((looking-at (format org-heading-keyword-regexp-format
21509 org-quote-string))
21510 (goto-char (match-end 1))
21511 (looking-at (concat " +" org-quote-string))
21512 (replace-match "" t t)
21513 (when (eolp) (insert " ")))
21514 ((looking-at org-outline-regexp)
21515 (goto-char (match-end 0))
21516 (insert org-quote-string " ")))))))
21518 (defun org-reftex-citation ()
21519 "Use reftex-citation to insert a citation into the buffer.
21520 This looks for a line like
21522 #+BIBLIOGRAPHY: foo plain option:-d
21524 and derives from it that foo.bib is the bibliography file relevant
21525 for this document. It then installs the necessary environment for RefTeX
21526 to work in this buffer and calls `reftex-citation' to insert a citation
21527 into the buffer.
21529 Export of such citations to both LaTeX and HTML is handled by the contributed
21530 package org-exp-bibtex by Taru Karttunen."
21531 (interactive)
21532 (let ((reftex-docstruct-symbol 'rds)
21533 (reftex-cite-format "\\cite{%l}")
21534 rds bib)
21535 (save-excursion
21536 (save-restriction
21537 (widen)
21538 (let ((case-fold-search t)
21539 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21540 (if (not (save-excursion
21541 (or (re-search-forward re nil t)
21542 (re-search-backward re nil t))))
21543 (error "No bibliography defined in file")
21544 (setq bib (concat (match-string 1) ".bib")
21545 rds (list (list 'bib bib)))))))
21546 (call-interactively 'reftex-citation)))
21548 ;;;; Functions extending outline functionality
21550 (defun org-beginning-of-line (&optional arg)
21551 "Go to the beginning of the current line. If that is invisible, continue
21552 to a visible line beginning. This makes the function of C-a more intuitive.
21553 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21554 first attempt, and only move to after the tags when the cursor is already
21555 beyond the end of the headline."
21556 (interactive "P")
21557 (let ((pos (point))
21558 (special (if (consp org-special-ctrl-a/e)
21559 (car org-special-ctrl-a/e)
21560 org-special-ctrl-a/e))
21561 refpos)
21562 (if (org-bound-and-true-p line-move-visual)
21563 (beginning-of-visual-line 1)
21564 (beginning-of-line 1))
21565 (if (and arg (fboundp 'move-beginning-of-line))
21566 (call-interactively 'move-beginning-of-line)
21567 (if (bobp)
21569 (backward-char 1)
21570 (if (org-truely-invisible-p)
21571 (while (and (not (bobp)) (org-truely-invisible-p))
21572 (backward-char 1)
21573 (beginning-of-line 1))
21574 (forward-char 1))))
21575 (when special
21576 (cond
21577 ((and (looking-at org-complex-heading-regexp)
21578 (= (char-after (match-end 1)) ?\ ))
21579 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21580 (point-at-eol)))
21581 (goto-char
21582 (if (eq special t)
21583 (cond ((> pos refpos) refpos)
21584 ((= pos (point)) refpos)
21585 (t (point)))
21586 (cond ((> pos (point)) (point))
21587 ((not (eq last-command this-command)) (point))
21588 (t refpos)))))
21589 ((org-at-item-p)
21590 ;; Being at an item and not looking at an the item means point
21591 ;; was previously moved to beginning of a visual line, which
21592 ;; doesn't contain the item. Therefore, do nothing special,
21593 ;; just stay here.
21594 (when (looking-at org-list-full-item-re)
21595 ;; Set special position at first white space character after
21596 ;; bullet, and check-box, if any.
21597 (let ((after-bullet
21598 (let ((box (match-end 3)))
21599 (if (not box) (match-end 1)
21600 (let ((after (char-after box)))
21601 (if (and after (= after ? )) (1+ box) box))))))
21602 ;; Special case: Move point to special position when
21603 ;; currently after it or at beginning of line.
21604 (if (eq special t)
21605 (when (or (> pos after-bullet) (= (point) pos))
21606 (goto-char after-bullet))
21607 ;; Reversed case: Move point to special position when
21608 ;; point was already at beginning of line and command is
21609 ;; repeated.
21610 (when (and (= (point) pos) (eq last-command this-command))
21611 (goto-char after-bullet))))))))
21612 (org-no-warnings
21613 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21615 (defun org-end-of-line (&optional arg)
21616 "Go to the end of the line.
21617 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21618 tags on the first attempt, and only move to after the tags when
21619 the cursor is already beyond the end of the headline."
21620 (interactive "P")
21621 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21622 org-special-ctrl-a/e))
21623 (type (org-element-type
21624 (save-excursion (beginning-of-line) (org-element-at-point)))))
21625 (cond
21626 ((or (not special) arg)
21627 (call-interactively
21628 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line)))
21629 ((memq type '(headline inlinetask))
21630 (let ((pos (point)))
21631 (beginning-of-line 1)
21632 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21633 (if (eq special t)
21634 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21635 (goto-char (match-beginning 1))
21636 (goto-char (match-end 0)))
21637 (if (or (< pos (match-end 0))
21638 (not (eq this-command last-command)))
21639 (goto-char (match-end 0))
21640 (goto-char (match-beginning 1))))
21641 (call-interactively
21642 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line)))))
21643 ((memq type
21644 '(center-block comment-block drawer dynamic-block example-block
21645 export-block item plain-list property-drawer
21646 quote-block special-block src-block verse-block))
21647 ;; Never move past the ellipsis.
21648 (or (eolp) (move-end-of-line 1))
21649 (when (org-invisible-p2) (backward-char)))
21651 (call-interactively
21652 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line))))
21653 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21655 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21656 (define-key org-mode-map "\C-e" 'org-end-of-line)
21658 (defun org-backward-sentence (&optional arg)
21659 "Go to beginning of sentence, or beginning of table field.
21660 This will call `backward-sentence' or `org-table-beginning-of-field',
21661 depending on context."
21662 (interactive "P")
21663 (cond
21664 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21665 (t (call-interactively 'backward-sentence))))
21667 (defun org-forward-sentence (&optional arg)
21668 "Go to end of sentence, or end of table field.
21669 This will call `forward-sentence' or `org-table-end-of-field',
21670 depending on context."
21671 (interactive "P")
21672 (cond
21673 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21674 (t (call-interactively 'forward-sentence))))
21676 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21677 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21679 (defun org-kill-line (&optional arg)
21680 "Kill line, to tags or end of line."
21681 (interactive "P")
21682 (cond
21683 ((or (not org-special-ctrl-k)
21684 (bolp)
21685 (not (org-at-heading-p)))
21686 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21687 org-ctrl-k-protect-subtree)
21688 (if (or (eq org-ctrl-k-protect-subtree 'error)
21689 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21690 (error "C-k aborted - would kill hidden subtree")))
21691 (call-interactively
21692 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21693 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21694 (kill-region (point) (match-beginning 1))
21695 (org-set-tags nil t))
21696 (t (kill-region (point) (point-at-eol)))))
21698 (define-key org-mode-map "\C-k" 'org-kill-line)
21700 (defun org-yank (&optional arg)
21701 "Yank. If the kill is a subtree, treat it specially.
21702 This command will look at the current kill and check if is a single
21703 subtree, or a series of subtrees[1]. If it passes the test, and if the
21704 cursor is at the beginning of a line or after the stars of a currently
21705 empty headline, then the yank is handled specially. How exactly depends
21706 on the value of the following variables, both set by default.
21708 org-yank-folded-subtrees
21709 When set, the subtree(s) will be folded after insertion, but only
21710 if doing so would now swallow text after the yanked text.
21712 org-yank-adjusted-subtrees
21713 When set, the subtree will be promoted or demoted in order to
21714 fit into the local outline tree structure, which means that the level
21715 will be adjusted so that it becomes the smaller one of the two
21716 *visible* surrounding headings.
21718 Any prefix to this command will cause `yank' to be called directly with
21719 no special treatment. In particular, a simple \\[universal-argument] prefix \
21720 will just
21721 plainly yank the text as it is.
21723 \[1] The test checks if the first non-white line is a heading
21724 and if there are no other headings with fewer stars."
21725 (interactive "P")
21726 (org-yank-generic 'yank arg))
21728 (defun org-yank-generic (command arg)
21729 "Perform some yank-like command.
21731 This function implements the behavior described in the `org-yank'
21732 documentation. However, it has been generalized to work for any
21733 interactive command with similar behavior."
21735 ;; pretend to be command COMMAND
21736 (setq this-command command)
21738 (if arg
21739 (call-interactively command)
21741 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21742 (and (org-kill-is-subtree-p)
21743 (or (bolp)
21744 (and (looking-at "[ \t]*$")
21745 (string-match
21746 "\\`\\*+\\'"
21747 (buffer-substring (point-at-bol) (point)))))))
21748 swallowp)
21749 (cond
21750 ((and subtreep org-yank-folded-subtrees)
21751 (let ((beg (point))
21752 end)
21753 (if (and subtreep org-yank-adjusted-subtrees)
21754 (org-paste-subtree nil nil 'for-yank)
21755 (call-interactively command))
21757 (setq end (point))
21758 (goto-char beg)
21759 (when (and (bolp) subtreep
21760 (not (setq swallowp
21761 (org-yank-folding-would-swallow-text beg end))))
21762 (org-with-limited-levels
21763 (or (looking-at org-outline-regexp)
21764 (re-search-forward org-outline-regexp-bol end t))
21765 (while (and (< (point) end) (looking-at org-outline-regexp))
21766 (hide-subtree)
21767 (org-cycle-show-empty-lines 'folded)
21768 (condition-case nil
21769 (outline-forward-same-level 1)
21770 (error (goto-char end))))))
21771 (when swallowp
21772 (message
21773 "Inserted text not folded because that would swallow text"))
21775 (goto-char end)
21776 (skip-chars-forward " \t\n\r")
21777 (beginning-of-line 1)
21778 (push-mark beg 'nomsg)))
21779 ((and subtreep org-yank-adjusted-subtrees)
21780 (let ((beg (point-at-bol)))
21781 (org-paste-subtree nil nil 'for-yank)
21782 (push-mark beg 'nomsg)))
21784 (call-interactively command))))))
21786 (defun org-yank-folding-would-swallow-text (beg end)
21787 "Would hide-subtree at BEG swallow any text after END?"
21788 (let (level)
21789 (org-with-limited-levels
21790 (save-excursion
21791 (goto-char beg)
21792 (when (or (looking-at org-outline-regexp)
21793 (re-search-forward org-outline-regexp-bol end t))
21794 (setq level (org-outline-level)))
21795 (goto-char end)
21796 (skip-chars-forward " \t\r\n\v\f")
21797 (if (or (eobp)
21798 (and (bolp) (looking-at org-outline-regexp)
21799 (<= (org-outline-level) level)))
21800 nil ; Nothing would be swallowed
21801 t))))) ; something would swallow
21803 (define-key org-mode-map "\C-y" 'org-yank)
21805 (defun org-truely-invisible-p ()
21806 "Check if point is at a character currently not visible.
21807 This version does not only check the character property, but also
21808 `visible-mode'."
21809 ;; Early versions of noutline don't have `outline-invisible-p'.
21810 (if (org-bound-and-true-p visible-mode)
21812 (outline-invisible-p)))
21814 (defun org-invisible-p2 ()
21815 "Check if point is at a character currently not visible."
21816 (save-excursion
21817 (if (and (eolp) (not (bobp))) (backward-char 1))
21818 ;; Early versions of noutline don't have `outline-invisible-p'.
21819 (outline-invisible-p)))
21821 (defun org-back-to-heading (&optional invisible-ok)
21822 "Call `outline-back-to-heading', but provide a better error message."
21823 (condition-case nil
21824 (outline-back-to-heading invisible-ok)
21825 (error (error "Before first headline at position %d in buffer %s"
21826 (point) (current-buffer)))))
21828 (defun org-before-first-heading-p ()
21829 "Before first heading?"
21830 (save-excursion
21831 (end-of-line)
21832 (null (re-search-backward org-outline-regexp-bol nil t))))
21834 (defun org-at-heading-p (&optional ignored)
21835 (outline-on-heading-p t))
21836 ;; Compatibility alias with Org versions < 7.8.03
21837 (defalias 'org-on-heading-p 'org-at-heading-p)
21839 (defun org-at-comment-p nil
21840 "Is cursor in a line starting with a # character?"
21841 (save-excursion
21842 (beginning-of-line)
21843 (looking-at "^#")))
21845 (defun org-at-drawer-p nil
21846 "Is cursor at a drawer keyword?"
21847 (save-excursion
21848 (move-beginning-of-line 1)
21849 (looking-at org-drawer-regexp)))
21851 (defun org-at-block-p nil
21852 "Is cursor at a block keyword?"
21853 (save-excursion
21854 (move-beginning-of-line 1)
21855 (looking-at org-block-regexp)))
21857 (defun org-point-at-end-of-empty-headline ()
21858 "If point is at the end of an empty headline, return t, else nil.
21859 If the heading only contains a TODO keyword, it is still still considered
21860 empty."
21861 (and (looking-at "[ \t]*$")
21862 (when org-todo-line-regexp
21863 (save-excursion
21864 (beginning-of-line 1)
21865 (let ((case-fold-search nil))
21866 (looking-at org-todo-line-regexp)
21867 (string= (match-string 3) ""))))))
21869 (defun org-at-heading-or-item-p ()
21870 (or (org-at-heading-p) (org-at-item-p)))
21872 (defun org-at-target-p ()
21873 (or (org-in-regexp org-radio-target-regexp)
21874 (org-in-regexp org-target-regexp)))
21875 ;; Compatibility alias with Org versions < 7.8.03
21876 (defalias 'org-on-target-p 'org-at-target-p)
21878 (defun org-up-heading-all (arg)
21879 "Move to the heading line of which the present line is a subheading.
21880 This function considers both visible and invisible heading lines.
21881 With argument, move up ARG levels."
21882 (if (fboundp 'outline-up-heading-all)
21883 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21884 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21886 (defun org-up-heading-safe ()
21887 "Move to the heading line of which the present line is a subheading.
21888 This version will not throw an error. It will return the level of the
21889 headline found, or nil if no higher level is found.
21891 Also, this function will be a lot faster than `outline-up-heading',
21892 because it relies on stars being the outline starters. This can really
21893 make a significant difference in outlines with very many siblings."
21894 (let (start-level re)
21895 (org-back-to-heading t)
21896 (setq start-level (funcall outline-level))
21897 (if (equal start-level 1)
21899 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21900 (if (re-search-backward re nil t)
21901 (funcall outline-level)))))
21903 (defun org-first-sibling-p ()
21904 "Is this heading the first child of its parents?"
21905 (interactive)
21906 (let ((re org-outline-regexp-bol)
21907 level l)
21908 (unless (org-at-heading-p t)
21909 (error "Not at a heading"))
21910 (setq level (funcall outline-level))
21911 (save-excursion
21912 (if (not (re-search-backward re nil t))
21914 (setq l (funcall outline-level))
21915 (< l level)))))
21917 (defun org-goto-sibling (&optional previous)
21918 "Goto the next sibling, even if it is invisible.
21919 When PREVIOUS is set, go to the previous sibling instead. Returns t
21920 when a sibling was found. When none is found, return nil and don't
21921 move point."
21922 (let ((fun (if previous 're-search-backward 're-search-forward))
21923 (pos (point))
21924 (re org-outline-regexp-bol)
21925 level l)
21926 (when (condition-case nil (org-back-to-heading t) (error nil))
21927 (setq level (funcall outline-level))
21928 (catch 'exit
21929 (or previous (forward-char 1))
21930 (while (funcall fun re nil t)
21931 (setq l (funcall outline-level))
21932 (when (< l level) (goto-char pos) (throw 'exit nil))
21933 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21934 (goto-char pos)
21935 nil))))
21937 (defun org-show-siblings ()
21938 "Show all siblings of the current headline."
21939 (save-excursion
21940 (while (org-goto-sibling) (org-flag-heading nil)))
21941 (save-excursion
21942 (while (org-goto-sibling 'previous)
21943 (org-flag-heading nil))))
21945 (defun org-goto-first-child ()
21946 "Goto the first child, even if it is invisible.
21947 Return t when a child was found. Otherwise don't move point and
21948 return nil."
21949 (let (level (pos (point)) (re org-outline-regexp-bol))
21950 (when (condition-case nil (org-back-to-heading t) (error nil))
21951 (setq level (outline-level))
21952 (forward-char 1)
21953 (if (and (re-search-forward re nil t) (> (outline-level) level))
21954 (progn (goto-char (match-beginning 0)) t)
21955 (goto-char pos) nil))))
21957 (defun org-show-hidden-entry ()
21958 "Show an entry where even the heading is hidden."
21959 (save-excursion
21960 (org-show-entry)))
21962 (defun org-flag-heading (flag &optional entry)
21963 "Flag the current heading. FLAG non-nil means make invisible.
21964 When ENTRY is non-nil, show the entire entry."
21965 (save-excursion
21966 (org-back-to-heading t)
21967 ;; Check if we should show the entire entry
21968 (if entry
21969 (progn
21970 (org-show-entry)
21971 (save-excursion
21972 (and (outline-next-heading)
21973 (org-flag-heading nil))))
21974 (outline-flag-region (max (point-min) (1- (point)))
21975 (save-excursion (outline-end-of-heading) (point))
21976 flag))))
21978 (defun org-get-next-sibling ()
21979 "Move to next heading of the same level, and return point.
21980 If there is no such heading, return nil.
21981 This is like outline-next-sibling, but invisible headings are ok."
21982 (let ((level (funcall outline-level)))
21983 (outline-next-heading)
21984 (while (and (not (eobp)) (> (funcall outline-level) level))
21985 (outline-next-heading))
21986 (if (or (eobp) (< (funcall outline-level) level))
21988 (point))))
21990 (defun org-get-last-sibling ()
21991 "Move to previous heading of the same level, and return point.
21992 If there is no such heading, return nil."
21993 (let ((opoint (point))
21994 (level (funcall outline-level)))
21995 (outline-previous-heading)
21996 (when (and (/= (point) opoint) (outline-on-heading-p t))
21997 (while (and (> (funcall outline-level) level)
21998 (not (bobp)))
21999 (outline-previous-heading))
22000 (if (< (funcall outline-level) level)
22002 (point)))))
22004 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22005 "Goto to the end of a subtree."
22006 ;; This contains an exact copy of the original function, but it uses
22007 ;; `org-back-to-heading', to make it work also in invisible
22008 ;; trees. And is uses an invisible-ok argument.
22009 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22010 ;; Furthermore, when used inside Org, finding the end of a large subtree
22011 ;; with many children and grandchildren etc, this can be much faster
22012 ;; than the outline version.
22013 (org-back-to-heading invisible-ok)
22014 (let ((first t)
22015 (level (funcall outline-level)))
22016 (if (and (derived-mode-p 'org-mode) (< level 1000))
22017 ;; A true heading (not a plain list item), in Org-mode
22018 ;; This means we can easily find the end by looking
22019 ;; only for the right number of stars. Using a regexp to do
22020 ;; this is so much faster than using a Lisp loop.
22021 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22022 (forward-char 1)
22023 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22024 ;; something else, do it the slow way
22025 (while (and (not (eobp))
22026 (or first (> (funcall outline-level) level)))
22027 (setq first nil)
22028 (outline-next-heading)))
22029 (unless to-heading
22030 (if (memq (preceding-char) '(?\n ?\^M))
22031 (progn
22032 ;; Go to end of line before heading
22033 (forward-char -1)
22034 (if (memq (preceding-char) '(?\n ?\^M))
22035 ;; leave blank line before heading
22036 (forward-char -1))))))
22037 (point))
22039 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22040 "Use Org version in org-mode, for dramatic speed-up."
22041 (if (derived-mode-p 'org-mode)
22042 (progn
22043 (org-end-of-subtree nil t)
22044 (unless (eobp) (backward-char 1)))
22045 ad-do-it))
22047 (defun org-end-of-meta-data-and-drawers ()
22048 "Jump to the first text after meta data and drawers in the current entry.
22049 This will move over empty lines, lines with planning time stamps,
22050 clocking lines, and drawers."
22051 (org-back-to-heading t)
22052 (let ((end (save-excursion (outline-next-heading) (point)))
22053 (re (concat "\\(" org-drawer-regexp "\\)"
22054 "\\|" "[ \t]*" org-keyword-time-regexp)))
22055 (forward-line 1)
22056 (while (re-search-forward re end t)
22057 (if (not (match-end 1))
22058 ;; empty or planning line
22059 (forward-line 1)
22060 ;; a drawer, find the end
22061 (re-search-forward "^[ \t]*:END:" end 'move)
22062 (forward-line 1)))
22063 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22064 (point)))
22066 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22067 "Move forward to the arg'th subheading at same level as this one.
22068 Stop at the first and last subheadings of a superior heading.
22069 Normally this only looks at visible headings, but when INVISIBLE-OK is
22070 non-nil it will also look at invisible ones."
22071 (interactive "p")
22072 (org-back-to-heading invisible-ok)
22073 (org-at-heading-p)
22074 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22075 (re (format "^\\*\\{1,%d\\} " level))
22077 (forward-char 1)
22078 (while (> arg 0)
22079 (while (and (re-search-forward re nil 'move)
22080 (setq l (- (match-end 0) (match-beginning 0) 1))
22081 (= l level)
22082 (not invisible-ok)
22083 (progn (backward-char 1) (outline-invisible-p)))
22084 (if (< l level) (setq arg 1)))
22085 (setq arg (1- arg)))
22086 (beginning-of-line 1)))
22088 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22089 "Move backward to the arg'th subheading at same level as this one.
22090 Stop at the first and last subheadings of a superior heading."
22091 (interactive "p")
22092 (org-back-to-heading)
22093 (org-at-heading-p)
22094 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22095 (re (format "^\\*\\{1,%d\\} " level))
22097 (while (> arg 0)
22098 (while (and (re-search-backward re nil 'move)
22099 (setq l (- (match-end 0) (match-beginning 0) 1))
22100 (= l level)
22101 (not invisible-ok)
22102 (outline-invisible-p))
22103 (if (< l level) (setq arg 1)))
22104 (setq arg (1- arg)))))
22106 (defun org-forward-element ()
22107 "Move forward by one element.
22108 Move to the next element at the same level, when possible."
22109 (interactive)
22110 (cond ((eobp) (error "Cannot move further down"))
22111 ((org-with-limited-levels (org-at-heading-p))
22112 (let ((origin (point)))
22113 (org-forward-heading-same-level 1)
22114 (unless (org-with-limited-levels (org-at-heading-p))
22115 (goto-char origin)
22116 (error "Cannot move further down"))))
22118 (let* ((elem (org-element-at-point))
22119 (end (org-element-property :end elem))
22120 (parent (org-element-property :parent elem)))
22121 (if (and parent (= (org-element-property :contents-end parent) end))
22122 (goto-char (org-element-property :end parent))
22123 (goto-char end))))))
22125 (defun org-backward-element ()
22126 "Move backward by one element.
22127 Move to the previous element at the same level, when possible."
22128 (interactive)
22129 (cond ((bobp) (error "Cannot move further up"))
22130 ((org-with-limited-levels (org-at-heading-p))
22131 ;; At an headline, move to the previous one, if any, or stay
22132 ;; here.
22133 (let ((origin (point)))
22134 (org-backward-heading-same-level 1)
22135 (unless (org-with-limited-levels (org-at-heading-p))
22136 (goto-char origin)
22137 (error "Cannot move further up"))))
22139 (let* ((trail (org-element-at-point 'keep-trail))
22140 (elem (car trail))
22141 (prev-elem (nth 1 trail))
22142 (beg (org-element-property :begin elem)))
22143 (cond
22144 ;; Move to beginning of current element if point isn't
22145 ;; there already.
22146 ((/= (point) beg) (goto-char beg))
22147 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22148 ((org-before-first-heading-p) (goto-char (point-min)))
22149 (t (org-back-to-heading)))))))
22151 (defun org-up-element ()
22152 "Move to upper element."
22153 (interactive)
22154 (if (org-with-limited-levels (org-at-heading-p))
22155 (unless (org-up-heading-safe) (error "No surrounding element"))
22156 (let* ((elem (org-element-at-point))
22157 (parent (org-element-property :parent elem)))
22158 (if parent (goto-char (org-element-property :begin parent))
22159 (if (org-with-limited-levels (org-before-first-heading-p))
22160 (error "No surrounding element")
22161 (org-with-limited-levels (org-back-to-heading)))))))
22163 (defvar org-element-greater-elements)
22164 (defun org-down-element ()
22165 "Move to inner element."
22166 (interactive)
22167 (let ((element (org-element-at-point)))
22168 (cond
22169 ((memq (org-element-type element) '(plain-list table))
22170 (goto-char (org-element-property :contents-begin element))
22171 (forward-char))
22172 ((memq (org-element-type element) org-element-greater-elements)
22173 ;; If contents are hidden, first disclose them.
22174 (when (org-element-property :hiddenp element) (org-cycle))
22175 (goto-char (or (org-element-property :contents-begin element)
22176 (error "No content for this element"))))
22177 (t (error "No inner element")))))
22179 (defun org-drag-element-backward ()
22180 "Move backward element at point."
22181 (interactive)
22182 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22183 (let* ((trail (org-element-at-point 'keep-trail))
22184 (elem (car trail))
22185 (prev-elem (nth 1 trail)))
22186 ;; Error out if no previous element or previous element is
22187 ;; a parent of the current one.
22188 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22189 (error "Cannot drag element backward")
22190 (let ((pos (point)))
22191 (org-element-swap-A-B prev-elem elem)
22192 (goto-char (+ (org-element-property :begin prev-elem)
22193 (- pos (org-element-property :begin elem)))))))))
22195 (defun org-drag-element-forward ()
22196 "Move forward element at point."
22197 (interactive)
22198 (let* ((pos (point))
22199 (elem (org-element-at-point)))
22200 (when (= (point-max) (org-element-property :end elem))
22201 (error "Cannot drag element forward"))
22202 (goto-char (org-element-property :end elem))
22203 (let ((next-elem (org-element-at-point)))
22204 (when (or (org-element-nested-p elem next-elem)
22205 (and (eq (org-element-type next-elem) 'headline)
22206 (not (eq (org-element-type elem) 'headline))))
22207 (goto-char pos)
22208 (error "Cannot drag element forward"))
22209 ;; Compute new position of point: it's shifted by NEXT-ELEM
22210 ;; body's length (without final blanks) and by the length of
22211 ;; blanks between ELEM and NEXT-ELEM.
22212 (let ((size-next (- (save-excursion
22213 (goto-char (org-element-property :end next-elem))
22214 (skip-chars-backward " \r\t\n")
22215 (forward-line)
22216 ;; Small correction if buffer doesn't end
22217 ;; with a newline character.
22218 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22219 (org-element-property :begin next-elem)))
22220 (size-blank (- (org-element-property :end elem)
22221 (save-excursion
22222 (goto-char (org-element-property :end elem))
22223 (skip-chars-backward " \r\t\n")
22224 (forward-line)
22225 (point)))))
22226 (org-element-swap-A-B elem next-elem)
22227 (goto-char (+ pos size-next size-blank))))))
22229 (defun org-mark-element ()
22230 "Put point at beginning of this element, mark at end.
22232 Interactively, if this command is repeated or (in Transient Mark
22233 mode) if the mark is active, it marks the next element after the
22234 ones already marked."
22235 (interactive)
22236 (let (deactivate-mark)
22237 (if (and (org-called-interactively-p 'any)
22238 (or (and (eq last-command this-command) (mark t))
22239 (and transient-mark-mode mark-active)))
22240 (set-mark
22241 (save-excursion
22242 (goto-char (mark))
22243 (goto-char (org-element-property :end (org-element-at-point)))))
22244 (let ((element (org-element-at-point)))
22245 (end-of-line)
22246 (push-mark (org-element-property :end element) t t)
22247 (goto-char (org-element-property :begin element))))))
22249 (defun org-narrow-to-element ()
22250 "Narrow buffer to current element."
22251 (interactive)
22252 (let ((elem (org-element-at-point)))
22253 (cond
22254 ((eq (car elem) 'headline)
22255 (narrow-to-region
22256 (org-element-property :begin elem)
22257 (org-element-property :end elem)))
22258 ((memq (car elem) org-element-greater-elements)
22259 (narrow-to-region
22260 (org-element-property :contents-begin elem)
22261 (org-element-property :contents-end elem)))
22263 (narrow-to-region
22264 (org-element-property :begin elem)
22265 (org-element-property :end elem))))))
22267 (defun org-transpose-element ()
22268 "Transpose current and previous elements, keeping blank lines between.
22269 Point is moved after both elements."
22270 (interactive)
22271 (org-skip-whitespace)
22272 (let ((end (org-element-property :end (org-element-at-point))))
22273 (org-drag-element-backward)
22274 (goto-char end)))
22276 (defun org-unindent-buffer ()
22277 "Un-indent the visible part of the buffer.
22278 Relative indentation (between items, inside blocks, etc.) isn't
22279 modified."
22280 (interactive)
22281 (unless (eq major-mode 'org-mode)
22282 (error "Cannot un-indent a buffer not in Org mode"))
22283 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22284 unindent-tree ; For byte-compiler.
22285 (unindent-tree
22286 (function
22287 (lambda (contents)
22288 (mapc
22289 (lambda (element)
22290 (if (memq (org-element-type element) '(headline section))
22291 (funcall unindent-tree (org-element-contents element))
22292 (save-excursion
22293 (save-restriction
22294 (narrow-to-region
22295 (org-element-property :begin element)
22296 (org-element-property :end element))
22297 (org-do-remove-indentation)))))
22298 (reverse contents))))))
22299 (funcall unindent-tree (org-element-contents parse-tree))))
22301 (defun org-show-subtree ()
22302 "Show everything after this heading at deeper levels."
22303 (interactive)
22304 (outline-flag-region
22305 (point)
22306 (save-excursion
22307 (org-end-of-subtree t t))
22308 nil))
22310 (defun org-show-entry ()
22311 "Show the body directly following this heading.
22312 Show the heading too, if it is currently invisible."
22313 (interactive)
22314 (save-excursion
22315 (condition-case nil
22316 (progn
22317 (org-back-to-heading t)
22318 (outline-flag-region
22319 (max (point-min) (1- (point)))
22320 (save-excursion
22321 (if (re-search-forward
22322 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22323 (match-beginning 1)
22324 (point-max)))
22325 nil)
22326 (org-cycle-hide-drawers 'children))
22327 (error nil))))
22329 (defun org-make-options-regexp (kwds &optional extra)
22330 "Make a regular expression for keyword lines."
22331 (concat
22332 "^#\\+\\("
22333 (mapconcat 'regexp-quote kwds "\\|")
22334 (if extra (concat "\\|" extra))
22335 "\\):[ \t]*\\(.*\\)"))
22337 ;; Make isearch reveal the necessary context
22338 (defun org-isearch-end ()
22339 "Reveal context after isearch exits."
22340 (when isearch-success ; only if search was successful
22341 (if (featurep 'xemacs)
22342 ;; Under XEmacs, the hook is run in the correct place,
22343 ;; we directly show the context.
22344 (org-show-context 'isearch)
22345 ;; In Emacs the hook runs *before* restoring the overlays.
22346 ;; So we have to use a one-time post-command-hook to do this.
22347 ;; (Emacs 22 has a special variable, see function `org-mode')
22348 (unless (and (boundp 'isearch-mode-end-hook-quit)
22349 isearch-mode-end-hook-quit)
22350 ;; Only when the isearch was not quitted.
22351 (org-add-hook 'post-command-hook 'org-isearch-post-command
22352 'append 'local)))))
22354 (defun org-isearch-post-command ()
22355 "Remove self from hook, and show context."
22356 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22357 (org-show-context 'isearch))
22360 ;;;; Integration with and fixes for other packages
22362 ;;; Imenu support
22364 (defvar org-imenu-markers nil
22365 "All markers currently used by Imenu.")
22366 (make-variable-buffer-local 'org-imenu-markers)
22368 (defun org-imenu-new-marker (&optional pos)
22369 "Return a new marker for use by Imenu, and remember the marker."
22370 (let ((m (make-marker)))
22371 (move-marker m (or pos (point)))
22372 (push m org-imenu-markers)
22375 (defun org-imenu-get-tree ()
22376 "Produce the index for Imenu."
22377 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22378 (setq org-imenu-markers nil)
22379 (let* ((n org-imenu-depth)
22380 (re (concat "^" (org-get-limited-outline-regexp)))
22381 (subs (make-vector (1+ n) nil))
22382 (last-level 0)
22383 m level head)
22384 (save-excursion
22385 (save-restriction
22386 (widen)
22387 (goto-char (point-max))
22388 (while (re-search-backward re nil t)
22389 (setq level (org-reduced-level (funcall outline-level)))
22390 (when (and (<= level n)
22391 (looking-at org-complex-heading-regexp))
22392 (setq head (org-link-display-format
22393 (org-match-string-no-properties 4))
22394 m (org-imenu-new-marker))
22395 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22396 (if (>= level last-level)
22397 (push (cons head m) (aref subs level))
22398 (push (cons head (aref subs (1+ level))) (aref subs level))
22399 (loop for i from (1+ level) to n do (aset subs i nil)))
22400 (setq last-level level)))))
22401 (aref subs 1)))
22403 (eval-after-load "imenu"
22404 '(progn
22405 (add-hook 'imenu-after-jump-hook
22406 (lambda ()
22407 (if (derived-mode-p 'org-mode)
22408 (org-show-context 'org-goto))))))
22410 (defun org-link-display-format (link)
22411 "Replace a link with either the description, or the link target
22412 if no description is present"
22413 (save-match-data
22414 (if (string-match org-bracket-link-analytic-regexp link)
22415 (replace-match (if (match-end 5)
22416 (match-string 5 link)
22417 (concat (match-string 1 link)
22418 (match-string 3 link)))
22419 nil t link)
22420 link)))
22422 (defun org-toggle-link-display ()
22423 "Toggle the literal or descriptive display of links."
22424 (interactive)
22425 (if org-descriptive-links
22426 (progn (org-remove-from-invisibility-spec '(org-link))
22427 (org-restart-font-lock)
22428 (setq org-descriptive-links nil))
22429 (progn (add-to-invisibility-spec '(org-link))
22430 (org-restart-font-lock)
22431 (setq org-descriptive-links t))))
22433 ;; Speedbar support
22435 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22436 "Overlay marking the agenda restriction line in speedbar.")
22437 (overlay-put org-speedbar-restriction-lock-overlay
22438 'face 'org-agenda-restriction-lock)
22439 (overlay-put org-speedbar-restriction-lock-overlay
22440 'help-echo "Agendas are currently limited to this item.")
22441 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22443 (defun org-speedbar-set-agenda-restriction ()
22444 "Restrict future agenda commands to the location at point in speedbar.
22445 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22446 (interactive)
22447 (require 'org-agenda)
22448 (let (p m tp np dir txt)
22449 (cond
22450 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22451 'org-imenu t))
22452 (setq m (get-text-property p 'org-imenu-marker))
22453 (with-current-buffer (marker-buffer m)
22454 (goto-char m)
22455 (org-agenda-set-restriction-lock 'subtree)))
22456 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22457 'speedbar-function 'speedbar-find-file))
22458 (setq tp (previous-single-property-change
22459 (1+ p) 'speedbar-function)
22460 np (next-single-property-change
22461 tp 'speedbar-function)
22462 dir (speedbar-line-directory)
22463 txt (buffer-substring-no-properties (or tp (point-min))
22464 (or np (point-max))))
22465 (with-current-buffer (find-file-noselect
22466 (let ((default-directory dir))
22467 (expand-file-name txt)))
22468 (unless (derived-mode-p 'org-mode)
22469 (error "Cannot restrict to non-Org-mode file"))
22470 (org-agenda-set-restriction-lock 'file)))
22471 (t (error "Don't know how to restrict Org-mode's agenda")))
22472 (move-overlay org-speedbar-restriction-lock-overlay
22473 (point-at-bol) (point-at-eol))
22474 (setq current-prefix-arg nil)
22475 (org-agenda-maybe-redo)))
22477 (eval-after-load "speedbar"
22478 '(progn
22479 (speedbar-add-supported-extension ".org")
22480 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22481 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22482 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22483 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22484 (add-hook 'speedbar-visiting-tag-hook
22485 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22487 ;;; Fixes and Hacks for problems with other packages
22489 ;; Make flyspell not check words in links, to not mess up our keymap
22490 (defun org-mode-flyspell-verify ()
22491 "Don't let flyspell put overlays at active buttons, or on
22492 {todo,all-time,additional-option-like}-keywords."
22493 (let ((pos (max (1- (point)) (point-min)))
22494 (word (thing-at-point 'word)))
22495 (and (not (get-text-property pos 'keymap))
22496 (not (get-text-property pos 'org-no-flyspell))
22497 (not (member word org-todo-keywords-1))
22498 (not (member word org-all-time-keywords))
22499 (not (member word org-options-keywords))
22500 (not (member word (mapcar 'car org-startup-options)))
22501 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22503 (defun org-remove-flyspell-overlays-in (beg end)
22504 "Remove flyspell overlays in region."
22505 (and (org-bound-and-true-p flyspell-mode)
22506 (fboundp 'flyspell-delete-region-overlays)
22507 (flyspell-delete-region-overlays beg end))
22508 (add-text-properties beg end '(org-no-flyspell t)))
22510 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22511 (eval-after-load "bookmark"
22512 '(if (boundp 'bookmark-after-jump-hook)
22513 ;; We can use the hook
22514 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22515 ;; Hook not available, use advice
22516 (defadvice bookmark-jump (after org-make-visible activate)
22517 "Make the position visible."
22518 (org-bookmark-jump-unhide))))
22520 ;; Make sure saveplace shows the location if it was hidden
22521 (eval-after-load "saveplace"
22522 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22523 "Make the position visible."
22524 (org-bookmark-jump-unhide)))
22526 ;; Make sure ecb shows the location if it was hidden
22527 (eval-after-load "ecb"
22528 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22529 "Make hierarchy visible when jumping into location from ECB tree buffer."
22530 (if (derived-mode-p 'org-mode)
22531 (org-show-context))))
22533 (defun org-bookmark-jump-unhide ()
22534 "Unhide the current position, to show the bookmark location."
22535 (and (derived-mode-p 'org-mode)
22536 (or (outline-invisible-p)
22537 (save-excursion (goto-char (max (point-min) (1- (point))))
22538 (outline-invisible-p)))
22539 (org-show-context 'bookmark-jump)))
22541 ;; Make session.el ignore our circular variable
22542 (eval-after-load "session"
22543 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22545 ;;;; Experimental code
22547 (defun org-closed-in-range ()
22548 "Sparse tree of items closed in a certain time range.
22549 Still experimental, may disappear in the future."
22550 (interactive)
22551 ;; Get the time interval from the user.
22552 (let* ((time1 (org-float-time
22553 (org-read-date nil 'to-time nil "Starting date: ")))
22554 (time2 (org-float-time
22555 (org-read-date nil 'to-time nil "End date:")))
22556 ;; callback function
22557 (callback (lambda ()
22558 (let ((time
22559 (org-float-time
22560 (apply 'encode-time
22561 (org-parse-time-string
22562 (match-string 1))))))
22563 ;; check if time in interval
22564 (and (>= time time1) (<= time time2))))))
22565 ;; make tree, check each match with the callback
22566 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22568 ;;;; Finish up
22570 (provide 'org)
22572 (run-hooks 'org-load-hook)
22574 ;;; org.el ends here