org.el: Add more explicit errors. Fix some declarations and one autoload.
[org-mode.git] / lisp / org.el
blobbdbba861102e877604dceca7e5b50e49791e36e4
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-timestamps-up "org-clock" ())
119 (declare-function org-clock-timestamps-down "org-clock" ())
120 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122 (declare-function orgtbl-mode "org-table" (&optional arg))
123 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
124 (declare-function org-beamer-mode "org-beamer" ())
125 (declare-function org-table-edit-field "org-table" (arg))
126 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
127 (declare-function org-id-get-create "org-id" (&optional force))
128 (declare-function org-id-find-id-file "org-id" (id))
129 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
130 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
131 (declare-function org-table-align "org-table" ())
132 (declare-function org-table-paste-rectangle "org-table" ())
133 (declare-function org-table-maybe-eval-formula "org-table" ())
134 (declare-function org-table-maybe-recalculate-line "org-table" ())
136 ;; load languages based on value of `org-babel-load-languages'
137 (defvar org-babel-load-languages)
139 ;;;###autoload
140 (defun org-babel-do-load-languages (sym value)
141 "Load the languages defined in `org-babel-load-languages'."
142 (set-default sym value)
143 (mapc (lambda (pair)
144 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
145 (if active
146 (progn
147 (require (intern (concat "ob-" lang))))
148 (progn
149 (funcall 'fmakunbound
150 (intern (concat "org-babel-execute:" lang)))
151 (funcall 'fmakunbound
152 (intern (concat "org-babel-expand-body:" lang)))))))
153 org-babel-load-languages))
155 (defcustom org-babel-load-languages '((emacs-lisp . t))
156 "Languages which can be evaluated in Org-mode buffers.
157 This list can be used to load support for any of the languages
158 below, note that each language will depend on a different set of
159 system executables and/or Emacs modes. When a language is
160 \"loaded\", then code blocks in that language can be evaluated
161 with `org-babel-execute-src-block' bound by default to C-c
162 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
163 be set to remove code block evaluation from the C-c C-c
164 keybinding. By default only Emacs Lisp (which has no
165 requirements) is loaded."
166 :group 'org-babel
167 :set 'org-babel-do-load-languages
168 :version "24.1"
169 :type '(alist :tag "Babel Languages"
170 :key-type
171 (choice
172 (const :tag "Awk" awk)
173 (const :tag "C" C)
174 (const :tag "R" R)
175 (const :tag "Asymptote" asymptote)
176 (const :tag "Calc" calc)
177 (const :tag "Clojure" clojure)
178 (const :tag "CSS" css)
179 (const :tag "Ditaa" ditaa)
180 (const :tag "Dot" dot)
181 (const :tag "Emacs Lisp" emacs-lisp)
182 (const :tag "Fortran" fortran)
183 (const :tag "Gnuplot" gnuplot)
184 (const :tag "Haskell" haskell)
185 (const :tag "IO" io)
186 (const :tag "Java" java)
187 (const :tag "Javascript" js)
188 (const :tag "LaTeX" latex)
189 (const :tag "Ledger" ledger)
190 (const :tag "Lilypond" lilypond)
191 (const :tag "Lisp" lisp)
192 (const :tag "Maxima" maxima)
193 (const :tag "Matlab" matlab)
194 (const :tag "Mscgen" mscgen)
195 (const :tag "Ocaml" ocaml)
196 (const :tag "Octave" octave)
197 (const :tag "Org" org)
198 (const :tag "Perl" perl)
199 (const :tag "Pico Lisp" picolisp)
200 (const :tag "PlantUML" plantuml)
201 (const :tag "Python" python)
202 (const :tag "Ruby" ruby)
203 (const :tag "Sass" sass)
204 (const :tag "Scala" scala)
205 (const :tag "Scheme" scheme)
206 (const :tag "Screen" screen)
207 (const :tag "Shell Script" sh)
208 (const :tag "Shen" shen)
209 (const :tag "Sql" sql)
210 (const :tag "Sqlite" sqlite))
211 :value-type (boolean :tag "Activate" :value t)))
213 ;;;; Customization variables
214 (defcustom org-clone-delete-id nil
215 "Remove ID property of clones of a subtree.
216 When non-nil, clones of a subtree don't inherit the ID property.
217 Otherwise they inherit the ID property with a new unique
218 identifier."
219 :type 'boolean
220 :version "24.1"
221 :group 'org-id)
223 ;;; Version
224 (require 'org-compat)
225 (org-check-version)
227 ;;;###autoload
228 (defun org-version (&optional here full message)
229 "Show the org-mode version in the echo area.
230 With prefix argument HERE, insert it at point.
231 When FULL is non-nil, use a verbose version string.
232 When MESSAGE is non-nil, display a message with the version."
233 (interactive "P")
234 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
235 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
236 (org-trash (or
237 (and (fboundp 'org-release) (fboundp 'org-git-version))
238 (load (concat org-dir "org-version.el")
239 'noerror 'nomessage 'nosuffix)))
240 (org-version (org-release))
241 (git-version (org-git-version))
242 (version (format "Org-mode version %s (%s @ %s)"
243 org-version
244 git-version
245 (if org-install-dir
246 (if (string= org-dir org-install-dir)
247 org-install-dir
248 (concat "mixed installation! " org-install-dir " and " org-dir))
249 "org-loaddefs.el can not be found!")))
250 (_version (if full version org-version)))
251 (if (org-called-interactively-p 'interactive)
252 (if here
253 (insert version)
254 (message version))
255 (if message (message _version))
256 _version)))
258 (defconst org-version (org-version))
260 ;;; Compatibility constants
262 ;;; The custom variables
264 (defgroup org nil
265 "Outline-based notes management and organizer."
266 :tag "Org"
267 :group 'outlines
268 :group 'calendar)
270 (defcustom org-mode-hook nil
271 "Mode hook for Org-mode, run after the mode was turned on."
272 :group 'org
273 :type 'hook)
275 (defcustom org-load-hook nil
276 "Hook that is run after org.el has been loaded."
277 :group 'org
278 :type 'hook)
280 (defcustom org-log-buffer-setup-hook nil
281 "Hook that is run after an Org log buffer is created."
282 :group 'org
283 :version "24.1"
284 :type 'hook)
286 (defvar org-modules) ; defined below
287 (defvar org-modules-loaded nil
288 "Have the modules been loaded already?")
290 (defun org-load-modules-maybe (&optional force)
291 "Load all extensions listed in `org-modules'."
292 (when (or force (not org-modules-loaded))
293 (mapc (lambda (ext)
294 (condition-case nil (require ext)
295 (error (message "Problems while trying to load feature `%s'" ext))))
296 org-modules)
297 (setq org-modules-loaded t)))
299 (defun org-set-modules (var value)
300 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
301 (set var value)
302 (when (featurep 'org)
303 (org-load-modules-maybe 'force)))
305 (when (org-bound-and-true-p org-modules)
306 (let ((a (member 'org-infojs org-modules)))
307 (and a (setcar a 'org-jsinfo))))
309 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
310 "Modules that should always be loaded together with org.el.
311 If a description starts with <C>, the file is not part of Emacs
312 and loading it will require that you have downloaded and properly installed
313 the org-mode distribution.
315 You can also use this system to load external packages (i.e. neither Org
316 core modules, nor modules from the CONTRIB directory). Just add symbols
317 to the end of the list. If the package is called org-xyz.el, then you need
318 to add the symbol `xyz', and the package must have a call to
320 (provide 'org-xyz)"
321 :group 'org
322 :set 'org-set-modules
323 :type
324 '(set :greedy t
325 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
326 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
327 (const :tag " crypt: Encryption of subtrees" org-crypt)
328 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
329 (const :tag " docview: Links to doc-view buffers" org-docview)
330 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
331 (const :tag " id: Global IDs for identifying entries" org-id)
332 (const :tag " info: Links to Info nodes" org-info)
333 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
334 (const :tag " habit: Track your consistency with habits" org-habit)
335 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
336 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
337 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
338 (const :tag " mew Links to Mew folders/messages" org-mew)
339 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
340 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
341 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
342 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
343 (const :tag " vm: Links to VM folders/messages" org-vm)
344 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
345 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
346 (const :tag " mouse: Additional mouse support" org-mouse)
347 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
349 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
350 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
351 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
352 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
353 (const :tag "C collector: Collect properties into tables" org-collector)
354 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
355 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
356 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
357 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
358 (const :tag "C eval: Include command output as text" org-eval)
359 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
360 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
361 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
362 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
363 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
365 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
367 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
368 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
369 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
370 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
371 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
372 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
373 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
374 (const :tag "C mtags: Support for muse-like tags" org-mtags)
375 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
376 (const :tag "C registry: A registry for Org-mode links" org-registry)
377 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
378 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
379 (const :tag "C secretary: Team management with org-mode" org-secretary)
380 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
381 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
382 (const :tag "C track: Keep up with Org-mode development" org-track)
383 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
384 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
385 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
387 (defcustom org-support-shift-select nil
388 "Non-nil means make shift-cursor commands select text when possible.
390 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
391 start selecting a region, or enlarge regions started in this way.
392 In Org-mode, in special contexts, these same keys are used for
393 other purposes, important enough to compete with shift selection.
394 Org tries to balance these needs by supporting `shift-select-mode'
395 outside these special contexts, under control of this variable.
397 The default of this variable is nil, to avoid confusing behavior. Shifted
398 cursor keys will then execute Org commands in the following contexts:
399 - on a headline, changing TODO state (left/right) and priority (up/down)
400 - on a time stamp, changing the time
401 - in a plain list item, changing the bullet type
402 - in a property definition line, switching between allowed values
403 - in the BEGIN line of a clock table (changing the time block).
404 Outside these contexts, the commands will throw an error.
406 When this variable is t and the cursor is not in a special
407 context, Org-mode will support shift-selection for making and
408 enlarging regions. To make this more effective, the bullet
409 cycling will no longer happen anywhere in an item line, but only
410 if the cursor is exactly on the bullet.
412 If you set this variable to the symbol `always', then the keys
413 will not be special in headlines, property lines, and item lines,
414 to make shift selection work there as well. If this is what you
415 want, you can use the following alternative commands: `C-c C-t'
416 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
417 can be used to switch TODO sets, `C-c -' to cycle item bullet
418 types, and properties can be edited by hand or in column view.
420 However, when the cursor is on a timestamp, shift-cursor commands
421 will still edit the time stamp - this is just too good to give up.
423 XEmacs user should have this variable set to nil, because
424 `shift-select-mode' is in Emacs 23 or later only."
425 :group 'org
426 :type '(choice
427 (const :tag "Never" nil)
428 (const :tag "When outside special context" t)
429 (const :tag "Everywhere except timestamps" always)))
431 (defcustom org-loop-over-headlines-in-active-region nil
432 "Shall some commands act upon headlines in the active region?
434 When set to `t', some commands will be performed in all headlines
435 within the active region.
437 When set to `start-level', some commands will be performed in all
438 headlines within the active region, provided that these headlines
439 are of the same level than the first one.
441 When set to a string, those commands will be performed on the
442 matching headlines within the active region. Such string must be
443 a tags/property/todo match as it is used in the agenda tags view.
445 The list of commands is: `org-schedule', `org-deadline',
446 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
447 `org-archive-to-archive-sibling'. The archiving commands skip
448 already archived entries."
449 :type '(choice (const :tag "Don't loop" nil)
450 (const :tag "All headlines in active region" t)
451 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
452 (string :tag "Tags/Property/Todo matcher"))
453 :version "24.1"
454 :group 'org-todo
455 :group 'org-archive)
457 (defgroup org-startup nil
458 "Options concerning startup of Org-mode."
459 :tag "Org Startup"
460 :group 'org)
462 (defcustom org-startup-folded t
463 "Non-nil means entering Org-mode will switch to OVERVIEW.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
467 #+STARTUP: fold (or `overview', this is equivalent)
468 #+STARTUP: nofold (or `showall', this is equivalent)
469 #+STARTUP: content
470 #+STARTUP: showeverything"
471 :group 'org-startup
472 :type '(choice
473 (const :tag "nofold: show all" nil)
474 (const :tag "fold: overview" t)
475 (const :tag "content: all headlines" content)
476 (const :tag "show everything, even drawers" showeverything)))
478 (defcustom org-startup-truncated t
479 "Non-nil means entering Org-mode will set `truncate-lines'.
480 This is useful since some lines containing links can be very long and
481 uninteresting. Also tables look terrible when wrapped."
482 :group 'org-startup
483 :type 'boolean)
485 (defcustom org-startup-indented nil
486 "Non-nil means turn on `org-indent-mode' on startup.
487 This can also be configured on a per-file basis by adding one of
488 the following lines anywhere in the buffer:
490 #+STARTUP: indent
491 #+STARTUP: noindent"
492 :group 'org-structure
493 :type '(choice
494 (const :tag "Not" nil)
495 (const :tag "Globally (slow on startup in large files)" t)))
497 (defcustom org-use-sub-superscripts t
498 "Non-nil means interpret \"_\" and \"^\" for export.
499 When this option is turned on, you can use TeX-like syntax for sub- and
500 superscripts. Several characters after \"_\" or \"^\" will be
501 considered as a single item - so grouping with {} is normally not
502 needed. For example, the following things will be parsed as single
503 sub- or superscripts.
505 10^24 or 10^tau several digits will be considered 1 item.
506 10^-12 or 10^-tau a leading sign with digits or a word
507 x^2-y^3 will be read as x^2 - y^3, because items are
508 terminated by almost any nonword/nondigit char.
509 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
511 Still, ambiguity is possible - so when in doubt use {} to enclose the
512 sub/superscript. If you set this variable to the symbol `{}',
513 the braces are *required* in order to trigger interpretations as
514 sub/superscript. This can be helpful in documents that need \"_\"
515 frequently in plain text.
517 Not all export backends support this, but HTML does.
519 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
520 :group 'org-startup
521 :group 'org-export-translation
522 :version "24.1"
523 :type '(choice
524 (const :tag "Always interpret" t)
525 (const :tag "Only with braces" {})
526 (const :tag "Never interpret" nil)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
532 (defcustom org-startup-with-beamer-mode nil
533 "Non-nil means turn on `org-beamer-mode' on startup.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
537 #+STARTUP: beamer"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-startup-align-all-tables nil
543 "Non-nil means align all tables when visiting a file.
544 This is useful when the column width in tables is forced with <N> cookies
545 in table fields. Such tables will look correct only after the first re-align.
546 This can also be configured on a per-file basis by adding one of
547 the following lines anywhere in the buffer:
548 #+STARTUP: align
549 #+STARTUP: noalign"
550 :group 'org-startup
551 :type 'boolean)
553 (defcustom org-startup-with-inline-images nil
554 "Non-nil means show inline images when loading a new Org file.
555 This can also be configured on a per-file basis by adding one of
556 the following lines anywhere in the buffer:
557 #+STARTUP: inlineimages
558 #+STARTUP: noinlineimages"
559 :group 'org-startup
560 :version "24.1"
561 :type 'boolean)
563 (defcustom org-insert-mode-line-in-empty-file nil
564 "Non-nil means insert the first line setting Org-mode in empty files.
565 When the function `org-mode' is called interactively in an empty file, this
566 normally means that the file name does not automatically trigger Org-mode.
567 To ensure that the file will always be in Org-mode in the future, a
568 line enforcing Org-mode will be inserted into the buffer, if this option
569 has been set."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-replace-disputed-keys nil
574 "Non-nil means use alternative key bindings for some keys.
575 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
576 These keys are also used by other packages like shift-selection-mode'
577 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
578 If you want to use Org-mode together with one of these other modes,
579 or more generally if you would like to move some Org-mode commands to
580 other keys, set this variable and configure the keys with the variable
581 `org-disputed-keys'.
583 This option is only relevant at load-time of Org-mode, and must be set
584 *before* org.el is loaded. Changing it requires a restart of Emacs to
585 become effective."
586 :group 'org-startup
587 :type 'boolean)
589 (defcustom org-use-extra-keys nil
590 "Non-nil means use extra key sequence definitions for certain commands.
591 This happens automatically if you run XEmacs or if `window-system'
592 is nil. This variable lets you do the same manually. You must
593 set it before loading org.
595 Example: on Carbon Emacs 22 running graphically, with an external
596 keyboard on a Powerbook, the default way of setting M-left might
597 not work for either Alt or ESC. Setting this variable will make
598 it work for ESC."
599 :group 'org-startup
600 :type 'boolean)
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
605 (defcustom org-disputed-keys
606 '(([(shift up)] . [(meta p)])
607 ([(shift down)] . [(meta n)])
608 ([(shift left)] . [(meta -)])
609 ([(shift right)] . [(meta +)])
610 ([(control shift right)] . [(meta shift +)])
611 ([(control shift left)] . [(meta shift -)]))
612 "Keys for which Org-mode and other modes compete.
613 This is an alist, cars are the default keys, second element specifies
614 the alternative to use when `org-replace-disputed-keys' is t.
616 Keys can be specified in any syntax supported by `define-key'.
617 The value of this option takes effect only at Org-mode's startup,
618 therefore you'll have to restart Emacs to apply it after changing."
619 :group 'org-startup
620 :type 'alist)
622 (defun org-key (key)
623 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
624 Or return the original if not disputed.
625 Also apply the translations defined in `org-xemacs-key-equivalents'."
626 (when org-replace-disputed-keys
627 (let* ((nkey (key-description key))
628 (x (org-find-if (lambda (x)
629 (equal (key-description (car x)) nkey))
630 org-disputed-keys)))
631 (setq key (if x (cdr x) key))))
632 (when (featurep 'xemacs)
633 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
634 key)
636 (defun org-find-if (predicate seq)
637 (catch 'exit
638 (while seq
639 (if (funcall predicate (car seq))
640 (throw 'exit (car seq))
641 (pop seq)))))
643 (defun org-defkey (keymap key def)
644 "Define a key, possibly translated, as returned by `org-key'."
645 (define-key keymap (org-key key) def))
647 (defcustom org-ellipsis nil
648 "The ellipsis to use in the Org-mode outline.
649 When nil, just use the standard three dots. When a string, use that instead,
650 When a face, use the standard 3 dots, but with the specified face.
651 The change affects only Org-mode (which will then use its own display table).
652 Changing this requires executing `M-x org-mode' in a buffer to become
653 effective."
654 :group 'org-startup
655 :type '(choice (const :tag "Default" nil)
656 (face :tag "Face" :value org-warning)
657 (string :tag "String" :value "...#")))
659 (defvar org-display-table nil
660 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
662 (defgroup org-keywords nil
663 "Keywords in Org-mode."
664 :tag "Org Keywords"
665 :group 'org)
667 (defcustom org-deadline-string "DEADLINE:"
668 "String to mark deadline entries.
669 A deadline is this string, followed by a time stamp. Should be a word,
670 terminated by a colon. You can insert a schedule keyword and
671 a timestamp with \\[org-deadline].
672 Changes become only effective after restarting Emacs."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-scheduled-string "SCHEDULED:"
677 "String to mark scheduled TODO entries.
678 A schedule is this string, followed by a time stamp. Should be a word,
679 terminated by a colon. You can insert a schedule keyword and
680 a timestamp with \\[org-schedule].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-closed-string "CLOSED:"
686 "String used as the prefix for timestamps logging closing a TODO entry."
687 :group 'org-keywords
688 :type 'string)
690 (defcustom org-clock-string "CLOCK:"
691 "String used as prefix for timestamps clocking work hours on an item."
692 :group 'org-keywords
693 :type 'string)
695 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
696 org-scheduled-string "\\|"
697 org-deadline-string "\\|"
698 org-closed-string "\\|"
699 org-clock-string "\\)")
700 "Matches a line with planning or clock info.")
702 (defcustom org-comment-string "COMMENT"
703 "Entries starting with this keyword will never be exported.
704 An entry can be toggled between COMMENT and normal with
705 \\[org-toggle-comment].
706 Changes become only effective after restarting Emacs."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-quote-string "QUOTE"
711 "Entries starting with this keyword will be exported in fixed-width font.
712 Quoting applies only to the text in the entry following the headline, and does
713 not extend beyond the next headline, even if that is lower level.
714 An entry can be toggled between QUOTE and normal with
715 \\[org-toggle-fixed-width-section]."
716 :group 'org-keywords
717 :type 'string)
719 (defconst org-repeat-re
720 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
721 "Regular expression for specifying repeated events.
722 After a match, group 1 contains the repeat expression.")
724 (defgroup org-structure nil
725 "Options concerning the general structure of Org-mode files."
726 :tag "Org Structure"
727 :group 'org)
729 (defgroup org-reveal-location nil
730 "Options about how to make context of a location visible."
731 :tag "Org Reveal Location"
732 :group 'org-structure)
734 (defconst org-context-choice
735 '(choice
736 (const :tag "Always" t)
737 (const :tag "Never" nil)
738 (repeat :greedy t :tag "Individual contexts"
739 (cons
740 (choice :tag "Context"
741 (const agenda)
742 (const org-goto)
743 (const occur-tree)
744 (const tags-tree)
745 (const link-search)
746 (const mark-goto)
747 (const bookmark-jump)
748 (const isearch)
749 (const default))
750 (boolean))))
751 "Contexts for the reveal options.")
753 (defcustom org-show-hierarchy-above '((default . t))
754 "Non-nil means show full hierarchy when revealing a location.
755 Org-mode often shows locations in an org-mode file which might have
756 been invisible before. When this is set, the hierarchy of headings
757 above the exposed location is shown.
758 Turning this off for example for sparse trees makes them very compact.
759 Instead of t, this can also be an alist specifying this option for different
760 contexts. Valid contexts are
761 agenda when exposing an entry from the agenda
762 org-goto when using the command `org-goto' on key C-c C-j
763 occur-tree when using the command `org-occur' on key C-c /
764 tags-tree when constructing a sparse tree based on tags matches
765 link-search when exposing search matches associated with a link
766 mark-goto when exposing the jump goal of a mark
767 bookmark-jump when exposing a bookmark location
768 isearch when exiting from an incremental search
769 default default for all contexts not set explicitly"
770 :group 'org-reveal-location
771 :type org-context-choice)
773 (defcustom org-show-following-heading '((default . nil))
774 "Non-nil means show following heading when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the heading following the
777 match is shown.
778 Turning this off for example for sparse trees makes them very compact,
779 but makes it harder to edit the location of the match. In such a case,
780 use the command \\[org-reveal] to show more context.
781 Instead of t, this can also be an alist specifying this option for different
782 contexts. See `org-show-hierarchy-above' for valid contexts."
783 :group 'org-reveal-location
784 :type org-context-choice)
786 (defcustom org-show-siblings '((default . nil) (isearch t))
787 "Non-nil means show all sibling heading when revealing a location.
788 Org-mode often shows locations in an org-mode file which might have
789 been invisible before. When this is set, the sibling of the current entry
790 heading are all made visible. If `org-show-hierarchy-above' is t,
791 the same happens on each level of the hierarchy above the current entry.
793 By default this is on for the isearch context, off for all other contexts.
794 Turning this off for example for sparse trees makes them very compact,
795 but makes it harder to edit the location of the match. In such a case,
796 use the command \\[org-reveal] to show more context.
797 Instead of t, this can also be an alist specifying this option for different
798 contexts. See `org-show-hierarchy-above' for valid contexts."
799 :group 'org-reveal-location
800 :type org-context-choice)
802 (defcustom org-show-entry-below '((default . nil))
803 "Non-nil means show the entry below a headline when revealing a location.
804 Org-mode often shows locations in an org-mode file which might have
805 been invisible before. When this is set, the text below the headline that is
806 exposed is also shown.
808 By default this is off for all contexts.
809 Instead of t, this can also be an alist specifying this option for different
810 contexts. See `org-show-hierarchy-above' for valid contexts."
811 :group 'org-reveal-location
812 :type org-context-choice)
814 (defcustom org-indirect-buffer-display 'other-window
815 "How should indirect tree buffers be displayed?
816 This applies to indirect buffers created with the commands
817 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
818 Valid values are:
819 current-window Display in the current window
820 other-window Just display in another window.
821 dedicated-frame Create one new frame, and re-use it each time.
822 new-frame Make a new frame each time. Note that in this case
823 previously-made indirect buffers are kept, and you need to
824 kill these buffers yourself."
825 :group 'org-structure
826 :group 'org-agenda-windows
827 :type '(choice
828 (const :tag "In current window" current-window)
829 (const :tag "In current frame, other window" other-window)
830 (const :tag "Each time a new frame" new-frame)
831 (const :tag "One dedicated frame" dedicated-frame)))
833 (defcustom org-use-speed-commands nil
834 "Non-nil means activate single letter commands at beginning of a headline.
835 This may also be a function to test for appropriate locations where speed
836 commands should be active."
837 :group 'org-structure
838 :type '(choice
839 (const :tag "Never" nil)
840 (const :tag "At beginning of headline stars" t)
841 (function)))
843 (defcustom org-speed-commands-user nil
844 "Alist of additional speed commands.
845 This list will be checked before `org-speed-commands-default'
846 when the variable `org-use-speed-commands' is non-nil
847 and when the cursor is at the beginning of a headline.
848 The car if each entry is a string with a single letter, which must
849 be assigned to `self-insert-command' in the global map.
850 The cdr is either a command to be called interactively, a function
851 to be called, or a form to be evaluated.
852 An entry that is just a list with a single string will be interpreted
853 as a descriptive headline that will be added when listing the speed
854 commands in the Help buffer using the `?' speed command."
855 :group 'org-structure
856 :type '(repeat :value ("k" . ignore)
857 (choice :value ("k" . ignore)
858 (list :tag "Descriptive Headline" (string :tag "Headline"))
859 (cons :tag "Letter and Command"
860 (string :tag "Command letter")
861 (choice
862 (function)
863 (sexp))))))
865 (defgroup org-cycle nil
866 "Options concerning visibility cycling in Org-mode."
867 :tag "Org Cycle"
868 :group 'org-structure)
870 (defcustom org-cycle-skip-children-state-if-no-children t
871 "Non-nil means skip CHILDREN state in entries that don't have any."
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-max-level nil
876 "Maximum level which should still be subject to visibility cycling.
877 Levels higher than this will, for cycling, be treated as text, not a headline.
878 When `org-odd-levels-only' is set, a value of N in this variable actually
879 means 2N-1 stars as the limiting headline.
880 When nil, cycle all levels.
881 Note that the limiting level of cycling is also influenced by
882 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
883 `org-inlinetask-min-level' is, cycling will be limited to levels one less
884 than its value."
885 :group 'org-cycle
886 :type '(choice
887 (const :tag "No limit" nil)
888 (integer :tag "Maximum level")))
890 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
891 "Names of drawers. Drawers are not opened by cycling on the headline above.
892 Drawers only open with a TAB on the drawer line itself. A drawer looks like
893 this:
894 :DRAWERNAME:
895 .....
896 :END:
897 The drawer \"PROPERTIES\" is special for capturing properties through
898 the property API.
900 Drawers can be defined on the per-file basis with a line like:
902 #+DRAWERS: HIDDEN STATE PROPERTIES"
903 :group 'org-structure
904 :group 'org-cycle
905 :type '(repeat (string :tag "Drawer Name")))
907 (defcustom org-hide-block-startup nil
908 "Non-nil means entering Org-mode will fold all blocks.
909 This can also be set in on a per-file basis with
911 #+STARTUP: hideblocks
912 #+STARTUP: showblocks"
913 :group 'org-startup
914 :group 'org-cycle
915 :type 'boolean)
917 (defcustom org-cycle-global-at-bob nil
918 "Cycle globally if cursor is at beginning of buffer and not at a headline.
919 This makes it possible to do global cycling without having to use S-TAB or
920 \\[universal-argument] TAB. For this special case to work, the first line
921 of the buffer must not be a headline -- it may be empty or some other text.
922 When used in this way, `org-cycle-hook' is disabled temporarily to make
923 sure the cursor stays at the beginning of the buffer. When this option is
924 nil, don't do anything special at the beginning of the buffer."
925 :group 'org-cycle
926 :type 'boolean)
928 (defcustom org-cycle-level-after-item/entry-creation t
929 "Non-nil means cycle entry level or item indentation in new empty entries.
931 When the cursor is at the end of an empty headline, i.e with only stars
932 and maybe a TODO keyword, TAB will then switch the entry to become a child,
933 and then all possible ancestor states, before returning to the original state.
934 This makes data entry extremely fast: M-RET to create a new headline,
935 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
937 When the cursor is at the end of an empty plain list item, one TAB will
938 make it a subitem, two or more tabs will back up to make this an item
939 higher up in the item hierarchy."
940 :group 'org-cycle
941 :type 'boolean)
943 (defcustom org-cycle-emulate-tab t
944 "Where should `org-cycle' emulate TAB.
945 nil Never
946 white Only in completely white lines
947 whitestart Only at the beginning of lines, before the first non-white char
948 t Everywhere except in headlines
949 exc-hl-bol Everywhere except at the start of a headline
950 If TAB is used in a place where it does not emulate TAB, the current subtree
951 visibility is cycled."
952 :group 'org-cycle
953 :type '(choice (const :tag "Never" nil)
954 (const :tag "Only in completely white lines" white)
955 (const :tag "Before first char in a line" whitestart)
956 (const :tag "Everywhere except in headlines" t)
957 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
960 (defcustom org-cycle-separator-lines 2
961 "Number of empty lines needed to keep an empty line between collapsed trees.
962 If you leave an empty line between the end of a subtree and the following
963 headline, this empty line is hidden when the subtree is folded.
964 Org-mode will leave (exactly) one empty line visible if the number of
965 empty lines is equal or larger to the number given in this variable.
966 So the default 2 means at least 2 empty lines after the end of a subtree
967 are needed to produce free space between a collapsed subtree and the
968 following headline.
970 If the number is negative, and the number of empty lines is at least -N,
971 all empty lines are shown.
973 Special case: when 0, never leave empty lines in collapsed view."
974 :group 'org-cycle
975 :type 'integer)
976 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
978 (defcustom org-pre-cycle-hook nil
979 "Hook that is run before visibility cycling is happening.
980 The function(s) in this hook must accept a single argument which indicates
981 the new state that will be set right after running this hook. The
982 argument is a symbol. Before a global state change, it can have the values
983 `overview', `content', or `all'. Before a local state change, it can have
984 the values `folded', `children', or `subtree'."
985 :group 'org-cycle
986 :type 'hook)
988 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
989 org-cycle-hide-drawers
990 org-cycle-show-empty-lines
991 org-optimize-window-after-visibility-change)
992 "Hook that is run after `org-cycle' has changed the buffer visibility.
993 The function(s) in this hook must accept a single argument which indicates
994 the new state that was set by the most recent `org-cycle' command. The
995 argument is a symbol. After a global state change, it can have the values
996 `overview', `contents', or `all'. After a local state change, it can have
997 the values `folded', `children', or `subtree'."
998 :group 'org-cycle
999 :type 'hook)
1001 (defgroup org-edit-structure nil
1002 "Options concerning structure editing in Org-mode."
1003 :tag "Org Edit Structure"
1004 :group 'org-structure)
1006 (defcustom org-odd-levels-only nil
1007 "Non-nil means skip even levels and only use odd levels for the outline.
1008 This has the effect that two stars are being added/taken away in
1009 promotion/demotion commands. It also influences how levels are
1010 handled by the exporters.
1011 Changing it requires restart of `font-lock-mode' to become effective
1012 for fontification also in regions already fontified.
1013 You may also set this on a per-file basis by adding one of the following
1014 lines to the buffer:
1016 #+STARTUP: odd
1017 #+STARTUP: oddeven"
1018 :group 'org-edit-structure
1019 :group 'org-appearance
1020 :type 'boolean)
1022 (defcustom org-adapt-indentation t
1023 "Non-nil means adapt indentation to outline node level.
1025 When this variable is set, Org assumes that you write outlines by
1026 indenting text in each node to align with the headline (after the stars).
1027 The following issues are influenced by this variable:
1029 - When this is set and the *entire* text in an entry is indented, the
1030 indentation is increased by one space in a demotion command, and
1031 decreased by one in a promotion command. If any line in the entry
1032 body starts with text at column 0, indentation is not changed at all.
1034 - Property drawers and planning information is inserted indented when
1035 this variable s set. When nil, they will not be indented.
1037 - TAB indents a line relative to context. The lines below a headline
1038 will be indented when this variable is set.
1040 Note that this is all about true indentation, by adding and removing
1041 space characters. See also `org-indent.el' which does level-dependent
1042 indentation in a virtual way, i.e. at display time in Emacs."
1043 :group 'org-edit-structure
1044 :type 'boolean)
1046 (defcustom org-special-ctrl-a/e nil
1047 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1049 When t, `C-a' will bring back the cursor to the beginning of the
1050 headline text, i.e. after the stars and after a possible TODO
1051 keyword. In an item, this will be the position after bullet and
1052 check-box, if any. When the cursor is already at that position,
1053 another `C-a' will bring it to the beginning of the line.
1055 `C-e' will jump to the end of the headline, ignoring the presence
1056 of tags in the headline. A second `C-e' will then jump to the
1057 true end of the line, after any tags. This also means that, when
1058 this variable is non-nil, `C-e' also will never jump beyond the
1059 end of the heading of a folded section, i.e. not after the
1060 ellipses.
1062 When set to the symbol `reversed', the first `C-a' or `C-e' works
1063 normally, going to the true line boundary first. Only a directly
1064 following, identical keypress will bring the cursor to the
1065 special positions.
1067 This may also be a cons cell where the behavior for `C-a' and
1068 `C-e' is set separately."
1069 :group 'org-edit-structure
1070 :type '(choice
1071 (const :tag "off" nil)
1072 (const :tag "on: after stars/bullet and before tags first" t)
1073 (const :tag "reversed: true line boundary first" reversed)
1074 (cons :tag "Set C-a and C-e separately"
1075 (choice :tag "Special C-a"
1076 (const :tag "off" nil)
1077 (const :tag "on: after stars/bullet first" t)
1078 (const :tag "reversed: before stars/bullet first" reversed))
1079 (choice :tag "Special C-e"
1080 (const :tag "off" nil)
1081 (const :tag "on: before tags first" t)
1082 (const :tag "reversed: after tags first" reversed)))))
1083 (if (fboundp 'defvaralias)
1084 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1086 (defcustom org-special-ctrl-k nil
1087 "Non-nil means `C-k' will behave specially in headlines.
1088 When nil, `C-k' will call the default `kill-line' command.
1089 When t, the following will happen while the cursor is in the headline:
1091 - When the cursor is at the beginning of a headline, kill the entire
1092 line and possible the folded subtree below the line.
1093 - When in the middle of the headline text, kill the headline up to the tags.
1094 - When after the headline text, kill the tags."
1095 :group 'org-edit-structure
1096 :type 'boolean)
1098 (defcustom org-ctrl-k-protect-subtree nil
1099 "Non-nil means, do not delete a hidden subtree with C-k.
1100 When set to the symbol `error', simply throw an error when C-k is
1101 used to kill (part-of) a headline that has hidden text behind it.
1102 Any other non-nil value will result in a query to the user, if it is
1103 OK to kill that hidden subtree. When nil, kill without remorse."
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not protect hidden subtrees" nil)
1108 (const :tag "Protect hidden subtrees with a security query" t)
1109 (const :tag "Never kill a hidden subtree with C-k" error)))
1111 (defcustom org-catch-invisible-edits nil
1112 "Check if in invisible region before inserting or deleting a character.
1113 Valid values are:
1115 nil Do not check, so just do invisible edits.
1116 error Throw an error and do nothing.
1117 show Make point visible, and do the requested edit.
1118 show-and-error Make point visible, then throw an error and abort the edit.
1119 smart Make point visible, and do insertion/deletion if it is
1120 adjacent to visible text and the change feels predictable.
1121 Never delete a previously invisible character or add in the
1122 middle or right after an invisible region. Basically, this
1123 allows insertion and backward-delete right before ellipses.
1124 FIXME: maybe in this case we should not even show?"
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not check" nil)
1129 (const :tag "Throw error when trying to edit" error)
1130 (const :tag "Unhide, but do not do the edit" show-and-error)
1131 (const :tag "Show invisible part and do the edit" show)
1132 (const :tag "Be smart and do the right thing" smart)))
1134 (defcustom org-yank-folded-subtrees t
1135 "Non-nil means when yanking subtrees, fold them.
1136 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1137 it starts with a heading and all other headings in it are either children
1138 or siblings, then fold all the subtrees. However, do this only if no
1139 text after the yank would be swallowed into a folded tree by this action."
1140 :group 'org-edit-structure
1141 :type 'boolean)
1143 (defcustom org-yank-adjusted-subtrees nil
1144 "Non-nil means when yanking subtrees, adjust the level.
1145 With this setting, `org-paste-subtree' is used to insert the subtree, see
1146 this function for details."
1147 :group 'org-edit-structure
1148 :type 'boolean)
1150 (defcustom org-M-RET-may-split-line '((default . t))
1151 "Non-nil means M-RET will split the line at the cursor position.
1152 When nil, it will go to the end of the line before making a
1153 new line.
1154 You may also set this option in a different way for different
1155 contexts. Valid contexts are:
1157 headline when creating a new headline
1158 item when creating a new item
1159 table in a table field
1160 default the value to be used for all contexts not explicitly
1161 customized"
1162 :group 'org-structure
1163 :group 'org-table
1164 :type '(choice
1165 (const :tag "Always" t)
1166 (const :tag "Never" nil)
1167 (repeat :greedy t :tag "Individual contexts"
1168 (cons
1169 (choice :tag "Context"
1170 (const headline)
1171 (const item)
1172 (const table)
1173 (const default))
1174 (boolean)))))
1177 (defcustom org-insert-heading-respect-content nil
1178 "Non-nil means insert new headings after the current subtree.
1179 When nil, the new heading is created directly after the current line.
1180 The commands \\[org-insert-heading-respect-content] and
1181 \\[org-insert-todo-heading-respect-content] turn this variable on
1182 for the duration of the command."
1183 :group 'org-structure
1184 :type 'boolean)
1186 (defcustom org-blank-before-new-entry '((heading . auto)
1187 (plain-list-item . auto))
1188 "Should `org-insert-heading' leave a blank line before new heading/item?
1189 The value is an alist, with `heading' and `plain-list-item' as CAR,
1190 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1191 which case Org will look at the surrounding headings/items and try to
1192 make an intelligent decision whether to insert a blank line or not.
1194 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1195 set, the setting here is ignored and no empty line is inserted, to avoid
1196 breaking the list structure."
1197 :group 'org-edit-structure
1198 :type '(list
1199 (cons (const heading)
1200 (choice (const :tag "Never" nil)
1201 (const :tag "Always" t)
1202 (const :tag "Auto" auto)))
1203 (cons (const plain-list-item)
1204 (choice (const :tag "Never" nil)
1205 (const :tag "Always" t)
1206 (const :tag "Auto" auto)))))
1208 (defcustom org-insert-heading-hook nil
1209 "Hook being run after inserting a new heading."
1210 :group 'org-edit-structure
1211 :type 'hook)
1213 (defcustom org-enable-fixed-width-editor t
1214 "Non-nil means lines starting with \":\" are treated as fixed-width.
1215 This currently only means they are never auto-wrapped.
1216 When nil, such lines will be treated like ordinary lines.
1217 See also the QUOTE keyword."
1218 :group 'org-edit-structure
1219 :type 'boolean)
1221 (defcustom org-goto-auto-isearch t
1222 "Non-nil means typing characters in `org-goto' starts incremental search."
1223 :group 'org-edit-structure
1224 :type 'boolean)
1226 (defgroup org-sparse-trees nil
1227 "Options concerning sparse trees in Org-mode."
1228 :tag "Org Sparse Trees"
1229 :group 'org-structure)
1231 (defcustom org-highlight-sparse-tree-matches t
1232 "Non-nil means highlight all matches that define a sparse tree.
1233 The highlights will automatically disappear the next time the buffer is
1234 changed by an edit command."
1235 :group 'org-sparse-trees
1236 :type 'boolean)
1238 (defcustom org-remove-highlights-with-change t
1239 "Non-nil means any change to the buffer will remove temporary highlights.
1240 Such highlights are created by `org-occur' and `org-clock-display'.
1241 When nil, `C-c C-c needs to be used to get rid of the highlights.
1242 The highlights created by `org-preview-latex-fragment' always need
1243 `C-c C-c' to be removed."
1244 :group 'org-sparse-trees
1245 :group 'org-time
1246 :type 'boolean)
1249 (defcustom org-occur-hook '(org-first-headline-recenter)
1250 "Hook that is run after `org-occur' has constructed a sparse tree.
1251 This can be used to recenter the window to show as much of the structure
1252 as possible."
1253 :group 'org-sparse-trees
1254 :type 'hook)
1256 (defgroup org-imenu-and-speedbar nil
1257 "Options concerning imenu and speedbar in Org-mode."
1258 :tag "Org Imenu and Speedbar"
1259 :group 'org-structure)
1261 (defcustom org-imenu-depth 2
1262 "The maximum level for Imenu access to Org-mode headlines.
1263 This also applied for speedbar access."
1264 :group 'org-imenu-and-speedbar
1265 :type 'integer)
1267 (defgroup org-table nil
1268 "Options concerning tables in Org-mode."
1269 :tag "Org Table"
1270 :group 'org)
1272 (defcustom org-enable-table-editor 'optimized
1273 "Non-nil means lines starting with \"|\" are handled by the table editor.
1274 When nil, such lines will be treated like ordinary lines.
1276 When equal to the symbol `optimized', the table editor will be optimized to
1277 do the following:
1278 - Automatic overwrite mode in front of whitespace in table fields.
1279 This makes the structure of the table stay in tact as long as the edited
1280 field does not exceed the column width.
1281 - Minimize the number of realigns. Normally, the table is aligned each time
1282 TAB or RET are pressed to move to another field. With optimization this
1283 happens only if changes to a field might have changed the column width.
1284 Optimization requires replacing the functions `self-insert-command',
1285 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1286 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1287 very good at guessing when a re-align will be necessary, but you can always
1288 force one with \\[org-ctrl-c-ctrl-c].
1290 If you would like to use the optimized version in Org-mode, but the
1291 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1293 This variable can be used to turn on and off the table editor during a session,
1294 but in order to toggle optimization, a restart is required.
1296 See also the variable `org-table-auto-blank-field'."
1297 :group 'org-table
1298 :type '(choice
1299 (const :tag "off" nil)
1300 (const :tag "on" t)
1301 (const :tag "on, optimized" optimized)))
1303 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1304 (version<= emacs-version "24.1"))
1305 "Non-nil means cluster self-insert commands for undo when possible.
1306 If this is set, then, like in the Emacs command loop, 20 consecutive
1307 characters will be undone together.
1308 This is configurable, because there is some impact on typing performance."
1309 :group 'org-table
1310 :type 'boolean)
1312 (defcustom org-table-tab-recognizes-table.el t
1313 "Non-nil means TAB will automatically notice a table.el table.
1314 When it sees such a table, it moves point into it and - if necessary -
1315 calls `table-recognize-table'."
1316 :group 'org-table-editing
1317 :type 'boolean)
1319 (defgroup org-link nil
1320 "Options concerning links in Org-mode."
1321 :tag "Org Link"
1322 :group 'org)
1324 (defvar org-link-abbrev-alist-local nil
1325 "Buffer-local version of `org-link-abbrev-alist', which see.
1326 The value of this is taken from the #+LINK lines.")
1327 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1329 (defcustom org-link-abbrev-alist nil
1330 "Alist of link abbreviations.
1331 The car of each element is a string, to be replaced at the start of a link.
1332 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1333 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1335 [[linkkey:tag][description]]
1337 The 'linkkey' must be a word word, starting with a letter, followed
1338 by letters, numbers, '-' or '_'.
1340 If REPLACE is a string, the tag will simply be appended to create the link.
1341 If the string contains \"%s\", the tag will be inserted there. If the string
1342 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1343 at that point (see the function `url-hexify-string'). If the string contains
1344 the specifier \"%(my-function)\", then the custom function `my-function' will
1345 be invoked: this function takes the tag as its only argument and must return
1346 a string.
1348 REPLACE may also be a function that will be called with the tag as the
1349 only argument to create the link, which should be returned as a string.
1351 See the manual for examples."
1352 :group 'org-link
1353 :type '(repeat
1354 (cons
1355 (string :tag "Protocol")
1356 (choice
1357 (string :tag "Format")
1358 (function)))))
1360 (defcustom org-descriptive-links t
1361 "Non-nil means Org will display descriptive links.
1362 E.g. [[http://orgmode.org][Org website]] will be displayed as
1363 \"Org Website\", hiding the link itself and just displaying its
1364 description. When set to `nil', Org will display the full links
1365 literally.
1367 You can interactively set the value of this variable by calling
1368 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1369 :group 'org-link
1370 :type 'boolean)
1372 (defcustom org-link-file-path-type 'adaptive
1373 "How the path name in file links should be stored.
1374 Valid values are:
1376 relative Relative to the current directory, i.e. the directory of the file
1377 into which the link is being inserted.
1378 absolute Absolute path, if possible with ~ for home directory.
1379 noabbrev Absolute path, no abbreviation of home directory.
1380 adaptive Use relative path for files in the current directory and sub-
1381 directories of it. For other files, use an absolute path."
1382 :group 'org-link
1383 :type '(choice
1384 (const relative)
1385 (const absolute)
1386 (const noabbrev)
1387 (const adaptive)))
1389 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1390 "Types of links that should be activated in Org-mode files.
1391 This is a list of symbols, each leading to the activation of a certain link
1392 type. In principle, it does not hurt to turn on most link types - there may
1393 be a small gain when turning off unused link types. The types are:
1395 bracket The recommended [[link][description]] or [[link]] links with hiding.
1396 angle Links in angular brackets that may contain whitespace like
1397 <bbdb:Carsten Dominik>.
1398 plain Plain links in normal text, no whitespace, like http://google.com.
1399 radio Text that is matched by a radio target, see manual for details.
1400 tag Tag settings in a headline (link to tag search).
1401 date Time stamps (link to calendar).
1402 footnote Footnote labels.
1404 Changing this variable requires a restart of Emacs to become effective."
1405 :group 'org-link
1406 :type '(set :greedy t
1407 (const :tag "Double bracket links" bracket)
1408 (const :tag "Angular bracket links" angle)
1409 (const :tag "Plain text links" plain)
1410 (const :tag "Radio target matches" radio)
1411 (const :tag "Tags" tag)
1412 (const :tag "Timestamps" date)
1413 (const :tag "Footnotes" footnote)))
1415 (defcustom org-make-link-description-function nil
1416 "Function to use for generating link descriptions from links.
1417 When nil, the link location will be used. This function must take
1418 two parameters: the first one is the link, the second one is the
1419 description generated by `org-insert-link'. The function should
1420 return the description to use."
1421 :group 'org-link
1422 :type 'function)
1424 (defgroup org-link-store nil
1425 "Options concerning storing links in Org-mode."
1426 :tag "Org Store Link"
1427 :group 'org-link)
1429 (defcustom org-url-hexify-p t
1430 "When non-nil, hexify URL when creating a link."
1431 :type 'boolean
1432 :version "24.3"
1433 :group 'org-link-store)
1435 (defcustom org-email-link-description-format "Email %c: %.30s"
1436 "Format of the description part of a link to an email or usenet message.
1437 The following %-escapes will be replaced by corresponding information:
1439 %F full \"From\" field
1440 %f name, taken from \"From\" field, address if no name
1441 %T full \"To\" field
1442 %t first name in \"To\" field, address if no name
1443 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1444 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1445 %s subject
1446 %d date
1447 %m message-id.
1449 You may use normal field width specification between the % and the letter.
1450 This is for example useful to limit the length of the subject.
1452 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1453 :group 'org-link-store
1454 :type 'string)
1456 (defcustom org-from-is-user-regexp
1457 (let (r1 r2)
1458 (when (and user-mail-address (not (string= user-mail-address "")))
1459 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1460 (when (and user-full-name (not (string= user-full-name "")))
1461 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1462 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1463 "Regexp matched against the \"From:\" header of an email or usenet message.
1464 It should match if the message is from the user him/herself."
1465 :group 'org-link-store
1466 :type 'regexp)
1468 (defcustom org-context-in-file-links t
1469 "Non-nil means file links from `org-store-link' contain context.
1470 A search string will be added to the file name with :: as separator and
1471 used to find the context when the link is activated by the command
1472 `org-open-at-point'. When this option is t, the entire active region
1473 will be placed in the search string of the file link. If set to a
1474 positive integer, only the first n lines of context will be stored.
1476 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1477 negates this setting for the duration of the command."
1478 :group 'org-link-store
1479 :type '(choice boolean integer))
1481 (defcustom org-keep-stored-link-after-insertion nil
1482 "Non-nil means keep link in list for entire session.
1484 The command `org-store-link' adds a link pointing to the current
1485 location to an internal list. These links accumulate during a session.
1486 The command `org-insert-link' can be used to insert links into any
1487 Org-mode file (offering completion for all stored links). When this
1488 option is nil, every link which has been inserted once using \\[org-insert-link]
1489 will be removed from the list, to make completing the unused links
1490 more efficient."
1491 :group 'org-link-store
1492 :type 'boolean)
1494 (defgroup org-link-follow nil
1495 "Options concerning following links in Org-mode."
1496 :tag "Org Follow Link"
1497 :group 'org-link)
1499 (defcustom org-link-translation-function nil
1500 "Function to translate links with different syntax to Org syntax.
1501 This can be used to translate links created for example by the Planner
1502 or emacs-wiki packages to Org syntax.
1503 The function must accept two parameters, a TYPE containing the link
1504 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1505 which is everything after the link protocol. It should return a cons
1506 with possibly modified values of type and path.
1507 Org contains a function for this, so if you set this variable to
1508 `org-translate-link-from-planner', you should be able follow many
1509 links created by planner."
1510 :group 'org-link-follow
1511 :type 'function)
1513 (defcustom org-follow-link-hook nil
1514 "Hook that is run after a link has been followed."
1515 :group 'org-link-follow
1516 :type 'hook)
1518 (defcustom org-tab-follows-link nil
1519 "Non-nil means on links TAB will follow the link.
1520 Needs to be set before org.el is loaded.
1521 This really should not be used, it does not make sense, and the
1522 implementation is bad."
1523 :group 'org-link-follow
1524 :type 'boolean)
1526 (defcustom org-return-follows-link nil
1527 "Non-nil means on links RET will follow the link."
1528 :group 'org-link-follow
1529 :type 'boolean)
1531 (defcustom org-mouse-1-follows-link
1532 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1533 "Non-nil means mouse-1 on a link will follow the link.
1534 A longer mouse click will still set point. Does not work on XEmacs.
1535 Needs to be set before org.el is loaded."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mark-ring-length 4
1540 "Number of different positions to be recorded in the ring.
1541 Changing this requires a restart of Emacs to work correctly."
1542 :group 'org-link-follow
1543 :type 'integer)
1545 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1546 "Non-nil means internal links in Org files must exactly match a headline.
1547 When nil, the link search tries to match a phrase with all words
1548 in the search text."
1549 :group 'org-link-follow
1550 :version "24.1"
1551 :type '(choice
1552 (const :tag "Use fuzzy text search" nil)
1553 (const :tag "Match only exact headline" t)
1554 (const :tag "Match exact headline or query to create it"
1555 query-to-create)))
1557 (defcustom org-link-frame-setup
1558 '((vm . vm-visit-folder-other-frame)
1559 (vm-imap . vm-visit-imap-folder-other-frame)
1560 (gnus . org-gnus-no-new-news)
1561 (file . find-file-other-window)
1562 (wl . wl-other-frame))
1563 "Setup the frame configuration for following links.
1564 When following a link with Emacs, it may often be useful to display
1565 this link in another window or frame. This variable can be used to
1566 set this up for the different types of links.
1567 For VM, use any of
1568 `vm-visit-folder'
1569 `vm-visit-folder-other-window'
1570 `vm-visit-folder-other-frame'
1571 For Gnus, use any of
1572 `gnus'
1573 `gnus-other-frame'
1574 `org-gnus-no-new-news'
1575 For FILE, use any of
1576 `find-file'
1577 `find-file-other-window'
1578 `find-file-other-frame'
1579 For Wanderlust use any of
1580 `wl'
1581 `wl-other-frame'
1582 For the calendar, use the variable `calendar-setup'.
1583 For BBDB, it is currently only possible to display the matches in
1584 another window."
1585 :group 'org-link-follow
1586 :type '(list
1587 (cons (const vm)
1588 (choice
1589 (const vm-visit-folder)
1590 (const vm-visit-folder-other-window)
1591 (const vm-visit-folder-other-frame)))
1592 (cons (const gnus)
1593 (choice
1594 (const gnus)
1595 (const gnus-other-frame)
1596 (const org-gnus-no-new-news)))
1597 (cons (const file)
1598 (choice
1599 (const find-file)
1600 (const find-file-other-window)
1601 (const find-file-other-frame)))
1602 (cons (const wl)
1603 (choice
1604 (const wl)
1605 (const wl-other-frame)))))
1607 (defcustom org-display-internal-link-with-indirect-buffer nil
1608 "Non-nil means use indirect buffer to display infile links.
1609 Activating internal links (from one location in a file to another location
1610 in the same file) normally just jumps to the location. When the link is
1611 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1612 is displayed in
1613 another window. When this option is set, the other window actually displays
1614 an indirect buffer clone of the current buffer, to avoid any visibility
1615 changes to the current buffer."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-open-non-existing-files nil
1620 "Non-nil means `org-open-file' will open non-existing files.
1621 When nil, an error will be generated.
1622 This variable applies only to external applications because they
1623 might choke on non-existing files. If the link is to a file that
1624 will be opened in Emacs, the variable is ignored."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-open-directory-means-index-dot-org nil
1629 "Non-nil means a link to a directory really means to index.org.
1630 When nil, following a directory link will run dired or open a finder/explorer
1631 window on that directory."
1632 :group 'org-link-follow
1633 :type 'boolean)
1635 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1636 "Function and arguments to call for following mailto links.
1637 This is a list with the first element being a Lisp function, and the
1638 remaining elements being arguments to the function. In string arguments,
1639 %a will be replaced by the address, and %s will be replaced by the subject
1640 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1641 :group 'org-link-follow
1642 :type '(choice
1643 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1644 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1645 (const :tag "message-mail" (message-mail "%a" "%s"))
1646 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1648 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1649 "Non-nil means ask for confirmation before executing shell links.
1650 Shell links can be dangerous: just think about a link
1652 [[shell:rm -rf ~/*][Google Search]]
1654 This link would show up in your Org-mode document as \"Google Search\",
1655 but really it would remove your entire home directory.
1656 Therefore we advise against setting this variable to nil.
1657 Just change it to `y-or-n-p' if you want to confirm with a
1658 single keystroke rather than having to type \"yes\"."
1659 :group 'org-link-follow
1660 :type '(choice
1661 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1662 (const :tag "with y-or-n (faster)" y-or-n-p)
1663 (const :tag "no confirmation (dangerous)" nil)))
1664 (put 'org-confirm-shell-link-function
1665 'safe-local-variable
1666 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1668 (defcustom org-confirm-shell-link-not-regexp ""
1669 "A regexp to skip confirmation for shell links."
1670 :group 'org-link-follow
1671 :version "24.1"
1672 :type 'regexp)
1674 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1675 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1676 Elisp links can be dangerous: just think about a link
1678 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1680 This link would show up in your Org-mode document as \"Google Search\",
1681 but really it would remove your entire home directory.
1682 Therefore we advise against setting this variable to nil.
1683 Just change it to `y-or-n-p' if you want to confirm with a
1684 single keystroke rather than having to type \"yes\"."
1685 :group 'org-link-follow
1686 :type '(choice
1687 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1688 (const :tag "with y-or-n (faster)" y-or-n-p)
1689 (const :tag "no confirmation (dangerous)" nil)))
1690 (put 'org-confirm-shell-link-function
1691 'safe-local-variable
1692 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1694 (defcustom org-confirm-elisp-link-not-regexp ""
1695 "A regexp to skip confirmation for Elisp links."
1696 :group 'org-link-follow
1697 :version "24.1"
1698 :type 'regexp)
1700 (defconst org-file-apps-defaults-gnu
1701 '((remote . emacs)
1702 (system . mailcap)
1703 (t . mailcap))
1704 "Default file applications on a UNIX or GNU/Linux system.
1705 See `org-file-apps'.")
1707 (defconst org-file-apps-defaults-macosx
1708 '((remote . emacs)
1709 (t . "open %s")
1710 (system . "open %s")
1711 ("ps.gz" . "gv %s")
1712 ("eps.gz" . "gv %s")
1713 ("dvi" . "xdvi %s")
1714 ("fig" . "xfig %s"))
1715 "Default file applications on a MacOS X system.
1716 The system \"open\" is known as a default, but we use X11 applications
1717 for some files for which the OS does not have a good default.
1718 See `org-file-apps'.")
1720 (defconst org-file-apps-defaults-windowsnt
1721 (list
1722 '(remote . emacs)
1723 (cons t
1724 (list (if (featurep 'xemacs)
1725 'mswindows-shell-execute
1726 'w32-shell-execute)
1727 "open" 'file))
1728 (cons 'system
1729 (list (if (featurep 'xemacs)
1730 'mswindows-shell-execute
1731 'w32-shell-execute)
1732 "open" 'file)))
1733 "Default file applications on a Windows NT system.
1734 The system \"open\" is used for most files.
1735 See `org-file-apps'.")
1737 (defcustom org-file-apps
1739 (auto-mode . emacs)
1740 ("\\.mm\\'" . default)
1741 ("\\.x?html?\\'" . default)
1742 ("\\.pdf\\'" . default)
1744 "External applications for opening `file:path' items in a document.
1745 Org-mode uses system defaults for different file types, but
1746 you can use this variable to set the application for a given file
1747 extension. The entries in this list are cons cells where the car identifies
1748 files and the cdr the corresponding command. Possible values for the
1749 file identifier are
1750 \"string\" A string as a file identifier can be interpreted in different
1751 ways, depending on its contents:
1753 - Alphanumeric characters only:
1754 Match links with this file extension.
1755 Example: (\"pdf\" . \"evince %s\")
1756 to open PDFs with evince.
1758 - Regular expression: Match links where the
1759 filename matches the regexp. If you want to
1760 use groups here, use shy groups.
1762 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1763 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1764 to open *.html and *.xhtml with firefox.
1766 - Regular expression which contains (non-shy) groups:
1767 Match links where the whole link, including \"::\", and
1768 anything after that, matches the regexp.
1769 In a custom command string, %1, %2, etc. are replaced with
1770 the parts of the link that were matched by the groups.
1771 For backwards compatibility, if a command string is given
1772 that does not use any of the group matches, this case is
1773 handled identically to the second one (i.e. match against
1774 file name only).
1775 In a custom lisp form, you can access the group matches with
1776 (match-string n link).
1778 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1779 to open [[file:document.pdf::5]] with evince at page 5.
1781 `directory' Matches a directory
1782 `remote' Matches a remote file, accessible through tramp or efs.
1783 Remote files most likely should be visited through Emacs
1784 because external applications cannot handle such paths.
1785 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1786 so all files Emacs knows how to handle. Using this with
1787 command `emacs' will open most files in Emacs. Beware that this
1788 will also open html files inside Emacs, unless you add
1789 (\"html\" . default) to the list as well.
1790 t Default for files not matched by any of the other options.
1791 `system' The system command to open files, like `open' on Windows
1792 and Mac OS X, and mailcap under GNU/Linux. This is the command
1793 that will be selected if you call `C-c C-o' with a double
1794 \\[universal-argument] \\[universal-argument] prefix.
1796 Possible values for the command are:
1797 `emacs' The file will be visited by the current Emacs process.
1798 `default' Use the default application for this file type, which is the
1799 association for t in the list, most likely in the system-specific
1800 part.
1801 This can be used to overrule an unwanted setting in the
1802 system-specific variable.
1803 `system' Use the system command for opening files, like \"open\".
1804 This command is specified by the entry whose car is `system'.
1805 Most likely, the system-specific version of this variable
1806 does define this command, but you can overrule/replace it
1807 here.
1808 string A command to be executed by a shell; %s will be replaced
1809 by the path to the file.
1810 sexp A Lisp form which will be evaluated. The file path will
1811 be available in the Lisp variable `file'.
1812 For more examples, see the system specific constants
1813 `org-file-apps-defaults-macosx'
1814 `org-file-apps-defaults-windowsnt'
1815 `org-file-apps-defaults-gnu'."
1816 :group 'org-link-follow
1817 :type '(repeat
1818 (cons (choice :value ""
1819 (string :tag "Extension")
1820 (const :tag "System command to open files" system)
1821 (const :tag "Default for unrecognized files" t)
1822 (const :tag "Remote file" remote)
1823 (const :tag "Links to a directory" directory)
1824 (const :tag "Any files that have Emacs modes"
1825 auto-mode))
1826 (choice :value ""
1827 (const :tag "Visit with Emacs" emacs)
1828 (const :tag "Use default" default)
1829 (const :tag "Use the system command" system)
1830 (string :tag "Command")
1831 (sexp :tag "Lisp form")))))
1833 (defcustom org-doi-server-url "http://dx.doi.org/"
1834 "The URL of the DOI server."
1835 :type 'string
1836 :version "24.3"
1837 :group 'org-link-follow)
1839 (defgroup org-refile nil
1840 "Options concerning refiling entries in Org-mode."
1841 :tag "Org Refile"
1842 :group 'org)
1844 (defcustom org-directory "~/org"
1845 "Directory with org files.
1846 This is just a default location to look for Org files. There is no need
1847 at all to put your files into this directory. It is only used in the
1848 following situations:
1850 1. When a capture template specifies a target file that is not an
1851 absolute path. The path will then be interpreted relative to
1852 `org-directory'
1853 2. When a capture note is filed away in an interactive way (when exiting the
1854 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1855 with `org-directory' as the default path."
1856 :group 'org-refile
1857 :group 'org-remember
1858 :group 'org-capture
1859 :type 'directory)
1861 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1862 "Default target for storing notes.
1863 Used as a fall back file for org-remember.el and org-capture.el, for
1864 templates that do not specify a target file."
1865 :group 'org-refile
1866 :group 'org-remember
1867 :group 'org-capture
1868 :type '(choice
1869 (const :tag "Default from remember-data-file" nil)
1870 file))
1872 (defcustom org-goto-interface 'outline
1873 "The default interface to be used for `org-goto'.
1874 Allowed values are:
1875 outline The interface shows an outline of the relevant file
1876 and the correct heading is found by moving through
1877 the outline or by searching with incremental search.
1878 outline-path-completion Headlines in the current buffer are offered via
1879 completion. This is the interface also used by
1880 the refile command."
1881 :group 'org-refile
1882 :type '(choice
1883 (const :tag "Outline" outline)
1884 (const :tag "Outline-path-completion" outline-path-completion)))
1886 (defcustom org-goto-max-level 5
1887 "Maximum target level when running `org-goto' with refile interface."
1888 :group 'org-refile
1889 :type 'integer)
1891 (defcustom org-reverse-note-order nil
1892 "Non-nil means store new notes at the beginning of a file or entry.
1893 When nil, new notes will be filed to the end of a file or entry.
1894 This can also be a list with cons cells of regular expressions that
1895 are matched against file names, and values."
1896 :group 'org-remember
1897 :group 'org-capture
1898 :group 'org-refile
1899 :type '(choice
1900 (const :tag "Reverse always" t)
1901 (const :tag "Reverse never" nil)
1902 (repeat :tag "By file name regexp"
1903 (cons regexp boolean))))
1905 (defcustom org-log-refile nil
1906 "Information to record when a task is refiled.
1908 Possible values are:
1910 nil Don't add anything
1911 time Add a time stamp to the task
1912 note Prompt for a note and add it with template `org-log-note-headings'
1914 This option can also be set with on a per-file-basis with
1916 #+STARTUP: nologrefile
1917 #+STARTUP: logrefile
1918 #+STARTUP: lognoterefile
1920 You can have local logging settings for a subtree by setting the LOGGING
1921 property to one or more of these keywords.
1923 When bulk-refiling from the agenda, the value `note' is forbidden and
1924 will temporarily be changed to `time'."
1925 :group 'org-refile
1926 :group 'org-progress
1927 :version "24.1"
1928 :type '(choice
1929 (const :tag "No logging" nil)
1930 (const :tag "Record timestamp" time)
1931 (const :tag "Record timestamp with note." note)))
1933 (defcustom org-refile-targets nil
1934 "Targets for refiling entries with \\[org-refile].
1935 This is a list of cons cells. Each cell contains:
1936 - a specification of the files to be considered, either a list of files,
1937 or a symbol whose function or variable value will be used to retrieve
1938 a file name or a list of file names. If you use `org-agenda-files' for
1939 that, all agenda files will be scanned for targets. Nil means consider
1940 headings in the current buffer.
1941 - A specification of how to find candidate refile targets. This may be
1942 any of:
1943 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1944 This tag has to be present in all target headlines, inheritance will
1945 not be considered.
1946 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1947 todo keyword.
1948 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1949 headlines that are refiling targets.
1950 - a cons cell (:level . N). Any headline of level N is considered a target.
1951 Note that, when `org-odd-levels-only' is set, level corresponds to
1952 order in hierarchy, not to the number of stars.
1953 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1954 Note that, when `org-odd-levels-only' is set, level corresponds to
1955 order in hierarchy, not to the number of stars.
1957 Each element of this list generates a set of possible targets.
1958 The union of these sets is presented (with completion) to
1959 the user by `org-refile'.
1961 You can set the variable `org-refile-target-verify-function' to a function
1962 to verify each headline found by the simple criteria above.
1964 When this variable is nil, all top-level headlines in the current buffer
1965 are used, equivalent to the value `((nil . (:level . 1))'."
1966 :group 'org-refile
1967 :type '(repeat
1968 (cons
1969 (choice :value org-agenda-files
1970 (const :tag "All agenda files" org-agenda-files)
1971 (const :tag "Current buffer" nil)
1972 (function) (variable) (file))
1973 (choice :tag "Identify target headline by"
1974 (cons :tag "Specific tag" (const :value :tag) (string))
1975 (cons :tag "TODO keyword" (const :value :todo) (string))
1976 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1977 (cons :tag "Level number" (const :value :level) (integer))
1978 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1980 (defcustom org-refile-target-verify-function nil
1981 "Function to verify if the headline at point should be a refile target.
1982 The function will be called without arguments, with point at the
1983 beginning of the headline. It should return t and leave point
1984 where it is if the headline is a valid target for refiling.
1986 If the target should not be selected, the function must return nil.
1987 In addition to this, it may move point to a place from where the search
1988 should be continued. For example, the function may decide that the entire
1989 subtree of the current entry should be excluded and move point to the end
1990 of the subtree."
1991 :group 'org-refile
1992 :type 'function)
1994 (defcustom org-refile-use-cache nil
1995 "Non-nil means cache refile targets to speed up the process.
1996 The cache for a particular file will be updated automatically when
1997 the buffer has been killed, or when any of the marker used for flagging
1998 refile targets no longer points at a live buffer.
1999 If you have added new entries to a buffer that might themselves be targets,
2000 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2001 find that easier, `C-u C-u C-u C-c C-w'."
2002 :group 'org-refile
2003 :version "24.1"
2004 :type 'boolean)
2006 (defcustom org-refile-use-outline-path nil
2007 "Non-nil means provide refile targets as paths.
2008 So a level 3 headline will be available as level1/level2/level3.
2010 When the value is `file', also include the file name (without directory)
2011 into the path. In this case, you can also stop the completion after
2012 the file name, to get entries inserted as top level in the file.
2014 When `full-file-path', include the full file path."
2015 :group 'org-refile
2016 :type '(choice
2017 (const :tag "Not" nil)
2018 (const :tag "Yes" t)
2019 (const :tag "Start with file name" file)
2020 (const :tag "Start with full file path" full-file-path)))
2022 (defcustom org-outline-path-complete-in-steps t
2023 "Non-nil means complete the outline path in hierarchical steps.
2024 When Org-mode uses the refile interface to select an outline path
2025 \(see variable `org-refile-use-outline-path'), the completion of
2026 the path can be done is a single go, or if can be done in steps down
2027 the headline hierarchy. Going in steps is probably the best if you
2028 do not use a special completion package like `ido' or `icicles'.
2029 However, when using these packages, going in one step can be very
2030 fast, while still showing the whole path to the entry."
2031 :group 'org-refile
2032 :type 'boolean)
2034 (defcustom org-refile-allow-creating-parent-nodes nil
2035 "Non-nil means allow to create new nodes as refile targets.
2036 New nodes are then created by adding \"/new node name\" to the completion
2037 of an existing node. When the value of this variable is `confirm',
2038 new node creation must be confirmed by the user (recommended)
2039 When nil, the completion must match an existing entry.
2041 Note that, if the new heading is not seen by the criteria
2042 listed in `org-refile-targets', multiple instances of the same
2043 heading would be created by trying again to file under the new
2044 heading."
2045 :group 'org-refile
2046 :type '(choice
2047 (const :tag "Never" nil)
2048 (const :tag "Always" t)
2049 (const :tag "Prompt for confirmation" confirm)))
2051 (defcustom org-refile-active-region-within-subtree nil
2052 "Non-nil means also refile active region within a subtree.
2054 By default `org-refile' doesn't allow refiling regions if they
2055 don't contain a set of subtrees, but it might be convenient to
2056 do so sometimes: in that case, the first line of the region is
2057 converted to a headline before refiling."
2058 :group 'org-refile
2059 :version "24.1"
2060 :type 'boolean)
2062 (defgroup org-todo nil
2063 "Options concerning TODO items in Org-mode."
2064 :tag "Org TODO"
2065 :group 'org)
2067 (defgroup org-progress nil
2068 "Options concerning Progress logging in Org-mode."
2069 :tag "Org Progress"
2070 :group 'org-time)
2072 (defvar org-todo-interpretation-widgets
2073 '((:tag "Sequence (cycling hits every state)" sequence)
2074 (:tag "Type (cycling directly to DONE)" type))
2075 "The available interpretation symbols for customizing `org-todo-keywords'.
2076 Interested libraries should add to this list.")
2078 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2079 "List of TODO entry keyword sequences and their interpretation.
2080 \\<org-mode-map>This is a list of sequences.
2082 Each sequence starts with a symbol, either `sequence' or `type',
2083 indicating if the keywords should be interpreted as a sequence of
2084 action steps, or as different types of TODO items. The first
2085 keywords are states requiring action - these states will select a headline
2086 for inclusion into the global TODO list Org-mode produces. If one of
2087 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2088 signify that no further action is necessary. If \"|\" is not found,
2089 the last keyword is treated as the only DONE state of the sequence.
2091 The command \\[org-todo] cycles an entry through these states, and one
2092 additional state where no keyword is present. For details about this
2093 cycling, see the manual.
2095 TODO keywords and interpretation can also be set on a per-file basis with
2096 the special #+SEQ_TODO and #+TYP_TODO lines.
2098 Each keyword can optionally specify a character for fast state selection
2099 \(in combination with the variable `org-use-fast-todo-selection')
2100 and specifiers for state change logging, using the same syntax that
2101 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2102 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2103 indicates to record a time stamp each time this state is selected.
2105 Each keyword may also specify if a timestamp or a note should be
2106 recorded when entering or leaving the state, by adding additional
2107 characters in the parenthesis after the keyword. This looks like this:
2108 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2109 record only the time of the state change. With X and Y being either
2110 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2111 Y when leaving the state if and only if the *target* state does not
2112 define X. You may omit any of the fast-selection key or X or /Y,
2113 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2115 For backward compatibility, this variable may also be just a list
2116 of keywords. In this case the interpretation (sequence or type) will be
2117 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2118 :group 'org-todo
2119 :group 'org-keywords
2120 :type '(choice
2121 (repeat :tag "Old syntax, just keywords"
2122 (string :tag "Keyword"))
2123 (repeat :tag "New syntax"
2124 (cons
2125 (choice
2126 :tag "Interpretation"
2127 ;;Quick and dirty way to see
2128 ;;`org-todo-interpretations'. This takes the
2129 ;;place of item arguments
2130 :convert-widget
2131 (lambda (widget)
2132 (widget-put widget
2133 :args (mapcar
2134 #'(lambda (x)
2135 (widget-convert
2136 (cons 'const x)))
2137 org-todo-interpretation-widgets))
2138 widget))
2139 (repeat
2140 (string :tag "Keyword"))))))
2142 (defvar org-todo-keywords-1 nil
2143 "All TODO and DONE keywords active in a buffer.")
2144 (make-variable-buffer-local 'org-todo-keywords-1)
2145 (defvar org-todo-keywords-for-agenda nil)
2146 (defvar org-done-keywords-for-agenda nil)
2147 (defvar org-drawers-for-agenda nil)
2148 (defvar org-todo-keyword-alist-for-agenda nil)
2149 (defvar org-tag-alist-for-agenda nil)
2150 (defvar org-agenda-contributing-files nil)
2151 (defvar org-not-done-keywords nil)
2152 (make-variable-buffer-local 'org-not-done-keywords)
2153 (defvar org-done-keywords nil)
2154 (make-variable-buffer-local 'org-done-keywords)
2155 (defvar org-todo-heads nil)
2156 (make-variable-buffer-local 'org-todo-heads)
2157 (defvar org-todo-sets nil)
2158 (make-variable-buffer-local 'org-todo-sets)
2159 (defvar org-todo-log-states nil)
2160 (make-variable-buffer-local 'org-todo-log-states)
2161 (defvar org-todo-kwd-alist nil)
2162 (make-variable-buffer-local 'org-todo-kwd-alist)
2163 (defvar org-todo-key-alist nil)
2164 (make-variable-buffer-local 'org-todo-key-alist)
2165 (defvar org-todo-key-trigger nil)
2166 (make-variable-buffer-local 'org-todo-key-trigger)
2168 (defcustom org-todo-interpretation 'sequence
2169 "Controls how TODO keywords are interpreted.
2170 This variable is in principle obsolete and is only used for
2171 backward compatibility, if the interpretation of todo keywords is
2172 not given already in `org-todo-keywords'. See that variable for
2173 more information."
2174 :group 'org-todo
2175 :group 'org-keywords
2176 :type '(choice (const sequence)
2177 (const type)))
2179 (defcustom org-use-fast-todo-selection t
2180 "Non-nil means use the fast todo selection scheme with C-c C-t.
2181 This variable describes if and under what circumstances the cycling
2182 mechanism for TODO keywords will be replaced by a single-key, direct
2183 selection scheme.
2185 When nil, fast selection is never used.
2187 When the symbol `prefix', it will be used when `org-todo' is called
2188 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2189 `C-u t' in an agenda buffer.
2191 When t, fast selection is used by default. In this case, the prefix
2192 argument forces cycling instead.
2194 In all cases, the special interface is only used if access keys have
2195 actually been assigned by the user, i.e. if keywords in the configuration
2196 are followed by a letter in parenthesis, like TODO(t)."
2197 :group 'org-todo
2198 :type '(choice
2199 (const :tag "Never" nil)
2200 (const :tag "By default" t)
2201 (const :tag "Only with C-u C-c C-t" prefix)))
2203 (defcustom org-provide-todo-statistics t
2204 "Non-nil means update todo statistics after insert and toggle.
2205 ALL-HEADLINES means update todo statistics by including headlines
2206 with no TODO keyword as well, counting them as not done.
2207 A list of TODO keywords means the same, but skip keywords that are
2208 not in this list.
2210 When this is set, todo statistics is updated in the parent of the
2211 current entry each time a todo state is changed."
2212 :group 'org-todo
2213 :type '(choice
2214 (const :tag "Yes, only for TODO entries" t)
2215 (const :tag "Yes, including all entries" 'all-headlines)
2216 (repeat :tag "Yes, for TODOs in this list"
2217 (string :tag "TODO keyword"))
2218 (other :tag "No TODO statistics" nil)))
2220 (defcustom org-hierarchical-todo-statistics t
2221 "Non-nil means TODO statistics covers just direct children.
2222 When nil, all entries in the subtree are considered.
2223 This has only an effect if `org-provide-todo-statistics' is set.
2224 To set this to nil for only a single subtree, use a COOKIE_DATA
2225 property and include the word \"recursive\" into the value."
2226 :group 'org-todo
2227 :type 'boolean)
2229 (defcustom org-after-todo-state-change-hook nil
2230 "Hook which is run after the state of a TODO item was changed.
2231 The new state (a string with a TODO keyword, or nil) is available in the
2232 Lisp variable `org-state'."
2233 :group 'org-todo
2234 :type 'hook)
2236 (defvar org-blocker-hook nil
2237 "Hook for functions that are allowed to block a state change.
2239 Each function gets as its single argument a property list, see
2240 `org-trigger-hook' for more information about this list.
2242 If any of the functions in this hook returns nil, the state change
2243 is blocked.")
2245 (defvar org-trigger-hook nil
2246 "Hook for functions that are triggered by a state change.
2248 Each function gets as its single argument a property list with at least
2249 the following elements:
2251 (:type type-of-change :position pos-at-entry-start
2252 :from old-state :to new-state)
2254 Depending on the type, more properties may be present.
2256 This mechanism is currently implemented for:
2258 TODO state changes
2259 ------------------
2260 :type todo-state-change
2261 :from previous state (keyword as a string), or nil, or a symbol
2262 'todo' or 'done', to indicate the general type of state.
2263 :to new state, like in :from")
2265 (defcustom org-enforce-todo-dependencies nil
2266 "Non-nil means undone TODO entries will block switching the parent to DONE.
2267 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2268 be blocked if any prior sibling is not yet done.
2269 Finally, if the parent is blocked because of ordered siblings of its own,
2270 the child will also be blocked."
2271 :set (lambda (var val)
2272 (set var val)
2273 (if val
2274 (add-hook 'org-blocker-hook
2275 'org-block-todo-from-children-or-siblings-or-parent)
2276 (remove-hook 'org-blocker-hook
2277 'org-block-todo-from-children-or-siblings-or-parent)))
2278 :group 'org-todo
2279 :type 'boolean)
2281 (defcustom org-enforce-todo-checkbox-dependencies nil
2282 "Non-nil means unchecked boxes will block switching the parent to DONE.
2283 When this is nil, checkboxes have no influence on switching TODO states.
2284 When non-nil, you first need to check off all check boxes before the TODO
2285 entry can be switched to DONE.
2286 This variable needs to be set before org.el is loaded, and you need to
2287 restart Emacs after a change to make the change effective. The only way
2288 to change is while Emacs is running is through the customize interface."
2289 :set (lambda (var val)
2290 (set var val)
2291 (if val
2292 (add-hook 'org-blocker-hook
2293 'org-block-todo-from-checkboxes)
2294 (remove-hook 'org-blocker-hook
2295 'org-block-todo-from-checkboxes)))
2296 :group 'org-todo
2297 :type 'boolean)
2299 (defcustom org-treat-insert-todo-heading-as-state-change nil
2300 "Non-nil means inserting a TODO heading is treated as state change.
2301 So when the command \\[org-insert-todo-heading] is used, state change
2302 logging will apply if appropriate. When nil, the new TODO item will
2303 be inserted directly, and no logging will take place."
2304 :group 'org-todo
2305 :type 'boolean)
2307 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2308 "Non-nil means switching TODO states with S-cursor counts as state change.
2309 This is the default behavior. However, setting this to nil allows a
2310 convenient way to select a TODO state and bypass any logging associated
2311 with that."
2312 :group 'org-todo
2313 :type 'boolean)
2315 (defcustom org-todo-state-tags-triggers nil
2316 "Tag changes that should be triggered by TODO state changes.
2317 This is a list. Each entry is
2319 (state-change (tag . flag) .......)
2321 State-change can be a string with a state, and empty string to indicate the
2322 state that has no TODO keyword, or it can be one of the symbols `todo'
2323 or `done', meaning any not-done or done state, respectively."
2324 :group 'org-todo
2325 :group 'org-tags
2326 :type '(repeat
2327 (cons (choice :tag "When changing to"
2328 (const :tag "Not-done state" todo)
2329 (const :tag "Done state" done)
2330 (string :tag "State"))
2331 (repeat
2332 (cons :tag "Tag action"
2333 (string :tag "Tag")
2334 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2336 (defcustom org-log-done nil
2337 "Information to record when a task moves to the DONE state.
2339 Possible values are:
2341 nil Don't add anything, just change the keyword
2342 time Add a time stamp to the task
2343 note Prompt for a note and add it with template `org-log-note-headings'
2345 This option can also be set with on a per-file-basis with
2347 #+STARTUP: nologdone
2348 #+STARTUP: logdone
2349 #+STARTUP: lognotedone
2351 You can have local logging settings for a subtree by setting the LOGGING
2352 property to one or more of these keywords."
2353 :group 'org-todo
2354 :group 'org-progress
2355 :type '(choice
2356 (const :tag "No logging" nil)
2357 (const :tag "Record CLOSED timestamp" time)
2358 (const :tag "Record CLOSED timestamp with note." note)))
2360 ;; Normalize old uses of org-log-done.
2361 (cond
2362 ((eq org-log-done t) (setq org-log-done 'time))
2363 ((and (listp org-log-done) (memq 'done org-log-done))
2364 (setq org-log-done 'note)))
2366 (defcustom org-log-reschedule nil
2367 "Information to record when the scheduling date of a tasks is modified.
2369 Possible values are:
2371 nil Don't add anything, just change the date
2372 time Add a time stamp to the task
2373 note Prompt for a note and add it with template `org-log-note-headings'
2375 This option can also be set with on a per-file-basis with
2377 #+STARTUP: nologreschedule
2378 #+STARTUP: logreschedule
2379 #+STARTUP: lognotereschedule"
2380 :group 'org-todo
2381 :group 'org-progress
2382 :type '(choice
2383 (const :tag "No logging" nil)
2384 (const :tag "Record timestamp" time)
2385 (const :tag "Record timestamp with note." note)))
2387 (defcustom org-log-redeadline nil
2388 "Information to record when the deadline 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: nologredeadline
2399 #+STARTUP: logredeadline
2400 #+STARTUP: lognoteredeadline
2402 You can have local logging settings for a subtree by setting the LOGGING
2403 property to one or more of these keywords."
2404 :group 'org-todo
2405 :group 'org-progress
2406 :type '(choice
2407 (const :tag "No logging" nil)
2408 (const :tag "Record timestamp" time)
2409 (const :tag "Record timestamp with note." note)))
2411 (defcustom org-log-note-clock-out nil
2412 "Non-nil means record a note when clocking out of an item.
2413 This can also be configured on a per-file basis by adding one of
2414 the following lines anywhere in the buffer:
2416 #+STARTUP: lognoteclock-out
2417 #+STARTUP: nolognoteclock-out"
2418 :group 'org-todo
2419 :group 'org-progress
2420 :type 'boolean)
2422 (defcustom org-log-done-with-time t
2423 "Non-nil means the CLOSED time stamp will contain date and time.
2424 When nil, only the date will be recorded."
2425 :group 'org-progress
2426 :type 'boolean)
2428 (defcustom org-log-note-headings
2429 '((done . "CLOSING NOTE %t")
2430 (state . "State %-12s from %-12S %t")
2431 (note . "Note taken on %t")
2432 (reschedule . "Rescheduled from %S on %t")
2433 (delschedule . "Not scheduled, was %S on %t")
2434 (redeadline . "New deadline from %S on %t")
2435 (deldeadline . "Removed deadline, was %S on %t")
2436 (refile . "Refiled on %t")
2437 (clock-out . ""))
2438 "Headings for notes added to entries.
2439 The value is an alist, with the car being a symbol indicating the note
2440 context, and the cdr is the heading to be used. The heading may also be the
2441 empty string.
2442 %t in the heading will be replaced by a time stamp.
2443 %T will be an active time stamp instead the default inactive one
2444 %d will be replaced by a short-format time stamp.
2445 %D will be replaced by an active short-format time stamp.
2446 %s will be replaced by the new TODO state, in double quotes.
2447 %S will be replaced by the old TODO state, in double quotes.
2448 %u will be replaced by the user name.
2449 %U will be replaced by the full user name.
2451 In fact, it is not a good idea to change the `state' entry, because
2452 agenda log mode depends on the format of these entries."
2453 :group 'org-todo
2454 :group 'org-progress
2455 :type '(list :greedy t
2456 (cons (const :tag "Heading when closing an item" done) string)
2457 (cons (const :tag
2458 "Heading when changing todo state (todo sequence only)"
2459 state) string)
2460 (cons (const :tag "Heading when just taking a note" note) string)
2461 (cons (const :tag "Heading when clocking out" clock-out) string)
2462 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2463 (cons (const :tag "Heading when rescheduling" reschedule) string)
2464 (cons (const :tag "Heading when changing deadline" redeadline) string)
2465 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2466 (cons (const :tag "Heading when refiling" refile) string)))
2468 (unless (assq 'note org-log-note-headings)
2469 (push '(note . "%t") org-log-note-headings))
2471 (defcustom org-log-into-drawer nil
2472 "Non-nil means insert state change notes and time stamps into a drawer.
2473 When nil, state changes notes will be inserted after the headline and
2474 any scheduling and clock lines, but not inside a drawer.
2476 The value of this variable should be the name of the drawer to use.
2477 LOGBOOK is proposed as the default drawer for this purpose, you can
2478 also set this to a string to define the drawer of your choice.
2480 A value of t is also allowed, representing \"LOGBOOK\".
2482 If this variable is set, `org-log-state-notes-insert-after-drawers'
2483 will be ignored.
2485 You can set the property LOG_INTO_DRAWER to overrule this setting for
2486 a subtree."
2487 :group 'org-todo
2488 :group 'org-progress
2489 :type '(choice
2490 (const :tag "Not into a drawer" nil)
2491 (const :tag "LOGBOOK" t)
2492 (string :tag "Other")))
2494 (if (fboundp 'defvaralias)
2495 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2497 (defun org-log-into-drawer ()
2498 "Return the value of `org-log-into-drawer', but let properties overrule.
2499 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2500 used instead of the default value."
2501 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2502 (cond
2503 ((or (not p) (equal p "nil")) org-log-into-drawer)
2504 ((equal p "t") "LOGBOOK")
2505 (t p))))
2507 (defcustom org-log-state-notes-insert-after-drawers nil
2508 "Non-nil means insert state change notes after any drawers in entry.
2509 Only the drawers that *immediately* follow the headline and the
2510 deadline/scheduled line are skipped.
2511 When nil, insert notes right after the heading and perhaps the line
2512 with deadline/scheduling if present.
2514 This variable will have no effect if `org-log-into-drawer' is
2515 set."
2516 :group 'org-todo
2517 :group 'org-progress
2518 :type 'boolean)
2520 (defcustom org-log-states-order-reversed t
2521 "Non-nil means the latest state note will be directly after heading.
2522 When nil, the state change notes will be ordered according to time."
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type 'boolean)
2527 (defcustom org-todo-repeat-to-state nil
2528 "The TODO state to which a repeater should return the repeating task.
2529 By default this is the first task in a TODO sequence, or the previous state
2530 in a TODO_TYP set. But you can specify another task here.
2531 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2532 :group 'org-todo
2533 :version "24.1"
2534 :type '(choice (const :tag "Head of sequence" nil)
2535 (string :tag "Specific state")))
2537 (defcustom org-log-repeat 'time
2538 "Non-nil means record moving through the DONE state when triggering repeat.
2539 An auto-repeating task is immediately switched back to TODO when
2540 marked DONE. If you are not logging state changes (by adding \"@\"
2541 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2542 record a closing note, there will be no record of the task moving
2543 through DONE. This variable forces taking a note anyway.
2545 nil Don't force a record
2546 time Record a time stamp
2547 note Prompt for a note and add it with template `org-log-note-headings'
2549 This option can also be set with on a per-file-basis with
2551 #+STARTUP: nologrepeat
2552 #+STARTUP: logrepeat
2553 #+STARTUP: lognoterepeat
2555 You can have local logging settings for a subtree by setting the LOGGING
2556 property to one or more of these keywords."
2557 :group 'org-todo
2558 :group 'org-progress
2559 :type '(choice
2560 (const :tag "Don't force a record" nil)
2561 (const :tag "Force recording the DONE state" time)
2562 (const :tag "Force recording a note with the DONE state" note)))
2565 (defgroup org-priorities nil
2566 "Priorities in Org-mode."
2567 :tag "Org Priorities"
2568 :group 'org-todo)
2570 (defcustom org-enable-priority-commands t
2571 "Non-nil means priority commands are active.
2572 When nil, these commands will be disabled, so that you never accidentally
2573 set a priority."
2574 :group 'org-priorities
2575 :type 'boolean)
2577 (defcustom org-highest-priority ?A
2578 "The highest priority of TODO items. A character like ?A, ?B etc.
2579 Must have a smaller ASCII number than `org-lowest-priority'."
2580 :group 'org-priorities
2581 :type 'character)
2583 (defcustom org-lowest-priority ?C
2584 "The lowest priority of TODO items. A character like ?A, ?B etc.
2585 Must have a larger ASCII number than `org-highest-priority'."
2586 :group 'org-priorities
2587 :type 'character)
2589 (defcustom org-default-priority ?B
2590 "The default priority of TODO items.
2591 This is the priority an item gets if no explicit priority is given.
2592 When starting to cycle on an empty priority the first step in the cycle
2593 depends on `org-priority-start-cycle-with-default'. The resulting first
2594 step priority must not exceed the range from `org-highest-priority' to
2595 `org-lowest-priority' which means that `org-default-priority' has to be
2596 in this range exclusive or inclusive the range boundaries. Else the
2597 first step refuses to set the default and the second will fall back
2598 to (depending on the command used) the highest or lowest priority."
2599 :group 'org-priorities
2600 :type 'character)
2602 (defcustom org-priority-start-cycle-with-default t
2603 "Non-nil means start with default priority when starting to cycle.
2604 When this is nil, the first step in the cycle will be (depending on the
2605 command used) one higher or lower than the default priority.
2606 See also `org-default-priority'."
2607 :group 'org-priorities
2608 :type 'boolean)
2610 (defcustom org-get-priority-function nil
2611 "Function to extract the priority from a string.
2612 The string is normally the headline. If this is nil Org computes the
2613 priority from the priority cookie like [#A] in the headline. It returns
2614 an integer, increasing by 1000 for each priority level.
2615 The user can set a different function here, which should take a string
2616 as an argument and return the numeric priority."
2617 :group 'org-priorities
2618 :version "24.1"
2619 :type 'function)
2621 (defgroup org-time nil
2622 "Options concerning time stamps and deadlines in Org-mode."
2623 :tag "Org Time"
2624 :group 'org)
2626 (defcustom org-insert-labeled-timestamps-at-point nil
2627 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2628 When nil, these labeled time stamps are forces into the second line of an
2629 entry, just after the headline. When scheduling from the global TODO list,
2630 the time stamp will always be forced into the second line."
2631 :group 'org-time
2632 :type 'boolean)
2634 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2635 "Formats for `format-time-string' which are used for time stamps.
2636 It is not recommended to change this constant.")
2638 (defcustom org-time-stamp-rounding-minutes '(0 5)
2639 "Number of minutes to round time stamps to.
2640 These are two values, the first applies when first creating a time stamp.
2641 The second applies when changing it with the commands `S-up' and `S-down'.
2642 When changing the time stamp, this means that it will change in steps
2643 of N minutes, as given by the second value.
2645 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2646 numbers should be factors of 60, so for example 5, 10, 15.
2648 When this is larger than 1, you can still force an exact time stamp by using
2649 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2650 and by using a prefix arg to `S-up/down' to specify the exact number
2651 of minutes to shift."
2652 :group 'org-time
2653 :get #'(lambda (var) ; Make sure both elements are there
2654 (if (integerp (default-value var))
2655 (list (default-value var) 5)
2656 (default-value var)))
2657 :type '(list
2658 (integer :tag "when inserting times")
2659 (integer :tag "when modifying times")))
2661 ;; Normalize old customizations of this variable.
2662 (when (integerp org-time-stamp-rounding-minutes)
2663 (setq org-time-stamp-rounding-minutes
2664 (list org-time-stamp-rounding-minutes
2665 org-time-stamp-rounding-minutes)))
2667 (defcustom org-display-custom-times nil
2668 "Non-nil means overlay custom formats over all time stamps.
2669 The formats are defined through the variable `org-time-stamp-custom-formats'.
2670 To turn this on on a per-file basis, insert anywhere in the file:
2671 #+STARTUP: customtime"
2672 :group 'org-time
2673 :set 'set-default
2674 :type 'sexp)
2675 (make-variable-buffer-local 'org-display-custom-times)
2677 (defcustom org-time-stamp-custom-formats
2678 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2679 "Custom formats for time stamps. See `format-time-string' for the syntax.
2680 These are overlaid over the default ISO format if the variable
2681 `org-display-custom-times' is set. Time like %H:%M should be at the
2682 end of the second format. The custom formats are also honored by export
2683 commands, if custom time display is turned on at the time of export."
2684 :group 'org-time
2685 :type 'sexp)
2687 (defun org-time-stamp-format (&optional long inactive)
2688 "Get the right format for a time string."
2689 (let ((f (if long (cdr org-time-stamp-formats)
2690 (car org-time-stamp-formats))))
2691 (if inactive
2692 (concat "[" (substring f 1 -1) "]")
2693 f)))
2695 (defcustom org-time-clocksum-format "%d:%02d"
2696 "The format string used when creating CLOCKSUM lines.
2697 This is also used when org-mode generates a time duration."
2698 :group 'org-time
2699 :type 'string)
2701 (defcustom org-time-clocksum-use-fractional nil
2702 "If non-nil, \\[org-clock-display] uses fractional times.
2703 org-mode generates a time duration."
2704 :group 'org-time
2705 :type 'boolean)
2707 (defcustom org-time-clocksum-fractional-format "%.2f"
2708 "The format string used when creating CLOCKSUM lines, or when
2709 org-mode generates a time duration."
2710 :group 'org-time
2711 :type 'string)
2713 (defcustom org-deadline-warning-days 14
2714 "No. of days before expiration during which a deadline becomes active.
2715 This variable governs the display in sparse trees and in the agenda.
2716 When 0 or negative, it means use this number (the absolute value of it)
2717 even if a deadline has a different individual lead time specified.
2719 Custom commands can set this variable in the options section."
2720 :group 'org-time
2721 :group 'org-agenda-daily/weekly
2722 :type 'integer)
2724 (defcustom org-read-date-prefer-future t
2725 "Non-nil means assume future for incomplete date input from user.
2726 This affects the following situations:
2727 1. The user gives a month but not a year.
2728 For example, if it is April and you enter \"feb 2\", this will be read
2729 as Feb 2, *next* year. \"May 5\", however, will be this year.
2730 2. The user gives a day, but no month.
2731 For example, if today is the 15th, and you enter \"3\", Org-mode will
2732 read this as the third of *next* month. However, if you enter \"17\",
2733 it will be considered as *this* month.
2735 If you set this variable to the symbol `time', then also the following
2736 will work:
2738 3. If the user gives a time.
2739 If the time is before now, it will be interpreted as tomorrow.
2741 Currently none of this works for ISO week specifications.
2743 When this option is nil, the current day, month and year will always be
2744 used as defaults.
2746 See also `org-agenda-jump-prefer-future'."
2747 :group 'org-time
2748 :type '(choice
2749 (const :tag "Never" nil)
2750 (const :tag "Check month and day" t)
2751 (const :tag "Check month, day, and time" time)))
2753 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2754 "Should the agenda jump command prefer the future for incomplete dates?
2755 The default is to do the same as configured in `org-read-date-prefer-future'.
2756 But you can also set a deviating value here.
2757 This may t or nil, or the symbol `org-read-date-prefer-future'."
2758 :group 'org-agenda
2759 :group 'org-time
2760 :version "24.1"
2761 :type '(choice
2762 (const :tag "Use org-read-date-prefer-future"
2763 org-read-date-prefer-future)
2764 (const :tag "Never" nil)
2765 (const :tag "Always" t)))
2767 (defcustom org-read-date-force-compatible-dates t
2768 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2770 Depending on the system Emacs is running on, certain dates cannot
2771 be represented with the type used internally to represent time.
2772 Dates between 1970-1-1 and 2038-1-1 can always be represented
2773 correctly. Some systems allow for earlier dates, some for later,
2774 some for both. One way to find out it to insert any date into an
2775 Org buffer, putting the cursor on the year and hitting S-up and
2776 S-down to test the range.
2778 When this variable is set to t, the date/time prompt will not let
2779 you specify dates outside the 1970-2037 range, so it is certain that
2780 these dates will work in whatever version of Emacs you are
2781 running, and also that you can move a file from one Emacs implementation
2782 to another. WHenever Org is forcing the year for you, it will display
2783 a message and beep.
2785 When this variable is nil, Org will check if the date is
2786 representable in the specific Emacs implementation you are using.
2787 If not, it will force a year, usually the current year, and beep
2788 to remind you. Currently this setting is not recommended because
2789 the likelihood that you will open your Org files in an Emacs that
2790 has limited date range is not negligible.
2792 A workaround for this problem is to use diary sexp dates for time
2793 stamps outside of this range."
2794 :group 'org-time
2795 :version "24.1"
2796 :type 'boolean)
2798 (defcustom org-read-date-display-live t
2799 "Non-nil means display current interpretation of date prompt live.
2800 This display will be in an overlay, in the minibuffer."
2801 :group 'org-time
2802 :type 'boolean)
2804 (defcustom org-read-date-popup-calendar t
2805 "Non-nil means pop up a calendar when prompting for a date.
2806 In the calendar, the date can be selected with mouse-1. However, the
2807 minibuffer will also be active, and you can simply enter the date as well.
2808 When nil, only the minibuffer will be available."
2809 :group 'org-time
2810 :type 'boolean)
2811 (if (fboundp 'defvaralias)
2812 (defvaralias 'org-popup-calendar-for-date-prompt
2813 'org-read-date-popup-calendar))
2815 (defcustom org-read-date-minibuffer-setup-hook nil
2816 "Hook to be used to set up keys for the date/time interface.
2817 Add key definitions to `minibuffer-local-map', which will be a temporary
2818 copy."
2819 :group 'org-time
2820 :type 'hook)
2822 (defcustom org-extend-today-until 0
2823 "The hour when your day really ends. Must be an integer.
2824 This has influence for the following applications:
2825 - When switching the agenda to \"today\". It it is still earlier than
2826 the time given here, the day recognized as TODAY is actually yesterday.
2827 - When a date is read from the user and it is still before the time given
2828 here, the current date and time will be assumed to be yesterday, 23:59.
2829 Also, timestamps inserted in capture templates follow this rule.
2831 IMPORTANT: This is a feature whose implementation is and likely will
2832 remain incomplete. Really, it is only here because past midnight seems to
2833 be the favorite working time of John Wiegley :-)"
2834 :group 'org-time
2835 :type 'integer)
2837 (defcustom org-use-effective-time nil
2838 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2839 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2840 \"effective time\" of any timestamps between midnight and 8am will be
2841 23:59 of the previous day."
2842 :group 'org-time
2843 :version "24.1"
2844 :type 'boolean)
2846 (defcustom org-edit-timestamp-down-means-later nil
2847 "Non-nil means S-down will increase the time in a time stamp.
2848 When nil, S-up will increase."
2849 :group 'org-time
2850 :type 'boolean)
2852 (defcustom org-calendar-follow-timestamp-change t
2853 "Non-nil means make the calendar window follow timestamp changes.
2854 When a timestamp is modified and the calendar window is visible, it will be
2855 moved to the new date."
2856 :group 'org-time
2857 :type 'boolean)
2859 (defgroup org-tags nil
2860 "Options concerning tags in Org-mode."
2861 :tag "Org Tags"
2862 :group 'org)
2864 (defcustom org-tag-alist nil
2865 "List of tags allowed in Org-mode files.
2866 When this list is nil, Org-mode will base TAG input on what is already in the
2867 buffer.
2868 The value of this variable is an alist, the car of each entry must be a
2869 keyword as a string, the cdr may be a character that is used to select
2870 that tag through the fast-tag-selection interface.
2871 See the manual for details."
2872 :group 'org-tags
2873 :type '(repeat
2874 (choice
2875 (cons (string :tag "Tag name")
2876 (character :tag "Access char"))
2877 (list :tag "Start radio group"
2878 (const :startgroup)
2879 (option (string :tag "Group description")))
2880 (list :tag "End radio group"
2881 (const :endgroup)
2882 (option (string :tag "Group description")))
2883 (const :tag "New line" (:newline)))))
2885 (defcustom org-tag-persistent-alist nil
2886 "List of tags that will always appear in all Org-mode files.
2887 This is in addition to any in buffer settings or customizations
2888 of `org-tag-alist'.
2889 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2890 The value of this variable is an alist, the car of each entry must be a
2891 keyword as a string, the cdr may be a character that is used to select
2892 that tag through the fast-tag-selection interface.
2893 See the manual for details.
2894 To disable these tags on a per-file basis, insert anywhere in the file:
2895 #+STARTUP: noptag"
2896 :group 'org-tags
2897 :type '(repeat
2898 (choice
2899 (cons (string :tag "Tag name")
2900 (character :tag "Access char"))
2901 (const :tag "Start radio group" (:startgroup))
2902 (const :tag "End radio group" (:endgroup))
2903 (const :tag "New line" (:newline)))))
2905 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2906 "If non-nil, always offer completion for all tags of all agenda files.
2907 Instead of customizing this variable directly, you might want to
2908 set it locally for capture buffers, because there no list of
2909 tags in that file can be created dynamically (there are none).
2911 (add-hook 'org-capture-mode-hook
2912 (lambda ()
2913 (set (make-local-variable
2914 'org-complete-tags-always-offer-all-agenda-tags)
2915 t)))"
2916 :group 'org-tags
2917 :version "24.1"
2918 :type 'boolean)
2920 (defvar org-file-tags nil
2921 "List of tags that can be inherited by all entries in the file.
2922 The tags will be inherited if the variable `org-use-tag-inheritance'
2923 says they should be.
2924 This variable is populated from #+FILETAGS lines.")
2926 (defcustom org-use-fast-tag-selection 'auto
2927 "Non-nil means use fast tag selection scheme.
2928 This is a special interface to select and deselect tags with single keys.
2929 When nil, fast selection is never used.
2930 When the symbol `auto', fast selection is used if and only if selection
2931 characters for tags have been configured, either through the variable
2932 `org-tag-alist' or through a #+TAGS line in the buffer.
2933 When t, fast selection is always used and selection keys are assigned
2934 automatically if necessary."
2935 :group 'org-tags
2936 :type '(choice
2937 (const :tag "Always" t)
2938 (const :tag "Never" nil)
2939 (const :tag "When selection characters are configured" 'auto)))
2941 (defcustom org-fast-tag-selection-single-key nil
2942 "Non-nil means fast tag selection exits after first change.
2943 When nil, you have to press RET to exit it.
2944 During fast tag selection, you can toggle this flag with `C-c'.
2945 This variable can also have the value `expert'. In this case, the window
2946 displaying the tags menu is not even shown, until you press C-c again."
2947 :group 'org-tags
2948 :type '(choice
2949 (const :tag "No" nil)
2950 (const :tag "Yes" t)
2951 (const :tag "Expert" expert)))
2953 (defvar org-fast-tag-selection-include-todo nil
2954 "Non-nil means fast tags selection interface will also offer TODO states.
2955 This is an undocumented feature, you should not rely on it.")
2957 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2958 "The column to which tags should be indented in a headline.
2959 If this number is positive, it specifies the column. If it is negative,
2960 it means that the tags should be flushright to that column. For example,
2961 -80 works well for a normal 80 character screen.
2962 When 0, place tags directly after headline text, with only one space in
2963 between."
2964 :group 'org-tags
2965 :type 'integer)
2967 (defcustom org-auto-align-tags t
2968 "Non-nil keeps tags aligned when modifying headlines.
2969 Some operations (i.e. demoting) change the length of a headline and
2970 therefore shift the tags around. With this option turned on, after
2971 each such operation the tags are again aligned to `org-tags-column'."
2972 :group 'org-tags
2973 :type 'boolean)
2975 (defcustom org-use-tag-inheritance t
2976 "Non-nil means tags in levels apply also for sublevels.
2977 When nil, only the tags directly given in a specific line apply there.
2978 This may also be a list of tags that should be inherited, or a regexp that
2979 matches tags that should be inherited. Additional control is possible
2980 with the variable `org-tags-exclude-from-inheritance' which gives an
2981 explicit list of tags to be excluded from inheritance., even if the value of
2982 `org-use-tag-inheritance' would select it for inheritance.
2984 If this option is t, a match early-on in a tree can lead to a large
2985 number of matches in the subtree when constructing the agenda or creating
2986 a sparse tree. If you only want to see the first match in a tree during
2987 a search, check out the variable `org-tags-match-list-sublevels'."
2988 :group 'org-tags
2989 :type '(choice
2990 (const :tag "Not" nil)
2991 (const :tag "Always" t)
2992 (repeat :tag "Specific tags" (string :tag "Tag"))
2993 (regexp :tag "Tags matched by regexp")))
2995 (defcustom org-tags-exclude-from-inheritance nil
2996 "List of tags that should never be inherited.
2997 This is a way to exclude a few tags from inheritance. For way to do
2998 the opposite, to actively allow inheritance for selected tags,
2999 see the variable `org-use-tag-inheritance'."
3000 :group 'org-tags
3001 :type '(repeat (string :tag "Tag")))
3003 (defun org-tag-inherit-p (tag)
3004 "Check if TAG is one that should be inherited."
3005 (cond
3006 ((member tag org-tags-exclude-from-inheritance) nil)
3007 ((eq org-use-tag-inheritance t) t)
3008 ((not org-use-tag-inheritance) nil)
3009 ((stringp org-use-tag-inheritance)
3010 (string-match org-use-tag-inheritance tag))
3011 ((listp org-use-tag-inheritance)
3012 (member tag org-use-tag-inheritance))
3013 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3015 (defcustom org-tags-match-list-sublevels t
3016 "Non-nil means list also sublevels of headlines matching a search.
3017 This variable applies to tags/property searches, and also to stuck
3018 projects because this search is based on a tags match as well.
3020 When set to the symbol `indented', sublevels are indented with
3021 leading dots.
3023 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3024 the sublevels of a headline matching a tag search often also match
3025 the same search. Listing all of them can create very long lists.
3026 Setting this variable to nil causes subtrees of a match to be skipped.
3028 This variable is semi-obsolete and probably should always be true. It
3029 is better to limit inheritance to certain tags using the variables
3030 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3031 :group 'org-tags
3032 :type '(choice
3033 (const :tag "No, don't list them" nil)
3034 (const :tag "Yes, do list them" t)
3035 (const :tag "List them, indented with leading dots" indented)))
3037 (defcustom org-tags-sort-function nil
3038 "When set, tags are sorted using this function as a comparator."
3039 :group 'org-tags
3040 :type '(choice
3041 (const :tag "No sorting" nil)
3042 (const :tag "Alphabetical" string<)
3043 (const :tag "Reverse alphabetical" string>)
3044 (function :tag "Custom function" nil)))
3046 (defvar org-tags-history nil
3047 "History of minibuffer reads for tags.")
3048 (defvar org-last-tags-completion-table nil
3049 "The last used completion table for tags.")
3050 (defvar org-after-tags-change-hook nil
3051 "Hook that is run after the tags in a line have changed.")
3053 (defgroup org-properties nil
3054 "Options concerning properties in Org-mode."
3055 :tag "Org Properties"
3056 :group 'org)
3058 (defcustom org-property-format "%-10s %s"
3059 "How property key/value pairs should be formatted by `indent-line'.
3060 When `indent-line' hits a property definition, it will format the line
3061 according to this format, mainly to make sure that the values are
3062 lined-up with respect to each other."
3063 :group 'org-properties
3064 :type 'string)
3066 (defcustom org-properties-postprocess-alist nil
3067 "Alist of properties and functions to adjust inserted values.
3068 Elements of this alist must be of the form
3070 ([string] [function])
3072 where [string] must be a property name and [function] must be a
3073 lambda expression: this lambda expression must take one argument,
3074 the value to adjust, and return the new value as a string.
3076 For example, this element will allow the property \"Remaining\"
3077 to be updated wrt the relation between the \"Effort\" property
3078 and the clock summary:
3080 ((\"Remaining\" (lambda(value)
3081 (let ((clocksum (org-clock-sum-current-item))
3082 (effort (org-duration-string-to-minutes
3083 (org-entry-get (point) \"Effort\"))))
3084 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3085 :group 'org-properties
3086 :version "24.1"
3087 :type '(alist :key-type (string :tag "Property")
3088 :value-type (function :tag "Function")))
3090 (defcustom org-use-property-inheritance nil
3091 "Non-nil means properties apply also for sublevels.
3093 This setting is chiefly used during property searches. Turning it on can
3094 cause significant overhead when doing a search, which is why it is not
3095 on by default.
3097 When nil, only the properties directly given in the current entry count.
3098 When t, every property is inherited. The value may also be a list of
3099 properties that should have inheritance, or a regular expression matching
3100 properties that should be inherited.
3102 However, note that some special properties use inheritance under special
3103 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3104 and the properties ending in \"_ALL\" when they are used as descriptor
3105 for valid values of a property.
3107 Note for programmers:
3108 When querying an entry with `org-entry-get', you can control if inheritance
3109 should be used. By default, `org-entry-get' looks only at the local
3110 properties. You can request inheritance by setting the inherit argument
3111 to t (to force inheritance) or to `selective' (to respect the setting
3112 in this variable)."
3113 :group 'org-properties
3114 :type '(choice
3115 (const :tag "Not" nil)
3116 (const :tag "Always" t)
3117 (repeat :tag "Specific properties" (string :tag "Property"))
3118 (regexp :tag "Properties matched by regexp")))
3120 (defun org-property-inherit-p (property)
3121 "Check if PROPERTY is one that should be inherited."
3122 (cond
3123 ((eq org-use-property-inheritance t) t)
3124 ((not org-use-property-inheritance) nil)
3125 ((stringp org-use-property-inheritance)
3126 (string-match org-use-property-inheritance property))
3127 ((listp org-use-property-inheritance)
3128 (member property org-use-property-inheritance))
3129 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3131 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3132 "The default column format, if no other format has been defined.
3133 This variable can be set on the per-file basis by inserting a line
3135 #+COLUMNS: %25ITEM ....."
3136 :group 'org-properties
3137 :type 'string)
3139 (defcustom org-columns-ellipses ".."
3140 "The ellipses to be used when a field in column view is truncated.
3141 When this is the empty string, as many characters as possible are shown,
3142 but then there will be no visual indication that the field has been truncated.
3143 When this is a string of length N, the last N characters of a truncated
3144 field are replaced by this string. If the column is narrower than the
3145 ellipses string, only part of the ellipses string will be shown."
3146 :group 'org-properties
3147 :type 'string)
3149 (defcustom org-columns-modify-value-for-display-function nil
3150 "Function that modifies values for display in column view.
3151 For example, it can be used to cut out a certain part from a time stamp.
3152 The function must take 2 arguments:
3154 column-title The title of the column (*not* the property name)
3155 value The value that should be modified.
3157 The function should return the value that should be displayed,
3158 or nil if the normal value should be used."
3159 :group 'org-properties
3160 :type 'function)
3162 (defcustom org-effort-property "Effort"
3163 "The property that is being used to keep track of effort estimates.
3164 Effort estimates given in this property need to have the format H:MM."
3165 :group 'org-properties
3166 :group 'org-progress
3167 :type '(string :tag "Property"))
3169 (defconst org-global-properties-fixed
3170 '(("VISIBILITY_ALL" . "folded children content all")
3171 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3172 "List of property/value pairs that can be inherited by any entry.
3174 These are fixed values, for the preset properties. The user variable
3175 that can be used to add to this list is `org-global-properties'.
3177 The entries in this list are cons cells where the car is a property
3178 name and cdr is a string with the value. If the value represents
3179 multiple items like an \"_ALL\" property, separate the items by
3180 spaces.")
3182 (defcustom org-global-properties nil
3183 "List of property/value pairs that can be inherited by any entry.
3185 This list will be combined with the constant `org-global-properties-fixed'.
3187 The entries in this list are cons cells where the car is a property
3188 name and cdr is a string with the value.
3190 You can set buffer-local values for the same purpose in the variable
3191 `org-file-properties' this by adding lines like
3193 #+PROPERTY: NAME VALUE"
3194 :group 'org-properties
3195 :type '(repeat
3196 (cons (string :tag "Property")
3197 (string :tag "Value"))))
3199 (defvar org-file-properties nil
3200 "List of property/value pairs that can be inherited by any entry.
3201 Valid for the current buffer.
3202 This variable is populated from #+PROPERTY lines.")
3203 (make-variable-buffer-local 'org-file-properties)
3205 (defgroup org-agenda nil
3206 "Options concerning agenda views in Org-mode."
3207 :tag "Org Agenda"
3208 :group 'org)
3210 (defvar org-category nil
3211 "Variable used by org files to set a category for agenda display.
3212 Such files should use a file variable to set it, for example
3214 # -*- mode: org; org-category: \"ELisp\"
3216 or contain a special line
3218 #+CATEGORY: ELisp
3220 If the file does not specify a category, then file's base name
3221 is used instead.")
3222 (make-variable-buffer-local 'org-category)
3223 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3225 (defcustom org-agenda-files nil
3226 "The files to be used for agenda display.
3227 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3228 \\[org-remove-file]. You can also use customize to edit the list.
3230 If an entry is a directory, all files in that directory that are matched by
3231 `org-agenda-file-regexp' will be part of the file list.
3233 If the value of the variable is not a list but a single file name, then
3234 the list of agenda files is actually stored and maintained in that file, one
3235 agenda file per line. In this file paths can be given relative to
3236 `org-directory'. Tilde expansion and environment variable substitution
3237 are also made."
3238 :group 'org-agenda
3239 :type '(choice
3240 (repeat :tag "List of files and directories" file)
3241 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3243 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3244 "Regular expression to match files for `org-agenda-files'.
3245 If any element in the list in that variable contains a directory instead
3246 of a normal file, all files in that directory that are matched by this
3247 regular expression will be included."
3248 :group 'org-agenda
3249 :type 'regexp)
3251 (defcustom org-agenda-text-search-extra-files nil
3252 "List of extra files to be searched by text search commands.
3253 These files will be search in addition to the agenda files by the
3254 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3255 Note that these files will only be searched for text search commands,
3256 not for the other agenda views like todo lists, tag searches or the weekly
3257 agenda. This variable is intended to list notes and possibly archive files
3258 that should also be searched by these two commands.
3259 In fact, if the first element in the list is the symbol `agenda-archives',
3260 than all archive files of all agenda files will be added to the search
3261 scope."
3262 :group 'org-agenda
3263 :type '(set :greedy t
3264 (const :tag "Agenda Archives" agenda-archives)
3265 (repeat :inline t (file))))
3267 (if (fboundp 'defvaralias)
3268 (defvaralias 'org-agenda-multi-occur-extra-files
3269 'org-agenda-text-search-extra-files))
3271 (defcustom org-agenda-skip-unavailable-files nil
3272 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3273 A nil value means to remove them, after a query, from the list."
3274 :group 'org-agenda
3275 :type 'boolean)
3277 (defcustom org-calendar-to-agenda-key [?c]
3278 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3279 The command `org-calendar-goto-agenda' will be bound to this key. The
3280 default is the character `c' because then `c' can be used to switch back and
3281 forth between agenda and calendar."
3282 :group 'org-agenda
3283 :type 'sexp)
3285 (defcustom org-calendar-insert-diary-entry-key [?i]
3286 "The key to be installed in `calendar-mode-map' for adding diary entries.
3287 This option is irrelevant until `org-agenda-diary-file' has been configured
3288 to point to an Org-mode file. When that is the case, the command
3289 `org-agenda-diary-entry' will be bound to the key given here, by default
3290 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3291 if you want to continue doing this, you need to change this to a different
3292 key."
3293 :group 'org-agenda
3294 :type 'sexp)
3296 (defcustom org-agenda-diary-file 'diary-file
3297 "File to which to add new entries with the `i' key in agenda and calendar.
3298 When this is the symbol `diary-file', the functionality in the Emacs
3299 calendar will be used to add entries to the `diary-file'. But when this
3300 points to a file, `org-agenda-diary-entry' will be used instead."
3301 :group 'org-agenda
3302 :type '(choice
3303 (const :tag "The standard Emacs diary file" diary-file)
3304 (file :tag "Special Org file diary entries")))
3306 (eval-after-load "calendar"
3307 '(progn
3308 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3309 'org-calendar-goto-agenda)
3310 (add-hook 'calendar-mode-hook
3311 (lambda ()
3312 (unless (eq org-agenda-diary-file 'diary-file)
3313 (define-key calendar-mode-map
3314 org-calendar-insert-diary-entry-key
3315 'org-agenda-diary-entry))))))
3317 (defgroup org-latex nil
3318 "Options for embedding LaTeX code into Org-mode."
3319 :tag "Org LaTeX"
3320 :group 'org)
3322 (defcustom org-format-latex-options
3323 '(:foreground default :background default :scale 1.0
3324 :html-foreground "Black" :html-background "Transparent"
3325 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3326 "Options for creating images from LaTeX fragments.
3327 This is a property list with the following properties:
3328 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3329 `default' means use the foreground of the default face.
3330 :background the background color, or \"Transparent\".
3331 `default' means use the background of the default face.
3332 :scale a scaling factor for the size of the images, to get more pixels
3333 :html-foreground, :html-background, :html-scale
3334 the same numbers for HTML export.
3335 :matchers a list indicating which matchers should be used to
3336 find LaTeX fragments. Valid members of this list are:
3337 \"begin\" find environments
3338 \"$1\" find single characters surrounded by $.$
3339 \"$\" find math expressions surrounded by $...$
3340 \"$$\" find math expressions surrounded by $$....$$
3341 \"\\(\" find math expressions surrounded by \\(...\\)
3342 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3343 :group 'org-latex
3344 :type 'plist)
3346 (defcustom org-format-latex-signal-error t
3347 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3348 When nil, just push out a message."
3349 :group 'org-latex
3350 :version "24.1"
3351 :type 'boolean)
3353 (defcustom org-latex-to-mathml-jar-file nil
3354 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3355 Use this to specify additional executable file say a jar file.
3357 When using MathToWeb as the converter, specify the full-path to
3358 your mathtoweb.jar file."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type '(choice
3362 (const :tag "None" nil)
3363 (file :tag "JAR file" :must-match t)))
3365 (defcustom org-latex-to-mathml-convert-command nil
3366 "Command to convert LaTeX fragments to MathML.
3367 Replace format-specifiers in the command as noted below and use
3368 `shell-command' to convert LaTeX to MathML.
3369 %j: Executable file in fully expanded form as specified by
3370 `org-latex-to-mathml-jar-file'.
3371 %I: Input LaTeX file in fully expanded form
3372 %o: Output MathML file
3373 This command is used by `org-create-math-formula'.
3375 When using MathToWeb as the converter, set this to
3376 \"java -jar %j -unicode -force -df %o %I\"."
3377 :group 'org-latex
3378 :version "24.1"
3379 :type '(choice
3380 (const :tag "None" nil)
3381 (string :tag "\nShell command")))
3383 (defcustom org-latex-create-formula-image-program 'dvipng
3384 "Program to convert LaTeX fragments with.
3386 dvipng Process the LaTeX fragments to dvi file, then convert
3387 dvi files to png files using dvipng.
3388 This will also include processing of non-math environments.
3389 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3390 to convert pdf files to png files"
3391 :group 'org-latex
3392 :version "24.1"
3393 :type '(choice
3394 (const :tag "dvipng" dvipng)
3395 (const :tag "imagemagick" imagemagick)))
3397 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3398 "Path to store latex preview images. A relative path here creates many
3399 directories relative to the processed org files paths. An absolute path
3400 puts all preview images at the same place."
3401 :group 'org-latex
3402 :version "24.3"
3403 :type 'string)
3405 (defun org-format-latex-mathml-available-p ()
3406 "Return t if `org-latex-to-mathml-convert-command' is usable."
3407 (save-match-data
3408 (when (and (boundp 'org-latex-to-mathml-convert-command)
3409 org-latex-to-mathml-convert-command)
3410 (let ((executable (car (split-string
3411 org-latex-to-mathml-convert-command))))
3412 (when (executable-find executable)
3413 (if (string-match
3414 "%j" org-latex-to-mathml-convert-command)
3415 (file-readable-p org-latex-to-mathml-jar-file)
3416 t))))))
3418 (defcustom org-format-latex-header "\\documentclass{article}
3419 \\usepackage[usenames]{color}
3420 \\usepackage{amsmath}
3421 \\usepackage[mathscr]{eucal}
3422 \\pagestyle{empty} % do not remove
3423 \[PACKAGES]
3424 \[DEFAULT-PACKAGES]
3425 % The settings below are copied from fullpage.sty
3426 \\setlength{\\textwidth}{\\paperwidth}
3427 \\addtolength{\\textwidth}{-3cm}
3428 \\setlength{\\oddsidemargin}{1.5cm}
3429 \\addtolength{\\oddsidemargin}{-2.54cm}
3430 \\setlength{\\evensidemargin}{\\oddsidemargin}
3431 \\setlength{\\textheight}{\\paperheight}
3432 \\addtolength{\\textheight}{-\\headheight}
3433 \\addtolength{\\textheight}{-\\headsep}
3434 \\addtolength{\\textheight}{-\\footskip}
3435 \\addtolength{\\textheight}{-3cm}
3436 \\setlength{\\topmargin}{1.5cm}
3437 \\addtolength{\\topmargin}{-2.54cm}"
3438 "The document header used for processing LaTeX fragments.
3439 It is imperative that this header make sure that no page number
3440 appears on the page. The package defined in the variables
3441 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3442 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3443 will be appended."
3444 :group 'org-latex
3445 :type 'string)
3447 (defvar org-format-latex-header-extra nil)
3449 (defun org-set-packages-alist (var val)
3450 "Set the packages alist and make sure it has 3 elements per entry."
3451 (set var (mapcar (lambda (x)
3452 (if (and (consp x) (= (length x) 2))
3453 (list (car x) (nth 1 x) t)
3455 val)))
3457 (defun org-get-packages-alist (var)
3459 "Get the packages alist and make sure it has 3 elements per entry."
3460 (mapcar (lambda (x)
3461 (if (and (consp x) (= (length x) 2))
3462 (list (car x) (nth 1 x) t)
3464 (default-value var)))
3466 ;; The following variables are defined here because is it also used
3467 ;; when formatting latex fragments. Originally it was part of the
3468 ;; LaTeX exporter, which is why the name includes "export".
3469 (defcustom org-export-latex-default-packages-alist
3470 '(("AUTO" "inputenc" t)
3471 ("T1" "fontenc" t)
3472 ("" "fixltx2e" nil)
3473 ("" "graphicx" t)
3474 ("" "longtable" nil)
3475 ("" "float" nil)
3476 ("" "wrapfig" nil)
3477 ("" "soul" t)
3478 ("" "textcomp" t)
3479 ("" "marvosym" t)
3480 ("" "wasysym" t)
3481 ("" "latexsym" t)
3482 ("" "amssymb" t)
3483 ("" "hyperref" nil)
3484 "\\tolerance=1000"
3486 "Alist of default packages to be inserted in the header.
3487 Change this only if one of the packages here causes an incompatibility
3488 with another package you are using.
3489 The packages in this list are needed by one part or another of Org-mode
3490 to function properly.
3492 - inputenc, fontenc: for basic font and character selection
3493 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3494 for interpreting the entities in `org-entities'. You can skip some of these
3495 packages if you don't use any of the symbols in it.
3496 - graphicx: for including images
3497 - float, wrapfig: for figure placement
3498 - longtable: for long tables
3499 - hyperref: for cross references
3501 Therefore you should not modify this variable unless you know what you
3502 are doing. The one reason to change it anyway is that you might be loading
3503 some other package that conflicts with one of the default packages.
3504 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3505 If SNIPPET-FLAG is t, the package also needs to be included when
3506 compiling LaTeX snippets into images for inclusion into HTML."
3507 :group 'org-export-latex
3508 :set 'org-set-packages-alist
3509 :get 'org-get-packages-alist
3510 :version "24.1"
3511 :type '(repeat
3512 (choice
3513 (list :tag "options/package pair"
3514 (string :tag "options")
3515 (string :tag "package")
3516 (boolean :tag "Snippet"))
3517 (string :tag "A line of LaTeX"))))
3519 (defcustom org-export-latex-packages-alist nil
3520 "Alist of packages to be inserted in every LaTeX header.
3521 These will be inserted after `org-export-latex-default-packages-alist'.
3522 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3523 SNIPPET-FLAG, when t, indicates that this package is also needed when
3524 turning LaTeX snippets into images for inclusion into HTML.
3525 Make sure that you only list packages here which:
3526 - you want in every file
3527 - do not conflict with the default packages in
3528 `org-export-latex-default-packages-alist'
3529 - do not conflict with the setup in `org-format-latex-header'."
3530 :group 'org-export-latex
3531 :set 'org-set-packages-alist
3532 :get 'org-get-packages-alist
3533 :type '(repeat
3534 (choice
3535 (list :tag "options/package pair"
3536 (string :tag "options")
3537 (string :tag "package")
3538 (boolean :tag "Snippet"))
3539 (string :tag "A line of LaTeX"))))
3542 (defgroup org-appearance nil
3543 "Settings for Org-mode appearance."
3544 :tag "Org Appearance"
3545 :group 'org)
3547 (defcustom org-level-color-stars-only nil
3548 "Non-nil means fontify only the stars in each headline.
3549 When nil, the entire headline is fontified.
3550 Changing it requires restart of `font-lock-mode' to become effective
3551 also in regions already fontified."
3552 :group 'org-appearance
3553 :type 'boolean)
3555 (defcustom org-hide-leading-stars nil
3556 "Non-nil means hide the first N-1 stars in a headline.
3557 This works by using the face `org-hide' for these stars. This
3558 face is white for a light background, and black for a dark
3559 background. You may have to customize the face `org-hide' to
3560 make this work.
3561 Changing it requires restart of `font-lock-mode' to become effective
3562 also in regions already fontified.
3563 You may also set this on a per-file basis by adding one of the following
3564 lines to the buffer:
3566 #+STARTUP: hidestars
3567 #+STARTUP: showstars"
3568 :group 'org-appearance
3569 :type 'boolean)
3571 (defcustom org-hidden-keywords nil
3572 "List of symbols corresponding to keywords to be hidden the org buffer.
3573 For example, a value '(title) for this list will make the document's title
3574 appear in the buffer without the initial #+TITLE: keyword."
3575 :group 'org-appearance
3576 :version "24.1"
3577 :type '(set (const :tag "#+AUTHOR" author)
3578 (const :tag "#+DATE" date)
3579 (const :tag "#+EMAIL" email)
3580 (const :tag "#+TITLE" title)))
3582 (defcustom org-custom-properties nil
3583 "List of properties (as strings) with a special meaning.
3584 The default use of these custom properties is to let the user
3585 hide them with `org-toggle-custom-properties-visibility'."
3586 :group 'org-properties
3587 :group 'org-appearance
3588 :version "24.3"
3589 :type '(repeat (string :tag "Property Name")))
3591 (defcustom org-fontify-done-headline nil
3592 "Non-nil means change the face of a headline if it is marked DONE.
3593 Normally, only the TODO/DONE keyword indicates the state of a headline.
3594 When this is non-nil, the headline after the keyword is set to the
3595 `org-headline-done' as an additional indication."
3596 :group 'org-appearance
3597 :type 'boolean)
3599 (defcustom org-fontify-emphasized-text t
3600 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3601 Changing this variable requires a restart of Emacs to take effect."
3602 :group 'org-appearance
3603 :type 'boolean)
3605 (defcustom org-fontify-whole-heading-line nil
3606 "Non-nil means fontify the whole line for headings.
3607 This is useful when setting a background color for the
3608 org-level-* faces."
3609 :group 'org-appearance
3610 :type 'boolean)
3612 (defcustom org-highlight-latex-fragments-and-specials nil
3613 "Non-nil means fontify what is treated specially by the exporters."
3614 :group 'org-appearance
3615 :type 'boolean)
3617 (defcustom org-hide-emphasis-markers nil
3618 "Non-nil mean font-lock should hide the emphasis marker characters."
3619 :group 'org-appearance
3620 :type 'boolean)
3622 (defcustom org-pretty-entities nil
3623 "Non-nil means show entities as UTF8 characters.
3624 When nil, the \\name form remains in the buffer."
3625 :group 'org-appearance
3626 :version "24.1"
3627 :type 'boolean)
3629 (defcustom org-pretty-entities-include-sub-superscripts t
3630 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3631 :group 'org-appearance
3632 :version "24.1"
3633 :type 'boolean)
3635 (defvar org-emph-re nil
3636 "Regular expression for matching emphasis.
3637 After a match, the match groups contain these elements:
3638 0 The match of the full regular expression, including the characters
3639 before and after the proper match
3640 1 The character before the proper match, or empty at beginning of line
3641 2 The proper match, including the leading and trailing markers
3642 3 The leading marker like * or /, indicating the type of highlighting
3643 4 The text between the emphasis markers, not including the markers
3644 5 The character after the match, empty at the end of a line")
3645 (defvar org-verbatim-re nil
3646 "Regular expression for matching verbatim text.")
3647 (defvar org-emphasis-regexp-components) ; defined just below
3648 (defvar org-emphasis-alist) ; defined just below
3649 (defun org-set-emph-re (var val)
3650 "Set variable and compute the emphasis regular expression."
3651 (set var val)
3652 (when (and (boundp 'org-emphasis-alist)
3653 (boundp 'org-emphasis-regexp-components)
3654 org-emphasis-alist org-emphasis-regexp-components)
3655 (let* ((e org-emphasis-regexp-components)
3656 (pre (car e))
3657 (post (nth 1 e))
3658 (border (nth 2 e))
3659 (body (nth 3 e))
3660 (nl (nth 4 e))
3661 (body1 (concat body "*?"))
3662 (markers (mapconcat 'car org-emphasis-alist ""))
3663 (vmarkers (mapconcat
3664 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3665 org-emphasis-alist "")))
3666 ;; make sure special characters appear at the right position in the class
3667 (if (string-match "\\^" markers)
3668 (setq markers (concat (replace-match "" t t markers) "^")))
3669 (if (string-match "-" markers)
3670 (setq markers (concat (replace-match "" t t markers) "-")))
3671 (if (string-match "\\^" vmarkers)
3672 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3673 (if (string-match "-" vmarkers)
3674 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3675 (if (> nl 0)
3676 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3677 (int-to-string nl) "\\}")))
3678 ;; Make the regexp
3679 (setq org-emph-re
3680 (concat "\\([" pre "]\\|^\\)"
3681 "\\("
3682 "\\([" markers "]\\)"
3683 "\\("
3684 "[^" border "]\\|"
3685 "[^" border "]"
3686 body1
3687 "[^" border "]"
3688 "\\)"
3689 "\\3\\)"
3690 "\\([" post "]\\|$\\)"))
3691 (setq org-verbatim-re
3692 (concat "\\([" pre "]\\|^\\)"
3693 "\\("
3694 "\\([" vmarkers "]\\)"
3695 "\\("
3696 "[^" border "]\\|"
3697 "[^" border "]"
3698 body1
3699 "[^" border "]"
3700 "\\)"
3701 "\\3\\)"
3702 "\\([" post "]\\|$\\)")))))
3704 (defcustom org-emphasis-regexp-components
3705 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3706 "Components used to build the regular expression for emphasis.
3707 This is a list with five entries. Terminology: In an emphasis string
3708 like \" *strong word* \", we call the initial space PREMATCH, the final
3709 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3710 and \"trong wor\" is the body. The different components in this variable
3711 specify what is allowed/forbidden in each part:
3713 pre Chars allowed as prematch. Beginning of line will be allowed too.
3714 post Chars allowed as postmatch. End of line will be allowed too.
3715 border The chars *forbidden* as border characters.
3716 body-regexp A regexp like \".\" to match a body character. Don't use
3717 non-shy groups here, and don't allow newline here.
3718 newline The maximum number of newlines allowed in an emphasis exp.
3720 Use customize to modify this, or restart Emacs after changing it."
3721 :group 'org-appearance
3722 :set 'org-set-emph-re
3723 :type '(list
3724 (sexp :tag "Allowed chars in pre ")
3725 (sexp :tag "Allowed chars in post ")
3726 (sexp :tag "Forbidden chars in border ")
3727 (sexp :tag "Regexp for body ")
3728 (integer :tag "number of newlines allowed")
3729 (option (boolean :tag "Please ignore this button"))))
3731 (defcustom org-emphasis-alist
3732 `(("*" bold "<b>" "</b>")
3733 ("/" italic "<i>" "</i>")
3734 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3735 ("=" org-code "<code>" "</code>" verbatim)
3736 ("~" org-verbatim "<code>" "</code>" verbatim)
3737 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3738 "<del>" "</del>")
3740 "Special syntax for emphasized text.
3741 Text starting and ending with a special character will be emphasized, for
3742 example *bold*, _underlined_ and /italic/. This variable sets the marker
3743 characters, the face to be used by font-lock for highlighting in Org-mode
3744 Emacs buffers, and the HTML tags to be used for this.
3745 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3746 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3747 Use customize to modify this, or restart Emacs after changing it."
3748 :group 'org-appearance
3749 :set 'org-set-emph-re
3750 :type '(repeat
3751 (list
3752 (string :tag "Marker character")
3753 (choice
3754 (face :tag "Font-lock-face")
3755 (plist :tag "Face property list"))
3756 (string :tag "HTML start tag")
3757 (string :tag "HTML end tag")
3758 (option (const verbatim)))))
3760 (defvar org-protecting-blocks
3761 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3762 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3763 This is needed for font-lock setup.")
3765 ;;; Miscellaneous options
3767 (defgroup org-completion nil
3768 "Completion in Org-mode."
3769 :tag "Org Completion"
3770 :group 'org)
3772 (defcustom org-completion-use-ido nil
3773 "Non-nil means use ido completion wherever possible.
3774 Note that `ido-mode' must be active for this variable to be relevant.
3775 If you decide to turn this variable on, you might well want to turn off
3776 `org-outline-path-complete-in-steps'.
3777 See also `org-completion-use-iswitchb'."
3778 :group 'org-completion
3779 :type 'boolean)
3781 (defcustom org-completion-use-iswitchb nil
3782 "Non-nil means use iswitchb completion wherever possible.
3783 Note that `iswitchb-mode' must be active for this variable to be relevant.
3784 If you decide to turn this variable on, you might well want to turn off
3785 `org-outline-path-complete-in-steps'.
3786 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3787 :group 'org-completion
3788 :type 'boolean)
3790 (defcustom org-completion-fallback-command 'hippie-expand
3791 "The expansion command called by \\[pcomplete] in normal context.
3792 Normal means, no org-mode-specific context."
3793 :group 'org-completion
3794 :type 'function)
3796 ;;; Functions and variables from their packages
3797 ;; Declared here to avoid compiler warnings
3799 ;; XEmacs only
3800 (defvar outline-mode-menu-heading)
3801 (defvar outline-mode-menu-show)
3802 (defvar outline-mode-menu-hide)
3803 (defvar zmacs-regions) ; XEmacs regions
3805 ;; Emacs only
3806 (defvar mark-active)
3808 ;; Various packages
3809 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3810 (declare-function calendar-forward-day "cal-move" (arg))
3811 (declare-function calendar-goto-date "cal-move" (date))
3812 (declare-function calendar-goto-today "cal-move" ())
3813 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3814 (defvar calc-embedded-close-formula)
3815 (defvar calc-embedded-open-formula)
3816 (declare-function cdlatex-tab "ext:cdlatex" ())
3817 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3818 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3819 (defvar font-lock-unfontify-region-function)
3820 (declare-function iswitchb-read-buffer "iswitchb"
3821 (prompt &optional default require-match start matches-set))
3822 (defvar iswitchb-temp-buflist)
3823 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3824 (defvar org-agenda-tags-todo-honor-ignore-options)
3825 (declare-function org-agenda-skip "org-agenda" ())
3826 (declare-function
3827 org-agenda-format-item "org-agenda"
3828 (extra txt &optional category tags dotime noprefix remove-re habitp))
3829 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3830 (declare-function org-agenda-change-all-lines "org-agenda"
3831 (newhead hdmarker &optional fixface just-this))
3832 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3833 (declare-function org-agenda-maybe-redo "org-agenda" ())
3834 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3835 (beg end))
3836 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3837 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3838 "org-agenda" (&optional end))
3839 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3840 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3841 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3842 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3843 (declare-function org-indent-mode "org-indent" (&optional arg))
3844 (declare-function parse-time-string "parse-time" (string))
3845 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3846 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3847 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3848 (defvar remember-data-file)
3849 (defvar texmathp-why)
3850 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3851 (declare-function table--at-cell-p "table" (position &optional object at-column))
3853 (defvar w3m-current-url)
3854 (defvar w3m-current-title)
3856 (defvar org-latex-regexps)
3858 ;;; Autoload and prepare some org modules
3860 ;; Some table stuff that needs to be defined here, because it is used
3861 ;; by the functions setting up org-mode or checking for table context.
3863 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3864 "Detect an org-type or table-type table.")
3865 (defconst org-table-line-regexp "^[ \t]*|"
3866 "Detect an org-type table line.")
3867 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3868 "Detect an org-type table line.")
3869 (defconst org-table-hline-regexp "^[ \t]*|-"
3870 "Detect an org-type table hline.")
3871 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3872 "Detect a table-type table hline.")
3873 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3874 "Detect the first line outside a table when searching from within it.
3875 This works for both table types.")
3877 ;; Autoload the functions in org-table.el that are needed by functions here.
3879 (eval-and-compile
3880 (org-autoload "org-table"
3881 '(org-table-begin org-table-blank-field org-table-end)))
3883 ;;;###autoload
3884 (defun turn-on-orgtbl ()
3885 "Unconditionally turn on `orgtbl-mode'."
3886 (require 'org-table)
3887 (orgtbl-mode 1))
3889 (defun org-at-table-p (&optional table-type)
3890 "Return t if the cursor is inside an org-type table.
3891 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3892 (if org-enable-table-editor
3893 (save-excursion
3894 (beginning-of-line 1)
3895 (looking-at (if table-type org-table-any-line-regexp
3896 org-table-line-regexp)))
3897 nil))
3898 (defsubst org-table-p () (org-at-table-p))
3900 (defun org-at-table.el-p ()
3901 "Return t if and only if we are at a table.el table."
3902 (and (org-at-table-p 'any)
3903 (save-excursion
3904 (goto-char (org-table-begin 'any))
3905 (looking-at org-table1-hline-regexp))))
3906 (defun org-table-recognize-table.el ()
3907 "If there is a table.el table nearby, recognize it and move into it."
3908 (if org-table-tab-recognizes-table.el
3909 (if (org-at-table.el-p)
3910 (progn
3911 (beginning-of-line 1)
3912 (if (looking-at org-table-dataline-regexp)
3914 (if (looking-at org-table1-hline-regexp)
3915 (progn
3916 (beginning-of-line 2)
3917 (if (looking-at org-table-any-border-regexp)
3918 (beginning-of-line -1)))))
3919 (if (re-search-forward "|" (org-table-end t) t)
3920 (progn
3921 (require 'table)
3922 (if (table--at-cell-p (point))
3924 (message "recognizing table.el table...")
3925 (table-recognize-table)
3926 (message "recognizing table.el table...done")))
3927 (error "This should not happen"))
3929 nil)
3930 nil))
3932 (defun org-at-table-hline-p ()
3933 "Return t if the cursor is inside a hline in a table."
3934 (if org-enable-table-editor
3935 (save-excursion
3936 (beginning-of-line 1)
3937 (looking-at org-table-hline-regexp))
3938 nil))
3940 (defvar org-table-clean-did-remove-column nil)
3942 (defun org-table-map-tables (function &optional quietly)
3943 "Apply FUNCTION to the start of all tables in the buffer."
3944 (save-excursion
3945 (save-restriction
3946 (widen)
3947 (goto-char (point-min))
3948 (while (re-search-forward org-table-any-line-regexp nil t)
3949 (unless quietly
3950 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3951 (beginning-of-line 1)
3952 (when (and (looking-at org-table-line-regexp)
3953 ;; Exclude tables in src/example/verbatim/clocktable blocks
3954 (not (org-in-block-p '("src" "example"))))
3955 (save-excursion (funcall function))
3956 (or (looking-at org-table-line-regexp)
3957 (forward-char 1)))
3958 (re-search-forward org-table-any-border-regexp nil 1))))
3959 (unless quietly (message "Mapping tables: done")))
3961 ;; Declare and autoload functions from org-exp.el & Co
3963 (declare-function org-default-export-plist "org-exp")
3964 (declare-function org-infile-export-plist "org-exp")
3965 (declare-function org-get-current-options "org-exp")
3967 ;; Declare and autoload functions from org-agenda.el
3969 (eval-and-compile
3970 (org-autoload "org-agenda"
3971 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3973 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3974 (declare-function org-clock-update-mode-line "org-clock" ())
3975 (declare-function org-resolve-clocks "org-clock"
3976 (&optional also-non-dangling-p prompt last-valid))
3977 (defvar org-clock-start-time)
3978 (defvar org-clock-marker (make-marker)
3979 "Marker recording the last clock-in.")
3980 (defvar org-clock-hd-marker (make-marker)
3981 "Marker recording the last clock-in, but the headline position.")
3982 (defvar org-clock-heading ""
3983 "The heading of the current clock entry.")
3984 (defun org-clock-is-active ()
3985 "Return non-nil if clock is currently running.
3986 The return value is actually the clock marker."
3987 (marker-buffer org-clock-marker))
3989 (eval-and-compile
3990 (org-autoload "org-clock" '(org-clock-remove-overlays
3991 org-clock-update-time-maybe
3992 org-clocktable-shift)))
3994 (defun org-check-running-clock ()
3995 "Check if the current buffer contains the running clock.
3996 If yes, offer to stop it and to save the buffer with the changes."
3997 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3998 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3999 (buffer-name))))
4000 (org-clock-out)
4001 (when (y-or-n-p "Save changed buffer?")
4002 (save-buffer))))
4004 (defun org-clocktable-try-shift (dir n)
4005 "Check if this line starts a clock table, if yes, shift the time block."
4006 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4007 (org-clocktable-shift dir n)))
4009 ;;;###autoload
4010 (defun org-clock-persistence-insinuate ()
4011 "Set up hooks for clock persistence."
4012 (require 'org-clock)
4013 (add-hook 'org-mode-hook 'org-clock-load)
4014 (add-hook 'kill-emacs-hook 'org-clock-save))
4016 ;; Define the variable already here, to make sure we have it.
4017 (defvar org-indent-mode nil
4018 "Non-nil if Org-Indent mode is enabled.
4019 Use the command `org-indent-mode' to change this variable.")
4021 ;; Autoload archiving code
4022 ;; The stuff that is needed for cycling and tags has to be defined here.
4024 (defgroup org-archive nil
4025 "Options concerning archiving in Org-mode."
4026 :tag "Org Archive"
4027 :group 'org-structure)
4029 (defcustom org-archive-location "%s_archive::"
4030 "The location where subtrees should be archived.
4032 The value of this variable is a string, consisting of two parts,
4033 separated by a double-colon. The first part is a filename and
4034 the second part is a headline.
4036 When the filename is omitted, archiving happens in the same file.
4037 %s in the filename will be replaced by the current file
4038 name (without the directory part). Archiving to a different file
4039 is useful to keep archived entries from contributing to the
4040 Org-mode Agenda.
4042 The archived entries will be filed as subtrees of the specified
4043 headline. When the headline is omitted, the subtrees are simply
4044 filed away at the end of the file, as top-level entries. Also in
4045 the heading you can use %s to represent the file name, this can be
4046 useful when using the same archive for a number of different files.
4048 Here are a few examples:
4049 \"%s_archive::\"
4050 If the current file is Projects.org, archive in file
4051 Projects.org_archive, as top-level trees. This is the default.
4053 \"::* Archived Tasks\"
4054 Archive in the current file, under the top-level headline
4055 \"* Archived Tasks\".
4057 \"~/org/archive.org::\"
4058 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4060 \"~/org/archive.org::* From %s\"
4061 Archive in file ~/org/archive.org (absolute path), under headlines
4062 \"From FILENAME\" where file name is the current file name.
4064 \"~/org/datetree.org::datetree/* Finished Tasks\"
4065 The \"datetree/\" string is special, signifying to archive
4066 items to the datetree. Items are placed in either the CLOSED
4067 date of the item, or the current date if there is no CLOSED date.
4068 The heading will be a subentry to the current date. There doesn't
4069 need to be a heading, but there always needs to be a slash after
4070 datetree. For example, to store archived items directly in the
4071 datetree, use \"~/org/datetree.org::datetree/\".
4073 \"basement::** Finished Tasks\"
4074 Archive in file ./basement (relative path), as level 3 trees
4075 below the level 2 heading \"** Finished Tasks\".
4077 You may set this option on a per-file basis by adding to the buffer a
4078 line like
4080 #+ARCHIVE: basement::** Finished Tasks
4082 You may also define it locally for a subtree by setting an ARCHIVE property
4083 in the entry. If such a property is found in an entry, or anywhere up
4084 the hierarchy, it will be used."
4085 :group 'org-archive
4086 :type 'string)
4088 (defcustom org-archive-tag "ARCHIVE"
4089 "The tag that marks a subtree as archived.
4090 An archived subtree does not open during visibility cycling, and does
4091 not contribute to the agenda listings.
4092 After changing this, font-lock must be restarted in the relevant buffers to
4093 get the proper fontification."
4094 :group 'org-archive
4095 :group 'org-keywords
4096 :type 'string)
4098 (defcustom org-agenda-skip-archived-trees t
4099 "Non-nil means the agenda will skip any items located in archived trees.
4100 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4101 variable is no longer recommended, you should leave it at the value t.
4102 Instead, use the key `v' to cycle the archives-mode in the agenda."
4103 :group 'org-archive
4104 :group 'org-agenda-skip
4105 :type 'boolean)
4107 (defcustom org-columns-skip-archived-trees t
4108 "Non-nil means ignore archived trees when creating column view."
4109 :group 'org-archive
4110 :group 'org-properties
4111 :type 'boolean)
4113 (defcustom org-cycle-open-archived-trees nil
4114 "Non-nil means `org-cycle' will open archived trees.
4115 An archived tree is a tree marked with the tag ARCHIVE.
4116 When nil, archived trees will stay folded. You can still open them with
4117 normal outline commands like `show-all', but not with the cycling commands."
4118 :group 'org-archive
4119 :group 'org-cycle
4120 :type 'boolean)
4122 (defcustom org-sparse-tree-open-archived-trees nil
4123 "Non-nil means sparse tree construction shows matches in archived trees.
4124 When nil, matches in these trees are highlighted, but the trees are kept in
4125 collapsed state."
4126 :group 'org-archive
4127 :group 'org-sparse-trees
4128 :type 'boolean)
4130 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4131 "The default date type when building a sparse tree.
4132 When this is nil, a date is a scheduled or a deadline timestamp.
4133 Otherwise, these types are allowed:
4135 all: all timestamps
4136 active: only active timestamps (<...>)
4137 inactive: only inactive timestamps (<...)
4138 scheduled: only scheduled timestamps
4139 deadline: only deadline timestamps"
4140 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4141 (const :tag "All timestamps" all)
4142 (const :tag "Only active timestamps" active)
4143 (const :tag "Only inactive timestamps" inactive)
4144 (const :tag "Only scheduled timestamps" scheduled)
4145 (const :tag "Only deadline timestamps" deadline))
4146 :version "24.3"
4147 :group 'org-sparse-trees)
4149 (defun org-cycle-hide-archived-subtrees (state)
4150 "Re-hide all archived subtrees after a visibility state change."
4151 (when (and (not org-cycle-open-archived-trees)
4152 (not (memq state '(overview folded))))
4153 (save-excursion
4154 (let* ((globalp (memq state '(contents all)))
4155 (beg (if globalp (point-min) (point)))
4156 (end (if globalp (point-max) (org-end-of-subtree t))))
4157 (org-hide-archived-subtrees beg end)
4158 (goto-char beg)
4159 (if (looking-at (concat ".*:" org-archive-tag ":"))
4160 (message "%s" (substitute-command-keys
4161 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4163 (defun org-force-cycle-archived ()
4164 "Cycle subtree even if it is archived."
4165 (interactive)
4166 (setq this-command 'org-cycle)
4167 (let ((org-cycle-open-archived-trees t))
4168 (call-interactively 'org-cycle)))
4170 (defun org-hide-archived-subtrees (beg end)
4171 "Re-hide all archived subtrees after a visibility state change."
4172 (save-excursion
4173 (let* ((re (concat ":" org-archive-tag ":")))
4174 (goto-char beg)
4175 (while (re-search-forward re end t)
4176 (when (org-at-heading-p)
4177 (org-flag-subtree t)
4178 (org-end-of-subtree t))))))
4180 (declare-function outline-end-of-heading "outline" ())
4181 (declare-function outline-flag-region "outline" (from to flag))
4182 (defun org-flag-subtree (flag)
4183 (save-excursion
4184 (org-back-to-heading t)
4185 (outline-end-of-heading)
4186 (outline-flag-region (point)
4187 (progn (org-end-of-subtree t) (point))
4188 flag)))
4190 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4192 (eval-and-compile
4193 (org-autoload "org-archive"
4194 '(org-add-archive-files)))
4196 ;; Autoload Column View Code
4198 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4199 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4200 (declare-function org-columns-compute "org-colview" (property))
4202 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4203 '(org-columns-number-to-string
4204 org-columns-get-format-and-top-level
4205 org-columns-compute
4206 org-columns-remove-overlays))
4208 ;; Autoload ID code
4210 (declare-function org-id-store-link "org-id")
4211 (declare-function org-id-locations-load "org-id")
4212 (declare-function org-id-locations-save "org-id")
4213 (defvar org-id-track-globally)
4214 (org-autoload "org-id"
4215 '(org-id-new
4216 org-id-copy
4217 org-id-get-with-outline-path-completion
4218 org-id-get-with-outline-drilling))
4220 ;;; Variables for pre-computed regular expressions, all buffer local
4222 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4223 "Matches first line of a hidden block.")
4224 (make-variable-buffer-local 'org-drawer-regexp)
4225 (defvar org-todo-regexp nil
4226 "Matches any of the TODO state keywords.")
4227 (make-variable-buffer-local 'org-todo-regexp)
4228 (defvar org-not-done-regexp nil
4229 "Matches any of the TODO state keywords except the last one.")
4230 (make-variable-buffer-local 'org-not-done-regexp)
4231 (defvar org-not-done-heading-regexp nil
4232 "Matches a TODO headline that is not done.")
4233 (make-variable-buffer-local 'org-not-done-regexp)
4234 (defvar org-todo-line-regexp nil
4235 "Matches a headline and puts TODO state into group 2 if present.")
4236 (make-variable-buffer-local 'org-todo-line-regexp)
4237 (defvar org-complex-heading-regexp nil
4238 "Matches a headline and puts everything into groups:
4239 group 1: the stars
4240 group 2: The todo keyword, maybe
4241 group 3: Priority cookie
4242 group 4: True headline
4243 group 5: Tags")
4244 (make-variable-buffer-local 'org-complex-heading-regexp)
4245 (defvar org-complex-heading-regexp-format nil
4246 "Printf format to make regexp to match an exact headline.
4247 This regexp will match the headline of any node which has the
4248 exact headline text that is put into the format, but may have any
4249 TODO state, priority and tags.")
4250 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4251 (defvar org-todo-line-tags-regexp nil
4252 "Matches a headline and puts TODO state into group 2 if present.
4253 Also put tags into group 4 if tags are present.")
4254 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4255 (defvar org-ds-keyword-length 12
4256 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4257 (make-variable-buffer-local 'org-ds-keyword-length)
4258 (defvar org-deadline-regexp nil
4259 "Matches the DEADLINE keyword.")
4260 (make-variable-buffer-local 'org-deadline-regexp)
4261 (defvar org-deadline-time-regexp nil
4262 "Matches the DEADLINE keyword together with a time stamp.")
4263 (make-variable-buffer-local 'org-deadline-time-regexp)
4264 (defvar org-deadline-line-regexp nil
4265 "Matches the DEADLINE keyword and the rest of the line.")
4266 (make-variable-buffer-local 'org-deadline-line-regexp)
4267 (defvar org-scheduled-regexp nil
4268 "Matches the SCHEDULED keyword.")
4269 (make-variable-buffer-local 'org-scheduled-regexp)
4270 (defvar org-scheduled-time-regexp nil
4271 "Matches the SCHEDULED keyword together with a time stamp.")
4272 (make-variable-buffer-local 'org-scheduled-time-regexp)
4273 (defvar org-closed-time-regexp nil
4274 "Matches the CLOSED keyword together with a time stamp.")
4275 (make-variable-buffer-local 'org-closed-time-regexp)
4277 (defvar org-keyword-time-regexp nil
4278 "Matches any of the 4 keywords, together with the time stamp.")
4279 (make-variable-buffer-local 'org-keyword-time-regexp)
4280 (defvar org-keyword-time-not-clock-regexp nil
4281 "Matches any of the 3 keywords, together with the time stamp.")
4282 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4283 (defvar org-maybe-keyword-time-regexp nil
4284 "Matches a timestamp, possibly preceded by a keyword.")
4285 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4286 (defvar org-all-time-keywords nil
4287 "List of time keywords.")
4288 (make-variable-buffer-local 'org-all-time-keywords)
4290 (defconst org-plain-time-of-day-regexp
4291 (concat
4292 "\\(\\<[012]?[0-9]"
4293 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4294 "\\(--?"
4295 "\\(\\<[012]?[0-9]"
4296 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4297 "\\)?")
4298 "Regular expression to match a plain time or time range.
4299 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4300 groups carry important information:
4301 0 the full match
4302 1 the first time, range or not
4303 8 the second time, if it is a range.")
4305 (defconst org-plain-time-extension-regexp
4306 (concat
4307 "\\(\\<[012]?[0-9]"
4308 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4309 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4310 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4311 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4312 groups carry important information:
4313 0 the full match
4314 7 hours of duration
4315 9 minutes of duration")
4317 (defconst org-stamp-time-of-day-regexp
4318 (concat
4319 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4320 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4321 "\\(--?"
4322 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4323 "Regular expression to match a timestamp time or time range.
4324 After a match, the following groups carry important information:
4325 0 the full match
4326 1 date plus weekday, for back referencing to make sure both times are on the same day
4327 2 the first time, range or not
4328 4 the second time, if it is a range.")
4330 (defconst org-startup-options
4331 '(("fold" org-startup-folded t)
4332 ("overview" org-startup-folded t)
4333 ("nofold" org-startup-folded nil)
4334 ("showall" org-startup-folded nil)
4335 ("showeverything" org-startup-folded showeverything)
4336 ("content" org-startup-folded content)
4337 ("indent" org-startup-indented t)
4338 ("noindent" org-startup-indented nil)
4339 ("hidestars" org-hide-leading-stars t)
4340 ("showstars" org-hide-leading-stars nil)
4341 ("odd" org-odd-levels-only t)
4342 ("oddeven" org-odd-levels-only nil)
4343 ("align" org-startup-align-all-tables t)
4344 ("noalign" org-startup-align-all-tables nil)
4345 ("inlineimages" org-startup-with-inline-images t)
4346 ("noinlineimages" org-startup-with-inline-images nil)
4347 ("customtime" org-display-custom-times t)
4348 ("logdone" org-log-done time)
4349 ("lognotedone" org-log-done note)
4350 ("nologdone" org-log-done nil)
4351 ("lognoteclock-out" org-log-note-clock-out t)
4352 ("nolognoteclock-out" org-log-note-clock-out nil)
4353 ("logrepeat" org-log-repeat state)
4354 ("lognoterepeat" org-log-repeat note)
4355 ("nologrepeat" org-log-repeat nil)
4356 ("logreschedule" org-log-reschedule time)
4357 ("lognotereschedule" org-log-reschedule note)
4358 ("nologreschedule" org-log-reschedule nil)
4359 ("logredeadline" org-log-redeadline time)
4360 ("lognoteredeadline" org-log-redeadline note)
4361 ("nologredeadline" org-log-redeadline nil)
4362 ("logrefile" org-log-refile time)
4363 ("lognoterefile" org-log-refile note)
4364 ("nologrefile" org-log-refile nil)
4365 ("fninline" org-footnote-define-inline t)
4366 ("nofninline" org-footnote-define-inline nil)
4367 ("fnlocal" org-footnote-section nil)
4368 ("fnauto" org-footnote-auto-label t)
4369 ("fnprompt" org-footnote-auto-label nil)
4370 ("fnconfirm" org-footnote-auto-label confirm)
4371 ("fnplain" org-footnote-auto-label plain)
4372 ("fnadjust" org-footnote-auto-adjust t)
4373 ("nofnadjust" org-footnote-auto-adjust nil)
4374 ("constcgs" constants-unit-system cgs)
4375 ("constSI" constants-unit-system SI)
4376 ("noptag" org-tag-persistent-alist nil)
4377 ("hideblocks" org-hide-block-startup t)
4378 ("nohideblocks" org-hide-block-startup nil)
4379 ("beamer" org-startup-with-beamer-mode t)
4380 ("entitiespretty" org-pretty-entities t)
4381 ("entitiesplain" org-pretty-entities nil))
4382 "Variable associated with STARTUP options for org-mode.
4383 Each element is a list of three items: the startup options (as written
4384 in the #+STARTUP line), the corresponding variable, and the value to set
4385 this variable to if the option is found. An optional forth element PUSH
4386 means to push this value onto the list in the variable.")
4388 (defun org-update-property-plist (key val props)
4389 "Update PROPS with KEY and VAL."
4390 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4391 (key (if appending (substring key 0 (- (length key) 1)) key))
4392 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4393 (previous (cdr (assoc key props))))
4394 (if appending
4395 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4396 (cons (cons key val) remainder))))
4398 (defconst org-block-regexp
4399 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4400 "Regular expression for hiding blocks.")
4401 (defconst org-heading-keyword-regexp-format
4402 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4403 "Printf format for a regexp matching an headline with some keyword.
4404 This regexp will match the headline of any node which has the
4405 exact keyword that is put into the format. The keyword isn't in
4406 any group by default, but the stars and the body are.")
4407 (defconst org-heading-keyword-maybe-regexp-format
4408 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4409 "Printf format for a regexp matching an headline, possibly with some keyword.
4410 This regexp can match any headline with the specified keyword, or
4411 without a keyword. The keyword isn't in any group by default,
4412 but the stars and the body are.")
4414 (defun org-set-regexps-and-options ()
4415 "Precompute regular expressions for current buffer."
4416 (when (derived-mode-p 'org-mode)
4417 (org-set-local 'org-todo-kwd-alist nil)
4418 (org-set-local 'org-todo-key-alist nil)
4419 (org-set-local 'org-todo-key-trigger nil)
4420 (org-set-local 'org-todo-keywords-1 nil)
4421 (org-set-local 'org-done-keywords nil)
4422 (org-set-local 'org-todo-heads nil)
4423 (org-set-local 'org-todo-sets nil)
4424 (org-set-local 'org-todo-log-states nil)
4425 (org-set-local 'org-file-properties nil)
4426 (org-set-local 'org-file-tags nil)
4427 (let ((re (org-make-options-regexp
4428 '("CATEGORY" "TODO" "COLUMNS"
4429 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4430 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4431 "OPTIONS")
4432 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4433 (splitre "[ \t]+")
4434 (scripts org-use-sub-superscripts)
4435 kwds kws0 kwsa key log value cat arch tags const links hw dws
4436 tail sep kws1 prio props ftags drawers beamer-p
4437 ext-setup-or-nil setup-contents (start 0))
4438 (save-excursion
4439 (save-restriction
4440 (widen)
4441 (goto-char (point-min))
4442 (while (or (and ext-setup-or-nil
4443 (string-match re ext-setup-or-nil start)
4444 (setq start (match-end 0)))
4445 (and (setq ext-setup-or-nil nil start 0)
4446 (re-search-forward re nil t)))
4447 (setq key (upcase (match-string 1 ext-setup-or-nil))
4448 value (org-match-string-no-properties 2 ext-setup-or-nil))
4449 (if (stringp value) (setq value (org-trim value)))
4450 (cond
4451 ((equal key "CATEGORY")
4452 (setq cat value))
4453 ((member key '("SEQ_TODO" "TODO"))
4454 (push (cons 'sequence (org-split-string value splitre)) kwds))
4455 ((equal key "TYP_TODO")
4456 (push (cons 'type (org-split-string value splitre)) kwds))
4457 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4458 ;; general TODO-like setup
4459 (push (cons (intern (downcase (match-string 1 key)))
4460 (org-split-string value splitre)) kwds))
4461 ((equal key "TAGS")
4462 (setq tags (append tags (if tags '("\\n") nil)
4463 (org-split-string value splitre))))
4464 ((equal key "COLUMNS")
4465 (org-set-local 'org-columns-default-format value))
4466 ((equal key "LINK")
4467 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4468 (push (cons (match-string 1 value)
4469 (org-trim (match-string 2 value)))
4470 links)))
4471 ((equal key "PRIORITIES")
4472 (setq prio (org-split-string value " +")))
4473 ((equal key "PROPERTY")
4474 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4475 (setq props (org-update-property-plist (match-string 1 value)
4476 (match-string 2 value)
4477 props))))
4478 ((equal key "FILETAGS")
4479 (when (string-match "\\S-" value)
4480 (setq ftags
4481 (append
4482 ftags
4483 (apply 'append
4484 (mapcar (lambda (x) (org-split-string x ":"))
4485 (org-split-string value)))))))
4486 ((equal key "DRAWERS")
4487 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4488 ((equal key "CONSTANTS")
4489 (setq const (append const (org-split-string value splitre))))
4490 ((equal key "STARTUP")
4491 (let ((opts (org-split-string value splitre))
4492 l var val)
4493 (while (setq l (pop opts))
4494 (when (setq l (assoc l org-startup-options))
4495 (setq var (nth 1 l) val (nth 2 l))
4496 (if (not (nth 3 l))
4497 (set (make-local-variable var) val)
4498 (if (not (listp (symbol-value var)))
4499 (set (make-local-variable var) nil))
4500 (set (make-local-variable var) (symbol-value var))
4501 (add-to-list var val))))))
4502 ((equal key "ARCHIVE")
4503 (setq arch value)
4504 (remove-text-properties 0 (length arch)
4505 '(face t fontified t) arch))
4506 ((equal key "LATEX_CLASS")
4507 (setq beamer-p (equal value "beamer")))
4508 ((equal key "OPTIONS")
4509 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4510 (setq scripts (read (match-string 2 value)))))
4511 ((equal key "SETUPFILE")
4512 (setq setup-contents (org-file-contents
4513 (expand-file-name
4514 (org-remove-double-quotes value))
4515 'noerror))
4516 (if (not ext-setup-or-nil)
4517 (setq ext-setup-or-nil setup-contents start 0)
4518 (setq ext-setup-or-nil
4519 (concat (substring ext-setup-or-nil 0 start)
4520 "\n" setup-contents "\n"
4521 (substring ext-setup-or-nil start)))))))
4522 ;; search for property blocks
4523 (goto-char (point-min))
4524 (while (re-search-forward org-block-regexp nil t)
4525 (when (equal "PROPERTY" (upcase (match-string 1)))
4526 (setq value (replace-regexp-in-string
4527 "[\n\r]" " " (match-string 4)))
4528 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4529 (setq props (org-update-property-plist (match-string 1 value)
4530 (match-string 2 value)
4531 props)))))))
4532 (org-set-local 'org-use-sub-superscripts scripts)
4533 (when cat
4534 (org-set-local 'org-category (intern cat))
4535 (push (cons "CATEGORY" cat) props))
4536 (when prio
4537 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4538 (setq prio (mapcar 'string-to-char prio))
4539 (org-set-local 'org-highest-priority (nth 0 prio))
4540 (org-set-local 'org-lowest-priority (nth 1 prio))
4541 (org-set-local 'org-default-priority (nth 2 prio)))
4542 (and props (org-set-local 'org-file-properties (nreverse props)))
4543 (and ftags (org-set-local 'org-file-tags
4544 (mapcar 'org-add-prop-inherited ftags)))
4545 (and drawers (org-set-local 'org-drawers drawers))
4546 (and arch (org-set-local 'org-archive-location arch))
4547 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4548 ;; Process the TODO keywords
4549 (unless kwds
4550 ;; Use the global values as if they had been given locally.
4551 (setq kwds (default-value 'org-todo-keywords))
4552 (if (stringp (car kwds))
4553 (setq kwds (list (cons org-todo-interpretation
4554 (default-value 'org-todo-keywords)))))
4555 (setq kwds (reverse kwds)))
4556 (setq kwds (nreverse kwds))
4557 (let (inter kws kw)
4558 (while (setq kws (pop kwds))
4559 (let ((kws (or
4560 (run-hook-with-args-until-success
4561 'org-todo-setup-filter-hook kws)
4562 kws)))
4563 (setq inter (pop kws) sep (member "|" kws)
4564 kws0 (delete "|" (copy-sequence kws))
4565 kwsa nil
4566 kws1 (mapcar
4567 (lambda (x)
4568 ;; 1 2
4569 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4570 (progn
4571 (setq kw (match-string 1 x)
4572 key (and (match-end 2) (match-string 2 x))
4573 log (org-extract-log-state-settings x))
4574 (push (cons kw (and key (string-to-char key))) kwsa)
4575 (and log (push log org-todo-log-states))
4577 (error "Invalid TODO keyword %s" x)))
4578 kws0)
4579 kwsa (if kwsa (append '((:startgroup))
4580 (nreverse kwsa)
4581 '((:endgroup))))
4582 hw (car kws1)
4583 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4584 tail (list inter hw (car dws) (org-last dws))))
4585 (add-to-list 'org-todo-heads hw 'append)
4586 (push kws1 org-todo-sets)
4587 (setq org-done-keywords (append org-done-keywords dws nil))
4588 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4589 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4590 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4591 (setq org-todo-sets (nreverse org-todo-sets)
4592 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4593 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4594 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4595 ;; Process the constants
4596 (when const
4597 (let (e cst)
4598 (while (setq e (pop const))
4599 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4600 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4601 (setq org-table-formula-constants-local cst)))
4603 ;; Process the tags.
4604 (when tags
4605 (let (e tgs)
4606 (while (setq e (pop tags))
4607 (cond
4608 ((equal e "{") (push '(:startgroup) tgs))
4609 ((equal e "}") (push '(:endgroup) tgs))
4610 ((equal e "\\n") (push '(:newline) tgs))
4611 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4612 (push (cons (match-string 1 e)
4613 (string-to-char (match-string 2 e)))
4614 tgs))
4615 (t (push (list e) tgs))))
4616 (org-set-local 'org-tag-alist nil)
4617 (while (setq e (pop tgs))
4618 (or (and (stringp (car e))
4619 (assoc (car e) org-tag-alist))
4620 (push e org-tag-alist)))))
4622 ;; Compute the regular expressions and other local variables.
4623 ;; Using `org-outline-regexp-bol' would complicate them much,
4624 ;; because of the fixed white space at the end of that string.
4625 (if (not org-done-keywords)
4626 (setq org-done-keywords (and org-todo-keywords-1
4627 (list (org-last org-todo-keywords-1)))))
4628 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4629 (length org-scheduled-string)
4630 (length org-clock-string)
4631 (length org-closed-string)))
4632 org-drawer-regexp
4633 (concat "^[ \t]*:\\("
4634 (mapconcat 'regexp-quote org-drawers "\\|")
4635 "\\):[ \t]*$")
4636 org-not-done-keywords
4637 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4638 org-todo-regexp
4639 (concat "\\("
4640 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4641 "\\)")
4642 org-not-done-regexp
4643 (concat "\\("
4644 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4645 "\\)")
4646 org-not-done-heading-regexp
4647 (format org-heading-keyword-regexp-format org-not-done-regexp)
4648 org-todo-line-regexp
4649 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4650 org-complex-heading-regexp
4651 (concat "^\\(\\*+\\)"
4652 "\\(?: +" org-todo-regexp "\\)?"
4653 "\\(?: +\\(\\[#.\\]\\)\\)?"
4654 "\\(?: +\\(.*?\\)\\)??"
4655 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4656 "[ \t]*$")
4657 org-complex-heading-regexp-format
4658 (concat "^\\(\\*+\\)"
4659 "\\(?: +" org-todo-regexp "\\)?"
4660 "\\(?: +\\(\\[#.\\]\\)\\)?"
4661 "\\(?: +"
4662 ;; Stats cookies can be stuck to body.
4663 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4664 "\\(%s\\)"
4665 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4666 "\\)"
4667 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4668 "[ \t]*$")
4669 org-todo-line-tags-regexp
4670 (concat "^\\(\\*+\\)"
4671 "\\(?: +" org-todo-regexp "\\)?"
4672 "\\(?: +\\(.*?\\)\\)??"
4673 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4674 "[ \t]*$")
4675 org-deadline-regexp (concat "\\<" org-deadline-string)
4676 org-deadline-time-regexp
4677 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4678 org-deadline-line-regexp
4679 (concat "\\<\\(" org-deadline-string "\\).*")
4680 org-scheduled-regexp
4681 (concat "\\<" org-scheduled-string)
4682 org-scheduled-time-regexp
4683 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4684 org-closed-time-regexp
4685 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4686 org-keyword-time-regexp
4687 (concat "\\<\\(" org-scheduled-string
4688 "\\|" org-deadline-string
4689 "\\|" org-closed-string
4690 "\\|" org-clock-string "\\)"
4691 " *[[<]\\([^]>]+\\)[]>]")
4692 org-keyword-time-not-clock-regexp
4693 (concat "\\<\\(" org-scheduled-string
4694 "\\|" org-deadline-string
4695 "\\|" org-closed-string
4696 "\\)"
4697 " *[[<]\\([^]>]+\\)[]>]")
4698 org-maybe-keyword-time-regexp
4699 (concat "\\(\\<\\(" org-scheduled-string
4700 "\\|" org-deadline-string
4701 "\\|" org-closed-string
4702 "\\|" org-clock-string "\\)\\)?"
4703 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4704 org-all-time-keywords
4705 (mapcar (lambda (w) (substring w 0 -1))
4706 (list org-scheduled-string org-deadline-string
4707 org-clock-string org-closed-string))
4709 (org-compute-latex-and-specials-regexp)
4710 (org-set-font-lock-defaults))))
4712 (defun org-file-contents (file &optional noerror)
4713 "Return the contents of FILE, as a string."
4714 (if (or (not file)
4715 (not (file-readable-p file)))
4716 (if noerror
4717 (progn
4718 (message "Cannot read file \"%s\"" file)
4719 (ding) (sit-for 2)
4721 (error "Cannot read file \"%s\"" file))
4722 (with-temp-buffer
4723 (insert-file-contents file)
4724 (buffer-string))))
4726 (defun org-extract-log-state-settings (x)
4727 "Extract the log state setting from a TODO keyword string.
4728 This will extract info from a string like \"WAIT(w@/!)\"."
4729 (let (kw key log1 log2)
4730 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4731 (setq kw (match-string 1 x)
4732 key (and (match-end 2) (match-string 2 x))
4733 log1 (and (match-end 3) (match-string 3 x))
4734 log2 (and (match-end 4) (match-string 4 x)))
4735 (and (or log1 log2)
4736 (list kw
4737 (and log1 (if (equal log1 "!") 'time 'note))
4738 (and log2 (if (equal log2 "!") 'time 'note)))))))
4740 (defun org-remove-keyword-keys (list)
4741 "Remove a pair of parenthesis at the end of each string in LIST."
4742 (mapcar (lambda (x)
4743 (if (string-match "(.*)$" x)
4744 (substring x 0 (match-beginning 0))
4746 list))
4748 (defun org-assign-fast-keys (alist)
4749 "Assign fast keys to a keyword-key alist.
4750 Respect keys that are already there."
4751 (let (new e (alt ?0))
4752 (while (setq e (pop alist))
4753 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4754 (cdr e)) ;; Key already assigned.
4755 (push e new)
4756 (let ((clist (string-to-list (downcase (car e))))
4757 (used (append new alist)))
4758 (when (= (car clist) ?@)
4759 (pop clist))
4760 (while (and clist (rassoc (car clist) used))
4761 (pop clist))
4762 (unless clist
4763 (while (rassoc alt used)
4764 (incf alt)))
4765 (push (cons (car e) (or (car clist) alt)) new))))
4766 (nreverse new)))
4768 ;;; Some variables used in various places
4770 (defvar org-window-configuration nil
4771 "Used in various places to store a window configuration.")
4772 (defvar org-selected-window nil
4773 "Used in various places to store a window configuration.")
4774 (defvar org-finish-function nil
4775 "Function to be called when `C-c C-c' is used.
4776 This is for getting out of special buffers like capture.")
4779 ;; FIXME: Occasionally check by commenting these, to make sure
4780 ;; no other functions uses these, forgetting to let-bind them.
4781 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4782 (defvar org-last-state)
4783 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4785 ;; Defined somewhere in this file, but used before definition.
4786 (defvar org-entities) ;; defined in org-entities.el
4787 (defvar org-struct-menu)
4788 (defvar org-org-menu)
4789 (defvar org-tbl-menu)
4791 ;;;; Define the Org-mode
4793 ;; We use a before-change function to check if a table might need
4794 ;; an update.
4795 (defvar org-table-may-need-update t
4796 "Indicates that a table might need an update.
4797 This variable is set by `org-before-change-function'.
4798 `org-table-align' sets it back to nil.")
4799 (defun org-before-change-function (beg end)
4800 "Every change indicates that a table might need an update."
4801 (setq org-table-may-need-update t))
4802 (defvar org-mode-map)
4803 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4804 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4805 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4806 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4807 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4808 (defvar org-table-buffer-is-an nil)
4810 (defvar bidi-paragraph-direction)
4811 (defvar buffer-face-mode-face)
4813 (require 'outline)
4814 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4815 (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"))
4816 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4818 ;; Other stuff we need.
4819 (require 'time-date)
4820 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4821 (require 'easymenu)
4822 (require 'overlay)
4824 (require 'org-macs)
4825 (require 'org-entities)
4826 ;; (require 'org-compat) moved higher up in the file before it is first used
4827 (require 'org-faces)
4828 (require 'org-list)
4829 (require 'org-pcomplete)
4830 (require 'org-src)
4831 (require 'org-footnote)
4833 ;; babel
4834 (require 'ob)
4835 (require 'ob-table)
4836 (require 'ob-lob)
4837 (require 'ob-ref)
4838 (require 'ob-tangle)
4839 (require 'ob-comint)
4840 (require 'ob-keys)
4842 ;;;###autoload
4843 (define-derived-mode org-mode outline-mode "Org"
4844 "Outline-based notes management and organizer, alias
4845 \"Carsten's outline-mode for keeping track of everything.\"
4847 Org-mode develops organizational tasks around a NOTES file which
4848 contains information about projects as plain text. Org-mode is
4849 implemented on top of outline-mode, which is ideal to keep the content
4850 of large files well structured. It supports ToDo items, deadlines and
4851 time stamps, which magically appear in the diary listing of the Emacs
4852 calendar. Tables are easily created with a built-in table editor.
4853 Plain text URL-like links connect to websites, emails (VM), Usenet
4854 messages (Gnus), BBDB entries, and any files related to the project.
4855 For printing and sharing of notes, an Org-mode file (or a part of it)
4856 can be exported as a structured ASCII or HTML file.
4858 The following commands are available:
4860 \\{org-mode-map}"
4862 ;; Get rid of Outline menus, they are not needed
4863 ;; Need to do this here because define-derived-mode sets up
4864 ;; the keymap so late. Still, it is a waste to call this each time
4865 ;; we switch another buffer into org-mode.
4866 (if (featurep 'xemacs)
4867 (when (boundp 'outline-mode-menu-heading)
4868 ;; Assume this is Greg's port, it uses easymenu
4869 (easy-menu-remove outline-mode-menu-heading)
4870 (easy-menu-remove outline-mode-menu-show)
4871 (easy-menu-remove outline-mode-menu-hide))
4872 (define-key org-mode-map [menu-bar headings] 'undefined)
4873 (define-key org-mode-map [menu-bar hide] 'undefined)
4874 (define-key org-mode-map [menu-bar show] 'undefined))
4876 (org-load-modules-maybe)
4877 (easy-menu-add org-org-menu)
4878 (easy-menu-add org-tbl-menu)
4879 (org-install-agenda-files-menu)
4880 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4881 (add-to-invisibility-spec '(org-cwidth))
4882 (add-to-invisibility-spec '(org-hide-block . t))
4883 (when (featurep 'xemacs)
4884 (org-set-local 'line-move-ignore-invisible t))
4885 (org-set-local 'outline-regexp org-outline-regexp)
4886 (org-set-local 'outline-level 'org-outline-level)
4887 (setq bidi-paragraph-direction 'left-to-right)
4888 (when (and org-ellipsis
4889 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4890 (fboundp 'make-glyph-code))
4891 (unless org-display-table
4892 (setq org-display-table (make-display-table)))
4893 (set-display-table-slot
4894 org-display-table 4
4895 (vconcat (mapcar
4896 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4897 org-ellipsis)))
4898 (if (stringp org-ellipsis) org-ellipsis "..."))))
4899 (setq buffer-display-table org-display-table))
4900 (org-set-regexps-and-options)
4901 (when (and org-tag-faces (not org-tags-special-faces-re))
4902 ;; tag faces set outside customize.... force initialization.
4903 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4904 ;; Calc embedded
4905 (org-set-local 'calc-embedded-open-mode "# ")
4906 (modify-syntax-entry ?@ "w")
4907 (if org-startup-truncated (setq truncate-lines t))
4908 (org-set-local 'font-lock-unfontify-region-function
4909 'org-unfontify-region)
4910 ;; Activate before-change-function
4911 (org-set-local 'org-table-may-need-update t)
4912 (org-add-hook 'before-change-functions 'org-before-change-function nil
4913 'local)
4914 ;; Check for running clock before killing a buffer
4915 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4916 ;; Indentation.
4917 (org-set-local 'indent-line-function 'org-indent-line)
4918 (org-set-local 'indent-region-function 'org-indent-region)
4919 ;; Initialize radio targets.
4920 (org-update-radio-target-regexp)
4921 ;; Filling and auto-filling.
4922 (org-setup-filling)
4923 ;; Comments.
4924 (org-setup-comments-handling)
4925 ;; Beginning/end of defun
4926 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4927 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4928 ;; Next error for sparse trees
4929 (org-set-local 'next-error-function 'org-occur-next-match)
4930 ;; Make sure dependence stuff works reliably, even for users who set it
4931 ;; too late :-(
4932 (if org-enforce-todo-dependencies
4933 (add-hook 'org-blocker-hook
4934 'org-block-todo-from-children-or-siblings-or-parent)
4935 (remove-hook 'org-blocker-hook
4936 'org-block-todo-from-children-or-siblings-or-parent))
4937 (if org-enforce-todo-checkbox-dependencies
4938 (add-hook 'org-blocker-hook
4939 'org-block-todo-from-checkboxes)
4940 (remove-hook 'org-blocker-hook
4941 'org-block-todo-from-checkboxes))
4943 ;; Align options lines
4944 (org-set-local
4945 'align-mode-rules-list
4946 '((org-in-buffer-settings
4947 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4948 (modes . '(org-mode)))))
4950 ;; Imenu
4951 (org-set-local 'imenu-create-index-function
4952 'org-imenu-get-tree)
4954 ;; Make isearch reveal context
4955 (if (or (featurep 'xemacs)
4956 (not (boundp 'outline-isearch-open-invisible-function)))
4957 ;; Emacs 21 and XEmacs make use of the hook
4958 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4959 ;; Emacs 22 deals with this through a special variable
4960 (org-set-local 'outline-isearch-open-invisible-function
4961 (lambda (&rest ignore) (org-show-context 'isearch))))
4963 ;; Turn on org-beamer-mode?
4964 (and org-startup-with-beamer-mode (org-beamer-mode))
4966 ;; Setup the pcomplete hooks
4967 (set (make-local-variable 'pcomplete-command-completion-function)
4968 'org-pcomplete-initial)
4969 (set (make-local-variable 'pcomplete-command-name-function)
4970 'org-command-at-point)
4971 (set (make-local-variable 'pcomplete-default-completion-function)
4972 'ignore)
4973 (set (make-local-variable 'pcomplete-parse-arguments-function)
4974 'org-parse-arguments)
4975 (set (make-local-variable 'pcomplete-termination-string) "")
4976 (when (>= emacs-major-version 23)
4977 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4979 ;; If empty file that did not turn on org-mode automatically, make it to.
4980 (if (and org-insert-mode-line-in-empty-file
4981 (org-called-interactively-p 'any)
4982 (= (point-min) (point-max)))
4983 (insert "# -*- mode: org -*-\n\n"))
4984 (unless org-inhibit-startup
4985 (when org-startup-align-all-tables
4986 (let ((bmp (buffer-modified-p)))
4987 (org-table-map-tables 'org-table-align 'quietly)
4988 (set-buffer-modified-p bmp)))
4989 (when org-startup-with-inline-images
4990 (org-display-inline-images))
4991 (when org-startup-indented
4992 (require 'org-indent)
4993 (org-indent-mode 1))
4994 (unless org-inhibit-startup-visibility-stuff
4995 (org-set-startup-visibility)))
4996 ;; Try to set org-hide correctly
4997 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
4999 (when (fboundp 'abbrev-table-put)
5000 (abbrev-table-put org-mode-abbrev-table
5001 :parents (list text-mode-abbrev-table)))
5003 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5006 (defun org-find-invisible-foreground ()
5007 (let ((candidates (remove
5008 "unspecified-bg"
5009 (list
5010 (face-background 'default)
5011 (face-background 'org-default)
5012 (cdr (assoc 'background-color default-frame-alist))
5013 (cdr (assoc 'background-color initial-frame-alist))
5014 (cdr (assoc 'background-color window-system-default-frame-alist))
5015 (face-foreground 'org-hide)))))
5016 (car (remove nil candidates))))
5018 (defun org-current-time ()
5019 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5020 (if (> (car org-time-stamp-rounding-minutes) 1)
5021 (let ((r (car org-time-stamp-rounding-minutes))
5022 (time (decode-time)))
5023 (apply 'encode-time
5024 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5025 (nthcdr 2 time))))
5026 (current-time)))
5028 (defun org-today ()
5029 "Return today date, considering `org-extend-today-until'."
5030 (time-to-days
5031 (time-subtract (current-time)
5032 (list 0 (* 3600 org-extend-today-until) 0))))
5034 ;;;; Font-Lock stuff, including the activators
5036 (defvar org-mouse-map (make-sparse-keymap))
5037 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5038 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5039 (when org-mouse-1-follows-link
5040 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5041 (when org-tab-follows-link
5042 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5043 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5045 (require 'font-lock)
5047 (defconst org-non-link-chars "]\t\n\r<>")
5048 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5049 "shell" "elisp" "doi" "message"))
5050 (defvar org-link-types-re nil
5051 "Matches a link that has a url-like prefix like \"http:\"")
5052 (defvar org-link-re-with-space nil
5053 "Matches a link with spaces, optional angular brackets around it.")
5054 (defvar org-link-re-with-space2 nil
5055 "Matches a link with spaces, optional angular brackets around it.")
5056 (defvar org-link-re-with-space3 nil
5057 "Matches a link with spaces, only for internal part in bracket links.")
5058 (defvar org-angle-link-re nil
5059 "Matches link with angular brackets, spaces are allowed.")
5060 (defvar org-plain-link-re nil
5061 "Matches plain link, without spaces.")
5062 (defvar org-bracket-link-regexp nil
5063 "Matches a link in double brackets.")
5064 (defvar org-bracket-link-analytic-regexp nil
5065 "Regular expression used to analyze links.
5066 Here is what the match groups contain after a match:
5067 1: http:
5068 2: http
5069 3: path
5070 4: [desc]
5071 5: desc")
5072 (defvar org-bracket-link-analytic-regexp++ nil
5073 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5074 (defvar org-any-link-re nil
5075 "Regular expression matching any link.")
5077 (defcustom org-match-sexp-depth 3
5078 "Number of stacked braces for sub/superscript matching.
5079 This has to be set before loading org.el to be effective."
5080 :group 'org-export-translation ; ??????????????????????????/
5081 :type 'integer)
5083 (defun org-create-multibrace-regexp (left right n)
5084 "Create a regular expression which will match a balanced sexp.
5085 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5086 as single character strings.
5087 The regexp returned will match the entire expression including the
5088 delimiters. It will also define a single group which contains the
5089 match except for the outermost delimiters. The maximum depth of
5090 stacked delimiters is N. Escaping delimiters is not possible."
5091 (let* ((nothing (concat "[^" left right "]*?"))
5092 (or "\\|")
5093 (re nothing)
5094 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5095 (while (> n 1)
5096 (setq n (1- n)
5097 re (concat re or next)
5098 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5099 (concat left "\\(" re "\\)" right)))
5101 (defvar org-match-substring-regexp
5102 (concat
5103 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5104 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5105 "\\|"
5106 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5107 "\\|"
5108 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5109 "The regular expression matching a sub- or superscript.")
5111 (defvar org-match-substring-with-braces-regexp
5112 (concat
5113 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5114 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5115 "\\)")
5116 "The regular expression matching a sub- or superscript, forcing braces.")
5118 (defun org-make-link-regexps ()
5119 "Update the link regular expressions.
5120 This should be called after the variable `org-link-types' has changed."
5121 (setq org-link-types-re
5122 (concat
5123 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5124 org-link-re-with-space
5125 (concat
5126 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5127 "\\([^" org-non-link-chars " ]"
5128 "[^" org-non-link-chars "]*"
5129 "[^" org-non-link-chars " ]\\)>?")
5130 org-link-re-with-space2
5131 (concat
5132 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5133 "\\([^" org-non-link-chars " ]"
5134 "[^\t\n\r]*"
5135 "[^" org-non-link-chars " ]\\)>?")
5136 org-link-re-with-space3
5137 (concat
5138 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5139 "\\([^" org-non-link-chars " ]"
5140 "[^\t\n\r]*\\)")
5141 org-angle-link-re
5142 (concat
5143 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5144 "\\([^" org-non-link-chars " ]"
5145 "[^" org-non-link-chars "]*"
5146 "\\)>")
5147 org-plain-link-re
5148 (concat
5149 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5150 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5151 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5152 org-bracket-link-regexp
5153 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5154 org-bracket-link-analytic-regexp
5155 (concat
5156 "\\[\\["
5157 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5158 "\\([^]]+\\)"
5159 "\\]"
5160 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5161 "\\]")
5162 org-bracket-link-analytic-regexp++
5163 (concat
5164 "\\[\\["
5165 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5166 "\\([^]]+\\)"
5167 "\\]"
5168 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5169 "\\]")
5170 org-any-link-re
5171 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5172 org-angle-link-re "\\)\\|\\("
5173 org-plain-link-re "\\)")))
5175 (org-make-link-regexps)
5177 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5178 "Regular expression for fast time stamp matching.")
5179 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5180 "Regular expression for fast time stamp matching.")
5181 (defconst org-ts-regexp0
5182 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5183 "Regular expression matching time strings for analysis.
5184 This one does not require the space after the date, so it can be used
5185 on a string that terminates immediately after the date.")
5186 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5187 "Regular expression matching time strings for analysis.")
5188 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5189 "Regular expression matching time stamps, with groups.")
5190 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5191 "Regular expression matching time stamps (also [..]), with groups.")
5192 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5193 "Regular expression matching a time stamp range.")
5194 (defconst org-tr-regexp-both
5195 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5196 "Regular expression matching a time stamp range.")
5197 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5198 org-ts-regexp "\\)?")
5199 "Regular expression matching a time stamp or time stamp range.")
5200 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5201 org-ts-regexp-both "\\)?")
5202 "Regular expression matching a time stamp or time stamp range.
5203 The time stamps may be either active or inactive.")
5205 (defvar org-emph-face nil)
5207 (defun org-do-emphasis-faces (limit)
5208 "Run through the buffer and add overlays to emphasized strings."
5209 (let (rtn a)
5210 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5211 (if (not (= (char-after (match-beginning 3))
5212 (char-after (match-beginning 4))))
5213 (progn
5214 (setq rtn t)
5215 (setq a (assoc (match-string 3) org-emphasis-alist))
5216 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5217 'face
5218 (nth 1 a))
5219 (and (nth 4 a)
5220 (org-remove-flyspell-overlays-in
5221 (match-beginning 0) (match-end 0)))
5222 (add-text-properties (match-beginning 2) (match-end 2)
5223 '(font-lock-multiline t org-emphasis t))
5224 (when org-hide-emphasis-markers
5225 (add-text-properties (match-end 4) (match-beginning 5)
5226 '(invisible org-link))
5227 (add-text-properties (match-beginning 3) (match-end 3)
5228 '(invisible org-link)))))
5229 (backward-char 1))
5230 rtn))
5232 (defun org-emphasize (&optional char)
5233 "Insert or change an emphasis, i.e. a font like bold or italic.
5234 If there is an active region, change that region to a new emphasis.
5235 If there is no region, just insert the marker characters and position
5236 the cursor between them.
5237 CHAR should be either the marker character, or the first character of the
5238 HTML tag associated with that emphasis. If CHAR is a space, the means
5239 to remove the emphasis of the selected region.
5240 If char is not given (for example in an interactive call) it
5241 will be prompted for."
5242 (interactive)
5243 (let ((eal org-emphasis-alist) e det
5244 (erc org-emphasis-regexp-components)
5245 (prompt "")
5246 (string "") beg end move tag c s)
5247 (if (org-region-active-p)
5248 (setq beg (region-beginning) end (region-end)
5249 string (buffer-substring beg end))
5250 (setq move t))
5252 (while (setq e (pop eal))
5253 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5254 c (aref tag 0))
5255 (push (cons c (string-to-char (car e))) det)
5256 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5257 (substring tag 1)))))
5258 (setq det (nreverse det))
5259 (unless char
5260 (message "%s" (concat "Emphasis marker or tag:" prompt))
5261 (setq char (read-char-exclusive)))
5262 (setq char (or (cdr (assoc char det)) char))
5263 (if (equal char ?\ )
5264 (setq s "" move nil)
5265 (unless (assoc (char-to-string char) org-emphasis-alist)
5266 (error "No such emphasis marker: \"%c\"" char))
5267 (setq s (char-to-string char)))
5268 (while (and (> (length string) 1)
5269 (equal (substring string 0 1) (substring string -1))
5270 (assoc (substring string 0 1) org-emphasis-alist))
5271 (setq string (substring string 1 -1)))
5272 (setq string (concat s string s))
5273 (if beg (delete-region beg end))
5274 (unless (or (bolp)
5275 (string-match (concat "[" (nth 0 erc) "\n]")
5276 (char-to-string (char-before (point)))))
5277 (insert " "))
5278 (unless (or (eobp)
5279 (string-match (concat "[" (nth 1 erc) "\n]")
5280 (char-to-string (char-after (point)))))
5281 (insert " ") (backward-char 1))
5282 (insert string)
5283 (and move (backward-char 1))))
5285 (defconst org-nonsticky-props
5286 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5288 (defsubst org-rear-nonsticky-at (pos)
5289 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5291 (defun org-activate-plain-links (limit)
5292 "Run through the buffer and add overlays to links."
5293 (catch 'exit
5294 (let (f)
5295 (when (re-search-forward (concat org-plain-link-re) limit t)
5296 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5297 (setq f (get-text-property (match-beginning 0) 'face))
5298 (if (or (eq f 'org-tag)
5299 (and (listp f) (memq 'org-tag f)))
5301 (add-text-properties (match-beginning 0) (match-end 0)
5302 (list 'mouse-face 'highlight
5303 'face 'org-link
5304 'keymap org-mouse-map))
5305 (org-rear-nonsticky-at (match-end 0)))
5306 t))))
5308 (defun org-activate-code (limit)
5309 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5310 (progn
5311 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5312 (remove-text-properties (match-beginning 0) (match-end 0)
5313 '(display t invisible t intangible t))
5314 t)))
5316 (defcustom org-src-fontify-natively nil
5317 "When non-nil, fontify code in code blocks."
5318 :type 'boolean
5319 :version "24.1"
5320 :group 'org-appearance
5321 :group 'org-babel)
5323 (defcustom org-allow-promoting-top-level-subtree nil
5324 "When non-nil, allow promoting a top level subtree.
5325 The leading star of the top level headline will be replaced
5326 by a #."
5327 :type 'boolean
5328 :version "24.1"
5329 :group 'org-appearance)
5331 (defun org-fontify-meta-lines-and-blocks (limit)
5332 (condition-case nil
5333 (org-fontify-meta-lines-and-blocks-1 limit)
5334 (error (message "org-mode fontification error"))))
5336 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5337 "Fontify #+ lines and blocks, in the correct ways."
5338 (let ((case-fold-search t))
5339 (if (re-search-forward
5340 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5341 limit t)
5342 (let ((beg (match-beginning 0))
5343 (block-start (match-end 0))
5344 (block-end nil)
5345 (lang (match-string 7))
5346 (beg1 (line-beginning-position 2))
5347 (dc1 (downcase (match-string 2)))
5348 (dc3 (downcase (match-string 3)))
5349 end end1 quoting block-type ovl)
5350 (cond
5351 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5352 ;; a single line of backend-specific content
5353 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5354 (remove-text-properties (match-beginning 0) (match-end 0)
5355 '(display t invisible t intangible t))
5356 (add-text-properties (match-beginning 1) (match-end 3)
5357 '(font-lock-fontified t face org-meta-line))
5358 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5359 '(font-lock-fontified t face org-block))
5360 ; for backend-specific code
5362 ((and (match-end 4) (equal dc3 "+begin"))
5363 ;; Truly a block
5364 (setq block-type (downcase (match-string 5))
5365 quoting (member block-type org-protecting-blocks))
5366 (when (re-search-forward
5367 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5368 nil t) ;; on purpose, we look further than LIMIT
5369 (setq end (min (point-max) (match-end 0))
5370 end1 (min (point-max) (1- (match-beginning 0))))
5371 (setq block-end (match-beginning 0))
5372 (when quoting
5373 (remove-text-properties beg end
5374 '(display t invisible t intangible t)))
5375 (add-text-properties
5376 beg end
5377 '(font-lock-fontified t font-lock-multiline t))
5378 (add-text-properties beg beg1 '(face org-meta-line))
5379 (add-text-properties end1 (min (point-max) (1+ end))
5380 '(face org-meta-line)) ; for end_src
5381 (cond
5382 ((and lang (not (string= lang "")) org-src-fontify-natively)
5383 (org-src-font-lock-fontify-block lang block-start block-end)
5384 ;; remove old background overlays
5385 (mapc (lambda (ov)
5386 (if (eq (overlay-get ov 'face) 'org-block-background)
5387 (delete-overlay ov)))
5388 (overlays-at (/ (+ beg1 block-end) 2)))
5389 ;; add a background overlay
5390 (setq ovl (make-overlay beg1 block-end))
5391 (overlay-put ovl 'face 'org-block-background)
5392 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5393 (quoting
5394 (add-text-properties beg1 (min (point-max) (1+ end1))
5395 '(face org-block))) ; end of source block
5396 ((not org-fontify-quote-and-verse-blocks))
5397 ((string= block-type "quote")
5398 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5399 ((string= block-type "verse")
5400 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5401 (add-text-properties beg beg1 '(face org-block-begin-line))
5402 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5403 '(face org-block-end-line))
5405 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5406 (add-text-properties
5407 beg (match-end 3)
5408 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5409 '(font-lock-fontified t invisible t)
5410 '(font-lock-fontified t face org-document-info-keyword)))
5411 (add-text-properties
5412 (match-beginning 6) (match-end 6)
5413 (if (string-equal dc1 "+title:")
5414 '(font-lock-fontified t face org-document-title)
5415 '(font-lock-fontified t face org-document-info))))
5416 ((or (equal dc1 "+results")
5417 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5418 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5419 "+call:" "+header:" "+headers:" "+name:"))
5420 (and (match-end 4) (equal dc3 "+attr")))
5421 (add-text-properties
5422 beg (match-end 0)
5423 '(font-lock-fontified t face org-meta-line))
5425 ((member dc3 '(" " ""))
5426 (add-text-properties
5427 beg (match-end 0)
5428 '(font-lock-fontified t face font-lock-comment-face)))
5429 ((not (member (char-after beg) '(?\ ?\t)))
5430 ;; just any other in-buffer setting, but not indented
5431 (add-text-properties
5432 beg (match-end 0)
5433 '(font-lock-fontified t face org-meta-line))
5435 (t nil))))))
5437 (defun org-activate-angle-links (limit)
5438 "Run through the buffer and add overlays to links."
5439 (if (re-search-forward org-angle-link-re limit t)
5440 (progn
5441 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5442 (add-text-properties (match-beginning 0) (match-end 0)
5443 (list 'mouse-face 'highlight
5444 'keymap org-mouse-map))
5445 (org-rear-nonsticky-at (match-end 0))
5446 t)))
5448 (defun org-activate-footnote-links (limit)
5449 "Run through the buffer and add overlays to footnotes."
5450 (let ((fn (org-footnote-next-reference-or-definition limit)))
5451 (when fn
5452 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5453 (org-remove-flyspell-overlays-in beg end)
5454 (add-text-properties beg end
5455 (list 'mouse-face 'highlight
5456 'keymap org-mouse-map
5457 'help-echo
5458 (if (= (point-at-bol) beg)
5459 "Footnote definition"
5460 "Footnote reference")
5461 'font-lock-fontified t
5462 'font-lock-multiline t
5463 'face 'org-footnote))))))
5465 (defun org-activate-bracket-links (limit)
5466 "Run through the buffer and add overlays to bracketed links."
5467 (if (re-search-forward org-bracket-link-regexp limit t)
5468 (let* ((help (concat "LINK: "
5469 (org-match-string-no-properties 1)))
5470 ;; FIXME: above we should remove the escapes.
5471 ;; but that requires another match, protecting match data,
5472 ;; a lot of overhead for font-lock.
5473 (ip (org-maybe-intangible
5474 (list 'invisible 'org-link
5475 'keymap org-mouse-map 'mouse-face 'highlight
5476 'font-lock-multiline t 'help-echo help)))
5477 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5478 'font-lock-multiline t 'help-echo help)))
5479 ;; We need to remove the invisible property here. Table narrowing
5480 ;; may have made some of this invisible.
5481 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5482 (remove-text-properties (match-beginning 0) (match-end 0)
5483 '(invisible nil))
5484 (if (match-end 3)
5485 (progn
5486 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5487 (org-rear-nonsticky-at (match-beginning 3))
5488 (add-text-properties (match-beginning 3) (match-end 3) vp)
5489 (org-rear-nonsticky-at (match-end 3))
5490 (add-text-properties (match-end 3) (match-end 0) ip)
5491 (org-rear-nonsticky-at (match-end 0)))
5492 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5493 (org-rear-nonsticky-at (match-beginning 1))
5494 (add-text-properties (match-beginning 1) (match-end 1) vp)
5495 (org-rear-nonsticky-at (match-end 1))
5496 (add-text-properties (match-end 1) (match-end 0) ip)
5497 (org-rear-nonsticky-at (match-end 0)))
5498 t)))
5500 (defun org-activate-dates (limit)
5501 "Run through the buffer and add overlays to dates."
5502 (if (re-search-forward org-tsr-regexp-both limit t)
5503 (progn
5504 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5505 (add-text-properties (match-beginning 0) (match-end 0)
5506 (list 'mouse-face 'highlight
5507 'keymap org-mouse-map))
5508 (org-rear-nonsticky-at (match-end 0))
5509 (when org-display-custom-times
5510 (if (match-end 3)
5511 (org-display-custom-time (match-beginning 3) (match-end 3)))
5512 (org-display-custom-time (match-beginning 1) (match-end 1)))
5513 t)))
5515 (defvar org-target-link-regexp nil
5516 "Regular expression matching radio targets in plain text.")
5517 (make-variable-buffer-local 'org-target-link-regexp)
5518 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5519 "Regular expression matching a link target.")
5520 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5521 "Regular expression matching a radio target.")
5522 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5523 "Regular expression matching any target.")
5525 (defun org-activate-target-links (limit)
5526 "Run through the buffer and add overlays to target matches."
5527 (when org-target-link-regexp
5528 (let ((case-fold-search t))
5529 (if (re-search-forward org-target-link-regexp limit t)
5530 (progn
5531 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5532 (add-text-properties (match-beginning 0) (match-end 0)
5533 (list 'mouse-face 'highlight
5534 'keymap org-mouse-map
5535 'help-echo "Radio target link"
5536 'org-linked-text t))
5537 (org-rear-nonsticky-at (match-end 0))
5538 t)))))
5540 (defun org-update-radio-target-regexp ()
5541 "Find all radio targets in this file and update the regular expression."
5542 (interactive)
5543 (when (memq 'radio org-activate-links)
5544 (setq org-target-link-regexp
5545 (org-make-target-link-regexp (org-all-targets 'radio)))
5546 (org-restart-font-lock)))
5548 (defun org-hide-wide-columns (limit)
5549 (let (s e)
5550 (setq s (text-property-any (point) (or limit (point-max))
5551 'org-cwidth t))
5552 (when s
5553 (setq e (next-single-property-change s 'org-cwidth))
5554 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5555 (goto-char e)
5556 t)))
5558 (defvar org-latex-and-specials-regexp nil
5559 "Regular expression for highlighting export special stuff.")
5560 (defvar org-match-substring-regexp)
5561 (defvar org-match-substring-with-braces-regexp)
5563 ;; This should be with the exporter code, but we also use if for font-locking
5564 (defconst org-export-html-special-string-regexps
5565 '(("\\\\-" . "&shy;")
5566 ("---\\([^-]\\)" . "&mdash;\\1")
5567 ("--\\([^-]\\)" . "&ndash;\\1")
5568 ("\\.\\.\\." . "&hellip;"))
5569 "Regular expressions for special string conversion.")
5572 (defun org-compute-latex-and-specials-regexp ()
5573 "Compute regular expression for stuff treated specially by exporters."
5574 (if (not org-highlight-latex-fragments-and-specials)
5575 (org-set-local 'org-latex-and-specials-regexp nil)
5576 (require 'org-exp)
5577 (let*
5578 ((matchers (plist-get org-format-latex-options :matchers))
5579 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5580 org-latex-regexps)))
5581 (org-export-allow-BIND nil)
5582 (options (org-combine-plists (org-default-export-plist)
5583 (org-infile-export-plist)))
5584 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5585 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5586 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5587 (org-export-html-expand (plist-get options :expand-quoted-html))
5588 (org-export-with-special-strings (plist-get options :special-strings))
5589 (re-sub
5590 (cond
5591 ((equal org-export-with-sub-superscripts '{})
5592 (list org-match-substring-with-braces-regexp))
5593 (org-export-with-sub-superscripts
5594 (list org-match-substring-regexp))))
5595 (re-latex
5596 (if org-export-with-LaTeX-fragments
5597 (mapcar (lambda (x) (nth 1 x)) latexs)))
5598 (re-macros
5599 (if org-export-with-TeX-macros
5600 (list (concat "\\\\"
5601 (regexp-opt
5602 (append
5604 (delq nil
5605 (mapcar 'car-safe
5606 (append org-entities-user
5607 org-entities)))
5608 (if (boundp 'org-latex-entities)
5609 (mapcar (lambda (x)
5610 (or (car-safe x) x))
5611 org-latex-entities)
5612 nil))
5613 'words))) ; FIXME
5615 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5616 (re-special (if org-export-with-special-strings
5617 (mapcar (lambda (x) (car x))
5618 org-export-html-special-string-regexps)))
5619 (re-rest
5620 (delq nil
5621 (list
5622 (if org-export-html-expand "@<[^>\n]+>")
5623 ))))
5624 (org-set-local
5625 'org-latex-and-specials-regexp
5626 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5627 re-rest) "\\|")))))
5629 (defun org-do-latex-and-special-faces (limit)
5630 "Run through the buffer and add overlays to links."
5631 (when org-latex-and-specials-regexp
5632 (let (rtn d)
5633 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5634 limit t))
5635 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5636 'face))
5637 '(org-code org-verbatim underline)))
5638 (progn
5639 (setq rtn t
5640 d (cond ((member (char-after (1+ (match-beginning 0)))
5641 '(?_ ?^)) 1)
5642 (t 0)))
5643 (font-lock-prepend-text-property
5644 (+ d (match-beginning 0)) (match-end 0)
5645 'face 'org-latex-and-export-specials)
5646 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5647 '(font-lock-multiline t)))))
5648 rtn)))
5650 (defun org-restart-font-lock ()
5651 "Restart `font-lock-mode', to force refontification."
5652 (when (and (boundp 'font-lock-mode) font-lock-mode)
5653 (font-lock-mode -1)
5654 (font-lock-mode 1)))
5656 (defun org-all-targets (&optional radio)
5657 "Return a list of all targets in this file.
5658 With optional argument RADIO, only find radio targets."
5659 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5660 rtn)
5661 (save-excursion
5662 (goto-char (point-min))
5663 (while (re-search-forward re nil t)
5664 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5665 rtn)))
5667 (defun org-make-target-link-regexp (targets)
5668 "Make regular expression matching all strings in TARGETS.
5669 The regular expression finds the targets also if there is a line break
5670 between words."
5671 (and targets
5672 (concat
5673 "\\<\\("
5674 (mapconcat
5675 (lambda (x)
5676 (setq x (regexp-quote x))
5677 (while (string-match " +" x)
5678 (setq x (replace-match "\\s-+" t t x)))
5680 targets
5681 "\\|")
5682 "\\)\\>")))
5684 (defun org-activate-tags (limit)
5685 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5686 (progn
5687 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5688 (add-text-properties (match-beginning 1) (match-end 1)
5689 (list 'mouse-face 'highlight
5690 'keymap org-mouse-map))
5691 (org-rear-nonsticky-at (match-end 1))
5692 t)))
5694 (defun org-outline-level ()
5695 "Compute the outline level of the heading at point.
5696 This function assumes that the cursor is at the beginning of a line matched
5697 by `outline-regexp'. Otherwise it returns garbage.
5698 If this is called at a normal headline, the level is the number of stars.
5699 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5700 (save-excursion
5701 (looking-at org-outline-regexp)
5702 (1- (- (match-end 0) (match-beginning 0)))))
5704 (defvar org-font-lock-keywords nil)
5706 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5707 "Regular expression matching a property line.")
5709 (defvar org-font-lock-hook nil
5710 "Functions to be called for special font lock stuff.")
5712 (defvar org-font-lock-set-keywords-hook nil
5713 "Functions that can manipulate `org-font-lock-extra-keywords'.
5714 This is called after `org-font-lock-extra-keywords' is defined, but before
5715 it is installed to be used by font lock. This can be useful if something
5716 needs to be inserted at a specific position in the font-lock sequence.")
5718 (defun org-font-lock-hook (limit)
5719 "Run `org-font-lock-hook' within LIMIT."
5720 (run-hook-with-args 'org-font-lock-hook limit))
5722 (defun org-set-font-lock-defaults ()
5723 "Set font lock defaults for the current buffer."
5724 (let* ((em org-fontify-emphasized-text)
5725 (lk org-activate-links)
5726 (org-font-lock-extra-keywords
5727 (list
5728 ;; Call the hook
5729 '(org-font-lock-hook)
5730 ;; Headlines
5731 `(,(if org-fontify-whole-heading-line
5732 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5733 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5734 (1 (org-get-level-face 1))
5735 (2 (org-get-level-face 2))
5736 (3 (org-get-level-face 3)))
5737 ;; Table lines
5738 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5739 (1 'org-table t))
5740 ;; Table internals
5741 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5742 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5743 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5744 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5745 ;; Drawers
5746 (list org-drawer-regexp '(0 'org-special-keyword t))
5747 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5748 ;; Properties
5749 (list org-property-re
5750 '(1 'org-special-keyword t)
5751 '(3 'org-property-value t))
5752 ;; Links
5753 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5754 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5755 (if (memq 'plain lk) '(org-activate-plain-links))
5756 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5757 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5758 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5759 (if (memq 'footnote lk) '(org-activate-footnote-links))
5760 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5761 '(org-hide-wide-columns (0 nil append))
5762 ;; TODO keyword
5763 (list (format org-heading-keyword-regexp-format
5764 org-todo-regexp)
5765 '(2 (org-get-todo-face 2) t))
5766 ;; DONE
5767 (if org-fontify-done-headline
5768 (list (format org-heading-keyword-regexp-format
5769 (concat
5770 "\\(?:"
5771 (mapconcat 'regexp-quote org-done-keywords "\\|")
5772 "\\)"))
5773 '(2 'org-headline-done t))
5774 nil)
5775 ;; Priorities
5776 '(org-font-lock-add-priority-faces)
5777 ;; Tags
5778 '(org-font-lock-add-tag-faces)
5779 ;; Special keywords
5780 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5781 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5782 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5783 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5784 ;; Emphasis
5785 (if em
5786 (if (featurep 'xemacs)
5787 '(org-do-emphasis-faces (0 nil append))
5788 '(org-do-emphasis-faces)))
5789 ;; Checkboxes
5790 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5791 1 'org-checkbox prepend)
5792 (if (cdr (assq 'checkbox org-list-automatic-rules))
5793 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5794 (0 (org-get-checkbox-statistics-face) t)))
5795 ;; Description list items
5796 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5797 1 'org-list-dt prepend)
5798 ;; ARCHIVEd headings
5799 (list (concat
5800 org-outline-regexp-bol
5801 "\\(.*:" org-archive-tag ":.*\\)")
5802 '(1 'org-archived prepend))
5803 ;; Specials
5804 '(org-do-latex-and-special-faces)
5805 '(org-fontify-entities)
5806 '(org-raise-scripts)
5807 ;; Code
5808 '(org-activate-code (1 'org-code t))
5809 ;; COMMENT
5810 (list (format org-heading-keyword-regexp-format
5811 (concat "\\("
5812 org-comment-string "\\|" org-quote-string
5813 "\\)"))
5814 '(2 'org-special-keyword t))
5815 ;; Blocks and meta lines
5816 '(org-fontify-meta-lines-and-blocks)
5818 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5819 (run-hooks 'org-font-lock-set-keywords-hook)
5820 ;; Now set the full font-lock-keywords
5821 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5822 (org-set-local 'font-lock-defaults
5823 '(org-font-lock-keywords t nil nil backward-paragraph))
5824 (kill-local-variable 'font-lock-keywords) nil))
5826 (defun org-toggle-pretty-entities ()
5827 "Toggle the composition display of entities as UTF8 characters."
5828 (interactive)
5829 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5830 (org-restart-font-lock)
5831 (if org-pretty-entities
5832 (message "Entities are displayed as UTF8 characters")
5833 (save-restriction
5834 (widen)
5835 (org-decompose-region (point-min) (point-max))
5836 (message "Entities are displayed plain"))))
5838 (defvar org-custom-properties-overlays nil
5839 "List of overlays used for custom properties.")
5840 (make-variable-buffer-local 'org-custom-properties-overlays)
5842 (defun org-toggle-custom-properties-visibility ()
5843 "Display or hide properties in `org-custom-properties'."
5844 (interactive)
5845 (if org-custom-properties-overlays
5846 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5847 (setq org-custom-properties-overlays nil))
5848 (unless (not org-custom-properties)
5849 (save-excursion
5850 (save-restriction
5851 (widen)
5852 (goto-char (point-min))
5853 (while (re-search-forward org-property-re nil t)
5854 (mapc (lambda(p)
5855 (when (equal p (substring (match-string 1) 1 -1))
5856 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5857 (overlay-put o 'invisible t)
5858 (overlay-put o 'org-custom-property t)
5859 (push o org-custom-properties-overlays))))
5860 org-custom-properties)))))))
5862 (defun org-fontify-entities (limit)
5863 "Find an entity to fontify."
5864 (let (ee)
5865 (when org-pretty-entities
5866 (catch 'match
5867 (while (re-search-forward
5868 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5869 limit t)
5870 (if (and (not (org-in-indented-comment-line))
5871 (setq ee (org-entity-get (match-string 1)))
5872 (= (length (nth 6 ee)) 1))
5873 (let*
5874 ((end (if (equal (match-string 2) "{}")
5875 (match-end 2)
5876 (match-end 1))))
5877 (add-text-properties
5878 (match-beginning 0) end
5879 (list 'font-lock-fontified t))
5880 (compose-region (match-beginning 0) end
5881 (nth 6 ee) nil)
5882 (backward-char 1)
5883 (throw 'match t))))
5884 nil))))
5886 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5887 "Fontify string S like in Org-mode."
5888 (with-temp-buffer
5889 (insert s)
5890 (let ((org-odd-levels-only odd-levels))
5891 (org-mode)
5892 (font-lock-fontify-buffer)
5893 (buffer-string))))
5895 (defvar org-m nil)
5896 (defvar org-l nil)
5897 (defvar org-f nil)
5898 (defun org-get-level-face (n)
5899 "Get the right face for match N in font-lock matching of headlines."
5900 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5901 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5902 (if org-cycle-level-faces
5903 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5904 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5905 (cond
5906 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5907 ((eq n 2) org-f)
5908 (t (if org-level-color-stars-only nil org-f))))
5911 (defun org-get-todo-face (kwd)
5912 "Get the right face for a TODO keyword KWD.
5913 If KWD is a number, get the corresponding match group."
5914 (if (numberp kwd) (setq kwd (match-string kwd)))
5915 (or (org-face-from-face-or-color
5916 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5917 (and (member kwd org-done-keywords) 'org-done)
5918 'org-todo))
5920 (defun org-face-from-face-or-color (context inherit face-or-color)
5921 "Create a face list that inherits INHERIT, but sets the foreground color.
5922 When FACE-OR-COLOR is not a string, just return it."
5923 (if (stringp face-or-color)
5924 (list :inherit inherit
5925 (cdr (assoc context org-faces-easy-properties))
5926 face-or-color)
5927 face-or-color))
5929 (defun org-font-lock-add-tag-faces (limit)
5930 "Add the special tag faces."
5931 (when (and org-tag-faces org-tags-special-faces-re)
5932 (while (re-search-forward org-tags-special-faces-re limit t)
5933 (add-text-properties (match-beginning 1) (match-end 1)
5934 (list 'face (org-get-tag-face 1)
5935 'font-lock-fontified t))
5936 (backward-char 1))))
5938 (defun org-font-lock-add-priority-faces (limit)
5939 "Add the special priority faces."
5940 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5941 (when (save-match-data (org-at-heading-p))
5942 (add-text-properties
5943 (match-beginning 0) (match-end 0)
5944 (list 'face (or (org-face-from-face-or-color
5945 'priority 'org-special-keyword
5946 (cdr (assoc (char-after (match-beginning 1))
5947 org-priority-faces)))
5948 'org-special-keyword)
5949 'font-lock-fontified t)))))
5951 (defun org-get-tag-face (kwd)
5952 "Get the right face for a TODO keyword KWD.
5953 If KWD is a number, get the corresponding match group."
5954 (if (numberp kwd) (setq kwd (match-string kwd)))
5955 (or (org-face-from-face-or-color
5956 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5957 'org-tag))
5959 (defun org-unfontify-region (beg end &optional maybe_loudly)
5960 "Remove fontification and activation overlays from links."
5961 (font-lock-default-unfontify-region beg end)
5962 (let* ((buffer-undo-list t)
5963 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5964 (inhibit-modification-hooks t)
5965 deactivate-mark buffer-file-name buffer-file-truename)
5966 (org-decompose-region beg end)
5967 (remove-text-properties beg end
5968 '(mouse-face t keymap t org-linked-text t
5969 invisible t intangible t
5970 org-no-flyspell t org-emphasis t))
5971 (org-remove-font-lock-display-properties beg end)))
5973 (defconst org-script-display '(((raise -0.3) (height 0.7))
5974 ((raise 0.3) (height 0.7))
5975 ((raise -0.5))
5976 ((raise 0.5)))
5977 "Display properties for showing superscripts and subscripts.")
5979 (defun org-remove-font-lock-display-properties (beg end)
5980 "Remove specific display properties that have been added by font lock.
5981 The will remove the raise properties that are used to show superscripts
5982 and subscripts."
5983 (let (next prop)
5984 (while (< beg end)
5985 (setq next (next-single-property-change beg 'display nil end)
5986 prop (get-text-property beg 'display))
5987 (if (member prop org-script-display)
5988 (put-text-property beg next 'display nil))
5989 (setq beg next))))
5991 (defun org-raise-scripts (limit)
5992 "Add raise properties to sub/superscripts."
5993 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5994 (if (re-search-forward
5995 (if (eq org-use-sub-superscripts t)
5996 org-match-substring-regexp
5997 org-match-substring-with-braces-regexp)
5998 limit t)
5999 (let* ((pos (point)) table-p comment-p
6000 (mpos (match-beginning 3))
6001 (emph-p (get-text-property mpos 'org-emphasis))
6002 (link-p (get-text-property mpos 'mouse-face))
6003 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6004 (goto-char (point-at-bol))
6005 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6006 comment-p (org-looking-at-p "[ \t]*#"))
6007 (goto-char pos)
6008 ;; FIXME: Should we go back one character here, for a_b^c
6009 ;; (goto-char (1- pos)) ;????????????????????
6010 (if (or comment-p emph-p link-p keyw-p)
6012 (put-text-property (match-beginning 3) (match-end 0)
6013 'display
6014 (if (equal (char-after (match-beginning 2)) ?^)
6015 (nth (if table-p 3 1) org-script-display)
6016 (nth (if table-p 2 0) org-script-display)))
6017 (add-text-properties (match-beginning 2) (match-end 2)
6018 (list 'invisible t
6019 'org-dwidth t 'org-dwidth-n 1))
6020 (if (and (eq (char-after (match-beginning 3)) ?{)
6021 (eq (char-before (match-end 3)) ?}))
6022 (progn
6023 (add-text-properties
6024 (match-beginning 3) (1+ (match-beginning 3))
6025 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6026 (add-text-properties
6027 (1- (match-end 3)) (match-end 3)
6028 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6029 t)))))
6031 ;;;; Visibility cycling, including org-goto and indirect buffer
6033 ;;; Cycling
6035 (defvar org-cycle-global-status nil)
6036 (make-variable-buffer-local 'org-cycle-global-status)
6037 (defvar org-cycle-subtree-status nil)
6038 (make-variable-buffer-local 'org-cycle-subtree-status)
6040 (defvar org-inlinetask-min-level)
6042 ;;;###autoload
6043 (defun org-cycle (&optional arg)
6044 "TAB-action and visibility cycling for Org-mode.
6046 This is the command invoked in Org-mode by the TAB key. Its main purpose
6047 is outline visibility cycling, but it also invokes other actions
6048 in special contexts.
6050 - When this function is called with a prefix argument, rotate the entire
6051 buffer through 3 states (global cycling)
6052 1. OVERVIEW: Show only top-level headlines.
6053 2. CONTENTS: Show all headlines of all levels, but no body text.
6054 3. SHOW ALL: Show everything.
6055 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6056 determined by the variable `org-startup-folded', and by any VISIBILITY
6057 properties in the buffer.
6058 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6059 including any drawers.
6061 - When inside a table, re-align the table and move to the next field.
6063 - When point is at the beginning of a headline, rotate the subtree started
6064 by this line through 3 different states (local cycling)
6065 1. FOLDED: Only the main headline is shown.
6066 2. CHILDREN: The main headline and the direct children are shown.
6067 From this state, you can move to one of the children
6068 and zoom in further.
6069 3. SUBTREE: Show the entire subtree, including body text.
6070 If there is no subtree, switch directly from CHILDREN to FOLDED.
6072 - When point is at the beginning of an empty headline and the variable
6073 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6074 of the headline by demoting and promoting it to likely levels. This
6075 speeds up creation document structure by pressing TAB once or several
6076 times right after creating a new headline.
6078 - When there is a numeric prefix, go up to a heading with level ARG, do
6079 a `show-subtree' and return to the previous cursor position. If ARG
6080 is negative, go up that many levels.
6082 - When point is not at the beginning of a headline, execute the global
6083 binding for TAB, which is re-indenting the line. See the option
6084 `org-cycle-emulate-tab' for details.
6086 - Special case: if point is at the beginning of the buffer and there is
6087 no headline in line 1, this function will act as if called with prefix arg
6088 (C-u TAB, same as S-TAB) also when called without prefix arg.
6089 But only if also the variable `org-cycle-global-at-bob' is t."
6090 (interactive "P")
6091 (org-load-modules-maybe)
6092 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6093 (and org-cycle-level-after-item/entry-creation
6094 (or (org-cycle-level)
6095 (org-cycle-item-indentation))))
6096 (let* ((limit-level
6097 (or org-cycle-max-level
6098 (and (boundp 'org-inlinetask-min-level)
6099 org-inlinetask-min-level
6100 (1- org-inlinetask-min-level))))
6101 (nstars (and limit-level
6102 (if org-odd-levels-only
6103 (and limit-level (1- (* limit-level 2)))
6104 limit-level)))
6105 (org-outline-regexp
6106 (if (not (derived-mode-p 'org-mode))
6107 outline-regexp
6108 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6109 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6110 (not (looking-at org-outline-regexp))))
6111 (org-cycle-hook
6112 (if bob-special
6113 (delq 'org-optimize-window-after-visibility-change
6114 (copy-sequence org-cycle-hook))
6115 org-cycle-hook))
6116 (pos (point)))
6118 (if (or bob-special (equal arg '(4)))
6119 ;; special case: use global cycling
6120 (setq arg t))
6122 (cond
6124 ((equal arg '(16))
6125 (setq last-command 'dummy)
6126 (org-set-startup-visibility)
6127 (message "Startup visibility, plus VISIBILITY properties"))
6129 ((equal arg '(64))
6130 (show-all)
6131 (message "Entire buffer visible, including drawers"))
6133 ;; Table: enter it or move to the next field.
6134 ((org-at-table-p 'any)
6135 (if (org-at-table.el-p)
6136 (message "Use C-c ' to edit table.el tables")
6137 (if arg (org-table-edit-field t)
6138 (org-table-justify-field-maybe)
6139 (call-interactively 'org-table-next-field))))
6141 ((run-hook-with-args-until-success
6142 'org-tab-after-check-for-table-hook))
6144 ;; Global cycling: delegate to `org-cycle-internal-global'.
6145 ((eq arg t) (org-cycle-internal-global))
6147 ;; Drawers: delegate to `org-flag-drawer'.
6148 ((and org-drawers org-drawer-regexp
6149 (save-excursion
6150 (beginning-of-line 1)
6151 (looking-at org-drawer-regexp)))
6152 (org-flag-drawer ; toggle block visibility
6153 (not (get-char-property (match-end 0) 'invisible))))
6155 ;; Show-subtree, ARG levels up from here.
6156 ((integerp arg)
6157 (save-excursion
6158 (org-back-to-heading)
6159 (outline-up-heading (if (< arg 0) (- arg)
6160 (- (funcall outline-level) arg)))
6161 (org-show-subtree)))
6163 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6164 ((and (featurep 'org-inlinetask)
6165 (org-inlinetask-at-task-p)
6166 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6167 (org-inlinetask-toggle-visibility))
6169 ((org-try-cdlatex-tab))
6171 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6172 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6173 (save-excursion (beginning-of-line 1)
6174 (looking-at org-outline-regexp)))
6175 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6176 (org-cycle-internal-local))
6178 ;; From there: TAB emulation and template completion.
6179 (buffer-read-only (org-back-to-heading))
6181 ((run-hook-with-args-until-success
6182 'org-tab-after-check-for-cycling-hook))
6184 ((org-try-structure-completion))
6186 ((run-hook-with-args-until-success
6187 'org-tab-before-tab-emulation-hook))
6189 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6190 (or (not (bolp))
6191 (not (looking-at org-outline-regexp))))
6192 (call-interactively (global-key-binding "\t")))
6194 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6195 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6196 (or (and (eq org-cycle-emulate-tab 'white)
6197 (= (match-end 0) (point-at-eol)))
6198 (and (eq org-cycle-emulate-tab 'whitestart)
6199 (>= (match-end 0) pos))))
6201 (eq org-cycle-emulate-tab t))
6202 (call-interactively (global-key-binding "\t")))
6204 (t (save-excursion
6205 (org-back-to-heading)
6206 (org-cycle)))))))
6208 (defun org-cycle-internal-global ()
6209 "Do the global cycling action."
6210 ;; Hack to avoid display of messages for .org attachments in Gnus
6211 (let ((ga (string-match "\\*fontification" (buffer-name))))
6212 (cond
6213 ((and (eq last-command this-command)
6214 (eq org-cycle-global-status 'overview))
6215 ;; We just created the overview - now do table of contents
6216 ;; This can be slow in very large buffers, so indicate action
6217 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6218 (unless ga (message "CONTENTS..."))
6219 (org-content)
6220 (unless ga (message "CONTENTS...done"))
6221 (setq org-cycle-global-status 'contents)
6222 (run-hook-with-args 'org-cycle-hook 'contents))
6224 ((and (eq last-command this-command)
6225 (eq org-cycle-global-status 'contents))
6226 ;; We just showed the table of contents - now show everything
6227 (run-hook-with-args 'org-pre-cycle-hook 'all)
6228 (show-all)
6229 (unless ga (message "SHOW ALL"))
6230 (setq org-cycle-global-status 'all)
6231 (run-hook-with-args 'org-cycle-hook 'all))
6234 ;; Default action: go to overview
6235 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6236 (org-overview)
6237 (unless ga (message "OVERVIEW"))
6238 (setq org-cycle-global-status 'overview)
6239 (run-hook-with-args 'org-cycle-hook 'overview)))))
6241 (defun org-cycle-internal-local ()
6242 "Do the local cycling action."
6243 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6244 ;; First, determine end of headline (EOH), end of subtree or item
6245 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6246 (save-excursion
6247 (if (org-at-item-p)
6248 (progn
6249 (beginning-of-line)
6250 (setq struct (org-list-struct))
6251 (setq eoh (point-at-eol))
6252 (setq eos (org-list-get-item-end-before-blank (point) struct))
6253 (setq has-children (org-list-has-child-p (point) struct)))
6254 (org-back-to-heading)
6255 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6256 (setq eos (save-excursion
6257 (org-end-of-subtree t)
6258 (unless (eobp)
6259 (skip-chars-forward " \t\n"))
6260 (if (eobp) (point) (1- (point)))))
6261 (setq has-children
6262 (or (save-excursion
6263 (let ((level (funcall outline-level)))
6264 (outline-next-heading)
6265 (and (org-at-heading-p t)
6266 (> (funcall outline-level) level))))
6267 (save-excursion
6268 (org-list-search-forward (org-item-beginning-re) eos t)))))
6269 ;; Determine end invisible part of buffer (EOL)
6270 (beginning-of-line 2)
6271 ;; XEmacs doesn't have `next-single-char-property-change'
6272 (if (featurep 'xemacs)
6273 (while (and (not (eobp)) ;; this is like `next-line'
6274 (get-char-property (1- (point)) 'invisible))
6275 (beginning-of-line 2))
6276 (while (and (not (eobp)) ;; this is like `next-line'
6277 (get-char-property (1- (point)) 'invisible))
6278 (goto-char (next-single-char-property-change (point) 'invisible))
6279 (and (eolp) (beginning-of-line 2))))
6280 (setq eol (point)))
6281 ;; Find out what to do next and set `this-command'
6282 (cond
6283 ((= eos eoh)
6284 ;; Nothing is hidden behind this heading
6285 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6286 (message "EMPTY ENTRY")
6287 (setq org-cycle-subtree-status nil)
6288 (save-excursion
6289 (goto-char eos)
6290 (outline-next-heading)
6291 (if (outline-invisible-p) (org-flag-heading nil))))
6292 ((and (or (>= eol eos)
6293 (not (string-match "\\S-" (buffer-substring eol eos))))
6294 (or has-children
6295 (not (setq children-skipped
6296 org-cycle-skip-children-state-if-no-children))))
6297 ;; Entire subtree is hidden in one line: children view
6298 (run-hook-with-args 'org-pre-cycle-hook 'children)
6299 (if (org-at-item-p)
6300 (org-list-set-item-visibility (point-at-bol) struct 'children)
6301 (org-show-entry)
6302 (org-with-limited-levels (show-children))
6303 ;; FIXME: This slows down the func way too much.
6304 ;; How keep drawers hidden in subtree anyway?
6305 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6306 ;; (org-cycle-hide-drawers 'subtree))
6308 ;; Fold every list in subtree to top-level items.
6309 (when (eq org-cycle-include-plain-lists 'integrate)
6310 (save-excursion
6311 (org-back-to-heading)
6312 (while (org-list-search-forward (org-item-beginning-re) eos t)
6313 (beginning-of-line 1)
6314 (let* ((struct (org-list-struct))
6315 (prevs (org-list-prevs-alist struct))
6316 (end (org-list-get-bottom-point struct)))
6317 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6318 (org-list-get-all-items (point) struct prevs))
6319 (goto-char end))))))
6320 (message "CHILDREN")
6321 (save-excursion
6322 (goto-char eos)
6323 (outline-next-heading)
6324 (if (outline-invisible-p) (org-flag-heading nil)))
6325 (setq org-cycle-subtree-status 'children)
6326 (run-hook-with-args 'org-cycle-hook 'children))
6327 ((or children-skipped
6328 (and (eq last-command this-command)
6329 (eq org-cycle-subtree-status 'children)))
6330 ;; We just showed the children, or no children are there,
6331 ;; now show everything.
6332 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6333 (outline-flag-region eoh eos nil)
6334 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6335 (setq org-cycle-subtree-status 'subtree)
6336 (run-hook-with-args 'org-cycle-hook 'subtree))
6338 ;; Default action: hide the subtree.
6339 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6340 (outline-flag-region eoh eos t)
6341 (message "FOLDED")
6342 (setq org-cycle-subtree-status 'folded)
6343 (run-hook-with-args 'org-cycle-hook 'folded)))))
6345 ;;;###autoload
6346 (defun org-global-cycle (&optional arg)
6347 "Cycle the global visibility. For details see `org-cycle'.
6348 With \\[universal-argument] prefix arg, switch to startup visibility.
6349 With a numeric prefix, show all headlines up to that level."
6350 (interactive "P")
6351 (let ((org-cycle-include-plain-lists
6352 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6353 (cond
6354 ((integerp arg)
6355 (show-all)
6356 (hide-sublevels arg)
6357 (setq org-cycle-global-status 'contents))
6358 ((equal arg '(4))
6359 (org-set-startup-visibility)
6360 (message "Startup visibility, plus VISIBILITY properties."))
6362 (org-cycle '(4))))))
6364 (defun org-set-startup-visibility ()
6365 "Set the visibility required by startup options and properties."
6366 (cond
6367 ((eq org-startup-folded t)
6368 (org-cycle '(4)))
6369 ((eq org-startup-folded 'content)
6370 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6371 (org-cycle '(4)) (org-cycle '(4)))))
6372 (unless (eq org-startup-folded 'showeverything)
6373 (if org-hide-block-startup (org-hide-block-all))
6374 (org-set-visibility-according-to-property 'no-cleanup)
6375 (org-cycle-hide-archived-subtrees 'all)
6376 (org-cycle-hide-drawers 'all)
6377 (org-cycle-show-empty-lines t)))
6379 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6380 "Switch subtree visibilities according to :VISIBILITY: property."
6381 (interactive)
6382 (let (org-show-entry-below state)
6383 (save-excursion
6384 (goto-char (point-min))
6385 (while (re-search-forward
6386 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6387 nil t)
6388 (setq state (match-string 1))
6389 (save-excursion
6390 (org-back-to-heading t)
6391 (hide-subtree)
6392 (org-reveal)
6393 (cond
6394 ((equal state '("fold" "folded"))
6395 (hide-subtree))
6396 ((equal state "children")
6397 (org-show-hidden-entry)
6398 (show-children))
6399 ((equal state "content")
6400 (save-excursion
6401 (save-restriction
6402 (org-narrow-to-subtree)
6403 (org-content))))
6404 ((member state '("all" "showall"))
6405 (show-subtree)))))
6406 (unless no-cleanup
6407 (org-cycle-hide-archived-subtrees 'all)
6408 (org-cycle-hide-drawers 'all)
6409 (org-cycle-show-empty-lines 'all)))))
6411 ;; This function uses outline-regexp instead of the more fundamental
6412 ;; org-outline-regexp so that org-cycle-global works outside of Org
6413 ;; buffers, where outline-regexp is needed.
6414 (defun org-overview ()
6415 "Switch to overview mode, showing only top-level headlines.
6416 Really, this shows all headlines with level equal or greater than the level
6417 of the first headline in the buffer. This is important, because if the
6418 first headline is not level one, then (hide-sublevels 1) gives confusing
6419 results."
6420 (interactive)
6421 (let ((level (save-excursion
6422 (goto-char (point-min))
6423 (if (re-search-forward (concat "^" outline-regexp) nil t)
6424 (progn
6425 (goto-char (match-beginning 0))
6426 (funcall outline-level))))))
6427 (and level (hide-sublevels level))))
6429 (defun org-content (&optional arg)
6430 "Show all headlines in the buffer, like a table of contents.
6431 With numerical argument N, show content up to level N."
6432 (interactive "P")
6433 (save-excursion
6434 ;; Visit all headings and show their offspring
6435 (and (integerp arg) (org-overview))
6436 (goto-char (point-max))
6437 (catch 'exit
6438 (while (and (progn (condition-case nil
6439 (outline-previous-visible-heading 1)
6440 (error (goto-char (point-min))))
6442 (looking-at org-outline-regexp))
6443 (if (integerp arg)
6444 (show-children (1- arg))
6445 (show-branches))
6446 (if (bobp) (throw 'exit nil))))))
6449 (defun org-optimize-window-after-visibility-change (state)
6450 "Adjust the window after a change in outline visibility.
6451 This function is the default value of the hook `org-cycle-hook'."
6452 (when (get-buffer-window (current-buffer))
6453 (cond
6454 ((eq state 'content) nil)
6455 ((eq state 'all) nil)
6456 ((eq state 'folded) nil)
6457 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6458 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6460 (defun org-remove-empty-overlays-at (pos)
6461 "Remove outline overlays that do not contain non-white stuff."
6462 (mapc
6463 (lambda (o)
6464 (and (eq 'outline (overlay-get o 'invisible))
6465 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6466 (overlay-end o))))
6467 (delete-overlay o)))
6468 (overlays-at pos)))
6470 (defun org-clean-visibility-after-subtree-move ()
6471 "Fix visibility issues after moving a subtree."
6472 ;; First, find a reasonable region to look at:
6473 ;; Start two siblings above, end three below
6474 (let* ((beg (save-excursion
6475 (and (org-get-last-sibling)
6476 (org-get-last-sibling))
6477 (point)))
6478 (end (save-excursion
6479 (and (org-get-next-sibling)
6480 (org-get-next-sibling)
6481 (org-get-next-sibling))
6482 (if (org-at-heading-p)
6483 (point-at-eol)
6484 (point))))
6485 (level (looking-at "\\*+"))
6486 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6487 (save-excursion
6488 (save-restriction
6489 (narrow-to-region beg end)
6490 (when re
6491 ;; Properly fold already folded siblings
6492 (goto-char (point-min))
6493 (while (re-search-forward re nil t)
6494 (if (and (not (outline-invisible-p))
6495 (save-excursion
6496 (goto-char (point-at-eol)) (outline-invisible-p)))
6497 (hide-entry))))
6498 (org-cycle-show-empty-lines 'overview)
6499 (org-cycle-hide-drawers 'overview)))))
6501 (defun org-cycle-show-empty-lines (state)
6502 "Show empty lines above all visible headlines.
6503 The region to be covered depends on STATE when called through
6504 `org-cycle-hook'. Lisp program can use t for STATE to get the
6505 entire buffer covered. Note that an empty line is only shown if there
6506 are at least `org-cycle-separator-lines' empty lines before the headline."
6507 (when (not (= org-cycle-separator-lines 0))
6508 (save-excursion
6509 (let* ((n (abs org-cycle-separator-lines))
6510 (re (cond
6511 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6512 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6513 (t (let ((ns (number-to-string (- n 2))))
6514 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6515 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6516 beg end b e)
6517 (cond
6518 ((memq state '(overview contents t))
6519 (setq beg (point-min) end (point-max)))
6520 ((memq state '(children folded))
6521 (setq beg (point) end (progn (org-end-of-subtree t t)
6522 (beginning-of-line 2)
6523 (point)))))
6524 (when beg
6525 (goto-char beg)
6526 (while (re-search-forward re end t)
6527 (unless (get-char-property (match-end 1) 'invisible)
6528 (setq e (match-end 1))
6529 (if (< org-cycle-separator-lines 0)
6530 (setq b (save-excursion
6531 (goto-char (match-beginning 0))
6532 (org-back-over-empty-lines)
6533 (if (save-excursion
6534 (goto-char (max (point-min) (1- (point))))
6535 (org-at-heading-p))
6536 (1- (point))
6537 (point))))
6538 (setq b (match-beginning 1)))
6539 (outline-flag-region b e nil)))))))
6540 ;; Never hide empty lines at the end of the file.
6541 (save-excursion
6542 (goto-char (point-max))
6543 (outline-previous-heading)
6544 (outline-end-of-heading)
6545 (if (and (looking-at "[ \t\n]+")
6546 (= (match-end 0) (point-max)))
6547 (outline-flag-region (point) (match-end 0) nil))))
6549 (defun org-show-empty-lines-in-parent ()
6550 "Move to the parent and re-show empty lines before visible headlines."
6551 (save-excursion
6552 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6553 (org-cycle-show-empty-lines context))))
6555 (defun org-files-list ()
6556 "Return `org-agenda-files' list, plus all open org-mode files.
6557 This is useful for operations that need to scan all of a user's
6558 open and agenda-wise Org files."
6559 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6560 (dolist (buf (buffer-list))
6561 (with-current-buffer buf
6562 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6563 (let ((file (expand-file-name (buffer-file-name))))
6564 (unless (member file files)
6565 (push file files))))))
6566 files))
6568 (defsubst org-entry-beginning-position ()
6569 "Return the beginning position of the current entry."
6570 (save-excursion (outline-back-to-heading t) (point)))
6572 (defsubst org-entry-end-position ()
6573 "Return the end position of the current entry."
6574 (save-excursion (outline-next-heading) (point)))
6576 (defun org-cycle-hide-drawers (state)
6577 "Re-hide all drawers after a visibility state change."
6578 (when (and (derived-mode-p 'org-mode)
6579 (not (memq state '(overview folded contents))))
6580 (save-excursion
6581 (let* ((globalp (memq state '(contents all)))
6582 (beg (if globalp (point-min) (point)))
6583 (end (if globalp (point-max)
6584 (if (eq state 'children)
6585 (save-excursion (outline-next-heading) (point))
6586 (org-end-of-subtree t)))))
6587 (goto-char beg)
6588 (while (re-search-forward org-drawer-regexp end t)
6589 (org-flag-drawer t))))))
6591 (defun org-flag-drawer (flag)
6592 "When FLAG is non-nil, hide the drawer we are within.
6593 Otherwise make it visible."
6594 (save-excursion
6595 (beginning-of-line 1)
6596 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6597 (let ((b (match-end 0)))
6598 (if (re-search-forward
6599 "^[ \t]*:END:"
6600 (save-excursion (outline-next-heading) (point)) t)
6601 (outline-flag-region b (point-at-eol) flag)
6602 (error ":END: line missing at position %s" b))))))
6604 (defun org-subtree-end-visible-p ()
6605 "Is the end of the current subtree visible?"
6606 (pos-visible-in-window-p
6607 (save-excursion (org-end-of-subtree t) (point))))
6609 (defun org-first-headline-recenter (&optional N)
6610 "Move cursor to the first headline and recenter the headline.
6611 Optional argument N means put the headline into the Nth line of the window."
6612 (goto-char (point-min))
6613 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6614 (beginning-of-line)
6615 (recenter (prefix-numeric-value N))))
6617 ;;; Saving and restoring visibility
6619 (defun org-outline-overlay-data (&optional use-markers)
6620 "Return a list of the locations of all outline overlays.
6621 These are overlays with the `invisible' property value `outline'.
6622 The return value is a list of cons cells, with start and stop
6623 positions for each overlay.
6624 If USE-MARKERS is set, return the positions as markers."
6625 (let (beg end)
6626 (save-excursion
6627 (save-restriction
6628 (widen)
6629 (delq nil
6630 (mapcar (lambda (o)
6631 (when (eq (overlay-get o 'invisible) 'outline)
6632 (setq beg (overlay-start o)
6633 end (overlay-end o))
6634 (and beg end (> end beg)
6635 (if use-markers
6636 (cons (move-marker (make-marker) beg)
6637 (move-marker (make-marker) end))
6638 (cons beg end)))))
6639 (overlays-in (point-min) (point-max))))))))
6641 (defun org-set-outline-overlay-data (data)
6642 "Create visibility overlays for all positions in DATA.
6643 DATA should have been made by `org-outline-overlay-data'."
6644 (let (o)
6645 (save-excursion
6646 (save-restriction
6647 (widen)
6648 (show-all)
6649 (mapc (lambda (c)
6650 (outline-flag-region (car c) (cdr c) t))
6651 data)))))
6653 ;;; Folding of blocks
6655 (defvar org-hide-block-overlays nil
6656 "Overlays hiding blocks.")
6657 (make-variable-buffer-local 'org-hide-block-overlays)
6659 (defun org-block-map (function &optional start end)
6660 "Call FUNCTION at the head of all source blocks in the current buffer.
6661 Optional arguments START and END can be used to limit the range."
6662 (let ((start (or start (point-min)))
6663 (end (or end (point-max))))
6664 (save-excursion
6665 (goto-char start)
6666 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6667 (save-excursion
6668 (save-match-data
6669 (goto-char (match-beginning 0))
6670 (funcall function)))))))
6672 (defun org-hide-block-toggle-all ()
6673 "Toggle the visibility of all blocks in the current buffer."
6674 (org-block-map #'org-hide-block-toggle))
6676 (defun org-hide-block-all ()
6677 "Fold all blocks in the current buffer."
6678 (interactive)
6679 (org-show-block-all)
6680 (org-block-map #'org-hide-block-toggle-maybe))
6682 (defun org-show-block-all ()
6683 "Unfold all blocks in the current buffer."
6684 (interactive)
6685 (mapc 'delete-overlay org-hide-block-overlays)
6686 (setq org-hide-block-overlays nil))
6688 (defun org-hide-block-toggle-maybe ()
6689 "Toggle visibility of block at point."
6690 (interactive)
6691 (let ((case-fold-search t))
6692 (if (save-excursion
6693 (beginning-of-line 1)
6694 (looking-at org-block-regexp))
6695 (progn (org-hide-block-toggle)
6696 t) ;; to signal that we took action
6697 nil))) ;; to signal that we did not
6699 (defun org-hide-block-toggle (&optional force)
6700 "Toggle the visibility of the current block."
6701 (interactive)
6702 (save-excursion
6703 (beginning-of-line)
6704 (if (re-search-forward org-block-regexp nil t)
6705 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6706 (end (match-end 0)) ;; end of entire body
6708 (if (memq t (mapcar (lambda (overlay)
6709 (eq (overlay-get overlay 'invisible)
6710 'org-hide-block))
6711 (overlays-at start)))
6712 (if (or (not force) (eq force 'off))
6713 (mapc (lambda (ov)
6714 (when (member ov org-hide-block-overlays)
6715 (setq org-hide-block-overlays
6716 (delq ov org-hide-block-overlays)))
6717 (when (eq (overlay-get ov 'invisible)
6718 'org-hide-block)
6719 (delete-overlay ov)))
6720 (overlays-at start)))
6721 (setq ov (make-overlay start end))
6722 (overlay-put ov 'invisible 'org-hide-block)
6723 ;; make the block accessible to isearch
6724 (overlay-put
6725 ov 'isearch-open-invisible
6726 (lambda (ov)
6727 (when (member ov org-hide-block-overlays)
6728 (setq org-hide-block-overlays
6729 (delq ov org-hide-block-overlays)))
6730 (when (eq (overlay-get ov 'invisible)
6731 'org-hide-block)
6732 (delete-overlay ov))))
6733 (push ov org-hide-block-overlays)))
6734 (error "Not looking at a source block"))))
6736 ;; org-tab-after-check-for-cycling-hook
6737 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6738 ;; Remove overlays when changing major mode
6739 (add-hook 'org-mode-hook
6740 (lambda () (org-add-hook 'change-major-mode-hook
6741 'org-show-block-all 'append 'local)))
6743 ;;; Org-goto
6745 (defvar org-goto-window-configuration nil)
6746 (defvar org-goto-marker nil)
6747 (defvar org-goto-map
6748 (let ((map (make-sparse-keymap)))
6749 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6750 (while (setq cmd (pop cmds))
6751 (substitute-key-definition cmd cmd map global-map)))
6752 (suppress-keymap map)
6753 (org-defkey map "\C-m" 'org-goto-ret)
6754 (org-defkey map [(return)] 'org-goto-ret)
6755 (org-defkey map [(left)] 'org-goto-left)
6756 (org-defkey map [(right)] 'org-goto-right)
6757 (org-defkey map [(control ?g)] 'org-goto-quit)
6758 (org-defkey map "\C-i" 'org-cycle)
6759 (org-defkey map [(tab)] 'org-cycle)
6760 (org-defkey map [(down)] 'outline-next-visible-heading)
6761 (org-defkey map [(up)] 'outline-previous-visible-heading)
6762 (if org-goto-auto-isearch
6763 (if (fboundp 'define-key-after)
6764 (define-key-after map [t] 'org-goto-local-auto-isearch)
6765 nil)
6766 (org-defkey map "q" 'org-goto-quit)
6767 (org-defkey map "n" 'outline-next-visible-heading)
6768 (org-defkey map "p" 'outline-previous-visible-heading)
6769 (org-defkey map "f" 'outline-forward-same-level)
6770 (org-defkey map "b" 'outline-backward-same-level)
6771 (org-defkey map "u" 'outline-up-heading))
6772 (org-defkey map "/" 'org-occur)
6773 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6774 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6775 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6776 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6777 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6778 map))
6780 (defconst org-goto-help
6781 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6782 RET=jump to location [Q]uit and return to previous location
6783 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6785 (defvar org-goto-start-pos) ; dynamically scoped parameter
6787 ;; FIXME: Docstring does not mention both interfaces
6788 (defun org-goto (&optional alternative-interface)
6789 "Look up a different location in the current file, keeping current visibility.
6791 When you want look-up or go to a different location in a
6792 document, the fastest way is often to fold the entire buffer and
6793 then dive into the tree. This method has the disadvantage, that
6794 the previous location will be folded, which may not be what you
6795 want.
6797 This command works around this by showing a copy of the current
6798 buffer in an indirect buffer, in overview mode. You can dive
6799 into the tree in that copy, use org-occur and incremental search
6800 to find a location. When pressing RET or `Q', the command
6801 returns to the original buffer in which the visibility is still
6802 unchanged. After RET it will also jump to the location selected
6803 in the indirect buffer and expose the headline hierarchy above.
6805 With a prefix argument, use the alternative interface: e.g. if
6806 `org-goto-interface' is 'outline use 'outline-path-completion."
6807 (interactive "P")
6808 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6809 (org-refile-use-outline-path t)
6810 (org-refile-target-verify-function nil)
6811 (interface
6812 (if (not alternative-interface)
6813 org-goto-interface
6814 (if (eq org-goto-interface 'outline)
6815 'outline-path-completion
6816 'outline)))
6817 (org-goto-start-pos (point))
6818 (selected-point
6819 (if (eq interface 'outline)
6820 (car (org-get-location (current-buffer) org-goto-help))
6821 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6822 (org-refile-check-position pa)
6823 (nth 3 pa)))))
6824 (if selected-point
6825 (progn
6826 (org-mark-ring-push org-goto-start-pos)
6827 (goto-char selected-point)
6828 (if (or (outline-invisible-p) (org-invisible-p2))
6829 (org-show-context 'org-goto)))
6830 (message "Quit"))))
6832 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6833 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6834 (defvar org-goto-local-auto-isearch-map) ; defined below
6836 (defun org-get-location (buf help)
6837 "Let the user select a location in the Org-mode buffer BUF.
6838 This function uses a recursive edit. It returns the selected position
6839 or nil."
6840 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6841 (isearch-hide-immediately nil)
6842 (isearch-search-fun-function
6843 (lambda () 'org-goto-local-search-headings))
6844 (org-goto-selected-point org-goto-exit-command)
6845 (pop-up-frames nil)
6846 (special-display-buffer-names nil)
6847 (special-display-regexps nil)
6848 (special-display-function nil))
6849 (save-excursion
6850 (save-window-excursion
6851 (delete-other-windows)
6852 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6853 (org-pop-to-buffer-same-window
6854 (condition-case nil
6855 (make-indirect-buffer (current-buffer) "*org-goto*")
6856 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6857 (with-output-to-temp-buffer "*Help*"
6858 (princ help))
6859 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6860 (setq buffer-read-only nil)
6861 (let ((org-startup-truncated t)
6862 (org-startup-folded nil)
6863 (org-startup-align-all-tables nil))
6864 (org-mode)
6865 (org-overview))
6866 (setq buffer-read-only t)
6867 (if (and (boundp 'org-goto-start-pos)
6868 (integer-or-marker-p org-goto-start-pos))
6869 (let ((org-show-hierarchy-above t)
6870 (org-show-siblings t)
6871 (org-show-following-heading t))
6872 (goto-char org-goto-start-pos)
6873 (and (outline-invisible-p) (org-show-context)))
6874 (goto-char (point-min)))
6875 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6876 (message "Select location and press RET")
6877 (use-local-map org-goto-map)
6878 (recursive-edit)
6880 (kill-buffer "*org-goto*")
6881 (cons org-goto-selected-point org-goto-exit-command)))
6883 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6884 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6885 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6886 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6888 (defun org-goto-local-search-headings (string bound noerror)
6889 "Search and make sure that any matches are in headlines."
6890 (catch 'return
6891 (while (if isearch-forward
6892 (search-forward string bound noerror)
6893 (search-backward string bound noerror))
6894 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6895 (and (member :headline context)
6896 (not (member :tags context))))
6897 (throw 'return (point))))))
6899 (defun org-goto-local-auto-isearch ()
6900 "Start isearch."
6901 (interactive)
6902 (goto-char (point-min))
6903 (let ((keys (this-command-keys)))
6904 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6905 (isearch-mode t)
6906 (isearch-process-search-char (string-to-char keys)))))
6908 (defun org-goto-ret (&optional arg)
6909 "Finish `org-goto' by going to the new location."
6910 (interactive "P")
6911 (setq org-goto-selected-point (point)
6912 org-goto-exit-command 'return)
6913 (throw 'exit nil))
6915 (defun org-goto-left ()
6916 "Finish `org-goto' by going to the new location."
6917 (interactive)
6918 (if (org-at-heading-p)
6919 (progn
6920 (beginning-of-line 1)
6921 (setq org-goto-selected-point (point)
6922 org-goto-exit-command 'left)
6923 (throw 'exit nil))
6924 (error "Not on a heading")))
6926 (defun org-goto-right ()
6927 "Finish `org-goto' by going to the new location."
6928 (interactive)
6929 (if (org-at-heading-p)
6930 (progn
6931 (setq org-goto-selected-point (point)
6932 org-goto-exit-command 'right)
6933 (throw 'exit nil))
6934 (error "Not on a heading")))
6936 (defun org-goto-quit ()
6937 "Finish `org-goto' without cursor motion."
6938 (interactive)
6939 (setq org-goto-selected-point nil)
6940 (setq org-goto-exit-command 'quit)
6941 (throw 'exit nil))
6943 ;;; Indirect buffer display of subtrees
6945 (defvar org-indirect-dedicated-frame nil
6946 "This is the frame being used for indirect tree display.")
6947 (defvar org-last-indirect-buffer nil)
6949 (defun org-tree-to-indirect-buffer (&optional arg)
6950 "Create indirect buffer and narrow it to current subtree.
6951 With a numerical prefix ARG, go up to this level and then take that tree.
6952 If ARG is negative, go up that many levels.
6954 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6955 indirect buffer previously made with this command, to avoid proliferation of
6956 indirect buffers. However, when you call the command with a \
6957 \\[universal-argument] prefix, or
6958 when `org-indirect-buffer-display' is `new-frame', the last buffer
6959 is kept so that you can work with several indirect buffers at the same time.
6960 If `org-indirect-buffer-display' is `dedicated-frame', the \
6961 \\[universal-argument] prefix also
6962 requests that a new frame be made for the new buffer, so that the dedicated
6963 frame is not changed."
6964 (interactive "P")
6965 (let ((cbuf (current-buffer))
6966 (cwin (selected-window))
6967 (pos (point))
6968 beg end level heading ibuf)
6969 (save-excursion
6970 (org-back-to-heading t)
6971 (when (numberp arg)
6972 (setq level (org-outline-level))
6973 (if (< arg 0) (setq arg (+ level arg)))
6974 (while (> (setq level (org-outline-level)) arg)
6975 (org-up-heading-safe)))
6976 (setq beg (point)
6977 heading (org-get-heading))
6978 (org-end-of-subtree t t)
6979 (if (org-at-heading-p) (backward-char 1))
6980 (setq end (point)))
6981 (if (and (buffer-live-p org-last-indirect-buffer)
6982 (not (eq org-indirect-buffer-display 'new-frame))
6983 (not arg))
6984 (kill-buffer org-last-indirect-buffer))
6985 (setq ibuf (org-get-indirect-buffer cbuf)
6986 org-last-indirect-buffer ibuf)
6987 (cond
6988 ((or (eq org-indirect-buffer-display 'new-frame)
6989 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6990 (select-frame (make-frame))
6991 (delete-other-windows)
6992 (org-pop-to-buffer-same-window ibuf)
6993 (org-set-frame-title heading))
6994 ((eq org-indirect-buffer-display 'dedicated-frame)
6995 (raise-frame
6996 (select-frame (or (and org-indirect-dedicated-frame
6997 (frame-live-p org-indirect-dedicated-frame)
6998 org-indirect-dedicated-frame)
6999 (setq org-indirect-dedicated-frame (make-frame)))))
7000 (delete-other-windows)
7001 (org-pop-to-buffer-same-window ibuf)
7002 (org-set-frame-title (concat "Indirect: " heading)))
7003 ((eq org-indirect-buffer-display 'current-window)
7004 (org-pop-to-buffer-same-window ibuf))
7005 ((eq org-indirect-buffer-display 'other-window)
7006 (pop-to-buffer ibuf))
7007 (t (error "Invalid value")))
7008 (if (featurep 'xemacs)
7009 (save-excursion (org-mode) (turn-on-font-lock)))
7010 (narrow-to-region beg end)
7011 (show-all)
7012 (goto-char pos)
7013 (run-hook-with-args 'org-cycle-hook 'all)
7014 (and (window-live-p cwin) (select-window cwin))))
7016 (defun org-get-indirect-buffer (&optional buffer)
7017 (setq buffer (or buffer (current-buffer)))
7018 (let ((n 1) (base (buffer-name buffer)) bname)
7019 (while (buffer-live-p
7020 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7021 (setq n (1+ n)))
7022 (condition-case nil
7023 (make-indirect-buffer buffer bname 'clone)
7024 (error (make-indirect-buffer buffer bname)))))
7026 (defun org-set-frame-title (title)
7027 "Set the title of the current frame to the string TITLE."
7028 ;; FIXME: how to name a single frame in XEmacs???
7029 (unless (featurep 'xemacs)
7030 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7032 ;;;; Structure editing
7034 ;;; Inserting headlines
7036 (defun org-previous-line-empty-p ()
7037 (save-excursion
7038 (and (not (bobp))
7039 (or (beginning-of-line 0) t)
7040 (save-match-data
7041 (looking-at "[ \t]*$")))))
7043 (defun org-insert-heading (&optional force-heading invisible-ok)
7044 "Insert a new heading or item with same depth at point.
7045 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7046 If point is at the beginning of a headline, insert a sibling before the
7047 current headline. If point is not at the beginning, split the line,
7048 create the new headline with the text in the current line after point
7049 \(but see also the variable `org-M-RET-may-split-line').
7051 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7052 This is important for non-interactive uses of the command."
7053 (interactive "P")
7054 (if (or (= (buffer-size) 0)
7055 (and (not (save-excursion
7056 (and (ignore-errors (org-back-to-heading invisible-ok))
7057 (org-at-heading-p))))
7058 (or force-heading (not (org-in-item-p)))))
7059 (progn
7060 (insert "\n* ")
7061 (run-hooks 'org-insert-heading-hook))
7062 (when (or force-heading (not (org-insert-item)))
7063 (let* ((empty-line-p nil)
7064 (level nil)
7065 (on-heading (org-at-heading-p))
7066 (head (save-excursion
7067 (condition-case nil
7068 (progn
7069 (org-back-to-heading invisible-ok)
7070 (when (and (not on-heading)
7071 (featurep 'org-inlinetask)
7072 (integerp org-inlinetask-min-level)
7073 (>= (length (match-string 0))
7074 org-inlinetask-min-level))
7075 ;; Find a heading level before the inline task
7076 (while (and (setq level (org-up-heading-safe))
7077 (>= level org-inlinetask-min-level)))
7078 (if (org-at-heading-p)
7079 (org-back-to-heading invisible-ok)
7080 (error "This should not happen")))
7081 (setq empty-line-p (org-previous-line-empty-p))
7082 (match-string 0))
7083 (error "*"))))
7084 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7085 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7086 pos hide-previous previous-pos)
7087 (cond
7088 ((and (org-at-heading-p) (bolp)
7089 (or (bobp)
7090 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7091 ;; insert before the current line
7092 (open-line (if blank 2 1)))
7093 ((and (bolp)
7094 (not org-insert-heading-respect-content)
7095 (or (bobp)
7096 (save-excursion
7097 (backward-char 1) (not (outline-invisible-p)))))
7098 ;; insert right here
7099 nil)
7101 ;; somewhere in the line
7102 (save-excursion
7103 (setq previous-pos (point-at-bol))
7104 (end-of-line)
7105 (setq hide-previous (outline-invisible-p)))
7106 (and org-insert-heading-respect-content (org-show-subtree))
7107 (let ((split
7108 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7109 (save-excursion
7110 (let ((p (point)))
7111 (goto-char (point-at-bol))
7112 (and (looking-at org-complex-heading-regexp)
7113 (match-beginning 4)
7114 (> p (match-beginning 4)))))))
7115 tags pos)
7116 (cond
7117 (org-insert-heading-respect-content
7118 (org-end-of-subtree nil t)
7119 (when (featurep 'org-inlinetask)
7120 (while (and (not (eobp))
7121 (looking-at "\\(\\*+\\)[ \t]+")
7122 (>= (length (match-string 1))
7123 org-inlinetask-min-level))
7124 (org-end-of-subtree nil t)))
7125 (or (bolp) (newline))
7126 (or (org-previous-line-empty-p)
7127 (and blank (newline)))
7128 (open-line 1))
7129 ((org-at-heading-p)
7130 (when hide-previous
7131 (show-children)
7132 (org-show-entry))
7133 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7134 (setq tags (and (match-end 2) (match-string 2)))
7135 (and (match-end 1)
7136 (delete-region (match-beginning 1) (match-end 1)))
7137 (setq pos (point-at-bol))
7138 (or split (end-of-line 1))
7139 (delete-horizontal-space)
7140 (if (string-match "\\`\\*+\\'"
7141 (buffer-substring (point-at-bol) (point)))
7142 (insert " "))
7143 (newline (if blank 2 1))
7144 (when tags
7145 (save-excursion
7146 (goto-char pos)
7147 (end-of-line 1)
7148 (insert " " tags)
7149 (org-set-tags nil 'align))))
7151 (or split (end-of-line 1))
7152 (newline (if blank 2 1)))))))
7153 (insert head) (just-one-space)
7154 (setq pos (point))
7155 (end-of-line 1)
7156 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7157 (when (and org-insert-heading-respect-content hide-previous)
7158 (save-excursion
7159 (goto-char previous-pos)
7160 (hide-subtree)))
7161 (run-hooks 'org-insert-heading-hook)))))
7163 (defun org-get-heading (&optional no-tags no-todo)
7164 "Return the heading of the current entry, without the stars.
7165 When NO-TAGS is non-nil, don't include tags.
7166 When NO-TODO is non-nil, don't include TODO keywords."
7167 (save-excursion
7168 (org-back-to-heading t)
7169 (cond
7170 ((and no-tags no-todo)
7171 (looking-at org-complex-heading-regexp)
7172 (match-string 4))
7173 (no-tags
7174 (looking-at (concat org-outline-regexp
7175 "\\(.*?\\)"
7176 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7177 (match-string 1))
7178 (no-todo
7179 (looking-at org-todo-line-regexp)
7180 (match-string 3))
7181 (t (looking-at org-heading-regexp)
7182 (match-string 2)))))
7184 (defun org-heading-components ()
7185 "Return the components of the current heading.
7186 This is a list with the following elements:
7187 - the level as an integer
7188 - the reduced level, different if `org-odd-levels-only' is set.
7189 - the TODO keyword, or nil
7190 - the priority character, like ?A, or nil if no priority is given
7191 - the headline text itself, or the tags string if no headline text
7192 - the tags string, or nil."
7193 (save-excursion
7194 (org-back-to-heading t)
7195 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7196 (list (length (match-string 1))
7197 (org-reduced-level (length (match-string 1)))
7198 (org-match-string-no-properties 2)
7199 (and (match-end 3) (aref (match-string 3) 2))
7200 (org-match-string-no-properties 4)
7201 (org-match-string-no-properties 5)))))
7203 (defun org-get-entry ()
7204 "Get the entry text, after heading, entire subtree."
7205 (save-excursion
7206 (org-back-to-heading t)
7207 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7209 (defun org-insert-heading-after-current ()
7210 "Insert a new heading with same level as current, after current subtree."
7211 (interactive)
7212 (org-back-to-heading)
7213 (org-insert-heading)
7214 (org-move-subtree-down)
7215 (end-of-line 1))
7217 (defun org-insert-heading-respect-content ()
7218 (interactive)
7219 (let ((org-insert-heading-respect-content t))
7220 (org-insert-heading t)))
7222 (defun org-insert-todo-heading-respect-content (&optional force-state)
7223 (interactive "P")
7224 (let ((org-insert-heading-respect-content t))
7225 (org-insert-todo-heading force-state t)))
7227 (defun org-insert-todo-heading (arg &optional force-heading)
7228 "Insert a new heading with the same level and TODO state as current heading.
7229 If the heading has no TODO state, or if the state is DONE, use the first
7230 state (TODO by default). Also with prefix arg, force first state."
7231 (interactive "P")
7232 (when (or force-heading (not (org-insert-item 'checkbox)))
7233 (org-insert-heading force-heading)
7234 (save-excursion
7235 (org-back-to-heading)
7236 (outline-previous-heading)
7237 (looking-at org-todo-line-regexp))
7238 (let*
7239 ((new-mark-x
7240 (if (or arg
7241 (not (match-beginning 2))
7242 (member (match-string 2) org-done-keywords))
7243 (car org-todo-keywords-1)
7244 (match-string 2)))
7245 (new-mark
7247 (run-hook-with-args-until-success
7248 'org-todo-get-default-hook new-mark-x nil)
7249 new-mark-x)))
7250 (beginning-of-line 1)
7251 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7252 (if org-treat-insert-todo-heading-as-state-change
7253 (org-todo new-mark)
7254 (insert new-mark " "))))
7255 (when org-provide-todo-statistics
7256 (org-update-parent-todo-statistics))))
7258 (defun org-insert-subheading (arg)
7259 "Insert a new subheading and demote it.
7260 Works for outline headings and for plain lists alike."
7261 (interactive "P")
7262 (org-insert-heading arg)
7263 (cond
7264 ((org-at-heading-p) (org-do-demote))
7265 ((org-at-item-p) (org-indent-item))))
7267 (defun org-insert-todo-subheading (arg)
7268 "Insert a new subheading with TODO keyword or checkbox and demote it.
7269 Works for outline headings and for plain lists alike."
7270 (interactive "P")
7271 (org-insert-todo-heading arg)
7272 (cond
7273 ((org-at-heading-p) (org-do-demote))
7274 ((org-at-item-p) (org-indent-item))))
7276 ;;; Promotion and Demotion
7278 (defvar org-after-demote-entry-hook nil
7279 "Hook run after an entry has been demoted.
7280 The cursor will be at the beginning of the entry.
7281 When a subtree is being demoted, the hook will be called for each node.")
7283 (defvar org-after-promote-entry-hook nil
7284 "Hook run after an entry has been promoted.
7285 The cursor will be at the beginning of the entry.
7286 When a subtree is being promoted, the hook will be called for each node.")
7288 (defun org-promote-subtree ()
7289 "Promote the entire subtree.
7290 See also `org-promote'."
7291 (interactive)
7292 (save-excursion
7293 (org-with-limited-levels (org-map-tree 'org-promote)))
7294 (org-fix-position-after-promote))
7296 (defun org-demote-subtree ()
7297 "Demote the entire subtree. See `org-demote'.
7298 See also `org-promote'."
7299 (interactive)
7300 (save-excursion
7301 (org-with-limited-levels (org-map-tree 'org-demote)))
7302 (org-fix-position-after-promote))
7305 (defun org-do-promote ()
7306 "Promote the current heading higher up the tree.
7307 If the region is active in `transient-mark-mode', promote all headings
7308 in the region."
7309 (interactive)
7310 (save-excursion
7311 (if (org-region-active-p)
7312 (org-map-region 'org-promote (region-beginning) (region-end))
7313 (org-promote)))
7314 (org-fix-position-after-promote))
7316 (defun org-do-demote ()
7317 "Demote the current heading lower down the tree.
7318 If the region is active in `transient-mark-mode', demote all headings
7319 in the region."
7320 (interactive)
7321 (save-excursion
7322 (if (org-region-active-p)
7323 (org-map-region 'org-demote (region-beginning) (region-end))
7324 (org-demote)))
7325 (org-fix-position-after-promote))
7327 (defun org-fix-position-after-promote ()
7328 "Make sure that after pro/demotion cursor position is right."
7329 (let ((pos (point)))
7330 (when (save-excursion
7331 (beginning-of-line 1)
7332 (looking-at org-todo-line-regexp)
7333 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7334 (cond ((eobp) (insert " "))
7335 ((eolp) (insert " "))
7336 ((equal (char-after) ?\ ) (forward-char 1))))))
7338 (defun org-current-level ()
7339 "Return the level of the current entry, or nil if before the first headline.
7340 The level is the number of stars at the beginning of the headline."
7341 (save-excursion
7342 (org-with-limited-levels
7343 (if (ignore-errors (org-back-to-heading t))
7344 (funcall outline-level)))))
7346 (defun org-get-previous-line-level ()
7347 "Return the outline depth of the last headline before the current line.
7348 Returns 0 for the first headline in the buffer, and nil if before the
7349 first headline."
7350 (let ((current-level (org-current-level))
7351 (prev-level (when (> (line-number-at-pos) 1)
7352 (save-excursion
7353 (beginning-of-line 0)
7354 (org-current-level)))))
7355 (cond ((null current-level) nil) ; Before first headline
7356 ((null prev-level) 0) ; At first headline
7357 (prev-level))))
7359 (defun org-reduced-level (l)
7360 "Compute the effective level of a heading.
7361 This takes into account the setting of `org-odd-levels-only'."
7362 (cond
7363 ((zerop l) 0)
7364 (org-odd-levels-only (1+ (floor (/ l 2))))
7365 (t l)))
7367 (defun org-level-increment ()
7368 "Return the number of stars that will be added or removed at a
7369 time to headlines when structure editing, based on the value of
7370 `org-odd-levels-only'."
7371 (if org-odd-levels-only 2 1))
7373 (defun org-get-valid-level (level &optional change)
7374 "Rectify a level change under the influence of `org-odd-levels-only'
7375 LEVEL is a current level, CHANGE is by how much the level should be
7376 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7377 even level numbers will become the next higher odd number."
7378 (if org-odd-levels-only
7379 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7380 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7381 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7382 (max 1 (+ level (or change 0)))))
7384 (if (boundp 'define-obsolete-function-alias)
7385 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7386 (define-obsolete-function-alias 'org-get-legal-level
7387 'org-get-valid-level)
7388 (define-obsolete-function-alias 'org-get-legal-level
7389 'org-get-valid-level "23.1")))
7391 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7392 ;; ̀org-with-limited-levels'
7393 (defun org-promote ()
7394 "Promote the current heading higher up the tree.
7395 If the region is active in `transient-mark-mode', promote all headings
7396 in the region."
7397 (org-back-to-heading t)
7398 (let* ((level (save-match-data (funcall outline-level)))
7399 (after-change-functions (remove 'flyspell-after-change-function
7400 after-change-functions))
7401 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7402 (diff (abs (- level (length up-head) -1))))
7403 (cond ((and (= level 1) org-called-with-limited-levels
7404 org-allow-promoting-top-level-subtree)
7405 (replace-match "# " nil t))
7406 ((= level 1)
7407 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7408 (t (replace-match up-head nil t)))
7409 ;; Fixup tag positioning
7410 (unless (= level 1)
7411 (and org-auto-align-tags (org-set-tags nil t))
7412 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7413 (run-hooks 'org-after-promote-entry-hook)))
7415 (defun org-demote ()
7416 "Demote the current heading lower down the tree.
7417 If the region is active in `transient-mark-mode', demote all headings
7418 in the region."
7419 (org-back-to-heading t)
7420 (let* ((level (save-match-data (funcall outline-level)))
7421 (after-change-functions (remove 'flyspell-after-change-function
7422 after-change-functions))
7423 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7424 (diff (abs (- level (length down-head) -1))))
7425 (replace-match down-head nil t)
7426 ;; Fixup tag positioning
7427 (and org-auto-align-tags (org-set-tags nil t))
7428 (if org-adapt-indentation (org-fixup-indentation diff))
7429 (run-hooks 'org-after-demote-entry-hook)))
7431 (defun org-cycle-level ()
7432 "Cycle the level of an empty headline through possible states.
7433 This goes first to child, then to parent, level, then up the hierarchy.
7434 After top level, it switches back to sibling level."
7435 (interactive)
7436 (let ((org-adapt-indentation nil))
7437 (when (org-point-at-end-of-empty-headline)
7438 (setq this-command 'org-cycle-level) ; Only needed for caching
7439 (let ((cur-level (org-current-level))
7440 (prev-level (org-get-previous-line-level)))
7441 (cond
7442 ;; If first headline in file, promote to top-level.
7443 ((= prev-level 0)
7444 (loop repeat (/ (- cur-level 1) (org-level-increment))
7445 do (org-do-promote)))
7446 ;; If same level as prev, demote one.
7447 ((= prev-level cur-level)
7448 (org-do-demote))
7449 ;; If parent is top-level, promote to top level if not already.
7450 ((= prev-level 1)
7451 (loop repeat (/ (- cur-level 1) (org-level-increment))
7452 do (org-do-promote)))
7453 ;; If top-level, return to prev-level.
7454 ((= cur-level 1)
7455 (loop repeat (/ (- prev-level 1) (org-level-increment))
7456 do (org-do-demote)))
7457 ;; If less than prev-level, promote one.
7458 ((< cur-level prev-level)
7459 (org-do-promote))
7460 ;; If deeper than prev-level, promote until higher than
7461 ;; prev-level.
7462 ((> cur-level prev-level)
7463 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7464 do (org-do-promote))))
7465 t))))
7467 (defun org-map-tree (fun)
7468 "Call FUN for every heading underneath the current one."
7469 (org-back-to-heading)
7470 (let ((level (funcall outline-level)))
7471 (save-excursion
7472 (funcall fun)
7473 (while (and (progn
7474 (outline-next-heading)
7475 (> (funcall outline-level) level))
7476 (not (eobp)))
7477 (funcall fun)))))
7479 (defun org-map-region (fun beg end)
7480 "Call FUN for every heading between BEG and END."
7481 (let ((org-ignore-region t))
7482 (save-excursion
7483 (setq end (copy-marker end))
7484 (goto-char beg)
7485 (if (and (re-search-forward org-outline-regexp-bol nil t)
7486 (< (point) end))
7487 (funcall fun))
7488 (while (and (progn
7489 (outline-next-heading)
7490 (< (point) end))
7491 (not (eobp)))
7492 (funcall fun)))))
7494 (defvar org-property-end-re) ; silence byte-compiler
7495 (defun org-fixup-indentation (diff)
7496 "Change the indentation in the current entry by DIFF.
7497 However, if any line in the current entry has no indentation, or if it
7498 would end up with no indentation after the change, nothing at all is done."
7499 (save-excursion
7500 (let ((end (save-excursion (outline-next-heading)
7501 (point-marker)))
7502 (prohibit (if (> diff 0)
7503 "^\\S-"
7504 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7505 col)
7506 (unless (save-excursion (end-of-line 1)
7507 (re-search-forward prohibit end t))
7508 (while (and (< (point) end)
7509 (re-search-forward "^[ \t]+" end t))
7510 (goto-char (match-end 0))
7511 (setq col (current-column))
7512 (if (< diff 0) (replace-match ""))
7513 (org-indent-to-column (+ diff col))))
7514 (move-marker end nil))))
7516 (defun org-convert-to-odd-levels ()
7517 "Convert an org-mode file with all levels allowed to one with odd levels.
7518 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7519 level 5 etc."
7520 (interactive)
7521 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7522 (let ((outline-level 'org-outline-level)
7523 (org-odd-levels-only nil) n)
7524 (save-excursion
7525 (goto-char (point-min))
7526 (while (re-search-forward "^\\*\\*+ " nil t)
7527 (setq n (- (length (match-string 0)) 2))
7528 (while (>= (setq n (1- n)) 0)
7529 (org-demote))
7530 (end-of-line 1))))))
7532 (defun org-convert-to-oddeven-levels ()
7533 "Convert an org-mode file with only odd levels to one with odd/even levels.
7534 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7535 file contains a section with an even level, conversion would
7536 destroy the structure of the file. An error is signaled in this
7537 case."
7538 (interactive)
7539 (goto-char (point-min))
7540 ;; First check if there are no even levels
7541 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7542 (org-show-context t)
7543 (error "Not all levels are odd in this file. Conversion not possible"))
7544 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7545 (let ((outline-regexp org-outline-regexp)
7546 (outline-level 'org-outline-level)
7547 (org-odd-levels-only nil) n)
7548 (save-excursion
7549 (goto-char (point-min))
7550 (while (re-search-forward "^\\*\\*+ " nil t)
7551 (setq n (/ (1- (length (match-string 0))) 2))
7552 (while (>= (setq n (1- n)) 0)
7553 (org-promote))
7554 (end-of-line 1))))))
7556 (defun org-tr-level (n)
7557 "Make N odd if required."
7558 (if org-odd-levels-only (1+ (/ n 2)) n))
7560 ;;; Vertical tree motion, cutting and pasting of subtrees
7562 (defun org-move-subtree-up (&optional arg)
7563 "Move the current subtree up past ARG headlines of the same level."
7564 (interactive "p")
7565 (org-move-subtree-down (- (prefix-numeric-value arg))))
7567 (defun org-move-subtree-down (&optional arg)
7568 "Move the current subtree down past ARG headlines of the same level."
7569 (interactive "p")
7570 (setq arg (prefix-numeric-value arg))
7571 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7572 'org-get-last-sibling))
7573 (ins-point (make-marker))
7574 (cnt (abs arg))
7575 (col (current-column))
7576 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7577 ;; Select the tree
7578 (org-back-to-heading)
7579 (setq beg0 (point))
7580 (save-excursion
7581 (setq ne-beg (org-back-over-empty-lines))
7582 (setq beg (point)))
7583 (save-match-data
7584 (save-excursion (outline-end-of-heading)
7585 (setq folded (outline-invisible-p)))
7586 (outline-end-of-subtree))
7587 (outline-next-heading)
7588 (setq ne-end (org-back-over-empty-lines))
7589 (setq end (point))
7590 (goto-char beg0)
7591 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7592 ;; include less whitespace
7593 (save-excursion
7594 (goto-char beg)
7595 (forward-line (- ne-beg ne-end))
7596 (setq beg (point))))
7597 ;; Find insertion point, with error handling
7598 (while (> cnt 0)
7599 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7600 (progn (goto-char beg0)
7601 (error "Cannot move past superior level or buffer limit")))
7602 (setq cnt (1- cnt)))
7603 (if (> arg 0)
7604 ;; Moving forward - still need to move over subtree
7605 (progn (org-end-of-subtree t t)
7606 (save-excursion
7607 (org-back-over-empty-lines)
7608 (or (bolp) (newline)))))
7609 (setq ne-ins (org-back-over-empty-lines))
7610 (move-marker ins-point (point))
7611 (setq txt (buffer-substring beg end))
7612 (org-save-markers-in-region beg end)
7613 (delete-region beg end)
7614 (org-remove-empty-overlays-at beg)
7615 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7616 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7617 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7618 (let ((bbb (point)))
7619 (insert-before-markers txt)
7620 (org-reinstall-markers-in-region bbb)
7621 (move-marker ins-point bbb))
7622 (or (bolp) (insert "\n"))
7623 (setq ins-end (point))
7624 (goto-char ins-point)
7625 (org-skip-whitespace)
7626 (when (and (< arg 0)
7627 (org-first-sibling-p)
7628 (> ne-ins ne-beg))
7629 ;; Move whitespace back to beginning
7630 (save-excursion
7631 (goto-char ins-end)
7632 (let ((kill-whole-line t))
7633 (kill-line (- ne-ins ne-beg)) (point)))
7634 (insert (make-string (- ne-ins ne-beg) ?\n)))
7635 (move-marker ins-point nil)
7636 (if folded
7637 (hide-subtree)
7638 (org-show-entry)
7639 (show-children)
7640 (org-cycle-hide-drawers 'children))
7641 (org-clean-visibility-after-subtree-move)
7642 ;; move back to the initial column we were at
7643 (move-to-column col)))
7645 (defvar org-subtree-clip ""
7646 "Clipboard for cut and paste of subtrees.
7647 This is actually only a copy of the kill, because we use the normal kill
7648 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7650 (defvar org-subtree-clip-folded nil
7651 "Was the last copied subtree folded?
7652 This is used to fold the tree back after pasting.")
7654 (defun org-cut-subtree (&optional n)
7655 "Cut the current subtree into the clipboard.
7656 With prefix arg N, cut this many sequential subtrees.
7657 This is a short-hand for marking the subtree and then cutting it."
7658 (interactive "p")
7659 (org-copy-subtree n 'cut))
7661 (defun org-copy-subtree (&optional n cut force-store-markers)
7662 "Cut the current subtree into the clipboard.
7663 With prefix arg N, cut this many sequential subtrees.
7664 This is a short-hand for marking the subtree and then copying it.
7665 If CUT is non-nil, actually cut the subtree.
7666 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7667 of some markers in the region, even if CUT is non-nil. This is
7668 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7669 (interactive "p")
7670 (let (beg end folded (beg0 (point)))
7671 (if (org-called-interactively-p 'any)
7672 (org-back-to-heading nil) ; take what looks like a subtree
7673 (org-back-to-heading t)) ; take what is really there
7674 (org-back-over-empty-lines)
7675 (setq beg (point))
7676 (skip-chars-forward " \t\r\n")
7677 (save-match-data
7678 (save-excursion (outline-end-of-heading)
7679 (setq folded (outline-invisible-p)))
7680 (condition-case nil
7681 (org-forward-heading-same-level (1- n) t)
7682 (error nil))
7683 (org-end-of-subtree t t))
7684 (org-back-over-empty-lines)
7685 (setq end (point))
7686 (goto-char beg0)
7687 (when (> end beg)
7688 (setq org-subtree-clip-folded folded)
7689 (when (or cut force-store-markers)
7690 (org-save-markers-in-region beg end))
7691 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7692 (setq org-subtree-clip (current-kill 0))
7693 (message "%s: Subtree(s) with %d characters"
7694 (if cut "Cut" "Copied")
7695 (length org-subtree-clip)))))
7697 (defun org-paste-subtree (&optional level tree for-yank)
7698 "Paste the clipboard as a subtree, with modification of headline level.
7699 The entire subtree is promoted or demoted in order to match a new headline
7700 level.
7702 If the cursor is at the beginning of a headline, the same level as
7703 that headline is used to paste the tree
7705 If not, the new level is derived from the *visible* headings
7706 before and after the insertion point, and taken to be the inferior headline
7707 level of the two. So if the previous visible heading is level 3 and the
7708 next is level 4 (or vice versa), level 4 will be used for insertion.
7709 This makes sure that the subtree remains an independent subtree and does
7710 not swallow low level entries.
7712 You can also force a different level, either by using a numeric prefix
7713 argument, or by inserting the heading marker by hand. For example, if the
7714 cursor is after \"*****\", then the tree will be shifted to level 5.
7716 If optional TREE is given, use this text instead of the kill ring.
7718 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7719 move back over whitespace before inserting, and move point to the end of
7720 the inserted text when done."
7721 (interactive "P")
7722 (setq tree (or tree (and kill-ring (current-kill 0))))
7723 (unless (org-kill-is-subtree-p tree)
7724 (error "%s"
7725 (substitute-command-keys
7726 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7727 (org-with-limited-levels
7728 (let* ((visp (not (outline-invisible-p)))
7729 (txt tree)
7730 (^re_ "\\(\\*+\\)[ \t]*")
7731 (old-level (if (string-match org-outline-regexp-bol txt)
7732 (- (match-end 0) (match-beginning 0) 1)
7733 -1))
7734 (force-level (cond (level (prefix-numeric-value level))
7735 ((and (looking-at "[ \t]*$")
7736 (string-match
7737 "^\\*+$" (buffer-substring
7738 (point-at-bol) (point))))
7739 (- (match-end 1) (match-beginning 1)))
7740 ((and (bolp)
7741 (looking-at org-outline-regexp))
7742 (- (match-end 0) (point) 1))))
7743 (previous-level (save-excursion
7744 (condition-case nil
7745 (progn
7746 (outline-previous-visible-heading 1)
7747 (if (looking-at ^re_)
7748 (- (match-end 0) (match-beginning 0) 1)
7750 (error 1))))
7751 (next-level (save-excursion
7752 (condition-case nil
7753 (progn
7754 (or (looking-at org-outline-regexp)
7755 (outline-next-visible-heading 1))
7756 (if (looking-at ^re_)
7757 (- (match-end 0) (match-beginning 0) 1)
7759 (error 1))))
7760 (new-level (or force-level (max previous-level next-level)))
7761 (shift (if (or (= old-level -1)
7762 (= new-level -1)
7763 (= old-level new-level))
7765 (- new-level old-level)))
7766 (delta (if (> shift 0) -1 1))
7767 (func (if (> shift 0) 'org-demote 'org-promote))
7768 (org-odd-levels-only nil)
7769 beg end newend)
7770 ;; Remove the forced level indicator
7771 (if force-level
7772 (delete-region (point-at-bol) (point)))
7773 ;; Paste
7774 (beginning-of-line (if (bolp) 1 2))
7775 (unless for-yank (org-back-over-empty-lines))
7776 (setq beg (point))
7777 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7778 (insert-before-markers txt)
7779 (unless (string-match "\n\\'" txt) (insert "\n"))
7780 (setq newend (point))
7781 (org-reinstall-markers-in-region beg)
7782 (setq end (point))
7783 (goto-char beg)
7784 (skip-chars-forward " \t\n\r")
7785 (setq beg (point))
7786 (if (and (outline-invisible-p) visp)
7787 (save-excursion (outline-show-heading)))
7788 ;; Shift if necessary
7789 (unless (= shift 0)
7790 (save-restriction
7791 (narrow-to-region beg end)
7792 (while (not (= shift 0))
7793 (org-map-region func (point-min) (point-max))
7794 (setq shift (+ delta shift)))
7795 (goto-char (point-min))
7796 (setq newend (point-max))))
7797 (when (or (org-called-interactively-p 'interactive) for-yank)
7798 (message "Clipboard pasted as level %d subtree" new-level))
7799 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7800 kill-ring
7801 (eq org-subtree-clip (current-kill 0))
7802 org-subtree-clip-folded)
7803 ;; The tree was folded before it was killed/copied
7804 (hide-subtree))
7805 (and for-yank (goto-char newend)))))
7807 (defun org-kill-is-subtree-p (&optional txt)
7808 "Check if the current kill is an outline subtree, or a set of trees.
7809 Returns nil if kill does not start with a headline, or if the first
7810 headline level is not the largest headline level in the tree.
7811 So this will actually accept several entries of equal levels as well,
7812 which is OK for `org-paste-subtree'.
7813 If optional TXT is given, check this string instead of the current kill."
7814 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7815 (re (org-get-limited-outline-regexp))
7816 (^re (concat "^" re))
7817 (start-level (and kill
7818 (string-match
7819 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7820 kill)
7821 (- (match-end 2) (match-beginning 2) 1)))
7822 (start (1+ (or (match-beginning 2) -1))))
7823 (if (not start-level)
7824 (progn
7825 nil) ;; does not even start with a heading
7826 (catch 'exit
7827 (while (setq start (string-match ^re kill (1+ start)))
7828 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7829 (throw 'exit nil)))
7830 t))))
7832 (defvar org-markers-to-move nil
7833 "Markers that should be moved with a cut-and-paste operation.
7834 Those markers are stored together with their positions relative to
7835 the start of the region.")
7837 (defun org-save-markers-in-region (beg end)
7838 "Check markers in region.
7839 If these markers are between BEG and END, record their position relative
7840 to BEG, so that after moving the block of text, we can put the markers back
7841 into place.
7842 This function gets called just before an entry or tree gets cut from the
7843 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7844 called immediately, to move the markers with the entries."
7845 (setq org-markers-to-move nil)
7846 (when (featurep 'org-clock)
7847 (org-clock-save-markers-for-cut-and-paste beg end))
7848 (when (featurep 'org-agenda)
7849 (org-agenda-save-markers-for-cut-and-paste beg end)))
7851 (defun org-check-and-save-marker (marker beg end)
7852 "Check if MARKER is between BEG and END.
7853 If yes, remember the marker and the distance to BEG."
7854 (when (and (marker-buffer marker)
7855 (equal (marker-buffer marker) (current-buffer)))
7856 (if (and (>= marker beg) (< marker end))
7857 (push (cons marker (- marker beg)) org-markers-to-move))))
7859 (defun org-reinstall-markers-in-region (beg)
7860 "Move all remembered markers to their position relative to BEG."
7861 (mapc (lambda (x)
7862 (move-marker (car x) (+ beg (cdr x))))
7863 org-markers-to-move)
7864 (setq org-markers-to-move nil))
7866 (defun org-narrow-to-subtree ()
7867 "Narrow buffer to the current subtree."
7868 (interactive)
7869 (save-excursion
7870 (save-match-data
7871 (org-with-limited-levels
7872 (narrow-to-region
7873 (progn (org-back-to-heading t) (point))
7874 (progn (org-end-of-subtree t t)
7875 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7876 (point)))))))
7878 (defun org-narrow-to-block ()
7879 "Narrow buffer to the current block."
7880 (interactive)
7881 (let* ((case-fold-search t)
7882 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7883 "^[ \t]*#\\+end_.*")))
7884 (if blockp
7885 (narrow-to-region (car blockp) (cdr blockp))
7886 (error "Not in a block"))))
7888 (eval-when-compile
7889 (defvar org-property-drawer-re))
7891 (defvar org-property-start-re) ;; defined below
7892 (defun org-clone-subtree-with-time-shift (n &optional shift)
7893 "Clone the task (subtree) at point N times.
7894 The clones will be inserted as siblings.
7896 In interactive use, the user will be prompted for the number of
7897 clones to be produced, and for a time SHIFT, which may be a
7898 repeater as used in time stamps, for example `+3d'.
7900 When a valid repeater is given and the entry contains any time
7901 stamps, the clones will become a sequence in time, with time
7902 stamps in the subtree shifted for each clone produced. If SHIFT
7903 is nil or the empty string, time stamps will be left alone. The
7904 ID property of the original subtree is removed.
7906 If the original subtree did contain time stamps with a repeater,
7907 the following will happen:
7908 - the repeater will be removed in each clone
7909 - an additional clone will be produced, with the current, unshifted
7910 date(s) in the entry.
7911 - the original entry will be placed *after* all the clones, with
7912 repeater intact.
7913 - the start days in the repeater in the original entry will be shifted
7914 to past the last clone.
7915 In this way you can spell out a number of instances of a repeating task,
7916 and still retain the repeater to cover future instances of the task."
7917 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7918 (let (beg end template task idprop
7919 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7920 (drawer-re org-drawer-regexp))
7921 (if (not (and (integerp n) (> n 0)))
7922 (error "Invalid number of replications %s" n))
7923 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7924 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7925 shift)))
7926 (error "Invalid shift specification %s" shift))
7927 (when doshift
7928 (setq shift-n (string-to-number (match-string 1 shift))
7929 shift-what (cdr (assoc (match-string 2 shift)
7930 '(("d" . day) ("w" . week)
7931 ("m" . month) ("y" . year))))))
7932 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7933 (setq nmin 1 nmax n)
7934 (org-back-to-heading t)
7935 (setq beg (point))
7936 (setq idprop (org-entry-get nil "ID"))
7937 (org-end-of-subtree t t)
7938 (or (bolp) (insert "\n"))
7939 (setq end (point))
7940 (setq template (buffer-substring beg end))
7941 (when (and doshift
7942 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7943 (delete-region beg end)
7944 (setq end beg)
7945 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7946 (goto-char end)
7947 (loop for n from nmin to nmax do
7948 ;; prepare clone
7949 (with-temp-buffer
7950 (insert template)
7951 (org-mode)
7952 (goto-char (point-min))
7953 (org-show-subtree)
7954 (and idprop (if org-clone-delete-id
7955 (org-entry-delete nil "ID")
7956 (org-id-get-create t)))
7957 (unless (= n 0)
7958 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7959 (kill-whole-line))
7960 (goto-char (point-min))
7961 (while (re-search-forward drawer-re nil t)
7962 (mapc (lambda (d)
7963 (org-remove-empty-drawer-at d (point))) org-drawers)))
7964 (goto-char (point-min))
7965 (when doshift
7966 (while (re-search-forward org-ts-regexp-both nil t)
7967 (org-timestamp-change (* n shift-n) shift-what))
7968 (unless (= n n-no-remove)
7969 (goto-char (point-min))
7970 (while (re-search-forward org-ts-regexp nil t)
7971 (save-excursion
7972 (goto-char (match-beginning 0))
7973 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7974 (delete-region (match-beginning 1) (match-end 1)))))))
7975 (setq task (buffer-string)))
7976 (insert task))
7977 (goto-char beg)))
7979 ;;; Outline Sorting
7981 (defun org-sort (with-case)
7982 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7983 Optional argument WITH-CASE means sort case-sensitively."
7984 (interactive "P")
7985 (cond
7986 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7987 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7989 (org-call-with-arg 'org-sort-entries with-case))))
7991 (defun org-sort-remove-invisible (s)
7992 (remove-text-properties 0 (length s) org-rm-props s)
7993 (while (string-match org-bracket-link-regexp s)
7994 (setq s (replace-match (if (match-end 2)
7995 (match-string 3 s)
7996 (match-string 1 s)) t t s)))
7999 (defvar org-priority-regexp) ; defined later in the file
8001 (defvar org-after-sorting-entries-or-items-hook nil
8002 "Hook that is run after a bunch of entries or items have been sorted.
8003 When children are sorted, the cursor is in the parent line when this
8004 hook gets called. When a region or a plain list is sorted, the cursor
8005 will be in the first entry of the sorted region/list.")
8007 (defun org-sort-entries
8008 (&optional with-case sorting-type getkey-func compare-func property)
8009 "Sort entries on a certain level of an outline tree.
8010 If there is an active region, the entries in the region are sorted.
8011 Else, if the cursor is before the first entry, sort the top-level items.
8012 Else, the children of the entry at point are sorted.
8014 Sorting can be alphabetically, numerically, by date/time as given by
8015 a time stamp, by a property or by priority.
8017 The command prompts for the sorting type unless it has been given to the
8018 function through the SORTING-TYPE argument, which needs to be a character,
8019 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8020 precise meaning of each character:
8022 n Numerically, by converting the beginning of the entry/item to a number.
8023 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8024 t By date/time, either the first active time stamp in the entry, or, if
8025 none exist, by the first inactive one.
8026 s By the scheduled date/time.
8027 d By deadline date/time.
8028 c By creation time, which is assumed to be the first inactive time stamp
8029 at the beginning of a line.
8030 p By priority according to the cookie.
8031 r By the value of a property.
8033 Capital letters will reverse the sort order.
8035 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8036 called with point at the beginning of the record. It must return either
8037 a string or a number that should serve as the sorting key for that record.
8039 Comparing entries ignores case by default. However, with an optional argument
8040 WITH-CASE, the sorting considers case as well."
8041 (interactive "P")
8042 (let ((case-func (if with-case 'identity 'downcase))
8043 start beg end stars re re2
8044 txt what tmp)
8045 ;; Find beginning and end of region to sort
8046 (cond
8047 ((org-region-active-p)
8048 ;; we will sort the region
8049 (setq end (region-end)
8050 what "region")
8051 (goto-char (region-beginning))
8052 (if (not (org-at-heading-p)) (outline-next-heading))
8053 (setq start (point)))
8054 ((or (org-at-heading-p)
8055 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8056 ;; we will sort the children of the current headline
8057 (org-back-to-heading)
8058 (setq start (point)
8059 end (progn (org-end-of-subtree t t)
8060 (or (bolp) (insert "\n"))
8061 (org-back-over-empty-lines)
8062 (point))
8063 what "children")
8064 (goto-char start)
8065 (show-subtree)
8066 (outline-next-heading))
8068 ;; we will sort the top-level entries in this file
8069 (goto-char (point-min))
8070 (or (org-at-heading-p) (outline-next-heading))
8071 (setq start (point))
8072 (goto-char (point-max))
8073 (beginning-of-line 1)
8074 (when (looking-at ".*?\\S-")
8075 ;; File ends in a non-white line
8076 (end-of-line 1)
8077 (insert "\n"))
8078 (setq end (point-max))
8079 (setq what "top-level")
8080 (goto-char start)
8081 (show-all)))
8083 (setq beg (point))
8084 (if (>= beg end) (error "Nothing to sort"))
8086 (looking-at "\\(\\*+\\)")
8087 (setq stars (match-string 1)
8088 re (concat "^" (regexp-quote stars) " +")
8089 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8090 txt (buffer-substring beg end))
8091 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8092 (if (and (not (equal stars "*")) (string-match re2 txt))
8093 (error "Region to sort contains a level above the first entry"))
8095 (unless sorting-type
8096 (message
8097 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8098 [t]ime [s]cheduled [d]eadline [c]reated
8099 A/N/T/S/D/C/P/O/F means reversed:"
8100 what)
8101 (setq sorting-type (read-char-exclusive))
8103 (and (= (downcase sorting-type) ?f)
8104 (setq getkey-func
8105 (org-icompleting-read "Sort using function: "
8106 obarray 'fboundp t nil nil))
8107 (setq getkey-func (intern getkey-func)))
8109 (and (= (downcase sorting-type) ?r)
8110 (setq property
8111 (org-icompleting-read "Property: "
8112 (mapcar 'list (org-buffer-property-keys t))
8113 nil t))))
8115 (message "Sorting entries...")
8117 (save-restriction
8118 (narrow-to-region start end)
8119 (let ((dcst (downcase sorting-type))
8120 (case-fold-search nil)
8121 (now (current-time)))
8122 (sort-subr
8123 (/= dcst sorting-type)
8124 ;; This function moves to the beginning character of the "record" to
8125 ;; be sorted.
8126 (lambda nil
8127 (if (re-search-forward re nil t)
8128 (goto-char (match-beginning 0))
8129 (goto-char (point-max))))
8130 ;; This function moves to the last character of the "record" being
8131 ;; sorted.
8132 (lambda nil
8133 (save-match-data
8134 (condition-case nil
8135 (outline-forward-same-level 1)
8136 (error
8137 (goto-char (point-max))))))
8138 ;; This function returns the value that gets sorted against.
8139 (lambda nil
8140 (cond
8141 ((= dcst ?n)
8142 (if (looking-at org-complex-heading-regexp)
8143 (string-to-number (match-string 4))
8144 nil))
8145 ((= dcst ?a)
8146 (if (looking-at org-complex-heading-regexp)
8147 (funcall case-func (match-string 4))
8148 nil))
8149 ((= dcst ?t)
8150 (let ((end (save-excursion (outline-next-heading) (point))))
8151 (if (or (re-search-forward org-ts-regexp end t)
8152 (re-search-forward org-ts-regexp-both end t))
8153 (org-time-string-to-seconds (match-string 0))
8154 (org-float-time now))))
8155 ((= dcst ?c)
8156 (let ((end (save-excursion (outline-next-heading) (point))))
8157 (if (re-search-forward
8158 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8159 end t)
8160 (org-time-string-to-seconds (match-string 0))
8161 (org-float-time now))))
8162 ((= dcst ?s)
8163 (let ((end (save-excursion (outline-next-heading) (point))))
8164 (if (re-search-forward org-scheduled-time-regexp end t)
8165 (org-time-string-to-seconds (match-string 1))
8166 (org-float-time now))))
8167 ((= dcst ?d)
8168 (let ((end (save-excursion (outline-next-heading) (point))))
8169 (if (re-search-forward org-deadline-time-regexp end t)
8170 (org-time-string-to-seconds (match-string 1))
8171 (org-float-time now))))
8172 ((= dcst ?p)
8173 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8174 (string-to-char (match-string 2))
8175 org-default-priority))
8176 ((= dcst ?r)
8177 (or (org-entry-get nil property) ""))
8178 ((= dcst ?o)
8179 (if (looking-at org-complex-heading-regexp)
8180 (- 9999 (length (member (match-string 2)
8181 org-todo-keywords-1)))))
8182 ((= dcst ?f)
8183 (if getkey-func
8184 (progn
8185 (setq tmp (funcall getkey-func))
8186 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8187 tmp)
8188 (error "Invalid key function `%s'" getkey-func)))
8189 (t (error "Invalid sorting type `%c'" sorting-type))))
8191 (cond
8192 ((= dcst ?a) 'string<)
8193 ((= dcst ?f) compare-func)
8194 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8195 (run-hooks 'org-after-sorting-entries-or-items-hook)
8196 (message "Sorting entries...done")))
8198 (defun org-do-sort (table what &optional with-case sorting-type)
8199 "Sort TABLE of WHAT according to SORTING-TYPE.
8200 The user will be prompted for the SORTING-TYPE if the call to this
8201 function does not specify it. WHAT is only for the prompt, to indicate
8202 what is being sorted. The sorting key will be extracted from
8203 the car of the elements of the table.
8204 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8205 (unless sorting-type
8206 (message
8207 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8208 what)
8209 (setq sorting-type (read-char-exclusive)))
8210 (let ((dcst (downcase sorting-type))
8211 extractfun comparefun)
8212 ;; Define the appropriate functions
8213 (cond
8214 ((= dcst ?n)
8215 (setq extractfun 'string-to-number
8216 comparefun (if (= dcst sorting-type) '< '>)))
8217 ((= dcst ?a)
8218 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8219 (lambda(x) (downcase (org-sort-remove-invisible x))))
8220 comparefun (if (= dcst sorting-type)
8221 'string<
8222 (lambda (a b) (and (not (string< a b))
8223 (not (string= a b)))))))
8224 ((= dcst ?t)
8225 (setq extractfun
8226 (lambda (x)
8227 (if (or (string-match org-ts-regexp x)
8228 (string-match org-ts-regexp-both x))
8229 (org-float-time
8230 (org-time-string-to-time (match-string 0 x)))
8232 comparefun (if (= dcst sorting-type) '< '>)))
8233 (t (error "Invalid sorting type `%c'" sorting-type)))
8235 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8236 table)
8237 (lambda (a b) (funcall comparefun (car a) (car b))))))
8240 ;;; The orgstruct minor mode
8242 ;; Define a minor mode which can be used in other modes in order to
8243 ;; integrate the org-mode structure editing commands.
8245 ;; This is really a hack, because the org-mode structure commands use
8246 ;; keys which normally belong to the major mode. Here is how it
8247 ;; works: The minor mode defines all the keys necessary to operate the
8248 ;; structure commands, but wraps the commands into a function which
8249 ;; tests if the cursor is currently at a headline or a plain list
8250 ;; item. If that is the case, the structure command is used,
8251 ;; temporarily setting many Org-mode variables like regular
8252 ;; expressions for filling etc. However, when any of those keys is
8253 ;; used at a different location, function uses `key-binding' to look
8254 ;; up if the key has an associated command in another currently active
8255 ;; keymap (minor modes, major mode, global), and executes that
8256 ;; command. There might be problems if any of the keys is otherwise
8257 ;; used as a prefix key.
8259 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8260 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8261 ;; addresses this by checking explicitly for both bindings.
8263 (defvar orgstruct-mode-map (make-sparse-keymap)
8264 "Keymap for the minor `orgstruct-mode'.")
8266 (defvar org-local-vars nil
8267 "List of local variables, for use by `orgstruct-mode'.")
8269 ;;;###autoload
8270 (define-minor-mode orgstruct-mode
8271 "Toggle the minor mode `orgstruct-mode'.
8272 This mode is for using Org-mode structure commands in other
8273 modes. The following keys behave as if Org-mode were active, if
8274 the cursor is on a headline, or on a plain list item (both as
8275 defined by Org-mode).
8277 M-up Move entry/item up
8278 M-down Move entry/item down
8279 M-left Promote
8280 M-right Demote
8281 M-S-up Move entry/item up
8282 M-S-down Move entry/item down
8283 M-S-left Promote subtree
8284 M-S-right Demote subtree
8285 M-q Fill paragraph and items like in Org-mode
8286 C-c ^ Sort entries
8287 C-c - Cycle list bullet
8288 TAB Cycle item visibility
8289 M-RET Insert new heading/item
8290 S-M-RET Insert new TODO heading / Checkbox item
8291 C-c C-c Set tags / toggle checkbox"
8292 nil " OrgStruct" nil
8293 (org-load-modules-maybe)
8294 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8296 ;;;###autoload
8297 (defun turn-on-orgstruct ()
8298 "Unconditionally turn on `orgstruct-mode'."
8299 (orgstruct-mode 1))
8301 (defvar org-fb-vars nil)
8302 (make-variable-buffer-local 'org-fb-vars)
8303 (defun orgstruct++-mode (&optional arg)
8304 "Toggle `orgstruct-mode', the enhanced version of it.
8305 In addition to setting orgstruct-mode, this also exports all
8306 indentation and autofilling variables from org-mode into the
8307 buffer. It will also recognize item context in multiline items."
8308 (interactive "P")
8309 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8310 (if (< arg 1)
8311 (progn (orgstruct-mode -1)
8312 (mapc (lambda(v)
8313 (org-set-local (car v)
8314 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8315 org-fb-vars))
8316 (orgstruct-mode 1)
8317 (setq org-fb-vars nil)
8318 (let (var val)
8319 (mapc
8320 (lambda (x)
8321 (when (string-match
8322 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8323 (symbol-name (car x)))
8324 (setq var (car x) val (nth 1 x))
8325 (push (list var `(quote ,(eval var))) org-fb-vars)
8326 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8327 org-local-vars)
8328 (org-set-local 'orgstruct-is-++ t))))
8330 (defvar orgstruct-is-++ nil
8331 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8332 (make-variable-buffer-local 'orgstruct-is-++)
8334 ;;;###autoload
8335 (defun turn-on-orgstruct++ ()
8336 "Unconditionally turn on `orgstruct++-mode'."
8337 (orgstruct++-mode 1))
8339 (defun orgstruct-error ()
8340 "Error when there is no default binding for a structure key."
8341 (interactive)
8342 (error "This key has no function outside structure elements"))
8344 (defun orgstruct-setup ()
8345 "Setup orgstruct keymaps."
8346 (let ((nfunc 0)
8347 (bindings
8348 (list
8349 '([(meta up)] org-metaup)
8350 '([(meta down)] org-metadown)
8351 '([(meta left)] org-metaleft)
8352 '([(meta right)] org-metaright)
8353 '([(meta shift up)] org-shiftmetaup)
8354 '([(meta shift down)] org-shiftmetadown)
8355 '([(meta shift left)] org-shiftmetaleft)
8356 '([(meta shift right)] org-shiftmetaright)
8357 '([?\e (up)] org-metaup)
8358 '([?\e (down)] org-metadown)
8359 '([?\e (left)] org-metaleft)
8360 '([?\e (right)] org-metaright)
8361 '([?\e (shift up)] org-shiftmetaup)
8362 '([?\e (shift down)] org-shiftmetadown)
8363 '([?\e (shift left)] org-shiftmetaleft)
8364 '([?\e (shift right)] org-shiftmetaright)
8365 '([(shift up)] org-shiftup)
8366 '([(shift down)] org-shiftdown)
8367 '([(shift left)] org-shiftleft)
8368 '([(shift right)] org-shiftright)
8369 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8370 '("\M-q" fill-paragraph)
8371 '("\C-c^" org-sort)
8372 '("\C-c-" org-cycle-list-bullet)))
8373 elt key fun cmd)
8374 (while (setq elt (pop bindings))
8375 (setq nfunc (1+ nfunc))
8376 (setq key (org-key (car elt))
8377 fun (nth 1 elt)
8378 cmd (orgstruct-make-binding fun nfunc key))
8379 (org-defkey orgstruct-mode-map key cmd))
8381 ;; Prevent an error for users who forgot to make autoloads
8382 (require 'org-element)
8384 ;; Special treatment needed for TAB and RET
8385 (org-defkey orgstruct-mode-map [(tab)]
8386 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8387 (org-defkey orgstruct-mode-map "\C-i"
8388 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8390 (org-defkey orgstruct-mode-map "\M-\C-m"
8391 (orgstruct-make-binding 'org-insert-heading 105
8392 "\M-\C-m" [(meta return)]))
8393 (org-defkey orgstruct-mode-map [(meta return)]
8394 (orgstruct-make-binding 'org-insert-heading 106
8395 [(meta return)] "\M-\C-m"))
8397 (org-defkey orgstruct-mode-map [(shift meta return)]
8398 (orgstruct-make-binding 'org-insert-todo-heading 107
8399 [(meta return)] "\M-\C-m"))
8401 (org-defkey orgstruct-mode-map "\e\C-m"
8402 (orgstruct-make-binding 'org-insert-heading 108
8403 "\e\C-m" [?\e (return)]))
8404 (org-defkey orgstruct-mode-map [?\e (return)]
8405 (orgstruct-make-binding 'org-insert-heading 109
8406 [?\e (return)] "\e\C-m"))
8407 (org-defkey orgstruct-mode-map [?\e (shift return)]
8408 (orgstruct-make-binding 'org-insert-todo-heading 110
8409 [?\e (return)] "\e\C-m"))
8411 (unless org-local-vars
8412 (setq org-local-vars (org-get-local-variables)))
8416 (defun orgstruct-make-binding (fun n &rest keys)
8417 "Create a function for binding in the structure minor mode.
8418 FUN is the command to call inside a table. N is used to create a unique
8419 command name. KEYS are keys that should be checked in for a command
8420 to execute outside of tables."
8421 (eval
8422 (list 'defun
8423 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8424 '(arg)
8425 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8426 "Outside of structure, run the binding of `"
8427 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8428 "'.")
8429 '(interactive "p")
8430 (list 'if
8431 `(org-context-p 'headline 'item
8432 (and orgstruct-is-++
8433 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8434 'item-body))
8435 (list 'org-run-like-in-org-mode (list 'quote fun))
8436 (list 'let '(orgstruct-mode)
8437 (list 'call-interactively
8438 (append '(or)
8439 (mapcar (lambda (k)
8440 (list 'key-binding k))
8441 keys)
8442 '('orgstruct-error))))))))
8444 (defun org-contextualize-keys (alist contexts)
8445 "Return valid elements in ALIST depending on CONTEXTS.
8447 `org-agenda-custom-commands' or `org-capture-templates' are the
8448 values used for ALIST, and `org-agenda-custom-commands-contexts'
8449 or `org-capture-templates-contexts' are the associated contexts
8450 definitions."
8451 (let ((contexts
8452 ;; normalize contexts
8453 (mapcar
8454 (lambda(c) (cond ((listp (cadr c))
8455 (list (car c) (car c) (cadr c)))
8456 ((string= "" (cadr c))
8457 (list (car c) (car c) (caddr c)))
8458 (t c))) contexts))
8459 (a alist) c r s)
8460 ;; loop over all commands or templates
8461 (while (setq c (pop a))
8462 (let (vrules repl)
8463 (cond
8464 ((not (assoc (car c) contexts))
8465 (push c r))
8466 ((and (assoc (car c) contexts)
8467 (setq vrules (org-contextualize-validate-key
8468 (car c) contexts)))
8469 (mapc (lambda (vr)
8470 (when (not (equal (car vr) (cadr vr)))
8471 (setq repl vr))) vrules)
8472 (if (not repl) (push c r)
8473 (push (cadr repl) s)
8474 (push
8475 (cons (car c)
8476 (cdr (or (assoc (cadr repl) alist)
8477 (error "Undefined key `%s' as contextual replacement for `%s'"
8478 (cadr repl) (car c)))))
8479 r))))))
8480 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8481 (delq
8483 (delete-dups
8484 (mapcar (lambda (x)
8485 (let ((tpl (car x)))
8486 (when (not (delq
8488 (mapcar (lambda(y)
8489 (equal y tpl)) s))) x)))
8490 (reverse r))))))
8492 (defun org-contextualize-validate-key (key contexts)
8493 "Check CONTEXTS for agenda or capture KEY."
8494 (let (r rr res)
8495 (while (setq r (pop contexts))
8496 (mapc
8497 (lambda (rr)
8498 (when
8499 (and (equal key (car r))
8500 (if (functionp rr) (funcall rr)
8501 (or (and (eq (car rr) 'in-file)
8502 (buffer-file-name)
8503 (string-match (cdr rr) (buffer-file-name)))
8504 (and (eq (car rr) 'in-mode)
8505 (string-match (cdr rr) (symbol-name major-mode)))
8506 (when (and (eq (car rr) 'not-in-file)
8507 (buffer-file-name))
8508 (not (string-match (cdr rr) (buffer-file-name))))
8509 (when (eq (car rr) 'not-in-mode)
8510 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8511 (push r res)))
8512 (car (last r))))
8513 (delete-dups (delq nil res))))
8515 (defun org-context-p (&rest contexts)
8516 "Check if local context is any of CONTEXTS.
8517 Possible values in the list of contexts are `table', `headline', and `item'."
8518 (let ((pos (point)))
8519 (goto-char (point-at-bol))
8520 (prog1 (or (and (memq 'table contexts)
8521 (looking-at "[ \t]*|"))
8522 (and (memq 'headline contexts)
8523 (looking-at org-outline-regexp))
8524 (and (memq 'item contexts)
8525 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8526 (and (memq 'item-body contexts)
8527 (org-in-item-p)))
8528 (goto-char pos))))
8530 (defun org-get-local-variables ()
8531 "Return a list of all local variables in an Org mode buffer."
8532 (let (varlist)
8533 (with-current-buffer (get-buffer-create "*Org tmp*")
8534 (erase-buffer)
8535 (org-mode)
8536 (setq varlist (buffer-local-variables)))
8537 (kill-buffer "*Org tmp*")
8538 (delq nil
8539 (mapcar
8540 (lambda (x)
8541 (setq x
8542 (if (symbolp x)
8543 (list x)
8544 (list (car x) (list 'quote (cdr x)))))
8545 (if (string-match
8546 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8547 (symbol-name (car x)))
8548 x nil))
8549 varlist))))
8551 (defun org-clone-local-variables (from-buffer &optional regexp)
8552 "Clone local variables from FROM-BUFFER.
8553 Optional argument REGEXP selects variables to clone."
8554 (mapc
8555 (lambda (pair)
8556 (and (symbolp (car pair))
8557 (or (null regexp)
8558 (string-match regexp (symbol-name (car pair))))
8559 (set (make-local-variable (car pair))
8560 (cdr pair))))
8561 (buffer-local-variables from-buffer)))
8563 ;;;###autoload
8564 (defun org-run-like-in-org-mode (cmd)
8565 "Run a command, pretending that the current buffer is in Org-mode.
8566 This will temporarily bind local variables that are typically bound in
8567 Org-mode to the values they have in Org-mode, and then interactively
8568 call CMD."
8569 (org-load-modules-maybe)
8570 (unless org-local-vars
8571 (setq org-local-vars (org-get-local-variables)))
8572 (eval (list 'let org-local-vars
8573 (list 'call-interactively (list 'quote cmd)))))
8575 ;;;; Archiving
8577 (defun org-get-category (&optional pos force-refresh)
8578 "Get the category applying to position POS."
8579 (save-match-data
8580 (if force-refresh (org-refresh-category-properties))
8581 (let ((pos (or pos (point))))
8582 (or (get-text-property pos 'org-category)
8583 (progn (org-refresh-category-properties)
8584 (get-text-property pos 'org-category))))))
8586 (defun org-refresh-category-properties ()
8587 "Refresh category text properties in the buffer."
8588 (let ((case-fold-search t)
8589 (inhibit-read-only t)
8590 (def-cat (cond
8591 ((null org-category)
8592 (if buffer-file-name
8593 (file-name-sans-extension
8594 (file-name-nondirectory buffer-file-name))
8595 "???"))
8596 ((symbolp org-category) (symbol-name org-category))
8597 (t org-category)))
8598 beg end cat pos optionp)
8599 (org-unmodified
8600 (save-excursion
8601 (save-restriction
8602 (widen)
8603 (goto-char (point-min))
8604 (put-text-property (point) (point-max) 'org-category def-cat)
8605 (while (re-search-forward
8606 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8607 (setq pos (match-end 0)
8608 optionp (equal (char-after (match-beginning 0)) ?#)
8609 cat (org-trim (match-string 2)))
8610 (if optionp
8611 (setq beg (point-at-bol) end (point-max))
8612 (org-back-to-heading t)
8613 (setq beg (point) end (org-end-of-subtree t t)))
8614 (put-text-property beg end 'org-category cat)
8615 (put-text-property beg end 'org-category-position beg)
8616 (goto-char pos)))))))
8619 ;;;; Link Stuff
8621 ;;; Link abbreviations
8623 (defun org-link-expand-abbrev (link)
8624 "Apply replacements as defined in `org-link-abbrev-alist'."
8625 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8626 (let* ((key (match-string 1 link))
8627 (as (or (assoc key org-link-abbrev-alist-local)
8628 (assoc key org-link-abbrev-alist)))
8629 (tag (and (match-end 2) (match-string 3 link)))
8630 rpl)
8631 (if (not as)
8632 link
8633 (setq rpl (cdr as))
8634 (cond
8635 ((symbolp rpl) (funcall rpl tag))
8636 ((string-match "%(\\([^)]+\\))" rpl)
8637 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8638 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8639 ((string-match "%h" rpl)
8640 (replace-match (url-hexify-string (or tag "")) t t rpl))
8641 (t (concat rpl tag)))))
8642 link))
8644 ;;; Storing and inserting links
8646 (defvar org-insert-link-history nil
8647 "Minibuffer history for links inserted with `org-insert-link'.")
8649 (defvar org-stored-links nil
8650 "Contains the links stored with `org-store-link'.")
8652 (defvar org-store-link-plist nil
8653 "Plist with info about the most recently link created with `org-store-link'.")
8655 (defvar org-link-protocols nil
8656 "Link protocols added to Org-mode using `org-add-link-type'.")
8658 (defvar org-store-link-functions nil
8659 "List of functions that are called to create and store a link.
8660 Each function will be called in turn until one returns a non-nil
8661 value. Each function should check if it is responsible for creating
8662 this link (for example by looking at the major mode).
8663 If not, it must exit and return nil.
8664 If yes, it should return a non-nil value after a calling
8665 `org-store-link-props' with a list of properties and values.
8666 Special properties are:
8668 :type The link prefix, like \"http\". This must be given.
8669 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8670 This is obligatory as well.
8671 :description Optional default description for the second pair
8672 of brackets in an Org-mode link. The user can still change
8673 this when inserting this link into an Org-mode buffer.
8675 In addition to these, any additional properties can be specified
8676 and then used in capture templates.")
8678 (defun org-add-link-type (type &optional follow export)
8679 "Add TYPE to the list of `org-link-types'.
8680 Re-compute all regular expressions depending on `org-link-types'
8682 FOLLOW and EXPORT are two functions.
8684 FOLLOW should take the link path as the single argument and do whatever
8685 is necessary to follow the link, for example find a file or display
8686 a mail message.
8688 EXPORT should format the link path for export to one of the export formats.
8689 It should be a function accepting three arguments:
8691 path the path of the link, the text after the prefix (like \"http:\")
8692 desc the description of the link, if any, or a description added by
8693 org-export-normalize-links if there is none
8694 format the export format, a symbol like `html' or `latex' or `ascii'..
8696 The function may use the FORMAT information to return different values
8697 depending on the format. The return value will be put literally into
8698 the exported file. If the return value is nil, this means Org should
8699 do what it normally does with links which do not have EXPORT defined.
8701 Org-mode has a built-in default for exporting links. If you are happy with
8702 this default, there is no need to define an export function for the link
8703 type. For a simple example of an export function, see `org-bbdb.el'."
8704 (add-to-list 'org-link-types type t)
8705 (org-make-link-regexps)
8706 (if (assoc type org-link-protocols)
8707 (setcdr (assoc type org-link-protocols) (list follow export))
8708 (push (list type follow export) org-link-protocols)))
8710 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8711 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8713 ;;;###autoload
8714 (defun org-store-link (arg)
8715 "\\<org-mode-map>Store an org-link to the current location.
8716 This link is added to `org-stored-links' and can later be inserted
8717 into an org-buffer with \\[org-insert-link].
8719 For some link types, a prefix arg is interpreted:
8720 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8721 For file links, arg negates `org-context-in-file-links'."
8722 (interactive "P")
8723 (org-load-modules-maybe)
8724 (setq org-store-link-plist nil) ; reset
8725 (org-with-limited-levels
8726 (let (link cpltxt desc description search txt custom-id agenda-link)
8727 (cond
8729 ((run-hook-with-args-until-success 'org-store-link-functions)
8730 (setq link (plist-get org-store-link-plist :link)
8731 desc (or (plist-get org-store-link-plist :description) link)))
8733 ((org-src-edit-buffer-p)
8734 (let (label gc)
8735 (while (or (not label)
8736 (save-excursion
8737 (save-restriction
8738 (widen)
8739 (goto-char (point-min))
8740 (re-search-forward
8741 (regexp-quote (format org-coderef-label-format label))
8742 nil t))))
8743 (when label (message "Label exists already") (sit-for 2))
8744 (setq label (read-string "Code line label: " label)))
8745 (end-of-line 1)
8746 (setq link (format org-coderef-label-format label))
8747 (setq gc (- 79 (length link)))
8748 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8749 (insert link)
8750 (setq link (concat "(" label ")") desc nil)))
8752 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8753 ;; We are in the agenda, link to referenced location
8754 (let ((m (or (get-text-property (point) 'org-hd-marker)
8755 (get-text-property (point) 'org-marker))))
8756 (when m
8757 (org-with-point-at m
8758 (setq agenda-link
8759 (if (org-called-interactively-p 'any)
8760 (call-interactively 'org-store-link)
8761 (org-store-link nil)))))))
8763 ((eq major-mode 'calendar-mode)
8764 (let ((cd (calendar-cursor-to-date)))
8765 (setq link
8766 (format-time-string
8767 (car org-time-stamp-formats)
8768 (apply 'encode-time
8769 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8770 nil nil nil))))
8771 (org-store-link-props :type "calendar" :date cd)))
8773 ((eq major-mode 'help-mode)
8774 (setq link (concat "help:" (save-excursion
8775 (goto-char (point-min))
8776 (looking-at "^[^ ]+")
8777 (match-string 0))))
8778 (org-store-link-props :type "help"))
8780 ((eq major-mode 'w3-mode)
8781 (setq cpltxt (if (and (buffer-name)
8782 (not (string-match "Untitled" (buffer-name))))
8783 (buffer-name)
8784 (url-view-url t))
8785 link (url-view-url t))
8786 (org-store-link-props :type "w3" :url (url-view-url t)))
8788 ((eq major-mode 'w3m-mode)
8789 (setq cpltxt (or w3m-current-title w3m-current-url)
8790 link w3m-current-url)
8791 (org-store-link-props :type "w3m" :url (url-view-url t)))
8793 ((setq search (run-hook-with-args-until-success
8794 'org-create-file-search-functions))
8795 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8796 "::" search))
8797 (setq cpltxt (or description link)))
8799 ((eq major-mode 'image-mode)
8800 (setq cpltxt (concat "file:"
8801 (abbreviate-file-name buffer-file-name))
8802 link cpltxt)
8803 (org-store-link-props :type "image" :file buffer-file-name))
8805 ((eq major-mode 'dired-mode)
8806 ;; link to the file in the current line
8807 (let ((file (dired-get-filename nil t)))
8808 (setq file (if file
8809 (abbreviate-file-name
8810 (expand-file-name (dired-get-filename nil t)))
8811 ;; otherwise, no file so use current directory.
8812 default-directory))
8813 (setq cpltxt (concat "file:" file)
8814 link cpltxt)))
8816 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8817 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8818 (cond
8819 ((org-in-regexp "<<\\(.*?\\)>>")
8820 (setq cpltxt
8821 (concat "file:"
8822 (abbreviate-file-name
8823 (buffer-file-name (buffer-base-buffer)))
8824 "::" (match-string 1))
8825 link cpltxt))
8826 ((and (featurep 'org-id)
8827 (or (eq org-link-to-org-use-id t)
8828 (and (org-called-interactively-p 'any)
8829 (or (eq org-link-to-org-use-id 'create-if-interactive)
8830 (and (eq org-link-to-org-use-id
8831 'create-if-interactive-and-no-custom-id)
8832 (not custom-id))))
8833 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8834 ;; We can make a link using the ID.
8835 (setq link (condition-case nil
8836 (prog1 (org-id-store-link)
8837 (setq desc (plist-get org-store-link-plist :description)))
8838 (error
8839 ;; probably before first headline, link to file only
8840 (concat "file:"
8841 (abbreviate-file-name
8842 (buffer-file-name (buffer-base-buffer))))))))
8844 ;; Just link to current headline
8845 (setq cpltxt (concat "file:"
8846 (abbreviate-file-name
8847 (buffer-file-name (buffer-base-buffer)))))
8848 ;; Add a context search string
8849 (when (org-xor org-context-in-file-links arg)
8850 (setq txt (cond
8851 ((org-at-heading-p) nil)
8852 ((org-region-active-p)
8853 (buffer-substring (region-beginning) (region-end)))))
8854 (when (or (null txt) (string-match "\\S-" txt))
8855 (setq cpltxt
8856 (concat cpltxt "::"
8857 (condition-case nil
8858 (org-make-org-heading-search-string txt)
8859 (error "")))
8860 desc (or (nth 4 (ignore-errors
8861 (org-heading-components))) "NONE"))))
8862 (if (string-match "::\\'" cpltxt)
8863 (setq cpltxt (substring cpltxt 0 -2)))
8864 (setq link cpltxt))))
8866 ((buffer-file-name (buffer-base-buffer))
8867 ;; Just link to this file here.
8868 (setq cpltxt (concat "file:"
8869 (abbreviate-file-name
8870 (buffer-file-name (buffer-base-buffer)))))
8871 ;; Add a context string
8872 (when (org-xor org-context-in-file-links arg)
8873 (setq txt (if (org-region-active-p)
8874 (buffer-substring (region-beginning) (region-end))
8875 (buffer-substring (point-at-bol) (point-at-eol))))
8876 ;; Only use search option if there is some text.
8877 (when (string-match "\\S-" txt)
8878 (setq cpltxt
8879 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8880 desc "NONE")))
8881 (setq link cpltxt))
8883 ((org-called-interactively-p 'interactive)
8884 (error "Cannot link to a buffer which is not visiting a file"))
8886 (t (setq link nil)))
8888 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8889 (setq link (or link cpltxt)
8890 desc (or desc cpltxt))
8891 (if (equal desc "NONE") (setq desc nil))
8893 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8894 (progn
8895 (setq org-stored-links
8896 (cons (list link desc) org-stored-links))
8897 (message "Stored: %s" (or desc link))
8898 (when custom-id
8899 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8900 "::#" custom-id))
8901 (setq org-stored-links
8902 (cons (list link desc) org-stored-links))))
8903 (or agenda-link (and link (org-make-link-string link desc)))))))
8905 (defun org-store-link-props (&rest plist)
8906 "Store link properties, extract names and addresses."
8907 (let (x adr)
8908 (when (setq x (plist-get plist :from))
8909 (setq adr (mail-extract-address-components x))
8910 (setq plist (plist-put plist :fromname (car adr)))
8911 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8912 (when (setq x (plist-get plist :to))
8913 (setq adr (mail-extract-address-components x))
8914 (setq plist (plist-put plist :toname (car adr)))
8915 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8916 (let ((from (plist-get plist :from))
8917 (to (plist-get plist :to)))
8918 (when (and from to org-from-is-user-regexp)
8919 (setq plist
8920 (plist-put plist :fromto
8921 (if (string-match org-from-is-user-regexp from)
8922 (concat "to %t")
8923 (concat "from %f"))))))
8924 (setq org-store-link-plist plist))
8926 (defun org-add-link-props (&rest plist)
8927 "Add these properties to the link property list."
8928 (let (key value)
8929 (while plist
8930 (setq key (pop plist) value (pop plist))
8931 (setq org-store-link-plist
8932 (plist-put org-store-link-plist key value)))))
8934 (defun org-email-link-description (&optional fmt)
8935 "Return the description part of an email link.
8936 This takes information from `org-store-link-plist' and formats it
8937 according to FMT (default from `org-email-link-description-format')."
8938 (setq fmt (or fmt org-email-link-description-format))
8939 (let* ((p org-store-link-plist)
8940 (to (plist-get p :toaddress))
8941 (from (plist-get p :fromaddress))
8942 (table
8943 (list
8944 (cons "%c" (plist-get p :fromto))
8945 (cons "%F" (plist-get p :from))
8946 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8947 (cons "%T" (plist-get p :to))
8948 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8949 (cons "%s" (plist-get p :subject))
8950 (cons "%d" (plist-get p :date))
8951 (cons "%m" (plist-get p :message-id)))))
8952 (when (string-match "%c" fmt)
8953 ;; Check if the user wrote this message
8954 (if (and org-from-is-user-regexp from to
8955 (save-match-data (string-match org-from-is-user-regexp from)))
8956 (setq fmt (replace-match "to %t" t t fmt))
8957 (setq fmt (replace-match "from %f" t t fmt))))
8958 (org-replace-escapes fmt table)))
8960 (defun org-make-org-heading-search-string (&optional string heading)
8961 "Make search string for STRING or current headline."
8962 (interactive)
8963 (let ((s (or string (org-get-heading)))
8964 (lines org-context-in-file-links))
8965 (unless (and string (not heading))
8966 ;; We are using a headline, clean up garbage in there.
8967 (if (string-match org-todo-regexp s)
8968 (setq s (replace-match "" t t s)))
8969 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8970 (setq s (replace-match "" t t s)))
8971 (setq s (org-trim s))
8972 (if (string-match (concat "^\\(" org-quote-string "\\|"
8973 org-comment-string "\\)") s)
8974 (setq s (replace-match "" t t s)))
8975 (while (string-match org-ts-regexp s)
8976 (setq s (replace-match "" t t s))))
8977 (or string (setq s (concat "*" s))) ; Add * for headlines
8978 (when (and string (integerp lines) (> lines 0))
8979 (let ((slines (org-split-string s "\n")))
8980 (when (< lines (length slines))
8981 (setq s (mapconcat
8982 'identity
8983 (reverse (nthcdr (- (length slines) lines)
8984 (reverse slines))) "\n")))))
8985 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8987 (defun org-make-link-string (link &optional description)
8988 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8989 (unless (string-match "\\S-" link)
8990 (error "Empty link"))
8991 (when (and description
8992 (stringp description)
8993 (not (string-match "\\S-" description)))
8994 (setq description nil))
8995 (when (stringp description)
8996 ;; Remove brackets from the description, they are fatal.
8997 (while (string-match "\\[" description)
8998 (setq description (replace-match "{" t t description)))
8999 (while (string-match "\\]" description)
9000 (setq description (replace-match "}" t t description))))
9001 (when (equal link description)
9002 ;; No description needed, it is identical
9003 (setq description nil))
9004 (when (and (not description)
9005 (not (string-match (org-image-file-name-regexp) link))
9006 (not (equal link (org-link-escape link))))
9007 (setq description (org-extract-attributes link)))
9008 (setq link
9009 (cond ((string-match (org-image-file-name-regexp) link) link)
9010 ((string-match org-link-types-re link)
9011 (concat (match-string 1 link)
9012 (org-link-escape (substring link (match-end 1)))))
9013 (t (org-link-escape link))))
9014 (concat "[[" link "]"
9015 (if description (concat "[" description "]") "")
9016 "]"))
9018 (defconst org-link-escape-chars
9019 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9020 "List of characters that should be escaped in link.
9021 This is the list that is used for internal purposes.")
9023 (defconst org-link-escape-chars-browser
9024 '(?\ )
9025 "List of escapes for characters that are problematic in links.
9026 This is the list that is used before handing over to the browser.")
9028 (defun org-link-escape (text &optional table merge)
9029 "Return percent escaped representation of TEXT.
9030 TEXT is a string with the text to escape.
9031 Optional argument TABLE is a list with characters that should be
9032 escaped. When nil, `org-link-escape-chars' is used.
9033 If optional argument MERGE is set, merge TABLE into
9034 `org-link-escape-chars'."
9035 (cond
9036 ((and table merge)
9037 (mapc (lambda (defchr)
9038 (unless (member defchr table)
9039 (setq table (cons defchr table)))) org-link-escape-chars))
9040 ((null table)
9041 (setq table org-link-escape-chars)))
9042 (mapconcat
9043 (lambda (char)
9044 (if (or (member char table)
9045 (and (or (< char 32) (= char 37) (> char 126))
9046 org-url-hexify-p))
9047 (mapconcat (lambda (sequence-element)
9048 (format "%%%.2X" sequence-element))
9049 (or (encode-coding-char char 'utf-8)
9050 (error "Unable to percent escape character: %s"
9051 (char-to-string char))) "")
9052 (char-to-string char))) text ""))
9054 (defun org-link-unescape (str)
9055 "Unhex hexified Unicode strings as returned from the JavaScript function
9056 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9057 (unless (and (null str) (string= "" str))
9058 (let ((pos 0) (case-fold-search t) unhexed)
9059 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9060 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9061 (setq str (replace-match unhexed t t str))
9062 (setq pos (+ pos (length unhexed))))))
9063 str)
9065 (defun org-link-unescape-compound (hex)
9066 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9067 Note: this function also decodes single byte encodings like
9068 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9069 (save-match-data
9070 (let* ((bytes (cdr (split-string hex "%")))
9071 (ret "")
9072 (eat 0)
9073 (sum 0))
9074 (while bytes
9075 (let* ((val (string-to-number (pop bytes) 16))
9076 (shift-xor
9077 (if (= 0 eat)
9078 (cond
9079 ((>= val 252) (cons 6 252))
9080 ((>= val 248) (cons 5 248))
9081 ((>= val 240) (cons 4 240))
9082 ((>= val 224) (cons 3 224))
9083 ((>= val 192) (cons 2 192))
9084 (t (cons 0 0)))
9085 (cons 6 128))))
9086 (if (>= val 192) (setq eat (car shift-xor)))
9087 (setq val (logxor val (cdr shift-xor)))
9088 (setq sum (+ (lsh sum (car shift-xor)) val))
9089 (if (> eat 0) (setq eat (- eat 1)))
9090 (cond
9091 ((= 0 eat) ;multi byte
9092 (setq ret (concat ret (org-char-to-string sum)))
9093 (setq sum 0))
9094 ((not bytes) ; single byte(s)
9095 (setq ret (org-link-unescape-single-byte-sequence hex))))
9096 )) ;; end (while bytes
9097 ret )))
9099 (defun org-link-unescape-single-byte-sequence (hex)
9100 "Unhexify hex-encoded single byte character sequences."
9101 (mapconcat (lambda (byte)
9102 (char-to-string (string-to-number byte 16)))
9103 (cdr (split-string hex "%")) ""))
9105 (defun org-xor (a b)
9106 "Exclusive or."
9107 (if a (not b) b))
9109 (defun org-fixup-message-id-for-http (s)
9110 "Replace special characters in a message id, so it can be used in an http query."
9111 (when (string-match "%" s)
9112 (setq s (mapconcat (lambda (c)
9113 (if (eq c ?%)
9114 "%25"
9115 (char-to-string c)))
9116 s "")))
9117 (while (string-match "<" s)
9118 (setq s (replace-match "%3C" t t s)))
9119 (while (string-match ">" s)
9120 (setq s (replace-match "%3E" t t s)))
9121 (while (string-match "@" s)
9122 (setq s (replace-match "%40" t t s)))
9125 (defun org-link-prettify (link)
9126 "Return a human-readable representation of LINK.
9127 The car of LINK must be a raw link the cdr of LINK must be either
9128 a link description or nil."
9129 (let ((desc (or (cadr link) "<no description>")))
9130 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9131 "<" (car link) ">")))
9133 ;;;###autoload
9134 (defun org-insert-link-global ()
9135 "Insert a link like Org-mode does.
9136 This command can be called in any mode to insert a link in Org-mode syntax."
9137 (interactive)
9138 (org-load-modules-maybe)
9139 (org-run-like-in-org-mode 'org-insert-link))
9141 (defun org-insert-all-links (&optional keep)
9142 "Insert all links in `org-stored-links'."
9143 (interactive "P")
9144 (let ((links (copy-sequence org-stored-links)) l)
9145 (while (setq l (if keep (pop links) (pop org-stored-links)))
9146 (insert "- ")
9147 (org-insert-link nil (car l) (cadr l))
9148 (insert "\n"))))
9150 (defun org-link-fontify-links-to-this-file ()
9151 "Fontify links to the current file in `org-stored-links'."
9152 (let ((f (buffer-file-name)) a b)
9153 (setq a (mapcar (lambda(l)
9154 (let ((ll (car l)))
9155 (when (and (string-match "^file:\\(.+\\)::" ll)
9156 (equal f (expand-file-name (match-string 1 ll))))
9157 ll)))
9158 org-stored-links))
9159 (when (featurep 'org-id)
9160 (setq b (mapcar (lambda(l)
9161 (let ((ll (car l)))
9162 (when (and (string-match "^id:\\(.+\\)$" ll)
9163 (equal f (expand-file-name
9164 (or (org-id-find-id-file
9165 (match-string 1 ll)) ""))))
9166 ll)))
9167 org-stored-links)))
9168 (mapcar (lambda(l)
9169 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9170 (delq nil (append a b)))))
9172 (defvar org-link-links-in-this-file nil)
9173 (defun org-insert-link (&optional complete-file link-location default-description)
9174 "Insert a link. At the prompt, enter the link.
9176 Completion can be used to insert any of the link protocol prefixes like
9177 http or ftp in use.
9179 The history can be used to select a link previously stored with
9180 `org-store-link'. When the empty string is entered (i.e. if you just
9181 press RET at the prompt), the link defaults to the most recently
9182 stored link. As SPC triggers completion in the minibuffer, you need to
9183 use M-SPC or C-q SPC to force the insertion of a space character.
9185 You will also be prompted for a description, and if one is given, it will
9186 be displayed in the buffer instead of the link.
9188 If there is already a link at point, this command will allow you to edit link
9189 and description parts.
9191 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9192 be selected using completion. The path to the file will be relative to the
9193 current directory if the file is in the current directory or a subdirectory.
9194 Otherwise, the link will be the absolute path as completed in the minibuffer
9195 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9196 option `org-link-file-path-type'.
9198 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9199 the current directory or below.
9201 With three \\[universal-argument] prefixes, negate the meaning of
9202 `org-keep-stored-link-after-insertion'.
9204 If `org-make-link-description-function' is non-nil, this function will be
9205 called with the link target, and the result will be the default
9206 link description.
9208 If the LINK-LOCATION parameter is non-nil, this value will be
9209 used as the link location instead of reading one interactively.
9211 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9212 be used as the default description."
9213 (interactive "P")
9214 (let* ((wcf (current-window-configuration))
9215 (region (if (org-region-active-p)
9216 (buffer-substring (region-beginning) (region-end))))
9217 (remove (and region (list (region-beginning) (region-end))))
9218 (desc region)
9219 tmphist ; byte-compile incorrectly complains about this
9220 (link link-location)
9221 (abbrevs org-link-abbrev-alist-local)
9222 entry file all-prefixes auto-desc)
9223 (cond
9224 (link-location) ; specified by arg, just use it.
9225 ((org-in-regexp org-bracket-link-regexp 1)
9226 ;; We do have a link at point, and we are going to edit it.
9227 (setq remove (list (match-beginning 0) (match-end 0)))
9228 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9229 (setq link (read-string "Link: "
9230 (org-link-unescape
9231 (org-match-string-no-properties 1)))))
9232 ((or (org-in-regexp org-angle-link-re)
9233 (org-in-regexp org-plain-link-re))
9234 ;; Convert to bracket link
9235 (setq remove (list (match-beginning 0) (match-end 0))
9236 link (read-string "Link: "
9237 (org-remove-angle-brackets (match-string 0)))))
9238 ((member complete-file '((4) (16)))
9239 ;; Completing read for file names.
9240 (setq link (org-file-complete-link complete-file)))
9242 ;; Read link, with completion for stored links.
9243 (org-link-fontify-links-to-this-file)
9244 (org-switch-to-buffer-other-window "*Org Links*")
9245 (with-current-buffer "*Org Links*"
9246 (erase-buffer)
9247 (insert "Insert a link.
9248 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9249 (when org-stored-links
9250 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9251 (insert (mapconcat 'org-link-prettify
9252 (reverse org-stored-links) "\n")))
9253 (goto-char (point-min)))
9254 (let ((cw (selected-window)))
9255 (select-window (get-buffer-window "*Org Links*" 'visible))
9256 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9257 (unless (pos-visible-in-window-p (point-max))
9258 (org-fit-window-to-buffer))
9259 (and (window-live-p cw) (select-window cw)))
9260 ;; Fake a link history, containing the stored links.
9261 (setq tmphist (append (mapcar 'car org-stored-links)
9262 org-insert-link-history))
9263 (setq all-prefixes (append (mapcar 'car abbrevs)
9264 (mapcar 'car org-link-abbrev-alist)
9265 org-link-types))
9266 (unwind-protect
9267 (progn
9268 (setq link
9269 (let ((org-completion-use-ido nil)
9270 (org-completion-use-iswitchb nil))
9271 (org-completing-read
9272 "Link: "
9273 (append
9274 (mapcar (lambda (x) (list (concat x ":")))
9275 all-prefixes)
9276 (mapcar 'car org-stored-links)
9277 (mapcar 'cadr org-stored-links))
9278 nil nil nil
9279 'tmphist
9280 (caar org-stored-links))))
9281 (if (not (string-match "\\S-" link))
9282 (error "No link selected"))
9283 (mapc (lambda(l)
9284 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9285 org-stored-links)
9286 (if (or (member link all-prefixes)
9287 (and (equal ":" (substring link -1))
9288 (member (substring link 0 -1) all-prefixes)
9289 (setq link (substring link 0 -1))))
9290 (setq link (org-link-try-special-completion link))))
9291 (set-window-configuration wcf)
9292 (kill-buffer "*Org Links*"))
9293 (setq entry (assoc link org-stored-links))
9294 (or entry (push link org-insert-link-history))
9295 (setq desc (or desc (nth 1 entry)))))
9297 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9298 (not org-keep-stored-link-after-insertion))
9299 (setq org-stored-links (delq (assoc link org-stored-links)
9300 org-stored-links)))
9302 (if (string-match org-plain-link-re link)
9303 ;; URL-like link, normalize the use of angular brackets.
9304 (setq link (org-remove-angle-brackets link)))
9306 ;; Check if we are linking to the current file with a search option
9307 ;; If yes, simplify the link by using only the search option.
9308 (when (and buffer-file-name
9309 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9310 (let* ((path (match-string 1 link))
9311 (case-fold-search nil)
9312 (search (match-string 2 link)))
9313 (save-match-data
9314 (if (equal (file-truename buffer-file-name) (file-truename path))
9315 ;; We are linking to this same file, with a search option
9316 (setq link search)))))
9318 ;; Check if we can/should use a relative path. If yes, simplify the link
9319 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9320 (let* ((type (match-string 1 link))
9321 (path (match-string 2 link))
9322 (origpath path)
9323 (case-fold-search nil))
9324 (cond
9325 ((or (eq org-link-file-path-type 'absolute)
9326 (equal complete-file '(16)))
9327 (setq path (abbreviate-file-name (expand-file-name path))))
9328 ((eq org-link-file-path-type 'noabbrev)
9329 (setq path (expand-file-name path)))
9330 ((eq org-link-file-path-type 'relative)
9331 (setq path (file-relative-name path)))
9333 (save-match-data
9334 (if (string-match (concat "^" (regexp-quote
9335 (expand-file-name
9336 (file-name-as-directory
9337 default-directory))))
9338 (expand-file-name path))
9339 ;; We are linking a file with relative path name.
9340 (setq path (substring (expand-file-name path)
9341 (match-end 0)))
9342 (setq path (abbreviate-file-name (expand-file-name path)))))))
9343 (setq link (concat type path))
9344 (if (equal desc origpath)
9345 (setq desc path))))
9347 (if org-make-link-description-function
9348 (setq desc
9349 (or (condition-case nil
9350 (funcall org-make-link-description-function link desc)
9351 (error (progn (message "Can't get link description from `%s'"
9352 (symbol-name org-make-link-description-function))
9353 (sit-for 2) nil)))
9354 (read-string "Description: " default-description)))
9355 (if default-description (setq desc default-description)
9356 (setq desc (or (and auto-desc desc)
9357 (read-string "Description: " desc)))))
9359 (unless (string-match "\\S-" desc) (setq desc nil))
9360 (if remove (apply 'delete-region remove))
9361 (insert (org-make-link-string link desc))))
9363 (defun org-link-try-special-completion (type)
9364 "If there is completion support for link type TYPE, offer it."
9365 (let ((fun (intern (concat "org-" type "-complete-link"))))
9366 (if (functionp fun)
9367 (funcall fun)
9368 (read-string "Link (no completion support): " (concat type ":")))))
9370 (defun org-file-complete-link (&optional arg)
9371 "Create a file link using completion."
9372 (let (file link)
9373 (setq file (read-file-name "File: "))
9374 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9375 (pwd1 (file-name-as-directory (abbreviate-file-name
9376 (expand-file-name ".")))))
9377 (cond
9378 ((equal arg '(16))
9379 (setq link (concat
9380 "file:"
9381 (abbreviate-file-name (expand-file-name file)))))
9382 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9383 (setq link (concat "file:" (match-string 1 file))))
9384 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9385 (expand-file-name file))
9386 (setq link (concat
9387 "file:" (match-string 1 (expand-file-name file)))))
9388 (t (setq link (concat "file:" file)))))
9389 link))
9391 (defun org-completing-read (&rest args)
9392 "Completing-read with SPACE being a normal character."
9393 (let ((enable-recursive-minibuffers t)
9394 (minibuffer-local-completion-map
9395 (copy-keymap minibuffer-local-completion-map)))
9396 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9397 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9398 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9399 (apply 'org-icompleting-read args)))
9401 (defun org-completing-read-no-i (&rest args)
9402 (let (org-completion-use-ido org-completion-use-iswitchb)
9403 (apply 'org-completing-read args)))
9405 (defun org-iswitchb-completing-read (prompt choices &rest args)
9406 "Use iswitch as a completing-read replacement to choose from choices.
9407 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9408 from."
9409 (let* ((iswitchb-use-virtual-buffers nil)
9410 (iswitchb-make-buflist-hook
9411 (lambda ()
9412 (setq iswitchb-temp-buflist choices))))
9413 (iswitchb-read-buffer prompt)))
9415 (defun org-icompleting-read (&rest args)
9416 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9417 (org-without-partial-completion
9418 (if (and org-completion-use-ido
9419 (fboundp 'ido-completing-read)
9420 (boundp 'ido-mode) ido-mode
9421 (listp (second args)))
9422 (let ((ido-enter-matching-directory nil))
9423 (apply 'ido-completing-read (concat (car args))
9424 (if (consp (car (nth 1 args)))
9425 (mapcar 'car (nth 1 args))
9426 (nth 1 args))
9427 (cddr args)))
9428 (if (and org-completion-use-iswitchb
9429 (boundp 'iswitchb-mode) iswitchb-mode
9430 (listp (second args)))
9431 (apply 'org-iswitchb-completing-read (concat (car args))
9432 (if (consp (car (nth 1 args)))
9433 (mapcar 'car (nth 1 args))
9434 (nth 1 args))
9435 (cddr args))
9436 (apply 'completing-read args)))))
9438 (defun org-extract-attributes (s)
9439 "Extract the attributes cookie from a string and set as text property."
9440 (let (a attr (start 0) key value)
9441 (save-match-data
9442 (when (string-match "{{\\([^}]+\\)}}$" s)
9443 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9444 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9445 (setq key (match-string 1 a) value (match-string 2 a)
9446 start (match-end 0)
9447 attr (plist-put attr (intern key) value))))
9448 (org-add-props s nil 'org-attr attr))
9451 (defun org-extract-attributes-from-string (tag)
9452 (let (key value attr)
9453 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9454 (setq key (match-string 1 tag) value (match-string 2 tag)
9455 tag (replace-match "" t t tag)
9456 attr (plist-put attr (intern key) value)))
9457 (cons tag attr)))
9459 (defun org-attributes-to-string (plist)
9460 "Format a property list into an HTML attribute list."
9461 (let ((s "") key value)
9462 (while plist
9463 (setq key (pop plist) value (pop plist))
9464 (and value
9465 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9468 ;;; Opening/following a link
9470 (defvar org-link-search-failed nil)
9472 (defvar org-open-link-functions nil
9473 "Hook for functions finding a plain text link.
9474 These functions must take a single argument, the link content.
9475 They will be called for links that look like [[link text][description]]
9476 when LINK TEXT does not have a protocol like \"http:\" and does not look
9477 like a filename (e.g. \"./blue.png\").
9479 These functions will be called *before* Org attempts to resolve the
9480 link by doing text searches in the current buffer - so if you want a
9481 link \"[[target]]\" to still find \"<<target>>\", your function should
9482 handle this as a special case.
9484 When the function does handle the link, it must return a non-nil value.
9485 If it decides that it is not responsible for this link, it must return
9486 nil to indicate that that Org-mode can continue with other options
9487 like exact and fuzzy text search.")
9489 (defun org-next-link ()
9490 "Move forward to the next link.
9491 If the link is in hidden text, expose it."
9492 (interactive)
9493 (when (and org-link-search-failed (eq this-command last-command))
9494 (goto-char (point-min))
9495 (message "Link search wrapped back to beginning of buffer"))
9496 (setq org-link-search-failed nil)
9497 (let* ((pos (point))
9498 (ct (org-context))
9499 (a (assoc :link ct)))
9500 (if a (goto-char (nth 2 a)))
9501 (if (re-search-forward org-any-link-re nil t)
9502 (progn
9503 (goto-char (match-beginning 0))
9504 (if (outline-invisible-p) (org-show-context)))
9505 (goto-char pos)
9506 (setq org-link-search-failed t)
9507 (error "No further link found"))))
9509 (defun org-previous-link ()
9510 "Move backward to the previous link.
9511 If the link is in hidden text, expose it."
9512 (interactive)
9513 (when (and org-link-search-failed (eq this-command last-command))
9514 (goto-char (point-max))
9515 (message "Link search wrapped back to end of buffer"))
9516 (setq org-link-search-failed nil)
9517 (let* ((pos (point))
9518 (ct (org-context))
9519 (a (assoc :link ct)))
9520 (if a (goto-char (nth 1 a)))
9521 (if (re-search-backward org-any-link-re nil t)
9522 (progn
9523 (goto-char (match-beginning 0))
9524 (if (outline-invisible-p) (org-show-context)))
9525 (goto-char pos)
9526 (setq org-link-search-failed t)
9527 (error "No further link found"))))
9529 (defun org-translate-link (s)
9530 "Translate a link string if a translation function has been defined."
9531 (if (and org-link-translation-function
9532 (fboundp org-link-translation-function)
9533 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9534 (progn
9535 (setq s (funcall org-link-translation-function
9536 (match-string 1 s) (match-string 2 s)))
9537 (concat (car s) ":" (cdr s)))
9540 (defun org-translate-link-from-planner (type path)
9541 "Translate a link from Emacs Planner syntax so that Org can follow it.
9542 This is still an experimental function, your mileage may vary."
9543 (cond
9544 ((member type '("http" "https" "news" "ftp"))
9545 ;; standard Internet links are the same.
9546 nil)
9547 ((and (equal type "irc") (string-match "^//" path))
9548 ;; Planner has two / at the beginning of an irc link, we have 1.
9549 ;; We should have zero, actually....
9550 (setq path (substring path 1)))
9551 ((and (equal type "lisp") (string-match "^/" path))
9552 ;; Planner has a slash, we do not.
9553 (setq type "elisp" path (substring path 1)))
9554 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9555 ;; A typical message link. Planner has the id after the final slash,
9556 ;; we separate it with a hash mark
9557 (setq path (concat (match-string 1 path) "#"
9558 (org-remove-angle-brackets (match-string 2 path)))))
9560 (cons type path))
9562 (defun org-find-file-at-mouse (ev)
9563 "Open file link or URL at mouse."
9564 (interactive "e")
9565 (mouse-set-point ev)
9566 (org-open-at-point 'in-emacs))
9568 (defun org-open-at-mouse (ev)
9569 "Open file link or URL at mouse.
9570 See the docstring of `org-open-file' for details."
9571 (interactive "e")
9572 (mouse-set-point ev)
9573 (if (eq major-mode 'org-agenda-mode)
9574 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9575 (org-open-at-point))
9577 (defvar org-window-config-before-follow-link nil
9578 "The window configuration before following a link.
9579 This is saved in case the need arises to restore it.")
9581 (defvar org-open-link-marker (make-marker)
9582 "Marker pointing to the location where `org-open-at-point; was called.")
9584 ;;;###autoload
9585 (defun org-open-at-point-global ()
9586 "Follow a link like Org-mode does.
9587 This command can be called in any mode to follow a link that has
9588 Org-mode syntax."
9589 (interactive)
9590 (org-run-like-in-org-mode 'org-open-at-point))
9592 ;;;###autoload
9593 (defun org-open-link-from-string (s &optional arg reference-buffer)
9594 "Open a link in the string S, as if it was in Org-mode."
9595 (interactive "sLink: \nP")
9596 (let ((reference-buffer (or reference-buffer (current-buffer))))
9597 (with-temp-buffer
9598 (let ((org-inhibit-startup (not reference-buffer)))
9599 (org-mode)
9600 (insert s)
9601 (goto-char (point-min))
9602 (when reference-buffer
9603 (setq org-link-abbrev-alist-local
9604 (with-current-buffer reference-buffer
9605 org-link-abbrev-alist-local)))
9606 (org-open-at-point arg reference-buffer)))))
9608 (defvar org-open-at-point-functions nil
9609 "Hook that is run when following a link at point.
9611 Functions in this hook must return t if they identify and follow
9612 a link at point. If they don't find anything interesting at point,
9613 they must return nil.")
9615 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9616 (defun org-open-at-point (&optional arg reference-buffer)
9617 "Open link at or after point.
9618 If there is no link at point, this function will search forward up to
9619 the end of the current line.
9620 Normally, files will be opened by an appropriate application. If the
9621 optional prefix argument ARG is non-nil, Emacs will visit the file.
9622 With a double prefix argument, try to open outside of Emacs, in the
9623 application the system uses for this file type."
9624 (interactive "P")
9625 ;; if in a code block, then open the block's results
9626 (unless (call-interactively #'org-babel-open-src-block-result)
9627 (org-load-modules-maybe)
9628 (move-marker org-open-link-marker (point))
9629 (setq org-window-config-before-follow-link (current-window-configuration))
9630 (org-remove-occur-highlights nil nil t)
9631 (cond
9632 ((and (org-at-heading-p)
9633 (not (org-at-timestamp-p t))
9634 (not (org-in-regexp
9635 (concat org-plain-link-re "\\|"
9636 org-bracket-link-regexp "\\|"
9637 org-angle-link-re "\\|"
9638 "[ \t]:[^ \t\n]+:[ \t]*$")))
9639 (not (get-text-property (point) 'org-linked-text)))
9640 (or (org-offer-links-in-entry arg)
9641 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9642 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9643 ((and (org-at-timestamp-p t)
9644 (not (org-in-regexp org-bracket-link-regexp)))
9645 (org-follow-timestamp-link))
9646 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9647 (not (org-in-regexp org-bracket-link-regexp)))
9648 (org-footnote-action))
9650 (let (type path link line search (pos (point)))
9651 (catch 'match
9652 (save-excursion
9653 (skip-chars-forward "^]\n\r")
9654 (when (org-in-regexp org-bracket-link-regexp 1)
9655 (setq link (org-extract-attributes
9656 (org-link-unescape (org-match-string-no-properties 1))))
9657 (while (string-match " *\n *" link)
9658 (setq link (replace-match " " t t link)))
9659 (setq link (org-link-expand-abbrev link))
9660 (cond
9661 ((or (file-name-absolute-p link)
9662 (string-match "^\\.\\.?/" link))
9663 (setq type "file" path link))
9664 ((string-match org-link-re-with-space3 link)
9665 (setq type (match-string 1 link) path (match-string 2 link)))
9666 ((string-match "^help:+\\(.+\\)" link)
9667 (setq type "help" path (match-string 1 link)))
9668 (t (setq type "thisfile" path link)))
9669 (throw 'match t)))
9671 (when (get-text-property (point) 'org-linked-text)
9672 (setq type "thisfile"
9673 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9674 (1+ (point)) (point))
9675 path (buffer-substring
9676 (or (previous-single-property-change pos 'org-linked-text)
9677 (point-min))
9678 (or (next-single-property-change pos 'org-linked-text)
9679 (point-max))))
9680 (throw 'match t))
9682 (save-excursion
9683 (when (or (org-in-regexp org-angle-link-re)
9684 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9685 (save-match-data (not (looking-back "\\[\\[")))))
9686 (setq type (match-string 1)
9687 path (org-link-unescape (match-string 2)))
9688 (throw 'match t)))
9689 (save-excursion
9690 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9691 (setq type "tags"
9692 path (match-string 1))
9693 (while (string-match ":" path)
9694 (setq path (replace-match "+" t t path)))
9695 (throw 'match t)))
9696 (when (org-in-regexp "<\\([^><\n]+\\)>")
9697 (setq type "tree-match"
9698 path (match-string 1))
9699 (throw 'match t)))
9700 (unless path
9701 (error "No link found"))
9703 ;; switch back to reference buffer
9704 ;; needed when if called in a temporary buffer through
9705 ;; org-open-link-from-string
9706 (with-current-buffer (or reference-buffer (current-buffer))
9708 ;; Remove any trailing spaces in path
9709 (if (string-match " +\\'" path)
9710 (setq path (replace-match "" t t path)))
9711 (if (and org-link-translation-function
9712 (fboundp org-link-translation-function))
9713 ;; Check if we need to translate the link
9714 (let ((tmp (funcall org-link-translation-function type path)))
9715 (setq type (car tmp) path (cdr tmp))))
9717 (cond
9719 ((assoc type org-link-protocols)
9720 (funcall (nth 1 (assoc type org-link-protocols)) path))
9722 ((equal type "help")
9723 (let ((f-or-v (intern path)))
9724 (cond ((fboundp f-or-v)
9725 (describe-function f-or-v))
9726 ((boundp f-or-v)
9727 (describe-variable f-or-v))
9728 (t (error "Not a known function or variable")))))
9730 ((equal type "mailto")
9731 (let ((cmd (car org-link-mailto-program))
9732 (args (cdr org-link-mailto-program)) args1
9733 (address path) (subject "") a)
9734 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9735 (setq address (match-string 1 path)
9736 subject (org-link-escape (match-string 2 path))))
9737 (while args
9738 (cond
9739 ((not (stringp (car args))) (push (pop args) args1))
9740 (t (setq a (pop args))
9741 (if (string-match "%a" a)
9742 (setq a (replace-match address t t a)))
9743 (if (string-match "%s" a)
9744 (setq a (replace-match subject t t a)))
9745 (push a args1))))
9746 (apply cmd (nreverse args1))))
9748 ((member type '("http" "https" "ftp" "news"))
9749 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9750 (org-link-escape
9751 path org-link-escape-chars-browser)
9752 path))))
9754 ((string= type "doi")
9755 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9756 (org-link-escape
9757 path org-link-escape-chars-browser)
9758 path))))
9760 ((member type '("message"))
9761 (browse-url (concat type ":" path)))
9763 ((string= type "tags")
9764 (org-tags-view arg path))
9766 ((string= type "tree-match")
9767 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9769 ((string= type "file")
9770 (if (string-match "::\\([0-9]+\\)\\'" path)
9771 (setq line (string-to-number (match-string 1 path))
9772 path (substring path 0 (match-beginning 0)))
9773 (if (string-match "::\\(.+\\)\\'" path)
9774 (setq search (match-string 1 path)
9775 path (substring path 0 (match-beginning 0)))))
9776 (if (string-match "[*?{]" (file-name-nondirectory path))
9777 (dired path)
9778 (org-open-file path arg line search)))
9780 ((string= type "shell")
9781 (let ((buf (generate-new-buffer "*Org Shell Output"))
9782 (cmd path))
9783 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9784 (string-match org-confirm-shell-link-not-regexp cmd))
9785 (not org-confirm-shell-link-function)
9786 (funcall org-confirm-shell-link-function
9787 (format "Execute \"%s\" in shell? "
9788 (org-add-props cmd nil
9789 'face 'org-warning))))
9790 (progn
9791 (message "Executing %s" cmd)
9792 (shell-command cmd buf)
9793 (if (featurep 'midnight)
9794 (setq clean-buffer-list-kill-buffer-names
9795 (cons buf clean-buffer-list-kill-buffer-names))))
9796 (error "Abort"))))
9798 ((string= type "elisp")
9799 (let ((cmd path))
9800 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9801 (string-match org-confirm-elisp-link-not-regexp cmd))
9802 (not org-confirm-elisp-link-function)
9803 (funcall org-confirm-elisp-link-function
9804 (format "Execute \"%s\" as elisp? "
9805 (org-add-props cmd nil
9806 'face 'org-warning))))
9807 (message "%s => %s" cmd
9808 (if (equal (string-to-char cmd) ?\()
9809 (eval (read cmd))
9810 (call-interactively (read cmd))))
9811 (error "Abort"))))
9813 ((and (string= type "thisfile")
9814 (run-hook-with-args-until-success
9815 'org-open-link-functions path)))
9817 ((string= type "thisfile")
9818 (if arg
9819 (switch-to-buffer-other-window
9820 (org-get-buffer-for-internal-link (current-buffer)))
9821 (org-mark-ring-push))
9822 (let ((cmd `(org-link-search
9823 ,path
9824 ,(cond ((equal arg '(4)) ''occur)
9825 ((equal arg '(16)) ''org-occur))
9826 ,pos)))
9827 (condition-case nil (let ((org-link-search-inhibit-query t))
9828 (eval cmd))
9829 (error (progn (widen) (eval cmd))))))
9831 (t (browse-url-at-point)))))))
9832 (move-marker org-open-link-marker nil)
9833 (run-hook-with-args 'org-follow-link-hook)))
9835 (defun org-offer-links-in-entry (&optional nth zero)
9836 "Offer links in the current entry and follow the selected link.
9837 If there is only one link, follow it immediately as well.
9838 If NTH is an integer, immediately pick the NTH link found.
9839 If ZERO is a string, check also this string for a link, and if
9840 there is one, offer it as link number zero."
9841 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9842 "\\(" org-angle-link-re "\\)\\|"
9843 "\\(" org-plain-link-re "\\)"))
9844 (cnt ?0)
9845 (in-emacs (if (integerp nth) nil nth))
9846 have-zero end links link c)
9847 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9848 (push (match-string 0 zero) links)
9849 (setq cnt (1- cnt) have-zero t))
9850 (save-excursion
9851 (org-back-to-heading t)
9852 (setq end (save-excursion (outline-next-heading) (point)))
9853 (while (re-search-forward re end t)
9854 (push (match-string 0) links))
9855 (setq links (org-uniquify (reverse links))))
9857 (cond
9858 ((null links)
9859 (message "No links"))
9860 ((equal (length links) 1)
9861 (setq link (list (car links))))
9862 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9863 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9864 (t ; we have to select a link
9865 (save-excursion
9866 (save-window-excursion
9867 (delete-other-windows)
9868 (with-output-to-temp-buffer "*Select Link*"
9869 (mapc (lambda (l)
9870 (if (not (string-match org-bracket-link-regexp l))
9871 (princ (format "[%c] %s\n" (incf cnt)
9872 (org-remove-angle-brackets l)))
9873 (if (match-end 3)
9874 (princ (format "[%c] %s (%s)\n" (incf cnt)
9875 (match-string 3 l) (match-string 1 l)))
9876 (princ (format "[%c] %s\n" (incf cnt)
9877 (match-string 1 l))))))
9878 links))
9879 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9880 (message "Select link to open, RET to open all:")
9881 (setq c (read-char-exclusive))
9882 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9883 (when (equal c ?q) (error "Abort"))
9884 (if (equal c ?\C-m)
9885 (setq link links)
9886 (setq nth (- c ?0))
9887 (if have-zero (setq nth (1+ nth)))
9888 (unless (and (integerp nth) (>= (length links) nth))
9889 (error "Invalid link selection"))
9890 (setq link (list (nth (1- nth) links))))))
9891 (if link
9892 (let ((buf (current-buffer)))
9893 (dolist (l link)
9894 (org-open-link-from-string l in-emacs buf))
9896 nil)))
9898 ;; Add special file links that specify the way of opening
9900 (org-add-link-type "file+sys" 'org-open-file-with-system)
9901 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9902 (defun org-open-file-with-system (path)
9903 "Open file at PATH using the system way of opening it."
9904 (org-open-file path 'system))
9905 (defun org-open-file-with-emacs (path)
9906 "Open file at PATH in Emacs."
9907 (org-open-file path 'emacs))
9908 (defun org-remove-file-link-modifiers ()
9909 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9910 (goto-char (point-min))
9911 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9912 (org-if-unprotected
9913 (replace-match "file:" t t))))
9914 (eval-after-load "org-exp"
9915 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9916 'org-remove-file-link-modifiers))
9918 ;;;; Time estimates
9920 (defun org-get-effort (&optional pom)
9921 "Get the effort estimate for the current entry."
9922 (org-entry-get pom org-effort-property))
9924 ;;; File search
9926 (defvar org-create-file-search-functions nil
9927 "List of functions to construct the right search string for a file link.
9928 These functions are called in turn with point at the location to
9929 which the link should point.
9931 A function in the hook should first test if it would like to
9932 handle this file type, for example by checking the `major-mode'
9933 or the file extension. If it decides not to handle this file, it
9934 should just return nil to give other functions a chance. If it
9935 does handle the file, it must return the search string to be used
9936 when following the link. The search string will be part of the
9937 file link, given after a double colon, and `org-open-at-point'
9938 will automatically search for it. If special measures must be
9939 taken to make the search successful, another function should be
9940 added to the companion hook `org-execute-file-search-functions',
9941 which see.
9943 A function in this hook may also use `setq' to set the variable
9944 `description' to provide a suggestion for the descriptive text to
9945 be used for this link when it gets inserted into an Org-mode
9946 buffer with \\[org-insert-link].")
9948 (defvar org-execute-file-search-functions nil
9949 "List of functions to execute a file search triggered by a link.
9951 Functions added to this hook must accept a single argument, the
9952 search string that was part of the file link, the part after the
9953 double colon. The function must first check if it would like to
9954 handle this search, for example by checking the `major-mode' or
9955 the file extension. If it decides not to handle this search, it
9956 should just return nil to give other functions a chance. If it
9957 does handle the search, it must return a non-nil value to keep
9958 other functions from trying.
9960 Each function can access the current prefix argument through the
9961 variable `current-prefix-argument'. Note that a single prefix is
9962 used to force opening a link in Emacs, so it may be good to only
9963 use a numeric or double prefix to guide the search function.
9965 In case this is needed, a function in this hook can also restore
9966 the window configuration before `org-open-at-point' was called using:
9968 (set-window-configuration org-window-config-before-follow-link)")
9970 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9971 (defun org-link-search (s &optional type avoid-pos stealth)
9972 "Search for a link search option.
9973 If S is surrounded by forward slashes, it is interpreted as a
9974 regular expression. In org-mode files, this will create an `org-occur'
9975 sparse tree. In ordinary files, `occur' will be used to list matches.
9976 If the current buffer is in `dired-mode', grep will be used to search
9977 in all files. If AVOID-POS is given, ignore matches near that position.
9979 When optional argument STEALTH is non-nil, do not modify
9980 visibility around point, thus ignoring
9981 `org-show-hierarchy-above', `org-show-following-heading' and
9982 `org-show-siblings' variables."
9983 (let ((case-fold-search t)
9984 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9985 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9986 (append '(("") (" ") ("\t") ("\n"))
9987 org-emphasis-alist)
9988 "\\|") "\\)"))
9989 (pos (point))
9990 (pre nil) (post nil)
9991 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9992 (cond
9993 ;; First check if there are any special search functions
9994 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9995 ;; Now try the builtin stuff
9996 ((and (equal (string-to-char s0) ?#)
9997 (> (length s0) 1)
9998 (save-excursion
9999 (goto-char (point-min))
10000 (and
10001 (re-search-forward
10002 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10003 (setq type 'dedicated
10004 pos (match-beginning 0))))
10005 ;; There is an exact target for this
10006 (goto-char pos)
10007 (org-back-to-heading t)))
10008 ((save-excursion
10009 (goto-char (point-min))
10010 (and
10011 (re-search-forward
10012 (concat "<<" (regexp-quote s0) ">>") nil t)
10013 (setq type 'dedicated
10014 pos (match-beginning 0))))
10015 ;; There is an exact target for this
10016 (goto-char pos))
10017 ((save-excursion
10018 (goto-char (point-min))
10019 (and
10020 (re-search-forward
10021 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10022 (setq type 'dedicated pos (match-beginning 0))))
10023 ;; Found an invisible target.
10024 (goto-char pos))
10025 ((save-excursion
10026 (goto-char (point-min))
10027 (and
10028 (re-search-forward
10029 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10030 (setq type 'dedicated pos (match-beginning 0))))
10031 ;; Found an element with a matching #+name affiliated keyword.
10032 (goto-char pos))
10033 ((and (string-match "^(\\(.*\\))$" s0)
10034 (save-excursion
10035 (goto-char (point-min))
10036 (and
10037 (re-search-forward
10038 (concat "[^[]" (regexp-quote
10039 (format org-coderef-label-format
10040 (match-string 1 s0))))
10041 nil t)
10042 (setq type 'dedicated
10043 pos (1+ (match-beginning 0))))))
10044 ;; There is a coderef target for this
10045 (goto-char pos))
10046 ((string-match "^/\\(.*\\)/$" s)
10047 ;; A regular expression
10048 (cond
10049 ((derived-mode-p 'org-mode)
10050 (org-occur (match-string 1 s)))
10051 ;;((eq major-mode 'dired-mode)
10052 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10053 (t (org-do-occur (match-string 1 s)))))
10054 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10055 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10056 (goto-char (point-min))
10057 (cond
10058 ((let (case-fold-search)
10059 (re-search-forward (format org-complex-heading-regexp-format
10060 (regexp-quote s))
10061 nil t))
10062 ;; OK, found a match
10063 (setq type 'dedicated)
10064 (goto-char (match-beginning 0)))
10065 ((and (not org-link-search-inhibit-query)
10066 (eq org-link-search-must-match-exact-headline 'query-to-create)
10067 (y-or-n-p "No match - create this as a new heading? "))
10068 (goto-char (point-max))
10069 (or (bolp) (newline))
10070 (insert "* " s "\n")
10071 (beginning-of-line 0))
10073 (goto-char pos)
10074 (error "No match"))))
10076 ;; A normal search string
10077 (when (equal (string-to-char s) ?*)
10078 ;; Anchor on headlines, post may include tags.
10079 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10080 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10081 s (substring s 1)))
10082 (remove-text-properties
10083 0 (length s)
10084 '(face nil mouse-face nil keymap nil fontified nil) s)
10085 ;; Make a series of regular expressions to find a match
10086 (setq words (org-split-string s "[ \n\r\t]+")
10088 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10089 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10090 "\\)" markers)
10091 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10092 re2a (concat "[ \t\r\n]" re2a_)
10093 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10094 re4 (concat "[^a-zA-Z_]" re4_)
10096 re1 (concat pre re2 post)
10097 re3 (concat pre (if pre re4_ re4) post)
10098 re5 (concat pre ".*" re4)
10099 re2 (concat pre re2)
10100 re2a (concat pre (if pre re2a_ re2a))
10101 re4 (concat pre (if pre re4_ re4))
10102 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10103 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10104 re5 "\\)"
10106 (cond
10107 ((eq type 'org-occur) (org-occur reall))
10108 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10109 (t (goto-char (point-min))
10110 (setq type 'fuzzy)
10111 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10112 (org-search-not-self 1 re1 nil t)
10113 (org-search-not-self 1 re2 nil t)
10114 (org-search-not-self 1 re2a nil t)
10115 (org-search-not-self 1 re3 nil t)
10116 (org-search-not-self 1 re4 nil t)
10117 (org-search-not-self 1 re5 nil t)
10119 (goto-char (match-beginning 1))
10120 (goto-char pos)
10121 (error "No match"))))))
10122 (and (derived-mode-p 'org-mode)
10123 (not stealth)
10124 (org-show-context 'link-search))
10125 type))
10127 (defun org-search-not-self (group &rest args)
10128 "Execute `re-search-forward', but only accept matches that do not
10129 enclose the position of `org-open-link-marker'."
10130 (let ((m org-open-link-marker))
10131 (catch 'exit
10132 (while (apply 're-search-forward args)
10133 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10134 (goto-char (match-end group))
10135 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10136 (> (match-beginning 0) (marker-position m))
10137 (< (match-end 0) (marker-position m)))
10138 (save-match-data
10139 (or (not (org-in-regexp
10140 org-bracket-link-analytic-regexp 1))
10141 (not (match-end 4)) ; no description
10142 (and (<= (match-beginning 4) (point))
10143 (>= (match-end 4) (point))))))
10144 (throw 'exit (point))))))))
10146 (defun org-get-buffer-for-internal-link (buffer)
10147 "Return a buffer to be used for displaying the link target of internal links."
10148 (cond
10149 ((not org-display-internal-link-with-indirect-buffer)
10150 buffer)
10151 ((string-match "(Clone)$" (buffer-name buffer))
10152 (message "Buffer is already a clone, not making another one")
10153 ;; we also do not modify visibility in this case
10154 buffer)
10155 (t ; make a new indirect buffer for displaying the link
10156 (let* ((bn (buffer-name buffer))
10157 (ibn (concat bn "(Clone)"))
10158 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10159 (with-current-buffer ib (org-overview))
10160 ib))))
10162 (defun org-do-occur (regexp &optional cleanup)
10163 "Call the Emacs command `occur'.
10164 If CLEANUP is non-nil, remove the printout of the regular expression
10165 in the *Occur* buffer. This is useful if the regex is long and not useful
10166 to read."
10167 (occur regexp)
10168 (when cleanup
10169 (let ((cwin (selected-window)) win beg end)
10170 (when (setq win (get-buffer-window "*Occur*"))
10171 (select-window win))
10172 (goto-char (point-min))
10173 (when (re-search-forward "match[a-z]+" nil t)
10174 (setq beg (match-end 0))
10175 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10176 (setq end (1- (match-beginning 0)))))
10177 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10178 (goto-char (point-min))
10179 (select-window cwin))))
10181 ;;; The mark ring for links jumps
10183 (defvar org-mark-ring nil
10184 "Mark ring for positions before jumps in Org-mode.")
10185 (defvar org-mark-ring-last-goto nil
10186 "Last position in the mark ring used to go back.")
10187 ;; Fill and close the ring
10188 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10189 (loop for i from 1 to org-mark-ring-length do
10190 (push (make-marker) org-mark-ring))
10191 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10192 org-mark-ring)
10194 (defun org-mark-ring-push (&optional pos buffer)
10195 "Put the current position or POS into the mark ring and rotate it."
10196 (interactive)
10197 (setq pos (or pos (point)))
10198 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10199 (move-marker (car org-mark-ring)
10200 (or pos (point))
10201 (or buffer (current-buffer)))
10202 (message "%s"
10203 (substitute-command-keys
10204 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10206 (defun org-mark-ring-goto (&optional n)
10207 "Jump to the previous position in the mark ring.
10208 With prefix arg N, jump back that many stored positions. When
10209 called several times in succession, walk through the entire ring.
10210 Org-mode commands jumping to a different position in the current file,
10211 or to another Org-mode file, automatically push the old position
10212 onto the ring."
10213 (interactive "p")
10214 (let (p m)
10215 (if (eq last-command this-command)
10216 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10217 (setq p org-mark-ring))
10218 (setq org-mark-ring-last-goto p)
10219 (setq m (car p))
10220 (org-pop-to-buffer-same-window (marker-buffer m))
10221 (goto-char m)
10222 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10224 (defun org-remove-angle-brackets (s)
10225 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10226 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10228 (defun org-add-angle-brackets (s)
10229 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10230 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10232 (defun org-remove-double-quotes (s)
10233 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10234 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10237 ;;; Following specific links
10239 (defun org-follow-timestamp-link ()
10240 "Open an agenda view for the time-stamp date/range at point."
10241 (cond
10242 ((org-at-date-range-p t)
10243 (let ((org-agenda-start-on-weekday)
10244 (t1 (match-string 1))
10245 (t2 (match-string 2)) tt1 tt2)
10246 (setq tt1 (time-to-days (org-time-string-to-time t1))
10247 tt2 (time-to-days (org-time-string-to-time t2)))
10248 (let ((org-agenda-buffer-tmp-name
10249 (format "*Org Agenda(a:%s)"
10250 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10251 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10252 ((org-at-timestamp-p t)
10253 (let ((org-agenda-buffer-tmp-name
10254 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10255 (org-agenda-list nil (time-to-days (org-time-string-to-time
10256 (substring (match-string 1) 0 10)))
10257 1)))
10258 (t (error "This should not happen"))))
10261 ;;; Following file links
10262 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10263 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10264 (declare-function mailcap-mime-info
10265 "mailcap" (string &optional request no-decode))
10266 (defvar org-wait nil)
10267 (defun org-open-file (path &optional in-emacs line search)
10268 "Open the file at PATH.
10269 First, this expands any special file name abbreviations. Then the
10270 configuration variable `org-file-apps' is checked if it contains an
10271 entry for this file type, and if yes, the corresponding command is launched.
10273 If no application is found, Emacs simply visits the file.
10275 With optional prefix argument IN-EMACS, Emacs will visit the file.
10276 With a double \\[universal-argument] \\[universal-argument] \
10277 prefix arg, Org tries to avoid opening in Emacs
10278 and to use an external application to visit the file.
10280 Optional LINE specifies a line to go to, optional SEARCH a string
10281 to search for. If LINE or SEARCH is given, the file will be
10282 opened in Emacs, unless an entry from org-file-apps that makes
10283 use of groups in a regexp matches.
10285 If you want to change the way frames are used when following a
10286 link, please customize `org-link-frame-setup'.
10288 If the file does not exist, an error is thrown."
10289 (let* ((file (if (equal path "")
10290 buffer-file-name
10291 (substitute-in-file-name (expand-file-name path))))
10292 (file-apps (append org-file-apps (org-default-apps)))
10293 (apps (org-remove-if
10294 'org-file-apps-entry-match-against-dlink-p file-apps))
10295 (apps-dlink (org-remove-if-not
10296 'org-file-apps-entry-match-against-dlink-p file-apps))
10297 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10298 (dirp (if remp nil (file-directory-p file)))
10299 (file (if (and dirp org-open-directory-means-index-dot-org)
10300 (concat (file-name-as-directory file) "index.org")
10301 file))
10302 (a-m-a-p (assq 'auto-mode apps))
10303 (dfile (downcase file))
10304 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10305 (link (cond ((and (eq line nil)
10306 (eq search nil))
10307 file)
10308 (line
10309 (concat file "::" (number-to-string line)))
10310 (search
10311 (concat file "::" search))))
10312 (dlink (downcase link))
10313 (old-buffer (current-buffer))
10314 (old-pos (point))
10315 (old-mode major-mode)
10316 ext cmd link-match-data)
10317 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10318 (setq ext (match-string 1 dfile))
10319 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10320 (setq ext (match-string 1 dfile))))
10321 (cond
10322 ((member in-emacs '((16) system))
10323 (setq cmd (cdr (assoc 'system apps))))
10324 (in-emacs (setq cmd 'emacs))
10326 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10327 (and dirp (cdr (assoc 'directory apps)))
10328 ; first, try matching against apps-dlink
10329 ; if we get a match here, store the match data for later
10330 (let ((match (assoc-default dlink apps-dlink
10331 'string-match)))
10332 (if match
10333 (progn (setq link-match-data (match-data))
10334 match)
10335 (progn (setq in-emacs (or in-emacs line search))
10336 nil))) ; if we have no match in apps-dlink,
10337 ; always open the file in emacs if line or search
10338 ; is given (for backwards compatibility)
10339 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10340 'string-match)
10341 (cdr (assoc ext apps))
10342 (cdr (assoc t apps))))))
10343 (when (eq cmd 'system)
10344 (setq cmd (cdr (assoc 'system apps))))
10345 (when (eq cmd 'default)
10346 (setq cmd (cdr (assoc t apps))))
10347 (when (eq cmd 'mailcap)
10348 (require 'mailcap)
10349 (mailcap-parse-mailcaps)
10350 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10351 (command (mailcap-mime-info mime-type)))
10352 (if (stringp command)
10353 (setq cmd command)
10354 (setq cmd 'emacs))))
10355 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10356 (not (file-exists-p file))
10357 (not org-open-non-existing-files))
10358 (error "No such file: %s" file))
10359 (cond
10360 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10361 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10362 (while (string-match "['\"]%s['\"]" cmd)
10363 (setq cmd (replace-match "%s" t t cmd)))
10364 (while (string-match "%s" cmd)
10365 (setq cmd (replace-match
10366 (save-match-data
10367 (shell-quote-argument
10368 (convert-standard-filename file)))
10369 t t cmd)))
10371 ;; Replace "%1", "%2" etc. in command with group matches from regex
10372 (save-match-data
10373 (let ((match-index 1)
10374 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10375 (set-match-data link-match-data)
10376 (while (<= match-index number-of-groups)
10377 (let ((regex (concat "%" (number-to-string match-index)))
10378 (replace-with (match-string match-index dlink)))
10379 (while (string-match regex cmd)
10380 (setq cmd (replace-match replace-with t t cmd))))
10381 (setq match-index (+ match-index 1)))))
10383 (save-window-excursion
10384 (start-process-shell-command cmd nil cmd)
10385 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10387 ((or (stringp cmd)
10388 (eq cmd 'emacs))
10389 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10390 (widen)
10391 (if line (org-goto-line line)
10392 (if search (org-link-search search))))
10393 ((consp cmd)
10394 (let ((file (convert-standard-filename file)))
10395 (save-match-data
10396 (set-match-data link-match-data)
10397 (eval cmd))))
10398 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10399 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10400 (or (not (equal old-buffer (current-buffer)))
10401 (not (equal old-pos (point))))
10402 (org-mark-ring-push old-pos old-buffer))))
10404 (defun org-file-apps-entry-match-against-dlink-p (entry)
10405 "This function returns non-nil if `entry' uses a regular
10406 expression which should be matched against the whole link by
10407 org-open-file.
10409 It assumes that is the case when the entry uses a regular
10410 expression which has at least one grouping construct and the
10411 action is either a lisp form or a command string containing
10412 '%1', i.e. using at least one subexpression match as a
10413 parameter."
10414 (let ((selector (car entry))
10415 (action (cdr entry)))
10416 (if (stringp selector)
10417 (and (> (regexp-opt-depth selector) 0)
10418 (or (and (stringp action)
10419 (string-match "%[0-9]" action))
10420 (consp action)))
10421 nil)))
10423 (defun org-default-apps ()
10424 "Return the default applications for this operating system."
10425 (cond
10426 ((eq system-type 'darwin)
10427 org-file-apps-defaults-macosx)
10428 ((eq system-type 'windows-nt)
10429 org-file-apps-defaults-windowsnt)
10430 (t org-file-apps-defaults-gnu)))
10432 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10433 "Convert extensions to regular expressions in the cars of LIST.
10434 Also, weed out any non-string entries, because the return value is used
10435 only for regexp matching.
10436 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10437 point to the symbol `emacs', indicating that the file should
10438 be opened in Emacs."
10439 (append
10440 (delq nil
10441 (mapcar (lambda (x)
10442 (if (not (stringp (car x)))
10444 (if (string-match "\\W" (car x))
10446 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10447 list))
10448 (if add-auto-mode
10449 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10451 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10452 (defun org-file-remote-p (file)
10453 "Test whether FILE specifies a location on a remote system.
10454 Return non-nil if the location is indeed remote.
10456 For example, the filename \"/user@host:/foo\" specifies a location
10457 on the system \"/user@host:\"."
10458 (cond ((fboundp 'file-remote-p)
10459 (file-remote-p file))
10460 ((fboundp 'tramp-handle-file-remote-p)
10461 (tramp-handle-file-remote-p file))
10462 ((and (boundp 'ange-ftp-name-format)
10463 (string-match (car ange-ftp-name-format) file))
10464 t)))
10467 ;;;; Refiling
10469 (defun org-get-org-file ()
10470 "Read a filename, with default directory `org-directory'."
10471 (let ((default (or org-default-notes-file remember-data-file)))
10472 (read-file-name (format "File name [%s]: " default)
10473 (file-name-as-directory org-directory)
10474 default)))
10476 (defun org-notes-order-reversed-p ()
10477 "Check if the current file should receive notes in reversed order."
10478 (cond
10479 ((not org-reverse-note-order) nil)
10480 ((eq t org-reverse-note-order) t)
10481 ((not (listp org-reverse-note-order)) nil)
10482 (t (catch 'exit
10483 (let ((all org-reverse-note-order)
10484 entry)
10485 (while (setq entry (pop all))
10486 (if (string-match (car entry) buffer-file-name)
10487 (throw 'exit (cdr entry))))
10488 nil)))))
10490 (defvar org-refile-target-table nil
10491 "The list of refile targets, created by `org-refile'.")
10493 (defvar org-agenda-new-buffers nil
10494 "Buffers created to visit agenda files.")
10496 (defvar org-refile-cache nil
10497 "Cache for refile targets.")
10499 (defvar org-refile-markers nil
10500 "All the markers used for caching refile locations.")
10502 (defun org-refile-marker (pos)
10503 "Get a new refile marker, but only if caching is in use."
10504 (if (not org-refile-use-cache)
10506 (let ((m (make-marker)))
10507 (move-marker m pos)
10508 (push m org-refile-markers)
10509 m)))
10511 (defun org-refile-cache-clear ()
10512 "Clear the refile cache and disable all the markers."
10513 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10514 (setq org-refile-markers nil)
10515 (setq org-refile-cache nil)
10516 (message "Refile cache has been cleared"))
10518 (defun org-refile-cache-check-set (set)
10519 "Check if all the markers in the cache still have live buffers."
10520 (let (marker)
10521 (catch 'exit
10522 (while (and set (setq marker (nth 3 (pop set))))
10523 ;; if org-refile-use-outline-path is 'file, marker may be nil
10524 (when (and marker (null (marker-buffer marker)))
10525 (message "not found") (sit-for 3)
10526 (throw 'exit nil)))
10527 t)))
10529 (defun org-refile-cache-put (set &rest identifiers)
10530 "Push the refile targets SET into the cache, under IDENTIFIERS."
10531 (let* ((key (sha1 (prin1-to-string identifiers)))
10532 (entry (assoc key org-refile-cache)))
10533 (if entry
10534 (setcdr entry set)
10535 (push (cons key set) org-refile-cache))))
10537 (defun org-refile-cache-get (&rest identifiers)
10538 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10539 (cond
10540 ((not org-refile-cache) nil)
10541 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10543 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10544 org-refile-cache))))
10545 (and set (org-refile-cache-check-set set) set)))))
10547 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10548 "Produce a table with refile targets."
10549 (let ((case-fold-search nil)
10550 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10551 (entries (or org-refile-targets '((nil . (:level . 1)))))
10552 targets tgs txt re files f desc descre fast-path-p level pos0)
10553 (message "Getting targets...")
10554 (with-current-buffer (or default-buffer (current-buffer))
10555 (while (setq entry (pop entries))
10556 (setq files (car entry) desc (cdr entry))
10557 (setq fast-path-p nil)
10558 (cond
10559 ((null files) (setq files (list (current-buffer))))
10560 ((eq files 'org-agenda-files)
10561 (setq files (org-agenda-files 'unrestricted)))
10562 ((and (symbolp files) (fboundp files))
10563 (setq files (funcall files)))
10564 ((and (symbolp files) (boundp files))
10565 (setq files (symbol-value files))))
10566 (if (stringp files) (setq files (list files)))
10567 (cond
10568 ((eq (car desc) :tag)
10569 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10570 ((eq (car desc) :todo)
10571 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10572 ((eq (car desc) :regexp)
10573 (setq descre (cdr desc)))
10574 ((eq (car desc) :level)
10575 (setq descre (concat "^\\*\\{" (number-to-string
10576 (if org-odd-levels-only
10577 (1- (* 2 (cdr desc)))
10578 (cdr desc)))
10579 "\\}[ \t]")))
10580 ((eq (car desc) :maxlevel)
10581 (setq fast-path-p t)
10582 (setq descre (concat "^\\*\\{1," (number-to-string
10583 (if org-odd-levels-only
10584 (1- (* 2 (cdr desc)))
10585 (cdr desc)))
10586 "\\}[ \t]")))
10587 (t (error "Bad refiling target description %s" desc)))
10588 (while (setq f (pop files))
10589 (with-current-buffer
10590 (if (bufferp f) f (org-get-agenda-file-buffer f))
10592 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10593 (progn
10594 (if (bufferp f) (setq f (buffer-file-name
10595 (buffer-base-buffer f))))
10596 (setq f (and f (expand-file-name f)))
10597 (if (eq org-refile-use-outline-path 'file)
10598 (push (list (file-name-nondirectory f) f nil nil) tgs))
10599 (save-excursion
10600 (save-restriction
10601 (widen)
10602 (goto-char (point-min))
10603 (while (re-search-forward descre nil t)
10604 (goto-char (setq pos0 (point-at-bol)))
10605 (catch 'next
10606 (when org-refile-target-verify-function
10607 (save-match-data
10608 (or (funcall org-refile-target-verify-function)
10609 (throw 'next t))))
10610 (when (and (looking-at org-complex-heading-regexp)
10611 (not (member (match-string 4) excluded-entries))
10612 (match-string 4))
10613 (setq level (org-reduced-level
10614 (- (match-end 1) (match-beginning 1)))
10615 txt (org-link-display-format (match-string 4))
10616 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10617 re (format org-complex-heading-regexp-format
10618 (regexp-quote (match-string 4))))
10619 (when org-refile-use-outline-path
10620 (setq txt (mapconcat
10621 'org-protect-slash
10622 (append
10623 (if (eq org-refile-use-outline-path
10624 'file)
10625 (list (file-name-nondirectory
10626 (buffer-file-name
10627 (buffer-base-buffer))))
10628 (if (eq org-refile-use-outline-path
10629 'full-file-path)
10630 (list (buffer-file-name
10631 (buffer-base-buffer)))))
10632 (org-get-outline-path fast-path-p
10633 level txt)
10634 (list txt))
10635 "/")))
10636 (push (list txt f re (org-refile-marker (point)))
10637 tgs)))
10638 (when (= (point) pos0)
10639 ;; verification function has not moved point
10640 (goto-char (point-at-eol))))))))
10641 (when org-refile-use-cache
10642 (org-refile-cache-put tgs (buffer-file-name) descre))
10643 (setq targets (append tgs targets))
10644 ))))
10645 (message "Getting targets...done")
10646 (nreverse targets)))
10648 (defun org-protect-slash (s)
10649 (while (string-match "/" s)
10650 (setq s (replace-match "\\" t t s)))
10653 (defvar org-olpa (make-vector 20 nil))
10655 (defun org-get-outline-path (&optional fastp level heading)
10656 "Return the outline path to the current entry, as a list.
10658 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10659 routine which makes outline path derivations for an entire file,
10660 avoiding backtracing. Refile target collection makes use of that."
10661 (if fastp
10662 (progn
10663 (if (> level 19)
10664 (error "Outline path failure, more than 19 levels"))
10665 (loop for i from level upto 19 do
10666 (aset org-olpa i nil))
10667 (prog1
10668 (delq nil (append org-olpa nil))
10669 (aset org-olpa level heading)))
10670 (let (rtn case-fold-search)
10671 (save-excursion
10672 (save-restriction
10673 (widen)
10674 (while (org-up-heading-safe)
10675 (when (looking-at org-complex-heading-regexp)
10676 (push (org-match-string-no-properties 4) rtn)))
10677 rtn)))))
10679 (defun org-format-outline-path (path &optional width prefix)
10680 "Format the outline path PATH for display.
10681 Width is the maximum number of characters that is available.
10682 Prefix is a prefix to be included in the returned string,
10683 such as the file name."
10684 (setq width (or width 79))
10685 (if prefix (setq width (- width (length prefix))))
10686 (if (not path)
10687 (or prefix "")
10688 (let* ((nsteps (length path))
10689 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10690 (maxwidth (if (<= total-width width)
10691 10000 ;; everything fits
10692 ;; we need to shorten the level headings
10693 (/ (- width nsteps) nsteps)))
10694 (org-odd-levels-only nil)
10695 (n 0)
10696 (total (1+ (length prefix))))
10697 (setq maxwidth (max maxwidth 10))
10698 (concat prefix
10699 (mapconcat
10700 (lambda (h)
10701 (setq n (1+ n))
10702 (if (and (= n nsteps) (< maxwidth 10000))
10703 (setq maxwidth (- total-width total)))
10704 (if (< (length h) maxwidth)
10705 (progn (setq total (+ total (length h) 1)) h)
10706 (setq h (substring h 0 (- maxwidth 2))
10707 total (+ total maxwidth 1))
10708 (if (string-match "[ \t]+\\'" h)
10709 (setq h (substring h 0 (match-beginning 0))))
10710 (setq h (concat h "..")))
10711 (org-add-props h nil 'face
10712 (nth (% (1- n) org-n-level-faces)
10713 org-level-faces))
10715 path "/")))))
10717 (defun org-display-outline-path (&optional file current)
10718 "Display the current outline path in the echo area."
10719 (interactive "P")
10720 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10721 (case-fold-search nil)
10722 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10723 (if current (setq path (append path
10724 (save-excursion
10725 (org-back-to-heading t)
10726 (if (looking-at org-complex-heading-regexp)
10727 (list (match-string 4)))))))
10728 (message "%s"
10729 (org-format-outline-path
10730 path
10731 (1- (frame-width))
10732 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10734 (defvar org-refile-history nil
10735 "History for refiling operations.")
10737 (defvar org-after-refile-insert-hook nil
10738 "Hook run after `org-refile' has inserted its stuff at the new location.
10739 Note that this is still *before* the stuff will be removed from
10740 the *old* location.")
10742 (defvar org-capture-last-stored-marker)
10743 (defun org-refile (&optional goto default-buffer rfloc)
10744 "Move the entry or entries at point to another heading.
10745 The list of target headings is compiled using the information in
10746 `org-refile-targets', which see.
10748 At the target location, the entry is filed as a subitem of the target
10749 heading. Depending on `org-reverse-note-order', the new subitem will
10750 either be the first or the last subitem.
10752 If there is an active region, all entries in that region will be moved.
10753 However, the region must fulfill the requirement that the first heading
10754 is the first one sets the top-level of the moved text - at most siblings
10755 below it are allowed.
10757 With prefix arg GOTO, the command will only visit the target location
10758 and not actually move anything.
10760 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10761 go to the location where the last refiling operation has put the subtree.
10762 With a prefix argument of `2', refile to the running clock.
10764 RFLOC can be a refile location obtained in a different way.
10766 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10768 If you are using target caching (see `org-refile-use-cache'),
10769 you have to clear the target cache in order to find new targets.
10770 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10771 prefix argument (`C-u C-u C-u C-c C-w')."
10773 (interactive "P")
10774 (if (member goto '(0 (64)))
10775 (org-refile-cache-clear)
10776 (let* ((cbuf (current-buffer))
10777 (regionp (org-region-active-p))
10778 (region-start (and regionp (region-beginning)))
10779 (region-end (and regionp (region-end)))
10780 (region-length (and regionp (- region-end region-start)))
10781 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10782 pos it nbuf file re level reversed)
10783 (setq last-command nil)
10784 (when regionp
10785 (goto-char region-start)
10786 (or (bolp) (goto-char (point-at-bol)))
10787 (setq region-start (point))
10788 (unless (or (org-kill-is-subtree-p
10789 (buffer-substring region-start region-end))
10790 (prog1 org-refile-active-region-within-subtree
10791 (org-toggle-heading)))
10792 (error "The region is not a (sequence of) subtree(s)")))
10793 (if (equal goto '(16))
10794 (org-refile-goto-last-stored)
10795 (when (or
10796 (and (equal goto 2)
10797 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10798 (prog1
10799 (setq it (list (or org-clock-heading "running clock")
10800 (buffer-file-name
10801 (marker-buffer org-clock-hd-marker))
10803 (marker-position org-clock-hd-marker)))
10804 (setq goto nil)))
10805 (setq it (or rfloc
10806 (let (heading-text)
10807 (save-excursion
10808 (unless goto
10809 (org-back-to-heading t)
10810 (setq heading-text
10811 (nth 4 (org-heading-components))))
10812 (org-refile-get-location
10813 (cond (goto "Goto")
10814 (regionp "Refile region to")
10815 (t (concat "Refile subtree \""
10816 heading-text "\" to")))
10817 default-buffer
10818 (and (not (equal '(4) goto))
10819 org-refile-allow-creating-parent-nodes)
10820 goto))))))
10821 (setq file (nth 1 it)
10822 re (nth 2 it)
10823 pos (nth 3 it))
10824 (if (and (not goto)
10826 (equal (buffer-file-name) file)
10827 (if regionp
10828 (and (>= pos region-start)
10829 (<= pos region-end))
10830 (and (>= pos (point))
10831 (< pos (save-excursion
10832 (org-end-of-subtree t t))))))
10833 (error "Cannot refile to position inside the tree or region"))
10835 (setq nbuf (or (find-buffer-visiting file)
10836 (find-file-noselect file)))
10837 (if goto
10838 (progn
10839 (org-pop-to-buffer-same-window nbuf)
10840 (goto-char pos)
10841 (org-show-context 'org-goto))
10842 (if regionp
10843 (progn
10844 (org-kill-new (buffer-substring region-start region-end))
10845 (org-save-markers-in-region region-start region-end))
10846 (org-copy-subtree 1 nil t))
10847 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10848 (find-file-noselect file)))
10849 (setq reversed (org-notes-order-reversed-p))
10850 (save-excursion
10851 (save-restriction
10852 (widen)
10853 (if pos
10854 (progn
10855 (goto-char pos)
10856 (looking-at org-outline-regexp)
10857 (setq level (org-get-valid-level (funcall outline-level) 1))
10858 (goto-char
10859 (if reversed
10860 (or (outline-next-heading) (point-max))
10861 (or (save-excursion (org-get-next-sibling))
10862 (org-end-of-subtree t t)
10863 (point-max)))))
10864 (setq level 1)
10865 (if (not reversed)
10866 (goto-char (point-max))
10867 (goto-char (point-min))
10868 (or (outline-next-heading) (goto-char (point-max)))))
10869 (if (not (bolp)) (newline))
10870 (org-paste-subtree level)
10871 (when org-log-refile
10872 (org-add-log-setup 'refile nil nil 'findpos
10873 org-log-refile)
10874 (unless (eq org-log-refile 'note)
10875 (save-excursion (org-add-log-note))))
10876 (and org-auto-align-tags
10877 (let ((org-loop-over-headlines-in-active-region nil))
10878 (org-set-tags nil t)))
10879 (bookmark-set "org-refile-last-stored")
10880 ;; If we are refiling for capture, make sure that the
10881 ;; last-capture pointers point here
10882 (when (org-bound-and-true-p org-refile-for-capture)
10883 (bookmark-set "org-capture-last-stored-marker")
10884 (move-marker org-capture-last-stored-marker (point)))
10885 (if (fboundp 'deactivate-mark) (deactivate-mark))
10886 (run-hooks 'org-after-refile-insert-hook))))
10887 (if regionp
10888 (delete-region (point) (+ (point) region-length))
10889 (org-cut-subtree))
10890 (when (featurep 'org-inlinetask)
10891 (org-inlinetask-remove-END-maybe))
10892 (setq org-markers-to-move nil)
10893 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10895 (defun org-refile-goto-last-stored ()
10896 "Go to the location where the last refile was stored."
10897 (interactive)
10898 (bookmark-jump "org-refile-last-stored")
10899 (message "This is the location of the last refile"))
10901 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10902 no-exclude)
10903 "Prompt the user for a refile location, using PROMPT.
10904 PROMPT should not be suffixed with a colon and a space, because
10905 this function appends the default value from
10906 `org-refile-history' automatically, if that is not empty.
10907 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10908 this is used for the GOTO interface."
10909 (let ((org-refile-targets org-refile-targets)
10910 (org-refile-use-outline-path org-refile-use-outline-path)
10911 excluded-entries)
10912 (when (and (derived-mode-p 'org-mode)
10913 (not org-refile-use-cache)
10914 (not no-exclude))
10915 (org-map-tree
10916 (lambda()
10917 (setq excluded-entries
10918 (append excluded-entries (list (org-get-heading t t)))))))
10919 (setq org-refile-target-table
10920 (org-refile-get-targets default-buffer excluded-entries)))
10921 (unless org-refile-target-table
10922 (error "No refile targets"))
10923 (let* ((prompt (concat prompt
10924 (and (car org-refile-history)
10925 (concat " (default " (car org-refile-history) ")"))
10926 ": "))
10927 (cbuf (current-buffer))
10928 (partial-completion-mode nil)
10929 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10930 (cfunc (if (and org-refile-use-outline-path
10931 org-outline-path-complete-in-steps)
10932 'org-olpath-completing-read
10933 'org-icompleting-read))
10934 (extra (if org-refile-use-outline-path "/" ""))
10935 (filename (and cfn (expand-file-name cfn)))
10936 (tbl (mapcar
10937 (lambda (x)
10938 (if (and (not (member org-refile-use-outline-path
10939 '(file full-file-path)))
10940 (not (equal filename (nth 1 x))))
10941 (cons (concat (car x) extra " ("
10942 (file-name-nondirectory (nth 1 x)) ")")
10943 (cdr x))
10944 (cons (concat (car x) extra) (cdr x))))
10945 org-refile-target-table))
10946 (completion-ignore-case t)
10947 pa answ parent-target child parent old-hist)
10948 (setq old-hist org-refile-history)
10949 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10950 nil 'org-refile-history (car org-refile-history)))
10951 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10952 (org-refile-check-position pa)
10953 (if pa
10954 (progn
10955 (when (or (not org-refile-history)
10956 (not (eq old-hist org-refile-history))
10957 (not (equal (car pa) (car org-refile-history))))
10958 (setq org-refile-history
10959 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10960 org-refile-history
10961 (cdr org-refile-history))))
10962 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10963 (pop org-refile-history)))
10965 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10966 (progn
10967 (setq parent (match-string 1 answ)
10968 child (match-string 2 answ))
10969 (setq parent-target (or (assoc parent tbl)
10970 (assoc (concat parent "/") tbl)))
10971 (when (and parent-target
10972 (or (eq new-nodes t)
10973 (and (eq new-nodes 'confirm)
10974 (y-or-n-p (format "Create new node \"%s\"? "
10975 child)))))
10976 (org-refile-new-child parent-target child)))
10977 (error "Invalid target location")))))
10979 (declare-function org-string-nw-p "org-macs" (s))
10980 (defun org-refile-check-position (refile-pointer)
10981 "Check if the refile pointer matches the headline to which it points."
10982 (let* ((file (nth 1 refile-pointer))
10983 (re (nth 2 refile-pointer))
10984 (pos (nth 3 refile-pointer))
10985 buffer)
10986 (if (and (not (markerp pos)) (not file))
10987 (error "Please save the buffer to a file before refiling")
10988 (when (org-string-nw-p re)
10989 (setq buffer (if (markerp pos)
10990 (marker-buffer pos)
10991 (or (find-buffer-visiting file)
10992 (find-file-noselect file))))
10993 (with-current-buffer buffer
10994 (save-excursion
10995 (save-restriction
10996 (widen)
10997 (goto-char pos)
10998 (beginning-of-line 1)
10999 (unless (org-looking-at-p re)
11000 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11002 (defun org-refile-new-child (parent-target child)
11003 "Use refile target PARENT-TARGET to add new CHILD below it."
11004 (unless parent-target
11005 (error "Cannot find parent for new node"))
11006 (let ((file (nth 1 parent-target))
11007 (pos (nth 3 parent-target))
11008 level)
11009 (with-current-buffer (or (find-buffer-visiting file)
11010 (find-file-noselect file))
11011 (save-excursion
11012 (save-restriction
11013 (widen)
11014 (if pos
11015 (goto-char pos)
11016 (goto-char (point-max))
11017 (if (not (bolp)) (newline)))
11018 (when (looking-at org-outline-regexp)
11019 (setq level (funcall outline-level))
11020 (org-end-of-subtree t t))
11021 (org-back-over-empty-lines)
11022 (insert "\n" (make-string
11023 (if pos (org-get-valid-level level 1) 1) ?*)
11024 " " child "\n")
11025 (beginning-of-line 0)
11026 (list (concat (car parent-target) "/" child) file "" (point)))))))
11028 (defun org-olpath-completing-read (prompt collection &rest args)
11029 "Read an outline path like a file name."
11030 (let ((thetable collection)
11031 (org-completion-use-ido nil) ; does not work with ido.
11032 (org-completion-use-iswitchb nil)) ; or iswitchb
11033 (apply
11034 'org-icompleting-read prompt
11035 (lambda (string predicate &optional flag)
11036 (let (rtn r f (l (length string)))
11037 (cond
11038 ((eq flag nil)
11039 ;; try completion
11040 (try-completion string thetable))
11041 ((eq flag t)
11042 ;; all-completions
11043 (setq rtn (all-completions string thetable predicate))
11044 (mapcar
11045 (lambda (x)
11046 (setq r (substring x l))
11047 (if (string-match " ([^)]*)$" x)
11048 (setq f (match-string 0 x))
11049 (setq f ""))
11050 (if (string-match "/" r)
11051 (concat string (substring r 0 (match-end 0)) f)
11053 rtn))
11054 ((eq flag 'lambda)
11055 ;; exact match?
11056 (assoc string thetable)))))
11057 args)))
11059 ;;;; Dynamic blocks
11061 (defun org-find-dblock (name)
11062 "Find the first dynamic block with name NAME in the buffer.
11063 If not found, stay at current position and return nil."
11064 (let ((case-fold-search t) pos)
11065 (save-excursion
11066 (goto-char (point-min))
11067 (setq pos (and (re-search-forward
11068 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11069 (match-beginning 0))))
11070 (if pos (goto-char pos))
11071 pos))
11073 (defconst org-dblock-start-re
11074 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11075 "Matches the start line of a dynamic block, with parameters.")
11077 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11078 "Matches the end of a dynamic block.")
11080 (defun org-create-dblock (plist)
11081 "Create a dynamic block section, with parameters taken from PLIST.
11082 PLIST must contain a :name entry which is used as name of the block."
11083 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11084 (end-of-line 1)
11085 (newline))
11086 (let ((col (current-column))
11087 (name (plist-get plist :name)))
11088 (insert "#+BEGIN: " name)
11089 (while plist
11090 (if (eq (car plist) :name)
11091 (setq plist (cddr plist))
11092 (insert " " (prin1-to-string (pop plist)))))
11093 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11094 (beginning-of-line -2)))
11096 (defun org-prepare-dblock ()
11097 "Prepare dynamic block for refresh.
11098 This empties the block, puts the cursor at the insert position and returns
11099 the property list including an extra property :name with the block name."
11100 (unless (looking-at org-dblock-start-re)
11101 (error "Not at a dynamic block"))
11102 (let* ((begdel (1+ (match-end 0)))
11103 (name (org-no-properties (match-string 1)))
11104 (params (append (list :name name)
11105 (read (concat "(" (match-string 3) ")")))))
11106 (save-excursion
11107 (beginning-of-line 1)
11108 (skip-chars-forward " \t")
11109 (setq params (plist-put params :indentation-column (current-column))))
11110 (unless (re-search-forward org-dblock-end-re nil t)
11111 (error "Dynamic block not terminated"))
11112 (setq params
11113 (append params
11114 (list :content (buffer-substring
11115 begdel (match-beginning 0)))))
11116 (delete-region begdel (match-beginning 0))
11117 (goto-char begdel)
11118 (open-line 1)
11119 params))
11121 (defun org-map-dblocks (&optional command)
11122 "Apply COMMAND to all dynamic blocks in the current buffer.
11123 If COMMAND is not given, use `org-update-dblock'."
11124 (let ((cmd (or command 'org-update-dblock)))
11125 (save-excursion
11126 (goto-char (point-min))
11127 (while (re-search-forward org-dblock-start-re nil t)
11128 (goto-char (match-beginning 0))
11129 (save-excursion
11130 (condition-case nil
11131 (funcall cmd)
11132 (error (message "Error during update of dynamic block"))))
11133 (unless (re-search-forward org-dblock-end-re nil t)
11134 (error "Dynamic block not terminated"))))))
11136 (defun org-dblock-update (&optional arg)
11137 "User command for updating dynamic blocks.
11138 Update the dynamic block at point. With prefix ARG, update all dynamic
11139 blocks in the buffer."
11140 (interactive "P")
11141 (if arg
11142 (org-update-all-dblocks)
11143 (or (looking-at org-dblock-start-re)
11144 (org-beginning-of-dblock))
11145 (org-update-dblock)))
11147 (defun org-update-dblock ()
11148 "Update the dynamic block at point.
11149 This means to empty the block, parse for parameters and then call
11150 the correct writing function."
11151 (interactive)
11152 (save-window-excursion
11153 (let* ((pos (point))
11154 (line (org-current-line))
11155 (params (org-prepare-dblock))
11156 (name (plist-get params :name))
11157 (indent (plist-get params :indentation-column))
11158 (cmd (intern (concat "org-dblock-write:" name))))
11159 (message "Updating dynamic block `%s' at line %d..." name line)
11160 (funcall cmd params)
11161 (message "Updating dynamic block `%s' at line %d...done" name line)
11162 (goto-char pos)
11163 (when (and indent (> indent 0))
11164 (setq indent (make-string indent ?\ ))
11165 (save-excursion
11166 (org-beginning-of-dblock)
11167 (forward-line 1)
11168 (while (not (looking-at org-dblock-end-re))
11169 (insert indent)
11170 (beginning-of-line 2))
11171 (when (looking-at org-dblock-end-re)
11172 (and (looking-at "[ \t]+")
11173 (replace-match ""))
11174 (insert indent)))))))
11176 (defun org-beginning-of-dblock ()
11177 "Find the beginning of the dynamic block at point.
11178 Error if there is no such block at point."
11179 (let ((pos (point))
11180 beg)
11181 (end-of-line 1)
11182 (if (and (re-search-backward org-dblock-start-re nil t)
11183 (setq beg (match-beginning 0))
11184 (re-search-forward org-dblock-end-re nil t)
11185 (> (match-end 0) pos))
11186 (goto-char beg)
11187 (goto-char pos)
11188 (error "Not in a dynamic block"))))
11190 (defun org-update-all-dblocks ()
11191 "Update all dynamic blocks in the buffer.
11192 This function can be used in a hook."
11193 (interactive)
11194 (when (derived-mode-p 'org-mode)
11195 (org-map-dblocks 'org-update-dblock)))
11198 ;;;; Completion
11200 (defconst org-additional-option-like-keywords
11201 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11202 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11203 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11204 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11205 "BEGIN:" "END:"
11206 "ORGTBL" "TBLFM:" "TBLNAME:"
11207 "BEGIN_EXAMPLE" "END_EXAMPLE"
11208 "BEGIN_VERBATIM" "END_VERBATIM"
11209 "BEGIN_QUOTE" "END_QUOTE"
11210 "BEGIN_VERSE" "END_VERSE"
11211 "BEGIN_CENTER" "END_CENTER"
11212 "BEGIN_SRC" "END_SRC"
11213 "BEGIN_RESULT" "END_RESULT"
11214 "BEGIN_lstlisting" "END_lstlisting"
11215 "NAME:" "RESULTS:"
11216 "HEADER:" "HEADERS:"
11217 "COLUMNS:" "PROPERTY:"
11218 "CAPTION:" "LABEL:"
11219 "SETUPFILE:"
11220 "INCLUDE:"
11221 "BIND:"
11222 "MACRO:"))
11224 (defconst org-options-keywords
11225 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11226 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11227 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11228 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11229 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11230 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11231 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11233 (defconst org-additional-option-like-keywords-for-flyspell
11234 (delete-dups
11235 (split-string
11236 (mapconcat (lambda(k)
11237 (replace-regexp-in-string
11238 "_\\|:" " "
11239 (concat k " " (downcase k) " " (upcase k))))
11240 (append org-options-keywords org-additional-option-like-keywords)
11241 " ")
11242 " +" t)))
11244 (defcustom org-structure-template-alist
11246 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11247 "<src lang=\"?\">\n\n</src>")
11248 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11249 "<example>\n?\n</example>")
11250 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11251 "<quote>\n?\n</quote>")
11252 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11253 "<verse>\n?\n</verse>")
11254 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11255 "<center>\n?\n</center>")
11256 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11257 "<literal style=\"latex\">\n?\n</literal>")
11258 ("L" "#+LaTeX: "
11259 "<literal style=\"latex\">?</literal>")
11260 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11261 "<literal style=\"html\">\n?\n</literal>")
11262 ("H" "#+HTML: "
11263 "<literal style=\"html\">?</literal>")
11264 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11265 ("A" "#+ASCII: ")
11266 ("i" "#+INDEX: ?"
11267 "#+INDEX: ?")
11268 ("I" "#+INCLUDE: %file ?"
11269 "<include file=%file markup=\"?\">")
11271 "Structure completion elements.
11272 This is a list of abbreviation keys and values. The value gets inserted
11273 if you type `<' followed by the key and then press the completion key,
11274 usually `M-TAB'. %file will be replaced by a file name after prompting
11275 for the file using completion. The cursor will be placed at the position
11276 of the `?` in the template.
11277 There are two templates for each key, the first uses the original Org syntax,
11278 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11279 the default when the /org-mtags.el/ module has been loaded. See also the
11280 variable `org-mtags-prefer-muse-templates'."
11281 :group 'org-completion
11282 :type '(repeat
11283 (string :tag "Key")
11284 (string :tag "Template")
11285 (string :tag "Muse Template")))
11287 (defun org-try-structure-completion ()
11288 "Try to complete a structure template before point.
11289 This looks for strings like \"<e\" on an otherwise empty line and
11290 expands them."
11291 (let ((l (buffer-substring (point-at-bol) (point)))
11293 (when (and (looking-at "[ \t]*$")
11294 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11295 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11296 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11297 (match-beginning 1)) a)
11298 t)))
11300 (defun org-complete-expand-structure-template (start cell)
11301 "Expand a structure template."
11302 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11303 (rpl (nth (if musep 2 1) cell))
11304 (ind ""))
11305 (delete-region start (point))
11306 (when (string-match "\\`#\\+" rpl)
11307 (cond
11308 ((bolp))
11309 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11310 (setq ind (buffer-substring (point-at-bol) (point))))
11311 (t (newline))))
11312 (setq start (point))
11313 (if (string-match "%file" rpl)
11314 (setq rpl (replace-match
11315 (concat
11316 "\""
11317 (save-match-data
11318 (abbreviate-file-name (read-file-name "Include file: ")))
11319 "\"")
11320 t t rpl)))
11321 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11322 (concat "\n" ind)))
11323 (insert rpl)
11324 (if (re-search-backward "\\?" start t) (delete-char 1))))
11326 ;;;; TODO, DEADLINE, Comments
11328 (defun org-toggle-comment ()
11329 "Change the COMMENT state of an entry."
11330 (interactive)
11331 (save-excursion
11332 (org-back-to-heading)
11333 (let (case-fold-search)
11334 (cond
11335 ((looking-at (format org-heading-keyword-regexp-format
11336 org-comment-string))
11337 (goto-char (match-end 1))
11338 (looking-at (concat " +" org-comment-string))
11339 (replace-match "" t t)
11340 (when (eolp) (insert " ")))
11341 ((looking-at org-outline-regexp)
11342 (goto-char (match-end 0))
11343 (insert org-comment-string " "))))))
11345 (defvar org-last-todo-state-is-todo nil
11346 "This is non-nil when the last TODO state change led to a TODO state.
11347 If the last change removed the TODO tag or switched to DONE, then
11348 this is nil.")
11350 (defvar org-setting-tags nil) ; dynamically skipped
11352 (defvar org-todo-setup-filter-hook nil
11353 "Hook for functions that pre-filter todo specs.
11354 Each function takes a todo spec and returns either nil or the spec
11355 transformed into canonical form." )
11357 (defvar org-todo-get-default-hook nil
11358 "Hook for functions that get a default item for todo.
11359 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11360 nil or a string to be used for the todo mark." )
11362 (defvar org-agenda-headline-snapshot-before-repeat)
11364 (defun org-current-effective-time ()
11365 "Return current time adjusted for `org-extend-today-until' variable."
11366 (let* ((ct (org-current-time))
11367 (dct (decode-time ct))
11368 (ct1
11369 (if (and org-use-effective-time
11370 (< (nth 2 dct) org-extend-today-until))
11371 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11372 ct)))
11373 ct1))
11375 (defun org-todo-yesterday (&optional arg)
11376 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11377 (interactive "P")
11378 (if (eq major-mode 'org-agenda-mode)
11379 (apply 'org-agenda-todo-yesterday arg)
11380 (let* ((hour (third (decode-time
11381 (org-current-time))))
11382 (org-extend-today-until (1+ hour)))
11383 (org-todo arg))))
11385 (defun org-todo (&optional arg)
11386 "Change the TODO state of an item.
11387 The state of an item is given by a keyword at the start of the heading,
11388 like
11389 *** TODO Write paper
11390 *** DONE Call mom
11392 The different keywords are specified in the variable `org-todo-keywords'.
11393 By default the available states are \"TODO\" and \"DONE\".
11394 So for this example: when the item starts with TODO, it is changed to DONE.
11395 When it starts with DONE, the DONE is removed. And when neither TODO nor
11396 DONE are present, add TODO at the beginning of the heading.
11398 With \\[universal-argument] prefix arg, use completion to determine the new \
11399 state.
11400 With numeric prefix arg, switch to that state.
11401 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11402 keywords (nextset).
11403 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11404 With a numeric prefix arg of 0, inhibit note taking for the change.
11406 For calling through lisp, arg is also interpreted in the following way:
11407 'none -> empty state
11408 \"\"(empty string) -> switch to empty state
11409 'done -> switch to DONE
11410 'nextset -> switch to the next set of keywords
11411 'previousset -> switch to the previous set of keywords
11412 \"WAITING\" -> switch to the specified keyword, but only if it
11413 really is a member of `org-todo-keywords'."
11414 (interactive "P")
11415 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11416 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11417 'region-start-level 'region))
11418 org-loop-over-headlines-in-active-region)
11419 (org-map-entries
11420 `(org-todo ,arg)
11421 org-loop-over-headlines-in-active-region
11422 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11423 (if (equal arg '(16)) (setq arg 'nextset))
11424 (let ((org-blocker-hook org-blocker-hook)
11425 (case-fold-search nil))
11426 (when (equal arg '(64))
11427 (setq arg nil org-blocker-hook nil))
11428 (when (and org-blocker-hook
11429 (or org-inhibit-blocking
11430 (org-entry-get nil "NOBLOCKING")))
11431 (setq org-blocker-hook nil))
11432 (save-excursion
11433 (catch 'exit
11434 (org-back-to-heading t)
11435 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11436 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11437 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11438 (let* ((match-data (match-data))
11439 (startpos (point-at-bol))
11440 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11441 (org-log-done org-log-done)
11442 (org-log-repeat org-log-repeat)
11443 (org-todo-log-states org-todo-log-states)
11444 (org-inhibit-logging
11445 (if (equal arg 0)
11446 (progn (setq arg nil) 'note) org-inhibit-logging))
11447 (this (match-string 1))
11448 (hl-pos (match-beginning 0))
11449 (head (org-get-todo-sequence-head this))
11450 (ass (assoc head org-todo-kwd-alist))
11451 (interpret (nth 1 ass))
11452 (done-word (nth 3 ass))
11453 (final-done-word (nth 4 ass))
11454 (org-last-state (or this ""))
11455 (completion-ignore-case t)
11456 (member (member this org-todo-keywords-1))
11457 (tail (cdr member))
11458 (org-state (cond
11459 ((and org-todo-key-trigger
11460 (or (and (equal arg '(4))
11461 (eq org-use-fast-todo-selection 'prefix))
11462 (and (not arg) org-use-fast-todo-selection
11463 (not (eq org-use-fast-todo-selection
11464 'prefix)))))
11465 ;; Use fast selection
11466 (org-fast-todo-selection))
11467 ((and (equal arg '(4))
11468 (or (not org-use-fast-todo-selection)
11469 (not org-todo-key-trigger)))
11470 ;; Read a state with completion
11471 (org-icompleting-read
11472 "State: " (mapcar (lambda(x) (list x))
11473 org-todo-keywords-1)
11474 nil t))
11475 ((eq arg 'right)
11476 (if this
11477 (if tail (car tail) nil)
11478 (car org-todo-keywords-1)))
11479 ((eq arg 'left)
11480 (if (equal member org-todo-keywords-1)
11482 (if this
11483 (nth (- (length org-todo-keywords-1)
11484 (length tail) 2)
11485 org-todo-keywords-1)
11486 (org-last org-todo-keywords-1))))
11487 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11488 (setq arg nil))) ; hack to fall back to cycling
11489 (arg
11490 ;; user or caller requests a specific state
11491 (cond
11492 ((equal arg "") nil)
11493 ((eq arg 'none) nil)
11494 ((eq arg 'done) (or done-word (car org-done-keywords)))
11495 ((eq arg 'nextset)
11496 (or (car (cdr (member head org-todo-heads)))
11497 (car org-todo-heads)))
11498 ((eq arg 'previousset)
11499 (let ((org-todo-heads (reverse org-todo-heads)))
11500 (or (car (cdr (member head org-todo-heads)))
11501 (car org-todo-heads))))
11502 ((car (member arg org-todo-keywords-1)))
11503 ((stringp arg)
11504 (error "State `%s' not valid in this file" arg))
11505 ((nth (1- (prefix-numeric-value arg))
11506 org-todo-keywords-1))))
11507 ((null member) (or head (car org-todo-keywords-1)))
11508 ((equal this final-done-word) nil) ;; -> make empty
11509 ((null tail) nil) ;; -> first entry
11510 ((memq interpret '(type priority))
11511 (if (eq this-command last-command)
11512 (car tail)
11513 (if (> (length tail) 0)
11514 (or done-word (car org-done-keywords))
11515 nil)))
11517 (car tail))))
11518 (org-state (or
11519 (run-hook-with-args-until-success
11520 'org-todo-get-default-hook org-state org-last-state)
11521 org-state))
11522 (next (if org-state (concat " " org-state " ") " "))
11523 (change-plist (list :type 'todo-state-change :from this :to org-state
11524 :position startpos))
11525 dolog now-done-p)
11526 (when org-blocker-hook
11527 (setq org-last-todo-state-is-todo
11528 (not (member this org-done-keywords)))
11529 (unless (save-excursion
11530 (save-match-data
11531 (org-with-wide-buffer
11532 (run-hook-with-args-until-failure
11533 'org-blocker-hook change-plist))))
11534 (if (org-called-interactively-p 'interactive)
11535 (error "TODO state change from %s to %s blocked" this org-state)
11536 ;; fail silently
11537 (message "TODO state change from %s to %s blocked" this org-state)
11538 (throw 'exit nil))))
11539 (store-match-data match-data)
11540 (replace-match next t t)
11541 (unless (pos-visible-in-window-p hl-pos)
11542 (message "TODO state changed to %s" (org-trim next)))
11543 (unless head
11544 (setq head (org-get-todo-sequence-head org-state)
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 (when (memq arg '(nextset previousset))
11550 (message "Keyword-Set %d/%d: %s"
11551 (- (length org-todo-sets) -1
11552 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11553 (length org-todo-sets)
11554 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11555 (setq org-last-todo-state-is-todo
11556 (not (member org-state org-done-keywords)))
11557 (setq now-done-p (and (member org-state org-done-keywords)
11558 (not (member this org-done-keywords))))
11559 (and logging (org-local-logging logging))
11560 (when (and (or org-todo-log-states org-log-done)
11561 (not (eq org-inhibit-logging t))
11562 (not (memq arg '(nextset previousset))))
11563 ;; we need to look at recording a time and note
11564 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11565 (nth 2 (assoc this org-todo-log-states))))
11566 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11567 (setq dolog 'time))
11568 (when (and org-state
11569 (member org-state org-not-done-keywords)
11570 (not (member this org-not-done-keywords)))
11571 ;; This is now a todo state and was not one before
11572 ;; If there was a CLOSED time stamp, get rid of it.
11573 (org-add-planning-info nil nil 'closed))
11574 (when (and now-done-p org-log-done)
11575 ;; It is now done, and it was not done before
11576 (org-add-planning-info 'closed (org-current-effective-time))
11577 (if (and (not dolog) (eq 'note org-log-done))
11578 (org-add-log-setup 'done org-state this 'findpos 'note)))
11579 (when (and org-state dolog)
11580 ;; This is a non-nil state, and we need to log it
11581 (org-add-log-setup 'state org-state this 'findpos dolog)))
11582 ;; Fixup tag positioning
11583 (org-todo-trigger-tag-changes org-state)
11584 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11585 (when org-provide-todo-statistics
11586 (org-update-parent-todo-statistics))
11587 (run-hooks 'org-after-todo-state-change-hook)
11588 (if (and arg (not (member org-state org-done-keywords)))
11589 (setq head (org-get-todo-sequence-head org-state)))
11590 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11591 ;; Do we need to trigger a repeat?
11592 (when now-done-p
11593 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11594 ;; This is for the agenda, take a snapshot of the headline.
11595 (save-match-data
11596 (setq org-agenda-headline-snapshot-before-repeat
11597 (org-get-heading))))
11598 (org-auto-repeat-maybe org-state))
11599 ;; Fixup cursor location if close to the keyword
11600 (if (and (outline-on-heading-p)
11601 (not (bolp))
11602 (save-excursion (beginning-of-line 1)
11603 (looking-at org-todo-line-regexp))
11604 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11605 (progn
11606 (goto-char (or (match-end 2) (match-end 1)))
11607 (and (looking-at " ") (just-one-space))))
11608 (when org-trigger-hook
11609 (save-excursion
11610 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11612 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11613 "Block turning an entry into a TODO, using the hierarchy.
11614 This checks whether the current task should be blocked from state
11615 changes. Such blocking occurs when:
11617 1. The task has children which are not all in a completed state.
11619 2. A task has a parent with the property :ORDERED:, and there
11620 are siblings prior to the current task with incomplete
11621 status.
11623 3. The parent of the task is blocked because it has siblings that should
11624 be done first, or is child of a block grandparent TODO entry."
11626 (if (not org-enforce-todo-dependencies)
11627 t ; if locally turned off don't block
11628 (catch 'dont-block
11629 ;; If this is not a todo state change, or if this entry is already DONE,
11630 ;; do not block
11631 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11632 (member (plist-get change-plist :from)
11633 (cons 'done org-done-keywords))
11634 (member (plist-get change-plist :to)
11635 (cons 'todo org-not-done-keywords))
11636 (not (plist-get change-plist :to)))
11637 (throw 'dont-block t))
11638 ;; If this task has children, and any are undone, it's blocked
11639 (save-excursion
11640 (org-back-to-heading t)
11641 (let ((this-level (funcall outline-level)))
11642 (outline-next-heading)
11643 (let ((child-level (funcall outline-level)))
11644 (while (and (not (eobp))
11645 (> child-level this-level))
11646 ;; this todo has children, check whether they are all
11647 ;; completed
11648 (if (and (not (org-entry-is-done-p))
11649 (org-entry-is-todo-p))
11650 (throw 'dont-block nil))
11651 (outline-next-heading)
11652 (setq child-level (funcall outline-level))))))
11653 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11654 ;; any previous siblings are undone, it's blocked
11655 (save-excursion
11656 (org-back-to-heading t)
11657 (let* ((pos (point))
11658 (parent-pos (and (org-up-heading-safe) (point))))
11659 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11660 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11661 (forward-line 1)
11662 (re-search-forward org-not-done-heading-regexp pos t))
11663 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11664 ;; Search further up the hierarchy, to see if an ancestor is blocked
11665 (while t
11666 (goto-char parent-pos)
11667 (if (not (looking-at org-not-done-heading-regexp))
11668 (throw 'dont-block t)) ; do not block, parent is not a TODO
11669 (setq pos (point))
11670 (setq parent-pos (and (org-up-heading-safe) (point)))
11671 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11672 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11673 (forward-line 1)
11674 (re-search-forward org-not-done-heading-regexp pos t))
11675 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11677 (defcustom org-track-ordered-property-with-tag nil
11678 "Should the ORDERED property also be shown as a tag?
11679 The ORDERED property decides if an entry should require subtasks to be
11680 completed in sequence. Since a property is not very visible, setting
11681 this option means that toggling the ORDERED property with the command
11682 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11683 not relevant for the behavior, but it makes things more visible.
11685 Note that toggling the tag with tags commands will not change the property
11686 and therefore not influence behavior!
11688 This can be t, meaning the tag ORDERED should be used, It can also be a
11689 string to select a different tag for this task."
11690 :group 'org-todo
11691 :type '(choice
11692 (const :tag "No tracking" nil)
11693 (const :tag "Track with ORDERED tag" t)
11694 (string :tag "Use other tag")))
11696 (defun org-toggle-ordered-property ()
11697 "Toggle the ORDERED property of the current entry.
11698 For better visibility, you can track the value of this property with a tag.
11699 See variable `org-track-ordered-property-with-tag'."
11700 (interactive)
11701 (let* ((t1 org-track-ordered-property-with-tag)
11702 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11703 (save-excursion
11704 (org-back-to-heading)
11705 (if (org-entry-get nil "ORDERED")
11706 (progn
11707 (org-delete-property "ORDERED")
11708 (and tag (org-toggle-tag tag 'off))
11709 (message "Subtasks can be completed in arbitrary order"))
11710 (org-entry-put nil "ORDERED" "t")
11711 (and tag (org-toggle-tag tag 'on))
11712 (message "Subtasks must be completed in sequence")))))
11714 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11715 (defun org-block-todo-from-checkboxes (change-plist)
11716 "Block turning an entry into a TODO, using checkboxes.
11717 This checks whether the current task should be blocked from state
11718 changes because there are unchecked boxes in this entry."
11719 (if (not org-enforce-todo-checkbox-dependencies)
11720 t ; if locally turned off don't block
11721 (catch 'dont-block
11722 ;; If this is not a todo state change, or if this entry is already DONE,
11723 ;; do not block
11724 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11725 (member (plist-get change-plist :from)
11726 (cons 'done org-done-keywords))
11727 (member (plist-get change-plist :to)
11728 (cons 'todo org-not-done-keywords))
11729 (not (plist-get change-plist :to)))
11730 (throw 'dont-block t))
11731 ;; If this task has checkboxes that are not checked, it's blocked
11732 (save-excursion
11733 (org-back-to-heading t)
11734 (let ((beg (point)) end)
11735 (outline-next-heading)
11736 (setq end (point))
11737 (goto-char beg)
11738 (if (org-list-search-forward
11739 (concat (org-item-beginning-re)
11740 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11741 "\\[[- ]\\]")
11742 end t)
11743 (progn
11744 (if (boundp 'org-blocked-by-checkboxes)
11745 (setq org-blocked-by-checkboxes t))
11746 (throw 'dont-block nil)))))
11747 t))) ; do not block
11749 (defun org-entry-blocked-p ()
11750 "Is the current entry blocked?"
11751 (if (org-entry-get nil "NOBLOCKING")
11752 nil ;; Never block this entry
11753 (not
11754 (run-hook-with-args-until-failure
11755 'org-blocker-hook
11756 (list :type 'todo-state-change
11757 :position (point)
11758 :from 'todo
11759 :to 'done)))))
11761 (defun org-update-statistics-cookies (all)
11762 "Update the statistics cookie, either from TODO or from checkboxes.
11763 This should be called with the cursor in a line with a statistics cookie."
11764 (interactive "P")
11765 (if all
11766 (progn
11767 (org-update-checkbox-count 'all)
11768 (org-map-entries 'org-update-parent-todo-statistics))
11769 (if (not (org-at-heading-p))
11770 (org-update-checkbox-count)
11771 (let ((pos (move-marker (make-marker) (point)))
11772 end l1 l2)
11773 (ignore-errors (org-back-to-heading t))
11774 (if (not (org-at-heading-p))
11775 (org-update-checkbox-count)
11776 (setq l1 (org-outline-level))
11777 (setq end (save-excursion
11778 (outline-next-heading)
11779 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11780 (point)))
11781 (if (and (save-excursion
11782 (re-search-forward
11783 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11784 (not (save-excursion (re-search-forward
11785 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11786 (org-update-checkbox-count)
11787 (if (and l2 (> l2 l1))
11788 (progn
11789 (goto-char end)
11790 (org-update-parent-todo-statistics))
11791 (goto-char pos)
11792 (beginning-of-line 1)
11793 (while (re-search-forward
11794 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11795 (point-at-eol) t)
11796 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11797 (goto-char pos)
11798 (move-marker pos nil)))))
11800 (defvar org-entry-property-inherited-from) ;; defined below
11801 (defun org-update-parent-todo-statistics ()
11802 "Update any statistics cookie in the parent of the current headline.
11803 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11804 the entire subtree and this will travel up the hierarchy and update
11805 statistics everywhere."
11806 (let* ((prop (save-excursion (org-up-heading-safe)
11807 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11808 (recursive (or (not org-hierarchical-todo-statistics)
11809 (and prop (string-match "\\<recursive\\>" prop))))
11810 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11812 (first t)
11813 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11814 level ltoggle l1 new ndel
11815 (cnt-all 0) (cnt-done 0) is-percent kwd
11816 checkbox-beg ov ovs ove cookie-present)
11817 (catch 'exit
11818 (save-excursion
11819 (beginning-of-line 1)
11820 (setq ltoggle (funcall outline-level))
11821 ;; Three situations are to consider:
11823 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11824 ;; to the top-level ancestor on the headline;
11826 ;; 2. If parent has "recursive" property, repeat up to the
11827 ;; headline setting that property, taking inheritance into
11828 ;; account;
11830 ;; 3. Else, move up to direct parent and proceed only once.
11831 (while (and (setq level (org-up-heading-safe))
11832 (or recursive first)
11833 (>= (point) lim))
11834 (setq first nil cookie-present nil)
11835 (unless (and level
11836 (not (string-match
11837 "\\<checkbox\\>"
11838 (downcase (or (org-entry-get nil "COOKIE_DATA")
11839 "")))))
11840 (throw 'exit nil))
11841 (while (re-search-forward box-re (point-at-eol) t)
11842 (setq cnt-all 0 cnt-done 0 cookie-present t)
11843 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11844 (save-match-data
11845 (unless (outline-next-heading) (throw 'exit nil))
11846 (while (and (looking-at org-complex-heading-regexp)
11847 (> (setq l1 (length (match-string 1))) level))
11848 (setq kwd (and (or recursive (= l1 ltoggle))
11849 (match-string 2)))
11850 (if (or (eq org-provide-todo-statistics 'all-headlines)
11851 (and (listp org-provide-todo-statistics)
11852 (or (member kwd org-provide-todo-statistics)
11853 (member kwd org-done-keywords))))
11854 (setq cnt-all (1+ cnt-all))
11855 (if (eq org-provide-todo-statistics t)
11856 (and kwd (setq cnt-all (1+ cnt-all)))))
11857 (and (member kwd org-done-keywords)
11858 (setq cnt-done (1+ cnt-done)))
11859 (outline-next-heading)))
11860 (setq new
11861 (if is-percent
11862 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11863 (format "[%d/%d]" cnt-done cnt-all))
11864 ndel (- (match-end 0) checkbox-beg))
11865 ;; handle overlays when updating cookie from column view
11866 (when (setq ov (car (overlays-at checkbox-beg)))
11867 (setq ovs (overlay-start ov) ove (overlay-end ov))
11868 (delete-overlay ov))
11869 (goto-char checkbox-beg)
11870 (insert new)
11871 (delete-region (point) (+ (point) ndel))
11872 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11873 (when ov (move-overlay ov ovs ove)))
11874 (when cookie-present
11875 (run-hook-with-args 'org-after-todo-statistics-hook
11876 cnt-done (- cnt-all cnt-done))))))
11877 (run-hooks 'org-todo-statistics-hook)))
11879 (defvar org-after-todo-statistics-hook nil
11880 "Hook that is called after a TODO statistics cookie has been updated.
11881 Each function is called with two arguments: the number of not-done entries
11882 and the number of done entries.
11884 For example, the following function, when added to this hook, will switch
11885 an entry to DONE when all children are done, and back to TODO when new
11886 entries are set to a TODO status. Note that this hook is only called
11887 when there is a statistics cookie in the headline!
11889 (defun org-summary-todo (n-done n-not-done)
11890 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11891 (let (org-log-done org-log-states) ; turn off logging
11892 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11895 (defvar org-todo-statistics-hook nil
11896 "Hook that is run whenever Org thinks TODO statistics should be updated.
11897 This hook runs even if there is no statistics cookie present, in which case
11898 `org-after-todo-statistics-hook' would not run.")
11900 (defun org-todo-trigger-tag-changes (state)
11901 "Apply the changes defined in `org-todo-state-tags-triggers'."
11902 (let ((l org-todo-state-tags-triggers)
11903 changes)
11904 (when (or (not state) (equal state ""))
11905 (setq changes (append changes (cdr (assoc "" l)))))
11906 (when (and (stringp state) (> (length state) 0))
11907 (setq changes (append changes (cdr (assoc state l)))))
11908 (when (member state org-not-done-keywords)
11909 (setq changes (append changes (cdr (assoc 'todo l)))))
11910 (when (member state org-done-keywords)
11911 (setq changes (append changes (cdr (assoc 'done l)))))
11912 (dolist (c changes)
11913 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11915 (defun org-local-logging (value)
11916 "Get logging settings from a property VALUE."
11917 (let* (words w a)
11918 ;; directly set the variables, they are already local.
11919 (setq org-log-done nil
11920 org-log-repeat nil
11921 org-todo-log-states nil)
11922 (setq words (org-split-string value))
11923 (while (setq w (pop words))
11924 (cond
11925 ((setq a (assoc w org-startup-options))
11926 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11927 (set (nth 1 a) (nth 2 a))))
11928 ((setq a (org-extract-log-state-settings w))
11929 (and (member (car a) org-todo-keywords-1)
11930 (push a org-todo-log-states)))))))
11932 (defun org-get-todo-sequence-head (kwd)
11933 "Return the head of the TODO sequence to which KWD belongs.
11934 If KWD is not set, check if there is a text property remembering the
11935 right sequence."
11936 (let (p)
11937 (cond
11938 ((not kwd)
11939 (or (get-text-property (point-at-bol) 'org-todo-head)
11940 (progn
11941 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11942 nil (point-at-eol)))
11943 (get-text-property p 'org-todo-head))))
11944 ((not (member kwd org-todo-keywords-1))
11945 (car org-todo-keywords-1))
11946 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11948 (defun org-fast-todo-selection ()
11949 "Fast TODO keyword selection with single keys.
11950 Returns the new TODO keyword, or nil if no state change should occur."
11951 (let* ((fulltable org-todo-key-alist)
11952 (done-keywords org-done-keywords) ;; needed for the faces.
11953 (maxlen (apply 'max (mapcar
11954 (lambda (x)
11955 (if (stringp (car x)) (string-width (car x)) 0))
11956 fulltable)))
11957 (expert nil)
11958 (fwidth (+ maxlen 3 1 3))
11959 (ncol (/ (- (window-width) 4) fwidth))
11960 tg cnt e c tbl
11961 groups ingroup)
11962 (save-excursion
11963 (save-window-excursion
11964 (if expert
11965 (set-buffer (get-buffer-create " *Org todo*"))
11966 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11967 (erase-buffer)
11968 (org-set-local 'org-done-keywords done-keywords)
11969 (setq tbl fulltable cnt 0)
11970 (while (setq e (pop tbl))
11971 (cond
11972 ((equal e '(:startgroup))
11973 (push '() groups) (setq ingroup t)
11974 (when (not (= cnt 0))
11975 (setq cnt 0)
11976 (insert "\n"))
11977 (insert "{ "))
11978 ((equal e '(:endgroup))
11979 (setq ingroup nil cnt 0)
11980 (insert "}\n"))
11981 ((equal e '(:newline))
11982 (when (not (= cnt 0))
11983 (setq cnt 0)
11984 (insert "\n")
11985 (setq e (car tbl))
11986 (while (equal (car tbl) '(:newline))
11987 (insert "\n")
11988 (setq tbl (cdr tbl)))))
11990 (setq tg (car e) c (cdr e))
11991 (if ingroup (push tg (car groups)))
11992 (setq tg (org-add-props tg nil 'face
11993 (org-get-todo-face tg)))
11994 (if (and (= cnt 0) (not ingroup)) (insert " "))
11995 (insert "[" c "] " tg (make-string
11996 (- fwidth 4 (length tg)) ?\ ))
11997 (when (= (setq cnt (1+ cnt)) ncol)
11998 (insert "\n")
11999 (if ingroup (insert " "))
12000 (setq cnt 0)))))
12001 (insert "\n")
12002 (goto-char (point-min))
12003 (if (not expert) (org-fit-window-to-buffer))
12004 (message "[a-z..]:Set [SPC]:clear")
12005 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12006 (cond
12007 ((or (= c ?\C-g)
12008 (and (= c ?q) (not (rassoc c fulltable))))
12009 (setq quit-flag t))
12010 ((= c ?\ ) nil)
12011 ((setq e (rassoc c fulltable) tg (car e))
12013 (t (setq quit-flag t)))))))
12015 (defun org-entry-is-todo-p ()
12016 (member (org-get-todo-state) org-not-done-keywords))
12018 (defun org-entry-is-done-p ()
12019 (member (org-get-todo-state) org-done-keywords))
12021 (defun org-get-todo-state ()
12022 (save-excursion
12023 (org-back-to-heading t)
12024 (and (looking-at org-todo-line-regexp)
12025 (match-end 2)
12026 (match-string 2))))
12028 (defun org-at-date-range-p (&optional inactive-ok)
12029 "Is the cursor inside a date range?"
12030 (interactive)
12031 (save-excursion
12032 (catch 'exit
12033 (let ((pos (point)))
12034 (skip-chars-backward "^[<\r\n")
12035 (skip-chars-backward "<[")
12036 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12037 (>= (match-end 0) pos)
12038 (throw 'exit t))
12039 (skip-chars-backward "^<[\r\n")
12040 (skip-chars-backward "<[")
12041 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12042 (>= (match-end 0) pos)
12043 (throw 'exit t)))
12044 nil)))
12046 (defun org-get-repeat (&optional tagline)
12047 "Check if there is a deadline/schedule with repeater in this entry."
12048 (save-match-data
12049 (save-excursion
12050 (org-back-to-heading t)
12051 (and (re-search-forward (if tagline
12052 (concat tagline "\\s-*" org-repeat-re)
12053 org-repeat-re)
12054 (org-entry-end-position) t)
12055 (match-string-no-properties 1)))))
12057 (defvar org-last-changed-timestamp)
12058 (defvar org-last-inserted-timestamp)
12059 (defvar org-log-post-message)
12060 (defvar org-log-note-purpose)
12061 (defvar org-log-note-how)
12062 (defvar org-log-note-extra)
12063 (defun org-auto-repeat-maybe (done-word)
12064 "Check if the current headline contains a repeated deadline/schedule.
12065 If yes, set TODO state back to what it was and change the base date
12066 of repeating deadline/scheduled time stamps to new date.
12067 This function is run automatically after each state change to a DONE state."
12068 ;; last-state is dynamically scoped into this function
12069 (let* ((repeat (org-get-repeat))
12070 (aa (assoc org-last-state org-todo-kwd-alist))
12071 (interpret (nth 1 aa))
12072 (head (nth 2 aa))
12073 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12074 (msg "Entry repeats: ")
12075 (org-log-done nil)
12076 (org-todo-log-states nil)
12077 re type n what ts time to-state)
12078 (when repeat
12079 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12080 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12081 org-todo-repeat-to-state))
12082 (unless (and to-state (member to-state org-todo-keywords-1))
12083 (setq to-state (if (eq interpret 'type) org-last-state head)))
12084 (org-todo to-state)
12085 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12086 (org-entry-put nil "LAST_REPEAT" (format-time-string
12087 (org-time-stamp-format t t))))
12088 (when org-log-repeat
12089 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12090 (memq 'org-add-log-note post-command-hook))
12091 ;; OK, we are already setup for some record
12092 (if (eq org-log-repeat 'note)
12093 ;; make sure we take a note, not only a time stamp
12094 (setq org-log-note-how 'note))
12095 ;; Set up for taking a record
12096 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12097 org-last-state
12098 'findpos org-log-repeat)))
12099 (org-back-to-heading t)
12100 (org-add-planning-info nil nil 'closed)
12101 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12102 org-deadline-time-regexp "\\)\\|\\("
12103 org-ts-regexp "\\)"))
12104 (while (re-search-forward
12105 re (save-excursion (outline-next-heading) (point)) t)
12106 (setq type (if (match-end 1) org-scheduled-string
12107 (if (match-end 3) org-deadline-string "Plain:"))
12108 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12109 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12110 (setq n (string-to-number (match-string 2 ts))
12111 what (match-string 3 ts))
12112 (if (equal what "w") (setq n (* n 7) what "d"))
12113 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12114 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12115 ;; Preparation, see if we need to modify the start date for the change
12116 (when (match-end 1)
12117 (setq time (save-match-data (org-time-string-to-time ts)))
12118 (cond
12119 ((equal (match-string 1 ts) ".")
12120 ;; Shift starting date to today
12121 (org-timestamp-change
12122 (- (org-today) (time-to-days time))
12123 'day))
12124 ((equal (match-string 1 ts) "+")
12125 (let ((nshiftmax 10) (nshift 0))
12126 (while (or (= nshift 0)
12127 (<= (time-to-days time)
12128 (time-to-days (current-time))))
12129 (when (= (incf nshift) nshiftmax)
12130 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12131 (error "Abort")))
12132 (org-timestamp-change n (cdr (assoc what whata)))
12133 (org-at-timestamp-p t)
12134 (setq ts (match-string 1))
12135 (setq time (save-match-data (org-time-string-to-time ts)))))
12136 (org-timestamp-change (- n) (cdr (assoc what whata)))
12137 ;; rematch, so that we have everything in place for the real shift
12138 (org-at-timestamp-p t)
12139 (setq ts (match-string 1))
12140 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12141 (org-timestamp-change n (cdr (assoc what whata)))
12142 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12143 (setq org-log-post-message msg)
12144 (message "%s" msg))))
12146 (defun org-show-todo-tree (arg)
12147 "Make a compact tree which shows all headlines marked with TODO.
12148 The tree will show the lines where the regexp matches, and all higher
12149 headlines above the match.
12150 With a \\[universal-argument] prefix, prompt for a regexp to match.
12151 With a numeric prefix N, construct a sparse tree for the Nth element
12152 of `org-todo-keywords-1'."
12153 (interactive "P")
12154 (let ((case-fold-search nil)
12155 (kwd-re
12156 (cond ((null arg) org-not-done-regexp)
12157 ((equal arg '(4))
12158 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12159 (mapcar 'list org-todo-keywords-1))))
12160 (concat "\\("
12161 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12162 "\\)\\>")))
12163 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12164 (regexp-quote (nth (1- (prefix-numeric-value arg))
12165 org-todo-keywords-1)))
12166 (t (error "Invalid prefix argument: %s" arg)))))
12167 (message "%d TODO entries found"
12168 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12170 (defun org-deadline (&optional remove time)
12171 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12172 With argument REMOVE, remove any deadline from the item.
12173 With argument TIME, set the deadline at the corresponding date. TIME
12174 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12175 (interactive "P")
12176 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12177 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12178 'region-start-level 'region))
12179 org-loop-over-headlines-in-active-region)
12180 (org-map-entries
12181 `(org-deadline ',remove ,time)
12182 org-loop-over-headlines-in-active-region
12183 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12184 (let* ((old-date (org-entry-get nil "DEADLINE"))
12185 (repeater (and old-date
12186 (string-match
12187 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12188 old-date)
12189 (match-string 1 old-date))))
12190 (if remove
12191 (progn
12192 (when (and old-date org-log-redeadline)
12193 (org-add-log-setup 'deldeadline nil old-date 'findpos
12194 org-log-redeadline))
12195 (org-remove-timestamp-with-keyword org-deadline-string)
12196 (message "Item no longer has a deadline."))
12197 (org-add-planning-info 'deadline time 'closed)
12198 (when (and old-date org-log-redeadline
12199 (not (equal old-date
12200 (substring org-last-inserted-timestamp 1 -1))))
12201 (org-add-log-setup 'redeadline nil old-date 'findpos
12202 org-log-redeadline))
12203 (when repeater
12204 (save-excursion
12205 (org-back-to-heading t)
12206 (when (re-search-forward (concat org-deadline-string " "
12207 org-last-inserted-timestamp)
12208 (save-excursion
12209 (outline-next-heading) (point)) t)
12210 (goto-char (1- (match-end 0)))
12211 (insert " " repeater)
12212 (setq org-last-inserted-timestamp
12213 (concat (substring org-last-inserted-timestamp 0 -1)
12214 " " repeater
12215 (substring org-last-inserted-timestamp -1))))))
12216 (message "Deadline on %s" org-last-inserted-timestamp)))))
12218 (defun org-schedule (&optional remove time)
12219 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12220 With argument REMOVE, remove any scheduling date from the item.
12221 With argument TIME, scheduled at the corresponding date. TIME can
12222 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12223 (interactive "P")
12224 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12225 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12226 'region-start-level 'region))
12227 org-loop-over-headlines-in-active-region)
12228 (org-map-entries
12229 `(org-schedule ',remove ,time)
12230 org-loop-over-headlines-in-active-region
12231 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12232 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12233 (repeater (and old-date
12234 (string-match
12235 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12236 old-date)
12237 (match-string 1 old-date))))
12238 (if remove
12239 (progn
12240 (when (and old-date org-log-reschedule)
12241 (org-add-log-setup 'delschedule nil old-date 'findpos
12242 org-log-reschedule))
12243 (org-remove-timestamp-with-keyword org-scheduled-string)
12244 (message "Item is no longer scheduled."))
12245 (org-add-planning-info 'scheduled time 'closed)
12246 (when (and old-date org-log-reschedule
12247 (not (equal old-date
12248 (substring org-last-inserted-timestamp 1 -1))))
12249 (org-add-log-setup 'reschedule nil old-date 'findpos
12250 org-log-reschedule))
12251 (when repeater
12252 (save-excursion
12253 (org-back-to-heading t)
12254 (when (re-search-forward (concat org-scheduled-string " "
12255 org-last-inserted-timestamp)
12256 (save-excursion
12257 (outline-next-heading) (point)) t)
12258 (goto-char (1- (match-end 0)))
12259 (insert " " repeater)
12260 (setq org-last-inserted-timestamp
12261 (concat (substring org-last-inserted-timestamp 0 -1)
12262 " " repeater
12263 (substring org-last-inserted-timestamp -1))))))
12264 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12266 (defun org-get-scheduled-time (pom &optional inherit)
12267 "Get the scheduled time as a time tuple, of a format suitable
12268 for calling org-schedule with, or if there is no scheduling,
12269 returns nil."
12270 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12271 (when time
12272 (apply 'encode-time (org-parse-time-string time)))))
12274 (defun org-get-deadline-time (pom &optional inherit)
12275 "Get the deadline as a time tuple, of a format suitable for
12276 calling org-deadline with, or if there is no scheduling, returns
12277 nil."
12278 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12279 (when time
12280 (apply 'encode-time (org-parse-time-string time)))))
12282 (defun org-remove-timestamp-with-keyword (keyword)
12283 "Remove all time stamps with KEYWORD in the current entry."
12284 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12285 beg)
12286 (save-excursion
12287 (org-back-to-heading t)
12288 (setq beg (point))
12289 (outline-next-heading)
12290 (while (re-search-backward re beg t)
12291 (replace-match "")
12292 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12293 (equal (char-before) ?\ ))
12294 (backward-delete-char 1)
12295 (if (string-match "^[ \t]*$" (buffer-substring
12296 (point-at-bol) (point-at-eol)))
12297 (delete-region (point-at-bol)
12298 (min (point-max) (1+ (point-at-eol))))))))))
12300 (defun org-add-planning-info (what &optional time &rest remove)
12301 "Insert new timestamp with keyword in the line directly after the headline.
12302 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12303 If non is given, the user is prompted for a date.
12304 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12305 be removed."
12306 (interactive)
12307 (let (org-time-was-given org-end-time-was-given ts
12308 end default-time default-input)
12310 (catch 'exit
12311 (when (and (memq what '(scheduled deadline))
12312 (or (not time)
12313 (and (stringp time)
12314 (string-match "^[-+]+[0-9]" time))))
12315 ;; Try to get a default date/time from existing timestamp
12316 (save-excursion
12317 (org-back-to-heading t)
12318 (setq end (save-excursion (outline-next-heading) (point)))
12319 (when (re-search-forward (if (eq what 'scheduled)
12320 org-scheduled-time-regexp
12321 org-deadline-time-regexp)
12322 end t)
12323 (setq ts (match-string 1)
12324 default-time
12325 (apply 'encode-time (org-parse-time-string ts))
12326 default-input (and ts (org-get-compact-tod ts))))))
12327 (when what
12328 (setq time
12329 (if (stringp time)
12330 ;; This is a string (relative or absolute), set proper date
12331 (apply 'encode-time
12332 (org-read-date-analyze
12333 time default-time (decode-time default-time)))
12334 ;; If necessary, get the time from the user
12335 (or time (org-read-date nil 'to-time nil nil
12336 default-time default-input)))))
12338 (when (and org-insert-labeled-timestamps-at-point
12339 (member what '(scheduled deadline)))
12340 (insert
12341 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12342 (org-insert-time-stamp time org-time-was-given
12343 nil nil nil (list org-end-time-was-given))
12344 (setq what nil))
12345 (save-excursion
12346 (save-restriction
12347 (let (col list elt ts buffer-invisibility-spec)
12348 (org-back-to-heading t)
12349 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12350 (goto-char (match-end 1))
12351 (setq col (current-column))
12352 (goto-char (match-end 0))
12353 (if (eobp) (insert "\n") (forward-char 1))
12354 (when (and (not what)
12355 (not (looking-at
12356 (concat "[ \t]*"
12357 org-keyword-time-not-clock-regexp))))
12358 ;; Nothing to add, nothing to remove...... :-)
12359 (throw 'exit nil))
12360 (if (and (not (looking-at org-outline-regexp))
12361 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12362 "[^\r\n]*"))
12363 (not (equal (match-string 1) org-clock-string)))
12364 (narrow-to-region (match-beginning 0) (match-end 0))
12365 (insert-before-markers "\n")
12366 (backward-char 1)
12367 (narrow-to-region (point) (point))
12368 (and org-adapt-indentation (org-indent-to-column col)))
12369 ;; Check if we have to remove something.
12370 (setq list (cons what remove))
12371 (while list
12372 (setq elt (pop list))
12373 (when (or (and (eq elt 'scheduled)
12374 (re-search-forward org-scheduled-time-regexp nil t))
12375 (and (eq elt 'deadline)
12376 (re-search-forward org-deadline-time-regexp nil t))
12377 (and (eq elt 'closed)
12378 (re-search-forward org-closed-time-regexp nil t)))
12379 (replace-match "")
12380 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12381 (and (looking-at "[ \t]+") (replace-match ""))
12382 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12383 (when what
12384 (insert
12385 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12386 (cond ((eq what 'scheduled) org-scheduled-string)
12387 ((eq what 'deadline) org-deadline-string)
12388 ((eq what 'closed) org-closed-string))
12389 " ")
12390 (setq ts (org-insert-time-stamp
12391 time
12392 (or org-time-was-given
12393 (and (eq what 'closed) org-log-done-with-time))
12394 (eq what 'closed)
12395 nil nil (list org-end-time-was-given)))
12396 (insert
12397 (if (not (or (bolp) (eq (char-before) ?\ )
12398 (memq (char-after) '(32 10))
12399 (eobp))) " " ""))
12400 (end-of-line 1))
12401 (goto-char (point-min))
12402 (widen)
12403 (if (and (looking-at "[ \t]*\n")
12404 (equal (char-before) ?\n))
12405 (delete-region (1- (point)) (point-at-eol)))
12406 ts))))))
12408 (defvar org-log-note-marker (make-marker))
12409 (defvar org-log-note-purpose nil)
12410 (defvar org-log-note-state nil)
12411 (defvar org-log-note-previous-state nil)
12412 (defvar org-log-note-how nil)
12413 (defvar org-log-note-extra nil)
12414 (defvar org-log-note-window-configuration nil)
12415 (defvar org-log-note-return-to (make-marker))
12416 (defvar org-log-note-effective-time nil
12417 "Remembered current time so that dynamically scoped
12418 `org-extend-today-until' affects tha timestamps in state change
12419 log")
12421 (defvar org-log-post-message nil
12422 "Message to be displayed after a log note has been stored.
12423 The auto-repeater uses this.")
12425 (defun org-add-note ()
12426 "Add a note to the current entry.
12427 This is done in the same way as adding a state change note."
12428 (interactive)
12429 (org-add-log-setup 'note nil nil 'findpos nil))
12431 (defvar org-property-end-re)
12432 (defun org-add-log-setup (&optional purpose state prev-state
12433 findpos how extra)
12434 "Set up the post command hook to take a note.
12435 If this is about to TODO state change, the new state is expected in STATE.
12436 When FINDPOS is non-nil, find the correct position for the note in
12437 the current entry. If not, assume that it can be inserted at point.
12438 HOW is an indicator what kind of note should be created.
12439 EXTRA is additional text that will be inserted into the notes buffer."
12440 (let* ((org-log-into-drawer (org-log-into-drawer))
12441 (drawer (cond ((stringp org-log-into-drawer)
12442 org-log-into-drawer)
12443 (org-log-into-drawer "LOGBOOK"))))
12444 (save-restriction
12445 (save-excursion
12446 (when findpos
12447 (org-back-to-heading t)
12448 (narrow-to-region (point) (save-excursion
12449 (outline-next-heading) (point)))
12450 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12451 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12452 "[^\r\n]*\\)?"))
12453 (goto-char (match-end 0))
12454 (cond
12455 (drawer
12456 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12457 nil t)
12458 (progn
12459 (goto-char (match-end 0))
12460 (or org-log-states-order-reversed
12461 (and (re-search-forward org-property-end-re nil t)
12462 (goto-char (1- (match-beginning 0))))))
12463 (insert "\n:" drawer ":\n:END:")
12464 (beginning-of-line 0)
12465 (org-indent-line)
12466 (beginning-of-line 2)
12467 (org-indent-line)
12468 (end-of-line 0)))
12469 ((and org-log-state-notes-insert-after-drawers
12470 (save-excursion
12471 (forward-line) (looking-at org-drawer-regexp)))
12472 (forward-line)
12473 (while (looking-at org-drawer-regexp)
12474 (goto-char (match-end 0))
12475 (re-search-forward org-property-end-re (point-max) t)
12476 (forward-line))
12477 (forward-line -1)))
12478 (unless org-log-states-order-reversed
12479 (and (= (char-after) ?\n) (forward-char 1))
12480 (org-skip-over-state-notes)
12481 (skip-chars-backward " \t\n\r")))
12482 (move-marker org-log-note-marker (point))
12483 (setq org-log-note-purpose purpose
12484 org-log-note-state state
12485 org-log-note-previous-state prev-state
12486 org-log-note-how how
12487 org-log-note-extra extra
12488 org-log-note-effective-time (org-current-effective-time))
12489 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12491 (defun org-skip-over-state-notes ()
12492 "Skip past the list of State notes in an entry."
12493 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12494 (when (ignore-errors (goto-char (org-in-item-p)))
12495 (let* ((struct (org-list-struct))
12496 (prevs (org-list-prevs-alist struct)))
12497 (while (looking-at "[ \t]*- State")
12498 (goto-char (or (org-list-get-next-item (point) struct prevs)
12499 (org-list-get-item-end (point) struct)))))))
12501 (defun org-add-log-note (&optional purpose)
12502 "Pop up a window for taking a note, and add this note later at point."
12503 (remove-hook 'post-command-hook 'org-add-log-note)
12504 (setq org-log-note-window-configuration (current-window-configuration))
12505 (delete-other-windows)
12506 (move-marker org-log-note-return-to (point))
12507 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12508 (goto-char org-log-note-marker)
12509 (org-switch-to-buffer-other-window "*Org Note*")
12510 (erase-buffer)
12511 (if (memq org-log-note-how '(time state))
12512 (let (current-prefix-arg) (org-store-log-note))
12513 (let ((org-inhibit-startup t)) (org-mode))
12514 (insert (format "# Insert note for %s.
12515 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12516 (cond
12517 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12518 ((eq org-log-note-purpose 'done) "closed todo item")
12519 ((eq org-log-note-purpose 'state)
12520 (format "state change from \"%s\" to \"%s\""
12521 (or org-log-note-previous-state "")
12522 (or org-log-note-state "")))
12523 ((eq org-log-note-purpose 'reschedule)
12524 "rescheduling")
12525 ((eq org-log-note-purpose 'delschedule)
12526 "no longer scheduled")
12527 ((eq org-log-note-purpose 'redeadline)
12528 "changing deadline")
12529 ((eq org-log-note-purpose 'deldeadline)
12530 "removing deadline")
12531 ((eq org-log-note-purpose 'refile)
12532 "refiling")
12533 ((eq org-log-note-purpose 'note)
12534 "this entry")
12535 (t (error "This should not happen")))))
12536 (if org-log-note-extra (insert org-log-note-extra))
12537 (org-set-local 'org-finish-function 'org-store-log-note)
12538 (run-hooks 'org-log-buffer-setup-hook)))
12540 (defvar org-note-abort nil) ; dynamically scoped
12541 (defun org-store-log-note ()
12542 "Finish taking a log note, and insert it to where it belongs."
12543 (let ((txt (buffer-string))
12544 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12545 lines ind bul)
12546 (kill-buffer (current-buffer))
12547 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12548 (setq txt (replace-match "" t t txt)))
12549 (if (string-match "\\s-+\\'" txt)
12550 (setq txt (replace-match "" t t txt)))
12551 (setq lines (org-split-string txt "\n"))
12552 (when (and note (string-match "\\S-" note))
12553 (setq note
12554 (org-replace-escapes
12555 note
12556 (list (cons "%u" (user-login-name))
12557 (cons "%U" user-full-name)
12558 (cons "%t" (format-time-string
12559 (org-time-stamp-format 'long 'inactive)
12560 org-log-note-effective-time))
12561 (cons "%T" (format-time-string
12562 (org-time-stamp-format 'long nil)
12563 org-log-note-effective-time))
12564 (cons "%d" (format-time-string
12565 (org-time-stamp-format nil 'inactive)
12566 org-log-note-effective-time))
12567 (cons "%D" (format-time-string
12568 (org-time-stamp-format nil nil)
12569 org-log-note-effective-time))
12570 (cons "%s" (if org-log-note-state
12571 (concat "\"" org-log-note-state "\"")
12572 ""))
12573 (cons "%S" (if org-log-note-previous-state
12574 (concat "\"" org-log-note-previous-state "\"")
12575 "\"\"")))))
12576 (if lines (setq note (concat note " \\\\")))
12577 (push note lines))
12578 (when (or current-prefix-arg org-note-abort)
12579 (when org-log-into-drawer
12580 (org-remove-empty-drawer-at
12581 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12582 org-log-note-marker))
12583 (setq lines nil))
12584 (when lines
12585 (with-current-buffer (marker-buffer org-log-note-marker)
12586 (save-excursion
12587 (goto-char org-log-note-marker)
12588 (move-marker org-log-note-marker nil)
12589 (end-of-line 1)
12590 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12591 (setq ind (save-excursion
12592 (if (ignore-errors (goto-char (org-in-item-p)))
12593 (let ((struct (org-list-struct)))
12594 (org-list-get-ind
12595 (org-list-get-top-point struct) struct))
12596 (skip-chars-backward " \r\t\n")
12597 (cond
12598 ((and (org-at-heading-p)
12599 org-adapt-indentation)
12600 (1+ (org-current-level)))
12601 ((org-at-heading-p) 0)
12602 (t (org-get-indentation))))))
12603 (setq bul (org-list-bullet-string "-"))
12604 (org-indent-line-to ind)
12605 (insert bul (pop lines))
12606 (let ((ind-body (+ (length bul) ind)))
12607 (while lines
12608 (insert "\n")
12609 (org-indent-line-to ind-body)
12610 (insert (pop lines))))
12611 (message "Note stored")
12612 (org-back-to-heading t)
12613 (org-cycle-hide-drawers 'children)))))
12614 (set-window-configuration org-log-note-window-configuration)
12615 (with-current-buffer (marker-buffer org-log-note-return-to)
12616 (goto-char org-log-note-return-to))
12617 (move-marker org-log-note-return-to nil)
12618 (and org-log-post-message (message "%s" org-log-post-message)))
12620 (defun org-remove-empty-drawer-at (drawer pos)
12621 "Remove an empty drawer DRAWER at position POS.
12622 POS may also be a marker."
12623 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12624 (save-excursion
12625 (save-restriction
12626 (widen)
12627 (goto-char pos)
12628 (if (org-in-regexp
12629 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12630 (replace-match ""))))))
12632 (defvar org-ts-type nil)
12633 (defun org-sparse-tree (&optional arg type)
12634 "Create a sparse tree, prompt for the details.
12635 This command can create sparse trees. You first need to select the type
12636 of match used to create the tree:
12638 t Show all TODO entries.
12639 T Show entries with a specific TODO keyword.
12640 m Show entries selected by a tags/property match.
12641 p Enter a property name and its value (both with completion on existing
12642 names/values) and show entries with that property.
12643 r Show entries matching a regular expression (`/' can be used as well).
12644 b Show deadlines and scheduled items before a date.
12645 a Show deadlines and scheduled items after a date.
12646 d Show deadlines due within `org-deadline-warning-days'.
12647 D Show deadlines and scheduled items between a date range."
12648 (interactive "P")
12649 (let (ans kwd value ts-type)
12650 (setq type (or type org-sparse-tree-default-date-type))
12651 (setq org-ts-type type)
12652 (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"
12653 (cond ((eq type 'all) "all timestamps")
12654 ((eq type 'scheduled) "only scheduled")
12655 ((eq type 'deadline) "only deadline")
12656 ((eq type 'active) "only active timestamps")
12657 ((eq type 'inactive) "only inactive timestamps")
12658 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12659 (t "scheduled/deadline")))
12660 (setq ans (read-char-exclusive))
12661 (cond
12662 ((equal ans ?c)
12663 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12664 ((equal ans ?d)
12665 (call-interactively 'org-check-deadlines))
12666 ((equal ans ?b)
12667 (call-interactively 'org-check-before-date))
12668 ((equal ans ?a)
12669 (call-interactively 'org-check-after-date))
12670 ((equal ans ?D)
12671 (call-interactively 'org-check-dates-range))
12672 ((equal ans ?t)
12673 (call-interactively 'org-show-todo-tree))
12674 ((equal ans ?T)
12675 (org-show-todo-tree '(4)))
12676 ((member ans '(?T ?m))
12677 (call-interactively 'org-match-sparse-tree))
12678 ((member ans '(?p ?P))
12679 (setq kwd (org-icompleting-read "Property: "
12680 (mapcar 'list (org-buffer-property-keys))))
12681 (setq value (org-icompleting-read "Value: "
12682 (mapcar 'list (org-property-values kwd))))
12683 (unless (string-match "\\`{.*}\\'" value)
12684 (setq value (concat "\"" value "\"")))
12685 (org-match-sparse-tree arg (concat kwd "=" value)))
12686 ((member ans '(?r ?R ?/))
12687 (call-interactively 'org-occur))
12688 (t (error "No such sparse tree command \"%c\"" ans)))))
12690 (defvar org-occur-highlights nil
12691 "List of overlays used for occur matches.")
12692 (make-variable-buffer-local 'org-occur-highlights)
12693 (defvar org-occur-parameters nil
12694 "Parameters of the active org-occur calls.
12695 This is a list, each call to org-occur pushes as cons cell,
12696 containing the regular expression and the callback, onto the list.
12697 The list can contain several entries if `org-occur' has been called
12698 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12699 will only contain one set of parameters. When the highlights are
12700 removed (for example with `C-c C-c', or with the next edit (depending
12701 on `org-remove-highlights-with-change'), this variable is emptied
12702 as well.")
12703 (make-variable-buffer-local 'org-occur-parameters)
12705 (defun org-occur (regexp &optional keep-previous callback)
12706 "Make a compact tree which shows all matches of REGEXP.
12707 The tree will show the lines where the regexp matches, and all higher
12708 headlines above the match. It will also show the heading after the match,
12709 to make sure editing the matching entry is easy.
12710 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12711 call to `org-occur' will be kept, to allow stacking of calls to this
12712 command.
12713 If CALLBACK is non-nil, it is a function which is called to confirm
12714 that the match should indeed be shown."
12715 (interactive "sRegexp: \nP")
12716 (when (equal regexp "")
12717 (error "Regexp cannot be empty"))
12718 (unless keep-previous
12719 (org-remove-occur-highlights nil nil t))
12720 (push (cons regexp callback) org-occur-parameters)
12721 (let ((cnt 0))
12722 (save-excursion
12723 (goto-char (point-min))
12724 (if (or (not keep-previous) ; do not want to keep
12725 (not org-occur-highlights)) ; no previous matches
12726 ;; hide everything
12727 (org-overview))
12728 (while (re-search-forward regexp nil t)
12729 (when (or (not callback)
12730 (save-match-data (funcall callback)))
12731 (setq cnt (1+ cnt))
12732 (when org-highlight-sparse-tree-matches
12733 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12734 (org-show-context 'occur-tree))))
12735 (when org-remove-highlights-with-change
12736 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12737 nil 'local))
12738 (unless org-sparse-tree-open-archived-trees
12739 (org-hide-archived-subtrees (point-min) (point-max)))
12740 (run-hooks 'org-occur-hook)
12741 (if (org-called-interactively-p 'interactive)
12742 (message "%d match(es) for regexp %s" cnt regexp))
12743 cnt))
12745 (defun org-occur-next-match (&optional n reset)
12746 "Function for `next-error-function' to find sparse tree matches.
12747 N is the number of matches to move, when negative move backwards.
12748 RESET is entirely ignored - this function always goes back to the
12749 starting point when no match is found."
12750 (let* ((limit (if (< n 0) (point-min) (point-max)))
12751 (search-func (if (< n 0)
12752 'previous-single-char-property-change
12753 'next-single-char-property-change))
12754 (n (abs n))
12755 (pos (point))
12757 (catch 'exit
12758 (while (setq p1 (funcall search-func (point) 'org-type))
12759 (when (equal p1 limit)
12760 (goto-char pos)
12761 (error "No more matches"))
12762 (when (equal (get-char-property p1 'org-type) 'org-occur)
12763 (setq n (1- n))
12764 (when (= n 0)
12765 (goto-char p1)
12766 (throw 'exit (point))))
12767 (goto-char p1))
12768 (goto-char p1)
12769 (error "No more matches"))))
12771 (defun org-show-context (&optional key)
12772 "Make sure point and context are visible.
12773 How much context is shown depends upon the variables
12774 `org-show-hierarchy-above', `org-show-following-heading',
12775 `org-show-entry-below' and `org-show-siblings'."
12776 (let ((heading-p (org-at-heading-p t))
12777 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12778 (following-p (org-get-alist-option org-show-following-heading key))
12779 (entry-p (org-get-alist-option org-show-entry-below key))
12780 (siblings-p (org-get-alist-option org-show-siblings key)))
12781 (catch 'exit
12782 ;; Show heading or entry text
12783 (if (and heading-p (not entry-p))
12784 (org-flag-heading nil) ; only show the heading
12785 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12786 (org-show-hidden-entry))) ; show entire entry
12787 (when following-p
12788 ;; Show next sibling, or heading below text
12789 (save-excursion
12790 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12791 (org-flag-heading nil))))
12792 (when siblings-p (org-show-siblings))
12793 (when hierarchy-p
12794 ;; show all higher headings, possibly with siblings
12795 (save-excursion
12796 (while (and (condition-case nil
12797 (progn (org-up-heading-all 1) t)
12798 (error nil))
12799 (not (bobp)))
12800 (org-flag-heading nil)
12801 (when siblings-p (org-show-siblings))))))))
12803 (defvar org-reveal-start-hook nil
12804 "Hook run before revealing a location.")
12806 (defun org-reveal (&optional siblings)
12807 "Show current entry, hierarchy above it, and the following headline.
12808 This can be used to show a consistent set of context around locations
12809 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12810 not t for the search context.
12812 With optional argument SIBLINGS, on each level of the hierarchy all
12813 siblings are shown. This repairs the tree structure to what it would
12814 look like when opened with hierarchical calls to `org-cycle'.
12815 With double optional argument \\[universal-argument] \\[universal-argument], \
12816 go to the parent and show the
12817 entire tree."
12818 (interactive "P")
12819 (run-hooks 'org-reveal-start-hook)
12820 (let ((org-show-hierarchy-above t)
12821 (org-show-following-heading t)
12822 (org-show-siblings (if siblings t org-show-siblings)))
12823 (org-show-context nil))
12824 (when (equal siblings '(16))
12825 (save-excursion
12826 (when (org-up-heading-safe)
12827 (org-show-subtree)
12828 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12830 (defun org-highlight-new-match (beg end)
12831 "Highlight from BEG to END and mark the highlight is an occur headline."
12832 (let ((ov (make-overlay beg end)))
12833 (overlay-put ov 'face 'secondary-selection)
12834 (overlay-put ov 'org-type 'org-occur)
12835 (push ov org-occur-highlights)))
12837 (defun org-remove-occur-highlights (&optional beg end noremove)
12838 "Remove the occur highlights from the buffer.
12839 BEG and END are ignored. If NOREMOVE is nil, remove this function
12840 from the `before-change-functions' in the current buffer."
12841 (interactive)
12842 (unless org-inhibit-highlight-removal
12843 (mapc 'delete-overlay org-occur-highlights)
12844 (setq org-occur-highlights nil)
12845 (setq org-occur-parameters nil)
12846 (unless noremove
12847 (remove-hook 'before-change-functions
12848 'org-remove-occur-highlights 'local))))
12850 ;;;; Priorities
12852 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12853 "Regular expression matching the priority indicator.")
12855 (defvar org-remove-priority-next-time nil)
12857 (defun org-priority-up ()
12858 "Increase the priority of the current item."
12859 (interactive)
12860 (org-priority 'up))
12862 (defun org-priority-down ()
12863 "Decrease the priority of the current item."
12864 (interactive)
12865 (org-priority 'down))
12867 (defun org-priority (&optional action show)
12868 "Change the priority of an item.
12869 ACTION can be `set', `up', `down', or a character."
12870 (interactive "P")
12871 (if (equal action '(4))
12872 (org-show-priority)
12873 (unless org-enable-priority-commands
12874 (error "Priority commands are disabled"))
12875 (setq action (or action 'set))
12876 (let (current new news have remove)
12877 (save-excursion
12878 (org-back-to-heading t)
12879 (if (looking-at org-priority-regexp)
12880 (setq current (string-to-char (match-string 2))
12881 have t))
12882 (cond
12883 ((eq action 'remove)
12884 (setq remove t new ?\ ))
12885 ((or (eq action 'set)
12886 (if (featurep 'xemacs) (characterp action) (integerp action)))
12887 (if (not (eq action 'set))
12888 (setq new action)
12889 (message "Priority %c-%c, SPC to remove: "
12890 org-highest-priority org-lowest-priority)
12891 (save-match-data
12892 (setq new (read-char-exclusive))))
12893 (if (and (= (upcase org-highest-priority) org-highest-priority)
12894 (= (upcase org-lowest-priority) org-lowest-priority))
12895 (setq new (upcase new)))
12896 (cond ((equal new ?\ ) (setq remove t))
12897 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12898 (error "Priority must be between `%c' and `%c'"
12899 org-highest-priority org-lowest-priority))))
12900 ((eq action 'up)
12901 (setq new (if have
12902 (1- current) ; normal cycling
12903 ;; last priority was empty
12904 (if (eq last-command this-command)
12905 org-lowest-priority ; wrap around empty to lowest
12906 ;; default
12907 (if org-priority-start-cycle-with-default
12908 org-default-priority
12909 (1- org-default-priority))))))
12910 ((eq action 'down)
12911 (setq new (if have
12912 (1+ current) ; normal cycling
12913 ;; last priority was empty
12914 (if (eq last-command this-command)
12915 org-highest-priority ; wrap around empty to highest
12916 ;; default
12917 (if org-priority-start-cycle-with-default
12918 org-default-priority
12919 (1+ org-default-priority))))))
12920 (t (error "Invalid action")))
12921 (if (or (< (upcase new) org-highest-priority)
12922 (> (upcase new) org-lowest-priority))
12923 (if (and (memq action '(up down))
12924 (not have) (not (eq last-command this-command)))
12925 ;; `new' is from default priority
12926 (error
12927 "The default can not be set, see `org-default-priority' why")
12928 ;; normal cycling: `new' is beyond highest/lowest priority
12929 ;; and is wrapped around to the empty priority
12930 (setq remove t)))
12931 (setq news (format "%c" new))
12932 (if have
12933 (if remove
12934 (replace-match "" t t nil 1)
12935 (replace-match news t t nil 2))
12936 (if remove
12937 (error "No priority cookie found in line")
12938 (let ((case-fold-search nil))
12939 (looking-at org-todo-line-regexp))
12940 (if (match-end 2)
12941 (progn
12942 (goto-char (match-end 2))
12943 (insert " [#" news "]"))
12944 (goto-char (match-beginning 3))
12945 (insert "[#" news "] "))))
12946 (org-preserve-lc (org-set-tags nil 'align)))
12947 (if remove
12948 (message "Priority removed")
12949 (message "Priority of current item set to %s" news)))))
12951 (defun org-show-priority ()
12952 "Show the priority of the current item.
12953 This priority is composed of the main priority given with the [#A] cookies,
12954 and by additional input from the age of a schedules or deadline entry."
12955 (interactive)
12956 (let ((pri (if (eq major-mode 'org-agenda-mode)
12957 (org-get-at-bol 'priority)
12958 (save-excursion
12959 (save-match-data
12960 (beginning-of-line)
12961 (and (looking-at org-heading-regexp)
12962 (org-get-priority (match-string 0))))))))
12963 (message "Priority is %d" (if pri pri -1000))))
12965 (defun org-get-priority (s)
12966 "Find priority cookie and return priority."
12967 (if (functionp org-get-priority-function)
12968 (funcall org-get-priority-function)
12969 (save-match-data
12970 (if (not (string-match org-priority-regexp s))
12971 (* 1000 (- org-lowest-priority org-default-priority))
12972 (* 1000 (- org-lowest-priority
12973 (string-to-char (match-string 2 s))))))))
12975 ;;;; Tags
12977 (defvar org-agenda-archives-mode)
12978 (defvar org-map-continue-from nil
12979 "Position from where mapping should continue.
12980 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12982 (defvar org-scanner-tags nil
12983 "The current tag list while the tags scanner is running.")
12984 (defvar org-trust-scanner-tags nil
12985 "Should `org-get-tags-at' use the tags for the scanner.
12986 This is for internal dynamical scoping only.
12987 When this is non-nil, the function `org-get-tags-at' will return the value
12988 of `org-scanner-tags' instead of building the list by itself. This
12989 can lead to large speed-ups when the tags scanner is used in a file with
12990 many entries, and when the list of tags is retrieved, for example to
12991 obtain a list of properties. Building the tags list for each entry in such
12992 a file becomes an N^2 operation - but with this variable set, it scales
12993 as N.")
12995 (defun org-scan-tags (action matcher todo-only &optional start-level)
12996 "Scan headline tags with inheritance and produce output ACTION.
12998 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12999 or `agenda' to produce an entry list for an agenda view. It can also be
13000 a Lisp form or a function that should be called at each matched headline, in
13001 this case the return value is a list of all return values from these calls.
13003 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13004 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13005 only lines with a not-done TODO keyword are included in the output.
13006 This should be the same variable that was scoped into
13007 and set by `org-make-tags-matcher' when it constructed MATCHER.
13009 START-LEVEL can be a string with asterisks, reducing the scope to
13010 headlines matching this string."
13011 (require 'org-agenda)
13012 (let* ((re (concat "^"
13013 (if start-level
13014 ;; Get the correct level to match
13015 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13016 org-outline-regexp)
13017 " *\\(\\<\\("
13018 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13019 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13020 (props (list 'face 'default
13021 'done-face 'org-agenda-done
13022 'undone-face 'default
13023 'mouse-face 'highlight
13024 'org-not-done-regexp org-not-done-regexp
13025 'org-todo-regexp org-todo-regexp
13026 'org-complex-heading-regexp org-complex-heading-regexp
13027 'help-echo
13028 (format "mouse-2 or RET jump to org file %s"
13029 (abbreviate-file-name
13030 (or (buffer-file-name (buffer-base-buffer))
13031 (buffer-name (buffer-base-buffer)))))))
13032 (case-fold-search nil)
13033 (org-map-continue-from nil)
13034 lspos tags tags-list
13035 (tags-alist (list (cons 0 org-file-tags)))
13036 (llast 0) rtn rtn1 level category i txt
13037 todo marker entry priority)
13038 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13039 (setq action (list 'lambda nil action)))
13040 (save-excursion
13041 (goto-char (point-min))
13042 (when (eq action 'sparse-tree)
13043 (org-overview)
13044 (org-remove-occur-highlights))
13045 (while (re-search-forward re nil t)
13046 (setq org-map-continue-from nil)
13047 (catch :skip
13048 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13049 tags (if (match-end 4) (org-match-string-no-properties 4)))
13050 (goto-char (setq lspos (match-beginning 0)))
13051 (setq level (org-reduced-level (funcall outline-level))
13052 category (org-get-category))
13053 (setq i llast llast level)
13054 ;; remove tag lists from same and sublevels
13055 (while (>= i level)
13056 (when (setq entry (assoc i tags-alist))
13057 (setq tags-alist (delete entry tags-alist)))
13058 (setq i (1- i)))
13059 ;; add the next tags
13060 (when tags
13061 (setq tags (org-split-string tags ":")
13062 tags-alist
13063 (cons (cons level tags) tags-alist)))
13064 ;; compile tags for current headline
13065 (setq tags-list
13066 (if org-use-tag-inheritance
13067 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13068 tags)
13069 org-scanner-tags tags-list)
13070 (when org-use-tag-inheritance
13071 (setcdr (car tags-alist)
13072 (mapcar (lambda (x)
13073 (setq x (copy-sequence x))
13074 (org-add-prop-inherited x))
13075 (cdar tags-alist))))
13076 (when (and tags org-use-tag-inheritance
13077 (or (not (eq t org-use-tag-inheritance))
13078 org-tags-exclude-from-inheritance))
13079 ;; selective inheritance, remove uninherited ones
13080 (setcdr (car tags-alist)
13081 (org-remove-uninherited-tags (cdar tags-alist))))
13082 (when (and
13084 ;; eval matcher only when the todo condition is OK
13085 (and (or (not todo-only) (member todo org-not-done-keywords))
13086 (let ((case-fold-search t) (org-trust-scanner-tags t))
13087 (eval matcher)))
13089 ;; Call the skipper, but return t if it does not skip,
13090 ;; so that the `and' form continues evaluating
13091 (progn
13092 (unless (eq action 'sparse-tree) (org-agenda-skip))
13095 ;; Check if timestamps are deselecting this entry
13096 (or (not todo-only)
13097 (and (member todo org-not-done-keywords)
13098 (or (not org-agenda-tags-todo-honor-ignore-options)
13099 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13101 ;; Extra check for the archive tag
13102 ;; FIXME: Does the skipper already do this????
13104 (not (member org-archive-tag tags-list))
13105 ;; we have an archive tag, should we use this anyway?
13106 (or (not org-agenda-skip-archived-trees)
13107 (and (eq action 'agenda) org-agenda-archives-mode))))
13109 ;; select this headline
13111 (cond
13112 ((eq action 'sparse-tree)
13113 (and org-highlight-sparse-tree-matches
13114 (org-get-heading) (match-end 0)
13115 (org-highlight-new-match
13116 (match-beginning 1) (match-end 1)))
13117 (org-show-context 'tags-tree))
13118 ((eq action 'agenda)
13119 (setq txt (org-agenda-format-item
13121 (concat
13122 (if (eq org-tags-match-list-sublevels 'indented)
13123 (make-string (1- level) ?.) "")
13124 (org-get-heading))
13125 category
13126 tags-list)
13127 priority (org-get-priority txt))
13128 (goto-char lspos)
13129 (setq marker (org-agenda-new-marker))
13130 (org-add-props txt props
13131 'org-marker marker 'org-hd-marker marker 'org-category category
13132 'todo-state todo
13133 'priority priority 'type "tagsmatch")
13134 (push txt rtn))
13135 ((functionp action)
13136 (setq org-map-continue-from nil)
13137 (save-excursion
13138 (setq rtn1 (funcall action))
13139 (push rtn1 rtn)))
13140 (t (error "Invalid action")))
13142 ;; if we are to skip sublevels, jump to end of subtree
13143 (unless org-tags-match-list-sublevels
13144 (org-end-of-subtree t)
13145 (backward-char 1))))
13146 ;; Get the correct position from where to continue
13147 (if org-map-continue-from
13148 (goto-char org-map-continue-from)
13149 (and (= (point) lspos) (end-of-line 1)))))
13150 (when (and (eq action 'sparse-tree)
13151 (not org-sparse-tree-open-archived-trees))
13152 (org-hide-archived-subtrees (point-min) (point-max)))
13153 (nreverse rtn)))
13155 (defun org-remove-uninherited-tags (tags)
13156 "Remove all tags that are not inherited from the list TAGS."
13157 (cond
13158 ((eq org-use-tag-inheritance t)
13159 (if org-tags-exclude-from-inheritance
13160 (org-delete-all org-tags-exclude-from-inheritance tags)
13161 tags))
13162 ((not org-use-tag-inheritance) nil)
13163 ((stringp org-use-tag-inheritance)
13164 (delq nil (mapcar
13165 (lambda (x)
13166 (if (and (string-match org-use-tag-inheritance x)
13167 (not (member x org-tags-exclude-from-inheritance)))
13168 x nil))
13169 tags)))
13170 ((listp org-use-tag-inheritance)
13171 (delq nil (mapcar
13172 (lambda (x)
13173 (if (member x org-use-tag-inheritance) x nil))
13174 tags)))))
13176 (defun org-match-sparse-tree (&optional todo-only match)
13177 "Create a sparse tree according to tags string MATCH.
13178 MATCH can contain positive and negative selection of tags, like
13179 \"+WORK+URGENT-WITHBOSS\".
13180 If optional argument TODO-ONLY is non-nil, only select lines that are
13181 also TODO lines."
13182 (interactive "P")
13183 (org-agenda-prepare-buffers (list (current-buffer)))
13184 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13186 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13188 (defvar org-cached-props nil)
13189 (defun org-cached-entry-get (pom property)
13190 (if (or (eq t org-use-property-inheritance)
13191 (and (stringp org-use-property-inheritance)
13192 (string-match org-use-property-inheritance property))
13193 (and (listp org-use-property-inheritance)
13194 (member property org-use-property-inheritance)))
13195 ;; Caching is not possible, check it directly
13196 (org-entry-get pom property 'inherit)
13197 ;; Get all properties, so that we can do complicated checks easily
13198 (cdr (assoc property (or org-cached-props
13199 (setq org-cached-props
13200 (org-entry-properties pom)))))))
13202 (defun org-global-tags-completion-table (&optional files)
13203 "Return the list of all tags in all agenda buffer/files.
13204 Optional FILES argument is a list of files which can be used
13205 instead of the agenda files."
13206 (save-excursion
13207 (org-uniquify
13208 (delq nil
13209 (apply 'append
13210 (mapcar
13211 (lambda (file)
13212 (set-buffer (find-file-noselect file))
13213 (append (org-get-buffer-tags)
13214 (mapcar (lambda (x) (if (stringp (car-safe x))
13215 (list (car-safe x)) nil))
13216 org-tag-alist)))
13217 (if (and files (car files))
13218 files
13219 (org-agenda-files))))))))
13221 (defun org-make-tags-matcher (match)
13222 "Create the TAGS/TODO matcher form for the selection string MATCH.
13224 The variable `todo-only' is scoped dynamically into this function.
13225 It will be set to t if the matcher restricts matching to TODO entries,
13226 otherwise will not be touched.
13228 Returns a cons of the selection string MATCH and the constructed
13229 lisp form implementing the matcher. The matcher is to be evaluated
13230 at an Org entry, with point on the headline, and returns t if the
13231 entry matches the selection string MATCH. The returned lisp form
13232 references two variables with information about the entry, which
13233 must be bound around the form's evaluation: todo, the TODO keyword
13234 at the entry (or nil of none); and tags-list, the list of all tags
13235 at the entry including inherited ones. Additionally, the category
13236 of the entry (if any) must be specified as the text property
13237 'org-category on the headline.
13239 See also `org-scan-tags'.
13241 (declare (special todo-only))
13242 (unless (boundp 'todo-only)
13243 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13244 (unless match
13245 ;; Get a new match request, with completion
13246 (let ((org-last-tags-completion-table
13247 (org-global-tags-completion-table)))
13248 (setq match (org-completing-read-no-i
13249 "Match: " 'org-tags-completion-function nil nil nil
13250 'org-tags-history))))
13252 ;; Parse the string and create a lisp form
13253 (let ((match0 match)
13254 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13255 minus tag mm
13256 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13257 orterms term orlist re-p str-p level-p level-op time-p
13258 prop-p pn pv po gv rest)
13259 (if (string-match "/+" match)
13260 ;; match contains also a todo-matching request
13261 (progn
13262 (setq tagsmatch (substring match 0 (match-beginning 0))
13263 todomatch (substring match (match-end 0)))
13264 (if (string-match "^!" todomatch)
13265 (setq todo-only t todomatch (substring todomatch 1)))
13266 (if (string-match "^\\s-*$" todomatch)
13267 (setq todomatch nil)))
13268 ;; only matching tags
13269 (setq tagsmatch match todomatch nil))
13271 ;; Make the tags matcher
13272 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13273 (setq tagsmatcher t)
13274 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13275 (while (setq term (pop orterms))
13276 (while (and (equal (substring term -1) "\\") orterms)
13277 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13278 (while (string-match re term)
13279 (setq rest (substring term (match-end 0))
13280 minus (and (match-end 1)
13281 (equal (match-string 1 term) "-"))
13282 tag (save-match-data (replace-regexp-in-string
13283 "\\\\-" "-"
13284 (match-string 2 term)))
13285 re-p (equal (string-to-char tag) ?{)
13286 level-p (match-end 4)
13287 prop-p (match-end 5)
13288 mm (cond
13289 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13290 (level-p
13291 (setq level-op (org-op-to-function (match-string 3 term)))
13292 `(,level-op level ,(string-to-number
13293 (match-string 4 term))))
13294 (prop-p
13295 (setq pn (match-string 5 term)
13296 po (match-string 6 term)
13297 pv (match-string 7 term)
13298 re-p (equal (string-to-char pv) ?{)
13299 str-p (equal (string-to-char pv) ?\")
13300 time-p (save-match-data
13301 (string-match "^\"[[<].*[]>]\"$" pv))
13302 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13303 (if time-p (setq pv (org-matcher-time pv)))
13304 (setq po (org-op-to-function po (if time-p 'time str-p)))
13305 (cond
13306 ((equal pn "CATEGORY")
13307 (setq gv '(get-text-property (point) 'org-category)))
13308 ((equal pn "TODO")
13309 (setq gv 'todo))
13311 (setq gv `(org-cached-entry-get nil ,pn))))
13312 (if re-p
13313 (if (eq po 'org<>)
13314 `(not (string-match ,pv (or ,gv "")))
13315 `(string-match ,pv (or ,gv "")))
13316 (if str-p
13317 `(,po (or ,gv "") ,pv)
13318 `(,po (string-to-number (or ,gv ""))
13319 ,(string-to-number pv) ))))
13320 (t `(member ,tag tags-list)))
13321 mm (if minus (list 'not mm) mm)
13322 term rest)
13323 (push mm tagsmatcher))
13324 (push (if (> (length tagsmatcher) 1)
13325 (cons 'and tagsmatcher)
13326 (car tagsmatcher))
13327 orlist)
13328 (setq tagsmatcher nil))
13329 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13330 (setq tagsmatcher
13331 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13332 ;; Make the todo matcher
13333 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13334 (setq todomatcher t)
13335 (setq orterms (org-split-string todomatch "|") orlist nil)
13336 (while (setq term (pop orterms))
13337 (while (string-match re term)
13338 (setq minus (and (match-end 1)
13339 (equal (match-string 1 term) "-"))
13340 kwd (match-string 2 term)
13341 re-p (equal (string-to-char kwd) ?{)
13342 term (substring term (match-end 0))
13343 mm (if re-p
13344 `(string-match ,(substring kwd 1 -1) todo)
13345 (list 'equal 'todo kwd))
13346 mm (if minus (list 'not mm) mm))
13347 (push mm todomatcher))
13348 (push (if (> (length todomatcher) 1)
13349 (cons 'and todomatcher)
13350 (car todomatcher))
13351 orlist)
13352 (setq todomatcher nil))
13353 (setq todomatcher (if (> (length orlist) 1)
13354 (cons 'or orlist) (car orlist))))
13356 ;; Return the string and lisp forms of the matcher
13357 (setq matcher (if todomatcher
13358 (list 'and tagsmatcher todomatcher)
13359 tagsmatcher))
13360 (when todo-only
13361 (setq matcher (list 'and '(member todo org-not-done-keywords)
13362 matcher)))
13363 (cons match0 matcher)))
13365 (defun org-op-to-function (op &optional stringp)
13366 "Turn an operator into the appropriate function."
13367 (setq op
13368 (cond
13369 ((equal op "<" ) '(< string< org-time<))
13370 ((equal op ">" ) '(> org-string> org-time>))
13371 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13372 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13373 ((member op '("=" "==")) '(= string= org-time=))
13374 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13375 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13377 (defun org<> (a b) (not (= a b)))
13378 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13379 (defun org-string>= (a b) (not (string< a b)))
13380 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13381 (defun org-string<> (a b) (not (string= a b)))
13382 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13383 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13384 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13385 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13386 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13387 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13388 (defun org-2ft (s)
13389 "Convert S to a floating point time.
13390 If S is already a number, just return it. If it is a string, parse
13391 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13392 (cond
13393 ((numberp s) s)
13394 ((stringp s)
13395 (condition-case nil
13396 (float-time (apply 'encode-time (org-parse-time-string s)))
13397 (error 0.)))
13398 (t 0.)))
13400 (defun org-time-today ()
13401 "Time in seconds today at 0:00.
13402 Returns the float number of seconds since the beginning of the
13403 epoch to the beginning of today (00:00)."
13404 (float-time (apply 'encode-time
13405 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13407 (defun org-matcher-time (s)
13408 "Interpret a time comparison value."
13409 (save-match-data
13410 (cond
13411 ((string= s "<now>") (float-time))
13412 ((string= s "<today>") (org-time-today))
13413 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13414 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13415 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13416 (+ (org-time-today)
13417 (* (string-to-number (match-string 1 s))
13418 (cdr (assoc (match-string 2 s)
13419 '(("d" . 86400.0) ("w" . 604800.0)
13420 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13421 (t (org-2ft s)))))
13423 (defun org-match-any-p (re list)
13424 "Does re match any element of list?"
13425 (setq list (mapcar (lambda (x) (string-match re x)) list))
13426 (delq nil list))
13428 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13429 (defvar org-tags-overlay (make-overlay 1 1))
13430 (org-detach-overlay org-tags-overlay)
13432 (defun org-get-local-tags-at (&optional pos)
13433 "Get a list of tags defined in the current headline."
13434 (org-get-tags-at pos 'local))
13436 (defun org-get-local-tags ()
13437 "Get a list of tags defined in the current headline."
13438 (org-get-tags-at nil 'local))
13440 (defun org-get-tags-at (&optional pos local)
13441 "Get a list of all headline tags applicable at POS.
13442 POS defaults to point. If tags are inherited, the list contains
13443 the targets in the same sequence as the headlines appear, i.e.
13444 the tags of the current headline come last.
13445 When LOCAL is non-nil, only return tags from the current headline,
13446 ignore inherited ones."
13447 (interactive)
13448 (if (and org-trust-scanner-tags
13449 (or (not pos) (equal pos (point)))
13450 (not local))
13451 org-scanner-tags
13452 (let (tags ltags lastpos parent)
13453 (save-excursion
13454 (save-restriction
13455 (widen)
13456 (goto-char (or pos (point)))
13457 (save-match-data
13458 (catch 'done
13459 (condition-case nil
13460 (progn
13461 (org-back-to-heading t)
13462 (while (not (equal lastpos (point)))
13463 (setq lastpos (point))
13464 (when (looking-at
13465 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13466 (setq ltags (org-split-string
13467 (org-match-string-no-properties 1) ":"))
13468 (when parent
13469 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13470 (setq tags (append
13471 (if parent
13472 (org-remove-uninherited-tags ltags)
13473 ltags)
13474 tags)))
13475 (or org-use-tag-inheritance (throw 'done t))
13476 (if local (throw 'done t))
13477 (or (org-up-heading-safe) (error nil))
13478 (setq parent t)))
13479 (error nil)))))
13480 (if local
13481 tags
13482 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13484 (defun org-add-prop-inherited (s)
13485 (add-text-properties 0 (length s) '(inherited t) s)
13488 (defun org-toggle-tag (tag &optional onoff)
13489 "Toggle the tag TAG for the current line.
13490 If ONOFF is `on' or `off', don't toggle but set to this state."
13491 (let (res current)
13492 (save-excursion
13493 (org-back-to-heading t)
13494 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13495 (point-at-eol) t)
13496 (progn
13497 (setq current (match-string 1))
13498 (replace-match ""))
13499 (setq current ""))
13500 (setq current (nreverse (org-split-string current ":")))
13501 (cond
13502 ((eq onoff 'on)
13503 (setq res t)
13504 (or (member tag current) (push tag current)))
13505 ((eq onoff 'off)
13506 (or (not (member tag current)) (setq current (delete tag current))))
13507 (t (if (member tag current)
13508 (setq current (delete tag current))
13509 (setq res t)
13510 (push tag current))))
13511 (end-of-line 1)
13512 (if current
13513 (progn
13514 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13515 (org-set-tags nil t))
13516 (delete-horizontal-space))
13517 (run-hooks 'org-after-tags-change-hook))
13518 res))
13520 (defun org-align-tags-here (to-col)
13521 ;; Assumes that this is a headline
13522 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13523 (beginning-of-line 1)
13524 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13525 (< pos (match-beginning 2)))
13526 (progn
13527 (setq tags-l (- (match-end 2) (match-beginning 2)))
13528 (goto-char (match-beginning 1))
13529 (insert " ")
13530 (delete-region (point) (1+ (match-beginning 2)))
13531 (setq ncol (max (current-column)
13532 (1+ col)
13533 (if (> to-col 0)
13534 to-col
13535 (- (abs to-col) tags-l))))
13536 (setq p (point))
13537 (insert (make-string (- ncol (current-column)) ?\ ))
13538 (setq ncol (current-column))
13539 (when indent-tabs-mode (tabify p (point-at-eol)))
13540 (org-move-to-column (min ncol col) t))
13541 (goto-char pos))))
13543 (defun org-set-tags-command (&optional arg just-align)
13544 "Call the set-tags command for the current entry."
13545 (interactive "P")
13546 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13547 (org-set-tags arg just-align)
13548 (save-excursion
13549 (org-back-to-heading t)
13550 (org-set-tags arg just-align))))
13552 (defun org-set-tags-to (data)
13553 "Set the tags of the current entry to DATA, replacing the current tags.
13554 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13555 If DATA is nil or the empty string, any tags will be removed."
13556 (interactive "sTags: ")
13557 (setq data
13558 (cond
13559 ((eq data nil) "")
13560 ((equal data "") "")
13561 ((stringp data)
13562 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13563 ":"))
13564 ((listp data)
13565 (concat ":" (mapconcat 'identity data ":") ":"))))
13566 (when data
13567 (save-excursion
13568 (org-back-to-heading t)
13569 (when (looking-at org-complex-heading-regexp)
13570 (if (match-end 5)
13571 (progn
13572 (goto-char (match-beginning 5))
13573 (insert data)
13574 (delete-region (point) (point-at-eol))
13575 (org-set-tags nil 'align))
13576 (goto-char (point-at-eol))
13577 (insert " " data)
13578 (org-set-tags nil 'align)))
13579 (beginning-of-line 1)
13580 (if (looking-at ".*?\\([ \t]+\\)$")
13581 (delete-region (match-beginning 1) (match-end 1))))))
13583 (defun org-align-all-tags ()
13584 "Align the tags i all headings."
13585 (interactive)
13586 (save-excursion
13587 (or (ignore-errors (org-back-to-heading t))
13588 (outline-next-heading))
13589 (if (org-at-heading-p)
13590 (org-set-tags t)
13591 (message "No headings"))))
13593 (defvar org-indent-indentation-per-level)
13594 (defun org-set-tags (&optional arg just-align)
13595 "Set the tags for the current headline.
13596 With prefix ARG, realign all tags in headings in the current buffer."
13597 (interactive "P")
13598 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13599 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13600 'region-start-level 'region))
13601 org-loop-over-headlines-in-active-region)
13602 (org-map-entries
13603 ;; We don't use ARG and JUST-ALIGN here these args are not
13604 ;; useful when looping over headlines
13605 `(org-set-tags)
13606 org-loop-over-headlines-in-active-region
13607 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13608 (let* ((re org-outline-regexp-bol)
13609 (current (unless arg (org-get-tags-string)))
13610 (col (current-column))
13611 (org-setting-tags t)
13612 table current-tags inherited-tags ; computed below when needed
13613 tags p0 c0 c1 rpl di tc level)
13614 (if arg
13615 (save-excursion
13616 (goto-char (point-min))
13617 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13618 (while (re-search-forward re nil t)
13619 (org-set-tags nil t)
13620 (end-of-line 1)))
13621 (message "All tags realigned to column %d" org-tags-column))
13622 (if just-align
13623 (setq tags current)
13624 ;; Get a new set of tags from the user
13625 (save-excursion
13626 (setq table (append org-tag-persistent-alist
13627 (or org-tag-alist (org-get-buffer-tags))
13628 (and
13629 org-complete-tags-always-offer-all-agenda-tags
13630 (org-global-tags-completion-table
13631 (org-agenda-files))))
13632 org-last-tags-completion-table table
13633 current-tags (org-split-string current ":")
13634 inherited-tags (nreverse
13635 (nthcdr (length current-tags)
13636 (nreverse (org-get-tags-at))))
13637 tags
13638 (if (or (eq t org-use-fast-tag-selection)
13639 (and org-use-fast-tag-selection
13640 (delq nil (mapcar 'cdr table))))
13641 (org-fast-tag-selection
13642 current-tags inherited-tags table
13643 (if org-fast-tag-selection-include-todo
13644 org-todo-key-alist))
13645 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13646 (org-trim
13647 (org-icompleting-read "Tags: "
13648 'org-tags-completion-function
13649 nil nil current 'org-tags-history))))))
13650 (while (string-match "[-+&]+" tags)
13651 ;; No boolean logic, just a list
13652 (setq tags (replace-match ":" t t tags))))
13654 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13656 (if org-tags-sort-function
13657 (setq tags (mapconcat 'identity
13658 (sort (org-split-string
13659 tags (org-re "[^[:alnum:]_@#%]+"))
13660 org-tags-sort-function) ":")))
13662 (if (string-match "\\`[\t ]*\\'" tags)
13663 (setq tags "")
13664 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13665 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13667 ;; Insert new tags at the correct column
13668 (beginning-of-line 1)
13669 (setq level (or (and (looking-at org-outline-regexp)
13670 (- (match-end 0) (point) 1))
13672 (cond
13673 ((and (equal current "") (equal tags "")))
13674 ((re-search-forward
13675 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13676 (point-at-eol) t)
13677 (if (equal tags "")
13678 (setq rpl "")
13679 (goto-char (match-beginning 0))
13680 (setq c0 (current-column)
13681 ;; compute offset for the case of org-indent-mode active
13682 di (if org-indent-mode
13683 (* (1- org-indent-indentation-per-level) (1- level))
13685 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13686 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13687 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13688 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13689 (replace-match rpl t t)
13690 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13691 tags)
13692 (t (error "Tags alignment failed")))
13693 (org-move-to-column col)
13694 (unless just-align
13695 (run-hooks 'org-after-tags-change-hook))))))
13697 (defun org-change-tag-in-region (beg end tag off)
13698 "Add or remove TAG for each entry in the region.
13699 This works in the agenda, and also in an org-mode buffer."
13700 (interactive
13701 (list (region-beginning) (region-end)
13702 (let ((org-last-tags-completion-table
13703 (if (derived-mode-p 'org-mode)
13704 (org-get-buffer-tags)
13705 (org-global-tags-completion-table))))
13706 (org-icompleting-read
13707 "Tag: " 'org-tags-completion-function nil nil nil
13708 'org-tags-history))
13709 (progn
13710 (message "[s]et or [r]emove? ")
13711 (equal (read-char-exclusive) ?r))))
13712 (if (fboundp 'deactivate-mark) (deactivate-mark))
13713 (let ((agendap (equal major-mode 'org-agenda-mode))
13714 l1 l2 m buf pos newhead (cnt 0))
13715 (goto-char end)
13716 (setq l2 (1- (org-current-line)))
13717 (goto-char beg)
13718 (setq l1 (org-current-line))
13719 (loop for l from l1 to l2 do
13720 (org-goto-line l)
13721 (setq m (get-text-property (point) 'org-hd-marker))
13722 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13723 (and agendap m))
13724 (setq buf (if agendap (marker-buffer m) (current-buffer))
13725 pos (if agendap m (point)))
13726 (with-current-buffer buf
13727 (save-excursion
13728 (save-restriction
13729 (goto-char pos)
13730 (setq cnt (1+ cnt))
13731 (org-toggle-tag tag (if off 'off 'on))
13732 (setq newhead (org-get-heading)))))
13733 (and agendap (org-agenda-change-all-lines newhead m))))
13734 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13736 (defun org-tags-completion-function (string predicate &optional flag)
13737 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13738 (confirm (lambda (x) (stringp (car x)))))
13739 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13740 (setq s1 (match-string 1 string)
13741 s2 (match-string 2 string))
13742 (setq s1 "" s2 string))
13743 (cond
13744 ((eq flag nil)
13745 ;; try completion
13746 (setq rtn (try-completion s2 ctable confirm))
13747 (if (stringp rtn)
13748 (setq rtn
13749 (concat s1 s2 (substring rtn (length s2))
13750 (if (and org-add-colon-after-tag-completion
13751 (assoc rtn ctable))
13752 ":" ""))))
13753 rtn)
13754 ((eq flag t)
13755 ;; all-completions
13756 (all-completions s2 ctable confirm)
13758 ((eq flag 'lambda)
13759 ;; exact match?
13760 (assoc s2 ctable)))
13763 (defun org-fast-tag-insert (kwd tags face &optional end)
13764 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13765 (insert (format "%-12s" (concat kwd ":"))
13766 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13767 (or end "")))
13769 (defun org-fast-tag-show-exit (flag)
13770 (save-excursion
13771 (org-goto-line 3)
13772 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13773 (replace-match ""))
13774 (when flag
13775 (end-of-line 1)
13776 (org-move-to-column (- (window-width) 19) t)
13777 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13779 (defun org-set-current-tags-overlay (current prefix)
13780 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13781 (if (featurep 'xemacs)
13782 (org-overlay-display org-tags-overlay (concat prefix s)
13783 'secondary-selection)
13784 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13785 (org-overlay-display org-tags-overlay (concat prefix s)))))
13787 (defvar org-last-tag-selection-key nil)
13788 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13789 "Fast tag selection with single keys.
13790 CURRENT is the current list of tags in the headline, INHERITED is the
13791 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13792 possibly with grouping information. TODO-TABLE is a similar table with
13793 TODO keywords, should these have keys assigned to them.
13794 If the keys are nil, a-z are automatically assigned.
13795 Returns the new tags string, or nil to not change the current settings."
13796 (let* ((fulltable (append table todo-table))
13797 (maxlen (apply 'max (mapcar
13798 (lambda (x)
13799 (if (stringp (car x)) (string-width (car x)) 0))
13800 fulltable)))
13801 (buf (current-buffer))
13802 (expert (eq org-fast-tag-selection-single-key 'expert))
13803 (buffer-tags nil)
13804 (fwidth (+ maxlen 3 1 3))
13805 (ncol (/ (- (window-width) 4) fwidth))
13806 (i-face 'org-done)
13807 (c-face 'org-todo)
13808 tg cnt e c char c1 c2 ntable tbl rtn
13809 ov-start ov-end ov-prefix
13810 (exit-after-next org-fast-tag-selection-single-key)
13811 (done-keywords org-done-keywords)
13812 groups ingroup)
13813 (save-excursion
13814 (beginning-of-line 1)
13815 (if (looking-at
13816 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13817 (setq ov-start (match-beginning 1)
13818 ov-end (match-end 1)
13819 ov-prefix "")
13820 (setq ov-start (1- (point-at-eol))
13821 ov-end (1+ ov-start))
13822 (skip-chars-forward "^\n\r")
13823 (setq ov-prefix
13824 (concat
13825 (buffer-substring (1- (point)) (point))
13826 (if (> (current-column) org-tags-column)
13828 (make-string (- org-tags-column (current-column)) ?\ ))))))
13829 (move-overlay org-tags-overlay ov-start ov-end)
13830 (save-window-excursion
13831 (if expert
13832 (set-buffer (get-buffer-create " *Org tags*"))
13833 (delete-other-windows)
13834 (split-window-vertically)
13835 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13836 (erase-buffer)
13837 (org-set-local 'org-done-keywords done-keywords)
13838 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13839 (org-fast-tag-insert "Current" current c-face "\n\n")
13840 (org-fast-tag-show-exit exit-after-next)
13841 (org-set-current-tags-overlay current ov-prefix)
13842 (setq tbl fulltable char ?a cnt 0)
13843 (while (setq e (pop tbl))
13844 (cond
13845 ((equal (car e) :startgroup)
13846 (push '() groups) (setq ingroup t)
13847 (when (not (= cnt 0))
13848 (setq cnt 0)
13849 (insert "\n"))
13850 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13851 ((equal (car e) :endgroup)
13852 (setq ingroup nil cnt 0)
13853 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13854 ((equal e '(:newline))
13855 (when (not (= cnt 0))
13856 (setq cnt 0)
13857 (insert "\n")
13858 (setq e (car tbl))
13859 (while (equal (car tbl) '(:newline))
13860 (insert "\n")
13861 (setq tbl (cdr tbl)))))
13863 (setq tg (copy-sequence (car e)) c2 nil)
13864 (if (cdr e)
13865 (setq c (cdr e))
13866 ;; automatically assign a character.
13867 (setq c1 (string-to-char
13868 (downcase (substring
13869 tg (if (= (string-to-char tg) ?@) 1 0)))))
13870 (if (or (rassoc c1 ntable) (rassoc c1 table))
13871 (while (or (rassoc char ntable) (rassoc char table))
13872 (setq char (1+ char)))
13873 (setq c2 c1))
13874 (setq c (or c2 char)))
13875 (if ingroup (push tg (car groups)))
13876 (setq tg (org-add-props tg nil 'face
13877 (cond
13878 ((not (assoc tg table))
13879 (org-get-todo-face tg))
13880 ((member tg current) c-face)
13881 ((member tg inherited) i-face))))
13882 (if (and (= cnt 0) (not ingroup)) (insert " "))
13883 (insert "[" c "] " tg (make-string
13884 (- fwidth 4 (length tg)) ?\ ))
13885 (push (cons tg c) ntable)
13886 (when (= (setq cnt (1+ cnt)) ncol)
13887 (insert "\n")
13888 (if ingroup (insert " "))
13889 (setq cnt 0)))))
13890 (setq ntable (nreverse ntable))
13891 (insert "\n")
13892 (goto-char (point-min))
13893 (if (not expert) (org-fit-window-to-buffer))
13894 (setq rtn
13895 (catch 'exit
13896 (while t
13897 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13898 (if (not groups) "no " "")
13899 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13900 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13901 (setq org-last-tag-selection-key c)
13902 (cond
13903 ((= c ?\r) (throw 'exit t))
13904 ((= c ?!)
13905 (setq groups (not groups))
13906 (goto-char (point-min))
13907 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13908 ((= c ?\C-c)
13909 (if (not expert)
13910 (org-fast-tag-show-exit
13911 (setq exit-after-next (not exit-after-next)))
13912 (setq expert nil)
13913 (delete-other-windows)
13914 (set-window-buffer (split-window-vertically) " *Org tags*")
13915 (org-switch-to-buffer-other-window " *Org tags*")
13916 (org-fit-window-to-buffer)))
13917 ((or (= c ?\C-g)
13918 (and (= c ?q) (not (rassoc c ntable))))
13919 (org-detach-overlay org-tags-overlay)
13920 (setq quit-flag t))
13921 ((= c ?\ )
13922 (setq current nil)
13923 (if exit-after-next (setq exit-after-next 'now)))
13924 ((= c ?\t)
13925 (condition-case nil
13926 (setq tg (org-icompleting-read
13927 "Tag: "
13928 (or buffer-tags
13929 (with-current-buffer buf
13930 (org-get-buffer-tags)))))
13931 (quit (setq tg "")))
13932 (when (string-match "\\S-" tg)
13933 (add-to-list 'buffer-tags (list tg))
13934 (if (member tg current)
13935 (setq current (delete tg current))
13936 (push tg current)))
13937 (if exit-after-next (setq exit-after-next 'now)))
13938 ((setq e (rassoc c todo-table) tg (car e))
13939 (with-current-buffer buf
13940 (save-excursion (org-todo tg)))
13941 (if exit-after-next (setq exit-after-next 'now)))
13942 ((setq e (rassoc c ntable) tg (car e))
13943 (if (member tg current)
13944 (setq current (delete tg current))
13945 (loop for g in groups do
13946 (if (member tg g)
13947 (mapc (lambda (x)
13948 (setq current (delete x current)))
13949 g)))
13950 (push tg current))
13951 (if exit-after-next (setq exit-after-next 'now))))
13953 ;; Create a sorted list
13954 (setq current
13955 (sort current
13956 (lambda (a b)
13957 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13958 (if (eq exit-after-next 'now) (throw 'exit t))
13959 (goto-char (point-min))
13960 (beginning-of-line 2)
13961 (delete-region (point) (point-at-eol))
13962 (org-fast-tag-insert "Current" current c-face)
13963 (org-set-current-tags-overlay current ov-prefix)
13964 (while (re-search-forward
13965 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13966 (setq tg (match-string 1))
13967 (add-text-properties
13968 (match-beginning 1) (match-end 1)
13969 (list 'face
13970 (cond
13971 ((member tg current) c-face)
13972 ((member tg inherited) i-face)
13973 (t (get-text-property (match-beginning 1) 'face))))))
13974 (goto-char (point-min)))))
13975 (org-detach-overlay org-tags-overlay)
13976 (if rtn
13977 (mapconcat 'identity current ":")
13978 nil))))
13980 (defun org-get-tags-string ()
13981 "Get the TAGS string in the current headline."
13982 (unless (org-at-heading-p t)
13983 (error "Not on a heading"))
13984 (save-excursion
13985 (beginning-of-line 1)
13986 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13987 (org-match-string-no-properties 1)
13988 "")))
13990 (defun org-get-tags ()
13991 "Get the list of tags specified in the current headline."
13992 (org-split-string (org-get-tags-string) ":"))
13994 (defun org-get-buffer-tags ()
13995 "Get a table of all tags used in the buffer, for completion."
13996 (let (tags)
13997 (save-excursion
13998 (goto-char (point-min))
13999 (while (re-search-forward
14000 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14001 (when (equal (char-after (point-at-bol 0)) ?*)
14002 (mapc (lambda (x) (add-to-list 'tags x))
14003 (org-split-string (org-match-string-no-properties 1) ":")))))
14004 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14005 (mapcar 'list tags)))
14007 ;;;; The mapping API
14009 (defun org-map-entries (func &optional match scope &rest skip)
14010 "Call FUNC at each headline selected by MATCH in SCOPE.
14012 FUNC is a function or a lisp form. The function will be called without
14013 arguments, with the cursor positioned at the beginning of the headline.
14014 The return values of all calls to the function will be collected and
14015 returned as a list.
14017 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14018 does not need to preserve point. After evaluation, the cursor will be
14019 moved to the end of the line (presumably of the headline of the
14020 processed entry) and search continues from there. Under some
14021 circumstances, this may not produce the wanted results. For example,
14022 if you have removed (e.g. archived) the current (sub)tree it could
14023 mean that the next entry will be skipped entirely. In such cases, you
14024 can specify the position from where search should continue by making
14025 FUNC set the variable `org-map-continue-from' to the desired buffer
14026 position.
14028 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14029 Only headlines that are matched by this query will be considered during
14030 the iteration. When MATCH is nil or t, all headlines will be
14031 visited by the iteration.
14033 SCOPE determines the scope of this command. It can be any of:
14035 nil The current buffer, respecting the restriction if any
14036 tree The subtree started with the entry at point
14037 region The entries within the active region, if any
14038 region-start-level
14039 The entries within the active region, but only those at
14040 the same level than the first one.
14041 file The current buffer, without restriction
14042 file-with-archives
14043 The current buffer, and any archives associated with it
14044 agenda All agenda files
14045 agenda-with-archives
14046 All agenda files with any archive files associated with them
14047 \(file1 file2 ...)
14048 If this is a list, all files in the list will be scanned
14050 The remaining args are treated as settings for the skipping facilities of
14051 the scanner. The following items can be given here:
14053 archive skip trees with the archive tag.
14054 comment skip trees with the COMMENT keyword
14055 function or Emacs Lisp form:
14056 will be used as value for `org-agenda-skip-function', so whenever
14057 the function returns t, FUNC will not be called for that
14058 entry and search will continue from the point where the
14059 function leaves it.
14061 If your function needs to retrieve the tags including inherited tags
14062 at the *current* entry, you can use the value of the variable
14063 `org-scanner-tags' which will be much faster than getting the value
14064 with `org-get-tags-at'. If your function gets properties with
14065 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14066 to t around the call to `org-entry-properties' to get the same speedup.
14067 Note that if your function moves around to retrieve tags and properties at
14068 a *different* entry, you cannot use these techniques."
14069 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14070 (not (org-region-active-p)))
14071 (let* ((org-agenda-archives-mode nil) ; just to make sure
14072 (org-agenda-skip-archived-trees (memq 'archive skip))
14073 (org-agenda-skip-comment-trees (memq 'comment skip))
14074 (org-agenda-skip-function
14075 (car (org-delete-all '(comment archive) skip)))
14076 (org-tags-match-list-sublevels t)
14077 (start-level (eq scope 'region-start-level))
14078 matcher file res
14079 org-todo-keywords-for-agenda
14080 org-done-keywords-for-agenda
14081 org-todo-keyword-alist-for-agenda
14082 org-drawers-for-agenda
14083 org-tag-alist-for-agenda
14084 todo-only)
14086 (cond
14087 ((eq match t) (setq matcher t))
14088 ((eq match nil) (setq matcher t))
14089 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14091 (save-excursion
14092 (save-restriction
14093 (cond ((eq scope 'tree)
14094 (org-back-to-heading t)
14095 (org-narrow-to-subtree)
14096 (setq scope nil))
14097 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14098 (org-region-active-p))
14099 ;; If needed, set start-level to a string like "2"
14100 (when start-level
14101 (save-excursion
14102 (goto-char (region-beginning))
14103 (unless (org-at-heading-p) (outline-next-heading))
14104 (setq start-level (org-current-level))))
14105 (narrow-to-region (region-beginning)
14106 (save-excursion
14107 (goto-char (region-end))
14108 (unless (and (bolp) (org-at-heading-p))
14109 (outline-next-heading))
14110 (point)))
14111 (setq scope nil)))
14113 (if (not scope)
14114 (progn
14115 (org-agenda-prepare-buffers
14116 (list (buffer-file-name (current-buffer))))
14117 (setq res (org-scan-tags func matcher todo-only start-level)))
14118 ;; Get the right scope
14119 (cond
14120 ((and scope (listp scope) (symbolp (car scope)))
14121 (setq scope (eval scope)))
14122 ((eq scope 'agenda)
14123 (setq scope (org-agenda-files t)))
14124 ((eq scope 'agenda-with-archives)
14125 (setq scope (org-agenda-files t))
14126 (setq scope (org-add-archive-files scope)))
14127 ((eq scope 'file)
14128 (setq scope (list (buffer-file-name))))
14129 ((eq scope 'file-with-archives)
14130 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14131 (org-agenda-prepare-buffers scope)
14132 (while (setq file (pop scope))
14133 (with-current-buffer (org-find-base-buffer-visiting file)
14134 (save-excursion
14135 (save-restriction
14136 (widen)
14137 (goto-char (point-min))
14138 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14139 res)))
14141 ;;;; Properties
14143 ;;; Setting and retrieving properties
14145 (defconst org-special-properties
14146 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14147 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14148 "The special properties valid in Org-mode.
14150 These are properties that are not defined in the property drawer,
14151 but in some other way.")
14153 (defconst org-default-properties
14154 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14155 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14156 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14157 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14158 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14159 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14160 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14161 "Some properties that are used by Org-mode for various purposes.
14162 Being in this list makes sure that they are offered for completion.")
14164 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14165 "Regular expression matching the first line of a property drawer.")
14167 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14168 "Regular expression matching the last line of a property drawer.")
14170 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14171 "Regular expression matching the first line of a property drawer.")
14173 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14174 "Regular expression matching the first line of a property drawer.")
14176 (defconst org-property-drawer-re
14177 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14178 org-property-end-re "\\)\n?")
14179 "Matches an entire property drawer.")
14181 (defconst org-clock-drawer-re
14182 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14183 org-property-end-re "\\)\n?")
14184 "Matches an entire clock drawer.")
14186 (defsubst org-re-property (property)
14187 "Return a regexp matching a PROPERTY line.
14188 Match group 1 will be set to the value."
14189 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14191 (defsubst org-re-property-keyword (property)
14192 "Return a regexp matching a PROPERTY line, possibly with no
14193 value for the property."
14194 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14196 (defun org-property-action ()
14197 "Do an action on properties."
14198 (interactive)
14199 (let (c)
14200 (org-at-property-p)
14201 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14202 (setq c (read-char-exclusive))
14203 (cond
14204 ((equal c ?s)
14205 (call-interactively 'org-set-property))
14206 ((equal c ?d)
14207 (call-interactively 'org-delete-property))
14208 ((equal c ?D)
14209 (call-interactively 'org-delete-property-globally))
14210 ((equal c ?c)
14211 (call-interactively 'org-compute-property-at-point))
14212 (t (error "No such property action %c" c)))))
14214 (defun org-inc-effort ()
14215 "Increment the value of the effort property in the current entry."
14216 (interactive)
14217 (org-set-effort nil t))
14219 (defun org-set-effort (&optional value increment)
14220 "Set the effort property of the current entry.
14221 With numerical prefix arg, use the nth allowed value, 0 stands for the
14222 10th allowed value.
14224 When INCREMENT is non-nil, set the property to the next allowed value."
14225 (interactive "P")
14226 (if (equal value 0) (setq value 10))
14227 (let* ((completion-ignore-case t)
14228 (prop org-effort-property)
14229 (cur (org-entry-get nil prop))
14230 (allowed (org-property-get-allowed-values nil prop 'table))
14231 (existing (mapcar 'list (org-property-values prop)))
14233 (val (cond
14234 ((stringp value) value)
14235 ((and allowed (integerp value))
14236 (or (car (nth (1- value) allowed))
14237 (car (org-last allowed))))
14238 ((and allowed increment)
14239 (or (caadr (member (list cur) allowed))
14240 (error "Allowed effort values are not set")))
14241 (allowed
14242 (message "Select 1-9,0, [RET%s]: %s"
14243 (if cur (concat "=" cur) "")
14244 (mapconcat 'car allowed " "))
14245 (setq rpl (read-char-exclusive))
14246 (if (equal rpl ?\r)
14248 (setq rpl (- rpl ?0))
14249 (if (equal rpl 0) (setq rpl 10))
14250 (if (and (> rpl 0) (<= rpl (length allowed)))
14251 (car (nth (1- rpl) allowed))
14252 (org-completing-read "Effort: " allowed nil))))
14254 (let (org-completion-use-ido org-completion-use-iswitchb)
14255 (org-completing-read
14256 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14257 (concat "[" cur "]") "")
14258 ": ")
14259 existing nil nil "" nil cur))))))
14260 (unless (equal (org-entry-get nil prop) val)
14261 (org-entry-put nil prop val))
14262 (message "%s is now %s" prop val)))
14264 (defun org-at-property-p ()
14265 "Is cursor inside a property drawer?"
14266 (save-excursion
14267 (beginning-of-line 1)
14268 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14269 (save-match-data ;; Used by calling procedures
14270 (let ((p (point))
14271 (range (unless (org-before-first-heading-p)
14272 (org-get-property-block))))
14273 (and range (<= (car range) p) (< p (cdr range))))))))
14275 (defun org-get-property-block (&optional beg end force)
14276 "Return the (beg . end) range of the body of the property drawer.
14277 BEG and END are the beginning and end of the current subtree, or of
14278 the part before the first headline. If they are not given, they will
14279 be found. If the drawer does not exist and FORCE is non-nil, create
14280 the drawer."
14281 (catch 'exit
14282 (save-excursion
14283 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14284 (progn (org-back-to-heading t) (point))))
14285 (end (or end (and (not (outline-next-heading)) (point-max))
14286 (point))))
14287 (goto-char beg)
14288 (if (re-search-forward org-property-start-re end t)
14289 (setq beg (1+ (match-end 0)))
14290 (if force
14291 (save-excursion
14292 (org-insert-property-drawer)
14293 (setq end (progn (outline-next-heading) (point))))
14294 (throw 'exit nil))
14295 (goto-char beg)
14296 (if (re-search-forward org-property-start-re end t)
14297 (setq beg (1+ (match-end 0)))))
14298 (if (re-search-forward org-property-end-re end t)
14299 (setq end (match-beginning 0))
14300 (or force (throw 'exit nil))
14301 (goto-char beg)
14302 (setq end beg)
14303 (org-indent-line)
14304 (insert ":END:\n"))
14305 (cons beg end)))))
14307 (defun org-entry-properties (&optional pom which specific)
14308 "Get all properties of the entry at point-or-marker POM.
14309 This includes the TODO keyword, the tags, time strings for deadline,
14310 scheduled, and clocking, and any additional properties defined in the
14311 entry. The return value is an alist, keys may occur multiple times
14312 if the property key was used several times.
14313 POM may also be nil, in which case the current entry is used.
14314 If WHICH is nil or `all', get all properties. If WHICH is
14315 `special' or `standard', only get that subclass. If WHICH
14316 is a string only get exactly this property. SPECIFIC can be a string, the
14317 specific property we are interested in. Specifying it can speed
14318 things up because then unnecessary parsing is avoided."
14319 (setq which (or which 'all))
14320 (org-with-point-at pom
14321 (let ((clockstr (substring org-clock-string 0 -1))
14322 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14323 (case-fold-search nil)
14324 beg end range props sum-props key key1 value string clocksum clocksumt)
14325 (save-excursion
14326 (when (condition-case nil
14327 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14328 (error nil))
14329 (setq beg (point))
14330 (setq sum-props (get-text-property (point) 'org-summaries))
14331 (setq clocksum (get-text-property (point) :org-clock-minutes)
14332 clocksumt (get-text-property (point) :org-clock-minutes-today))
14333 (outline-next-heading)
14334 (setq end (point))
14335 (when (memq which '(all special))
14336 ;; Get the special properties, like TODO and tags
14337 (goto-char beg)
14338 (when (and (or (not specific) (string= specific "TODO"))
14339 (looking-at org-todo-line-regexp) (match-end 2))
14340 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14341 (when (and (or (not specific) (string= specific "PRIORITY"))
14342 (looking-at org-priority-regexp))
14343 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14344 (when (or (not specific) (string= specific "FILE"))
14345 (push (cons "FILE" buffer-file-name) props))
14346 (when (and (or (not specific) (string= specific "TAGS"))
14347 (setq value (org-get-tags-string))
14348 (string-match "\\S-" value))
14349 (push (cons "TAGS" value) props))
14350 (when (and (or (not specific) (string= specific "ALLTAGS"))
14351 (setq value (org-get-tags-at)))
14352 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14353 ":"))
14354 props))
14355 (when (or (not specific) (string= specific "BLOCKED"))
14356 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14357 (when (or (not specific)
14358 (member specific
14359 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14360 "TIMESTAMP" "TIMESTAMP_IA")))
14361 (catch 'match
14362 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14363 (setq key (if (match-end 1)
14364 (substring (org-match-string-no-properties 1)
14365 0 -1))
14366 string (if (equal key clockstr)
14367 (org-trim
14368 (buffer-substring-no-properties
14369 (match-beginning 3) (goto-char
14370 (point-at-eol))))
14371 (substring (org-match-string-no-properties 3)
14372 1 -1)))
14373 ;; Get the correct property name from the key. This is
14374 ;; necessary if the user has configured time keywords.
14375 (setq key1 (concat key ":"))
14376 (cond
14377 ((not key)
14378 (setq key
14379 (if (= (char-after (match-beginning 3)) ?\[)
14380 "TIMESTAMP_IA" "TIMESTAMP")))
14381 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14382 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14383 ((equal key1 org-closed-string) (setq key "CLOSED"))
14384 ((equal key1 org-clock-string) (setq key "CLOCK")))
14385 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14386 (progn
14387 (push (cons key string) props)
14388 ;; no need to search further if match is found
14389 (throw 'match t))
14390 (when (or (equal key "CLOCK") (not (assoc key props)))
14391 (push (cons key string) props)))))))
14393 (when (memq which '(all standard))
14394 ;; Get the standard properties, like :PROP: ...
14395 (setq range (org-get-property-block beg end))
14396 (when range
14397 (goto-char (car range))
14398 (while (re-search-forward
14399 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14400 (cdr range) t)
14401 (setq key (org-match-string-no-properties 1)
14402 value (org-trim (or (org-match-string-no-properties 2) "")))
14403 (unless (member key excluded)
14404 (push (cons key (or value "")) props)))))
14405 (if clocksum
14406 (push (cons "CLOCKSUM"
14407 (org-columns-number-to-string (/ (float clocksum) 60.)
14408 'add_times))
14409 props))
14410 (if clocksumt
14411 (push (cons "CLOCKSUM_T"
14412 (org-columns-number-to-string (/ (float clocksumt) 60.)
14413 'add_times))
14414 props))
14415 (unless (assoc "CATEGORY" props)
14416 (push (cons "CATEGORY" (org-get-category)) props))
14417 (append sum-props (nreverse props)))))))
14419 (defun org-entry-get (pom property &optional inherit literal-nil)
14420 "Get value of PROPERTY for entry or content at point-or-marker POM.
14421 If INHERIT is non-nil and the entry does not have the property,
14422 then also check higher levels of the hierarchy.
14423 If INHERIT is the symbol `selective', use inheritance only if the setting
14424 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14425 If the property is present but empty, the return value is the empty string.
14426 If the property is not present at all, nil is returned.
14428 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14429 do not interpret it as the list atom nil. This is used for inheritance
14430 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14431 (org-with-point-at pom
14432 (if (and inherit (if (eq inherit 'selective)
14433 (org-property-inherit-p property)
14435 (org-entry-get-with-inheritance property literal-nil)
14436 (if (member property org-special-properties)
14437 ;; We need a special property. Use `org-entry-properties' to
14438 ;; retrieve it, but specify the wanted property
14439 (cdr (assoc property (org-entry-properties nil 'special property)))
14440 (let* ((range (org-get-property-block))
14441 (props (list (or (assoc property org-file-properties)
14442 (assoc property org-global-properties)
14443 (assoc property org-global-properties-fixed))))
14444 (ap (lambda (key)
14445 (when (re-search-forward
14446 (org-re-property key) (cdr range) t)
14447 (setq props
14448 (org-update-property-plist
14450 (if (match-end 1)
14451 (org-match-string-no-properties 1) "")
14452 props)))))
14453 val)
14454 (when (and range (goto-char (car range)))
14455 (funcall ap property)
14456 (goto-char (car range))
14457 (while (funcall ap (concat property "+")))
14458 (setq val (cdr (assoc property props)))
14459 (when val (if literal-nil val (org-not-nil val)))))))))
14461 (defun org-property-or-variable-value (var &optional inherit)
14462 "Check if there is a property fixing the value of VAR.
14463 If yes, return this value. If not, return the current value of the variable."
14464 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14465 (if (and prop (stringp prop) (string-match "\\S-" prop))
14466 (read prop)
14467 (symbol-value var))))
14469 (defun org-entry-delete (pom property)
14470 "Delete the property PROPERTY from entry at point-or-marker POM."
14471 (org-with-point-at pom
14472 (if (member property org-special-properties)
14473 nil ; cannot delete these properties.
14474 (let ((range (org-get-property-block)))
14475 (if (and range
14476 (goto-char (car range))
14477 (re-search-forward
14478 (org-re-property property)
14479 (cdr range) t))
14480 (progn
14481 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14483 nil)))))
14485 ;; Multi-values properties are properties that contain multiple values
14486 ;; These values are assumed to be single words, separated by whitespace.
14487 (defun org-entry-add-to-multivalued-property (pom property value)
14488 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14489 (let* ((old (org-entry-get pom property))
14490 (values (and old (org-split-string old "[ \t]"))))
14491 (setq value (org-entry-protect-space value))
14492 (unless (member value values)
14493 (setq values (cons value values))
14494 (org-entry-put pom property
14495 (mapconcat 'identity values " ")))))
14497 (defun org-entry-remove-from-multivalued-property (pom property value)
14498 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14499 (let* ((old (org-entry-get pom property))
14500 (values (and old (org-split-string old "[ \t]"))))
14501 (setq value (org-entry-protect-space value))
14502 (when (member value values)
14503 (setq values (delete value values))
14504 (org-entry-put pom property
14505 (mapconcat 'identity values " ")))))
14507 (defun org-entry-member-in-multivalued-property (pom property value)
14508 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14509 (let* ((old (org-entry-get pom property))
14510 (values (and old (org-split-string old "[ \t]"))))
14511 (setq value (org-entry-protect-space value))
14512 (member value values)))
14514 (defun org-entry-get-multivalued-property (pom property)
14515 "Return a list of values in a multivalued property."
14516 (let* ((value (org-entry-get pom property))
14517 (values (and value (org-split-string value "[ \t]"))))
14518 (mapcar 'org-entry-restore-space values)))
14520 (defun org-entry-put-multivalued-property (pom property &rest values)
14521 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14522 VALUES should be a list of strings. Spaces will be protected."
14523 (org-entry-put pom property
14524 (mapconcat 'org-entry-protect-space values " "))
14525 (let* ((value (org-entry-get pom property))
14526 (values (and value (org-split-string value "[ \t]"))))
14527 (mapcar 'org-entry-restore-space values)))
14529 (defun org-entry-protect-space (s)
14530 "Protect spaces and newline in string S."
14531 (while (string-match " " s)
14532 (setq s (replace-match "%20" t t s)))
14533 (while (string-match "\n" s)
14534 (setq s (replace-match "%0A" t t s)))
14537 (defun org-entry-restore-space (s)
14538 "Restore spaces and newline in string S."
14539 (while (string-match "%20" s)
14540 (setq s (replace-match " " t t s)))
14541 (while (string-match "%0A" s)
14542 (setq s (replace-match "\n" t t s)))
14545 (defvar org-entry-property-inherited-from (make-marker)
14546 "Marker pointing to the entry from where a property was inherited.
14547 Each call to `org-entry-get-with-inheritance' will set this marker to the
14548 location of the entry where the inheritance search matched. If there was
14549 no match, the marker will point nowhere.
14550 Note that also `org-entry-get' calls this function, if the INHERIT flag
14551 is set.")
14553 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14554 "Get PROPERTY of entry or content at point, search higher levels if needed.
14555 The search will stop at the first ancestor which has the property defined.
14556 If the value found is \"nil\", return nil to show that the property
14557 should be considered as undefined (this is the meaning of nil here).
14558 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14559 (move-marker org-entry-property-inherited-from nil)
14560 (let (tmp)
14561 (save-excursion
14562 (save-restriction
14563 (widen)
14564 (catch 'ex
14565 (while t
14566 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14567 (or (ignore-errors (org-back-to-heading t))
14568 (goto-char (point-min)))
14569 (move-marker org-entry-property-inherited-from (point))
14570 (throw 'ex tmp))
14571 (or (ignore-errors (org-up-heading-safe))
14572 (throw 'ex nil))))))
14573 (setq tmp (or tmp
14574 (cdr (assoc property org-file-properties))
14575 (cdr (assoc property org-global-properties))
14576 (cdr (assoc property org-global-properties-fixed))))
14577 (if literal-nil tmp (org-not-nil tmp))))
14579 (defvar org-property-changed-functions nil
14580 "Hook called when the value of a property has changed.
14581 Each hook function should accept two arguments, the name of the property
14582 and the new value.")
14584 (defun org-entry-put (pom property value)
14585 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14586 (org-with-point-at pom
14587 (org-back-to-heading t)
14588 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14589 range)
14590 (cond
14591 ((equal property "TODO")
14592 (when (and (stringp value) (string-match "\\S-" value)
14593 (not (member value org-todo-keywords-1)))
14594 (error "\"%s\" is not a valid TODO state" value))
14595 (if (or (not value)
14596 (not (string-match "\\S-" value)))
14597 (setq value 'none))
14598 (org-todo value)
14599 (org-set-tags nil 'align))
14600 ((equal property "PRIORITY")
14601 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14602 (string-to-char value) ?\ ))
14603 (org-set-tags nil 'align))
14604 ((equal property "SCHEDULED")
14605 (if (re-search-forward org-scheduled-time-regexp end t)
14606 (cond
14607 ((eq value 'earlier) (org-timestamp-change -1 'day))
14608 ((eq value 'later) (org-timestamp-change 1 'day))
14609 (t (call-interactively 'org-schedule)))
14610 (call-interactively 'org-schedule)))
14611 ((equal property "DEADLINE")
14612 (if (re-search-forward org-deadline-time-regexp end t)
14613 (cond
14614 ((eq value 'earlier) (org-timestamp-change -1 'day))
14615 ((eq value 'later) (org-timestamp-change 1 'day))
14616 (t (call-interactively 'org-deadline)))
14617 (call-interactively 'org-deadline)))
14618 ((member property org-special-properties)
14619 (error "The %s property can not yet be set with `org-entry-put'"
14620 property))
14621 (t ; a non-special property
14622 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14623 (setq range (org-get-property-block beg end 'force))
14624 (goto-char (car range))
14625 (if (re-search-forward
14626 (org-re-property-keyword property) (cdr range) t)
14627 (progn
14628 (delete-region (match-beginning 0) (match-end 0))
14629 (goto-char (match-beginning 0)))
14630 (goto-char (cdr range))
14631 (insert "\n")
14632 (backward-char 1)
14633 (org-indent-line))
14634 (insert ":" property ":")
14635 (and value (insert " " value))
14636 (org-indent-line)))))
14637 (run-hook-with-args 'org-property-changed-functions property value)))
14639 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14640 "Get all property keys in the current buffer.
14641 With INCLUDE-SPECIALS, also list the special properties that reflect things
14642 like tags and TODO state.
14643 With INCLUDE-DEFAULTS, also include properties that has special meaning
14644 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14645 and others.
14646 With INCLUDE-COLUMNS, also include property names given in COLUMN
14647 formats in the current buffer."
14648 (let (rtn range cfmt s p)
14649 (save-excursion
14650 (save-restriction
14651 (widen)
14652 (goto-char (point-min))
14653 (while (re-search-forward org-property-start-re nil t)
14654 (setq range (org-get-property-block))
14655 (goto-char (car range))
14656 (while (re-search-forward
14657 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14658 (cdr range) t)
14659 (add-to-list 'rtn (org-match-string-no-properties 1)))
14660 (outline-next-heading))))
14662 (when include-specials
14663 (setq rtn (append org-special-properties rtn)))
14665 (when include-defaults
14666 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14667 (add-to-list 'rtn org-effort-property))
14669 (when include-columns
14670 (save-excursion
14671 (save-restriction
14672 (widen)
14673 (goto-char (point-min))
14674 (while (re-search-forward
14675 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14676 nil t)
14677 (setq cfmt (match-string 2) s 0)
14678 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14679 cfmt s)
14680 (setq s (match-end 0)
14681 p (match-string 1 cfmt))
14682 (unless (or (equal p "ITEM")
14683 (member p org-special-properties))
14684 (add-to-list 'rtn (match-string 1 cfmt))))))))
14686 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14688 (defun org-property-values (key)
14689 "Return a list of all values of property KEY in the current buffer."
14690 (save-excursion
14691 (save-restriction
14692 (widen)
14693 (goto-char (point-min))
14694 (let ((re (org-re-property key))
14695 values)
14696 (while (re-search-forward re nil t)
14697 (add-to-list 'values (org-trim (match-string 1))))
14698 (delete "" values)))))
14700 (defun org-insert-property-drawer ()
14701 "Insert a property drawer into the current entry."
14702 (org-back-to-heading t)
14703 (looking-at org-outline-regexp)
14704 (let ((indent (if org-adapt-indentation
14705 (- (match-end 0) (match-beginning 0))
14707 (beg (point))
14708 (re (concat "^[ \t]*" org-keyword-time-regexp))
14709 end hiddenp)
14710 (outline-next-heading)
14711 (setq end (point))
14712 (goto-char beg)
14713 (while (re-search-forward re end t))
14714 (setq hiddenp (outline-invisible-p))
14715 (end-of-line 1)
14716 (and (equal (char-after) ?\n) (forward-char 1))
14717 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14718 (if (member (match-string 1) '("CLOCK:" ":END:"))
14719 ;; just skip this line
14720 (beginning-of-line 2)
14721 ;; Drawer start, find the end
14722 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14723 (beginning-of-line 1)))
14724 (org-skip-over-state-notes)
14725 (skip-chars-backward " \t\n\r")
14726 (if (eq (char-before) ?*) (forward-char 1))
14727 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14728 (beginning-of-line 0)
14729 (org-indent-to-column indent)
14730 (beginning-of-line 2)
14731 (org-indent-to-column indent)
14732 (beginning-of-line 0)
14733 (if hiddenp
14734 (save-excursion
14735 (org-back-to-heading t)
14736 (hide-entry))
14737 (org-flag-drawer t))))
14739 (defun org-insert-drawer (&optional arg drawer)
14740 "Insert a drawer at point.
14742 Optional argument DRAWER, when non-nil, is a string representing
14743 drawer's name. Otherwise, the user is prompted for a name.
14745 If a region is active, insert the drawer around that region
14746 instead.
14748 Point is left between drawer's boundaries."
14749 (interactive "P")
14750 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14751 "LOGBOOK"))
14752 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14753 ;; internally by Org. They are meant to be inserted
14754 ;; automatically.
14755 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14756 ;; Remove system drawers from list. Note: For some reason,
14757 ;; `org-completing-read' ignores the predicate while
14758 ;; `completing-read' handles it fine.
14759 (drawer (if arg "PROPERTIES"
14760 (or drawer
14761 (completing-read
14762 "Drawer: " org-drawers
14763 (lambda (d) (not (member d system-drawers))))))))
14764 (cond
14765 ;; With C-u, fall back on `org-insert-property-drawer'
14766 (arg (org-insert-property-drawer))
14767 ;; With an active region, insert a drawer at point.
14768 ((not (org-region-active-p))
14769 (progn
14770 (unless (bolp) (insert "\n"))
14771 (insert (format ":%s:\n\n:END:\n" drawer))
14772 (forward-line -2)))
14773 ;; Otherwise, insert the drawer at point
14775 (let ((rbeg (region-beginning))
14776 (rend (copy-marker (region-end))))
14777 (unwind-protect
14778 (progn
14779 (goto-char rbeg)
14780 (beginning-of-line)
14781 (when (save-excursion
14782 (re-search-forward org-outline-regexp-bol rend t))
14783 (error "Drawers cannot contain headlines"))
14784 ;; Position point at the beginning of the first
14785 ;; non-blank line in region. Insert drawer's opening
14786 ;; there, then indent it.
14787 (org-skip-whitespace)
14788 (beginning-of-line)
14789 (insert ":" drawer ":\n")
14790 (forward-line -1)
14791 (indent-for-tab-command)
14792 ;; Move point to the beginning of the first blank line
14793 ;; after the last non-blank line in region. Insert
14794 ;; drawer's closing, then indent it.
14795 (goto-char rend)
14796 (skip-chars-backward " \r\t\n")
14797 (insert "\n:END:")
14798 (deactivate-mark t)
14799 (indent-for-tab-command)
14800 (unless (eolp) (insert "\n")))
14801 ;; Clear marker, whatever the outcome of insertion is.
14802 (set-marker rend nil)))))))
14804 (defvar org-property-set-functions-alist nil
14805 "Property set function alist.
14806 Each entry should have the following format:
14808 (PROPERTY . READ-FUNCTION)
14810 The read function will be called with the same argument as
14811 `org-completing-read'.")
14813 (defun org-set-property-function (property)
14814 "Get the function that should be used to set PROPERTY.
14815 This is computed according to `org-property-set-functions-alist'."
14816 (or (cdr (assoc property org-property-set-functions-alist))
14817 'org-completing-read))
14819 (defun org-read-property-value (property)
14820 "Read PROPERTY value from user."
14821 (let* ((completion-ignore-case t)
14822 (allowed (org-property-get-allowed-values nil property 'table))
14823 (cur (org-entry-get nil property))
14824 (prompt (concat property " value"
14825 (if (and cur (string-match "\\S-" cur))
14826 (concat " [" cur "]") "") ": "))
14827 (set-function (org-set-property-function property))
14828 (val (if allowed
14829 (funcall set-function prompt allowed nil
14830 (not (get-text-property 0 'org-unrestricted
14831 (caar allowed))))
14832 (let (org-completion-use-ido org-completion-use-iswitchb)
14833 (funcall set-function prompt
14834 (mapcar 'list (org-property-values property))
14835 nil nil "" nil cur)))))
14836 (if (equal val "")
14838 val)))
14840 (defvar org-last-set-property nil)
14841 (defun org-read-property-name ()
14842 "Read a property name."
14843 (let* ((completion-ignore-case t)
14844 (keys (org-buffer-property-keys nil t t))
14845 (default-prop (or (save-excursion
14846 (save-match-data
14847 (beginning-of-line)
14848 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14849 (null (string= (match-string 1) "END"))
14850 (match-string 1))))
14851 org-last-set-property))
14852 (property (org-icompleting-read
14853 (concat "Property"
14854 (if default-prop (concat " [" default-prop "]") "")
14855 ": ")
14856 (mapcar 'list keys)
14857 nil nil nil nil
14858 default-prop
14860 (if (member property keys)
14861 property
14862 (or (cdr (assoc (downcase property)
14863 (mapcar (lambda (x) (cons (downcase x) x))
14864 keys)))
14865 property))))
14867 (defun org-set-property (property value)
14868 "In the current entry, set PROPERTY to VALUE.
14869 When called interactively, this will prompt for a property name, offering
14870 completion on existing and default properties. And then it will prompt
14871 for a value, offering completion either on allowed values (via an inherited
14872 xxx_ALL property) or on existing values in other instances of this property
14873 in the current file."
14874 (interactive (list nil nil))
14875 (let* ((property (or property (org-read-property-name)))
14876 (value (or value (org-read-property-value property)))
14877 (fn (cdr (assoc property org-properties-postprocess-alist))))
14878 (setq org-last-set-property property)
14879 ;; Possibly postprocess the inserted value:
14880 (when fn (setq value (funcall fn value)))
14881 (unless (equal (org-entry-get nil property) value)
14882 (org-entry-put nil property value))))
14884 (defun org-delete-property (property)
14885 "In the current entry, delete PROPERTY."
14886 (interactive
14887 (let* ((completion-ignore-case t)
14888 (prop (org-icompleting-read "Property: "
14889 (org-entry-properties nil 'standard))))
14890 (list prop)))
14891 (message "Property %s %s" property
14892 (if (org-entry-delete nil property)
14893 "deleted"
14894 "was not present in the entry")))
14896 (defun org-delete-property-globally (property)
14897 "Remove PROPERTY globally, from all entries."
14898 (interactive
14899 (let* ((completion-ignore-case t)
14900 (prop (org-icompleting-read
14901 "Globally remove property: "
14902 (mapcar 'list (org-buffer-property-keys)))))
14903 (list prop)))
14904 (save-excursion
14905 (save-restriction
14906 (widen)
14907 (goto-char (point-min))
14908 (let ((cnt 0))
14909 (while (re-search-forward
14910 (org-re-property property)
14911 nil t)
14912 (setq cnt (1+ cnt))
14913 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14914 (message "Property \"%s\" removed from %d entries" property cnt)))))
14916 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14918 (defun org-compute-property-at-point ()
14919 "Compute the property at point.
14920 This looks for an enclosing column format, extracts the operator and
14921 then applies it to the property in the column format's scope."
14922 (interactive)
14923 (unless (org-at-property-p)
14924 (error "Not at a property"))
14925 (let ((prop (org-match-string-no-properties 2)))
14926 (org-columns-get-format-and-top-level)
14927 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14928 (error "No operator defined for property %s" prop))
14929 (org-columns-compute prop)))
14931 (defvar org-property-allowed-value-functions nil
14932 "Hook for functions supplying allowed values for a specific property.
14933 The functions must take a single argument, the name of the property, and
14934 return a flat list of allowed values. If \":ETC\" is one of
14935 the values, this means that these values are intended as defaults for
14936 completion, but that other values should be allowed too.
14937 The functions must return nil if they are not responsible for this
14938 property.")
14940 (defun org-property-get-allowed-values (pom property &optional table)
14941 "Get allowed values for the property PROPERTY.
14942 When TABLE is non-nil, return an alist that can directly be used for
14943 completion."
14944 (let (vals)
14945 (cond
14946 ((equal property "TODO")
14947 (setq vals (org-with-point-at pom
14948 (append org-todo-keywords-1 '("")))))
14949 ((equal property "PRIORITY")
14950 (let ((n org-lowest-priority))
14951 (while (>= n org-highest-priority)
14952 (push (char-to-string n) vals)
14953 (setq n (1- n)))))
14954 ((member property org-special-properties))
14955 ((setq vals (run-hook-with-args-until-success
14956 'org-property-allowed-value-functions property)))
14958 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14959 (when (and vals (string-match "\\S-" vals))
14960 (setq vals (car (read-from-string (concat "(" vals ")"))))
14961 (setq vals (mapcar (lambda (x)
14962 (cond ((stringp x) x)
14963 ((numberp x) (number-to-string x))
14964 ((symbolp x) (symbol-name x))
14965 (t "???")))
14966 vals)))))
14967 (when (member ":ETC" vals)
14968 (setq vals (remove ":ETC" vals))
14969 (org-add-props (car vals) '(org-unrestricted t)))
14970 (if table (mapcar 'list vals) vals)))
14972 (defun org-property-previous-allowed-value (&optional previous)
14973 "Switch to the next allowed value for this property."
14974 (interactive)
14975 (org-property-next-allowed-value t))
14977 (defun org-property-next-allowed-value (&optional previous)
14978 "Switch to the next allowed value for this property."
14979 (interactive)
14980 (unless (org-at-property-p)
14981 (error "Not at a property"))
14982 (let* ((key (match-string 2))
14983 (value (match-string 3))
14984 (allowed (or (org-property-get-allowed-values (point) key)
14985 (and (member value '("[ ]" "[-]" "[X]"))
14986 '("[ ]" "[X]"))))
14987 nval)
14988 (unless allowed
14989 (error "Allowed values for this property have not been defined"))
14990 (if previous (setq allowed (reverse allowed)))
14991 (if (member value allowed)
14992 (setq nval (car (cdr (member value allowed)))))
14993 (setq nval (or nval (car allowed)))
14994 (if (equal nval value)
14995 (error "Only one allowed value for this property"))
14996 (org-at-property-p)
14997 (replace-match (concat " :" key ": " nval) t t)
14998 (org-indent-line)
14999 (beginning-of-line 1)
15000 (skip-chars-forward " \t")
15001 (run-hook-with-args 'org-property-changed-functions key nval)))
15003 (defun org-find-olp (path &optional this-buffer)
15004 "Return a marker pointing to the entry at outline path OLP.
15005 If anything goes wrong, throw an error.
15006 You can wrap this call to catch the error like this:
15008 (condition-case msg
15009 (org-mobile-locate-entry (match-string 4))
15010 (error (nth 1 msg)))
15012 The return value will then be either a string with the error message,
15013 or a marker if everything is OK.
15015 If THIS-BUFFER is set, the outline path does not contain a file,
15016 only headings."
15017 (let* ((file (if this-buffer buffer-file-name (pop path)))
15018 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15019 (level 1)
15020 (lmin 1)
15021 (lmax 1)
15022 limit re end found pos heading cnt flevel)
15023 (unless buffer (error "File not found :%s" file))
15024 (with-current-buffer buffer
15025 (save-excursion
15026 (save-restriction
15027 (widen)
15028 (setq limit (point-max))
15029 (goto-char (point-min))
15030 (while (setq heading (pop path))
15031 (setq re (format org-complex-heading-regexp-format
15032 (regexp-quote heading)))
15033 (setq cnt 0 pos (point))
15034 (while (re-search-forward re end t)
15035 (setq level (- (match-end 1) (match-beginning 1)))
15036 (if (and (>= level lmin) (<= level lmax))
15037 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15038 (when (= cnt 0) (error "Heading not found on level %d: %s"
15039 lmax heading))
15040 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15041 lmax heading))
15042 (goto-char found)
15043 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15044 (setq end (save-excursion (org-end-of-subtree t t))))
15045 (when (org-at-heading-p)
15046 (move-marker (make-marker) (point))))))))
15048 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15049 "Find node HEADING in BUFFER.
15050 Return a marker to the heading if it was found, or nil if not.
15051 If POS-ONLY is set, return just the position instead of a marker.
15053 The heading text must match exact, but it may have a TODO keyword,
15054 a priority cookie and tags in the standard locations."
15055 (with-current-buffer (or buffer (current-buffer))
15056 (save-excursion
15057 (save-restriction
15058 (widen)
15059 (goto-char (point-min))
15060 (let (case-fold-search)
15061 (if (re-search-forward
15062 (format org-complex-heading-regexp-format
15063 (regexp-quote heading)) nil t)
15064 (if pos-only
15065 (match-beginning 0)
15066 (move-marker (make-marker) (match-beginning 0)))))))))
15068 (defun org-find-exact-heading-in-directory (heading &optional dir)
15069 "Find Org node headline HEADING in all .org files in directory DIR.
15070 When the target headline is found, return a marker to this location."
15071 (let ((files (directory-files (or dir default-directory)
15072 nil "\\`[^.#].*\\.org\\'"))
15073 file visiting m buffer)
15074 (catch 'found
15075 (while (setq file (pop files))
15076 (message "trying %s" file)
15077 (setq visiting (org-find-base-buffer-visiting file))
15078 (setq buffer (or visiting (find-file-noselect file)))
15079 (setq m (org-find-exact-headline-in-buffer
15080 heading buffer))
15081 (when (and (not m) (not visiting)) (kill-buffer buffer))
15082 (and m (throw 'found m))))))
15084 (defun org-find-entry-with-id (ident)
15085 "Locate the entry that contains the ID property with exact value IDENT.
15086 IDENT can be a string, a symbol or a number, this function will search for
15087 the string representation of it.
15088 Return the position where this entry starts, or nil if there is no such entry."
15089 (interactive "sID: ")
15090 (let ((id (cond
15091 ((stringp ident) ident)
15092 ((symbol-name ident) (symbol-name ident))
15093 ((numberp ident) (number-to-string ident))
15094 (t (error "IDENT %s must be a string, symbol or number" ident))))
15095 (case-fold-search nil))
15096 (save-excursion
15097 (save-restriction
15098 (widen)
15099 (goto-char (point-min))
15100 (when (re-search-forward
15101 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15102 nil t)
15103 (org-back-to-heading t)
15104 (point))))))
15106 ;;;; Timestamps
15108 (defvar org-last-changed-timestamp nil)
15109 (defvar org-last-inserted-timestamp nil
15110 "The last time stamp inserted with `org-insert-time-stamp'.")
15111 (defvar org-time-was-given) ; dynamically scoped parameter
15112 (defvar org-end-time-was-given) ; dynamically scoped parameter
15113 (defvar org-ts-what) ; dynamically scoped parameter
15115 (defun org-time-stamp (arg &optional inactive)
15116 "Prompt for a date/time and insert a time stamp.
15117 If the user specifies a time like HH:MM or if this command is
15118 called with at least one prefix argument, the time stamp contains
15119 the date and the time. Otherwise, only the date is be included.
15121 All parts of a date not specified by the user is filled in from
15122 the current date/time. So if you just press return without
15123 typing anything, the time stamp will represent the current
15124 date/time.
15126 If there is already a timestamp at the cursor, it will be
15127 modified.
15129 With two universal prefix arguments, insert an active timestamp
15130 with the current time without prompting the user."
15131 (interactive "P")
15132 (let* ((ts nil)
15133 (default-time
15134 ;; Default time is either today, or, when entering a range,
15135 ;; the range start.
15136 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15137 (save-excursion
15138 (re-search-backward
15139 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15140 (- (point) 20) t)))
15141 (apply 'encode-time (org-parse-time-string (match-string 1)))
15142 (current-time)))
15143 (default-input (and ts (org-get-compact-tod ts)))
15144 (repeater (save-excursion
15145 (save-match-data
15146 (beginning-of-line)
15147 (when (re-search-forward
15148 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15149 (save-excursion (progn (end-of-line) (point))) t)
15150 (match-string 0)))))
15151 org-time-was-given org-end-time-was-given time)
15152 (cond
15153 ((and (org-at-timestamp-p t)
15154 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15155 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15156 (insert "--")
15157 (setq time (let ((this-command this-command))
15158 (org-read-date arg 'totime nil nil
15159 default-time default-input inactive)))
15160 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15161 ((org-at-timestamp-p t)
15162 (setq time (let ((this-command this-command))
15163 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15164 (when (org-at-timestamp-p t) ; just to get the match data
15165 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15166 (replace-match "")
15167 (setq org-last-changed-timestamp
15168 (org-insert-time-stamp
15169 time (or org-time-was-given arg)
15170 inactive nil nil (list org-end-time-was-given)))
15171 (when repeater (goto-char (1- (point))) (insert " " repeater)
15172 (setq org-last-changed-timestamp
15173 (concat (substring org-last-inserted-timestamp 0 -1)
15174 " " repeater ">"))))
15175 (message "Timestamp updated"))
15176 ((equal arg '(16))
15177 (org-insert-time-stamp (current-time) t))
15179 (setq time (let ((this-command this-command))
15180 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15181 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15182 nil nil (list org-end-time-was-given))))))
15184 ;; FIXME: can we use this for something else, like computing time differences?
15185 (defun org-get-compact-tod (s)
15186 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15187 (let* ((t1 (match-string 1 s))
15188 (h1 (string-to-number (match-string 2 s)))
15189 (m1 (string-to-number (match-string 3 s)))
15190 (t2 (and (match-end 4) (match-string 5 s)))
15191 (h2 (and t2 (string-to-number (match-string 6 s))))
15192 (m2 (and t2 (string-to-number (match-string 7 s))))
15193 dh dm)
15194 (if (not t2)
15196 (setq dh (- h2 h1) dm (- m2 m1))
15197 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15198 (concat t1 "+" (number-to-string dh)
15199 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15201 (defun org-time-stamp-inactive (&optional arg)
15202 "Insert an inactive time stamp.
15203 An inactive time stamp is enclosed in square brackets instead of angle
15204 brackets. It is inactive in the sense that it does not trigger agenda entries,
15205 does not link to the calendar and cannot be changed with the S-cursor keys.
15206 So these are more for recording a certain time/date."
15207 (interactive "P")
15208 (org-time-stamp arg 'inactive))
15210 (defvar org-date-ovl (make-overlay 1 1))
15211 (overlay-put org-date-ovl 'face 'org-date-selected)
15212 (org-detach-overlay org-date-ovl)
15214 (defvar org-ans1) ; dynamically scoped parameter
15215 (defvar org-ans2) ; dynamically scoped parameter
15217 (defvar org-plain-time-of-day-regexp) ; defined below
15219 (defvar org-overriding-default-time nil) ; dynamically scoped
15220 (defvar org-read-date-overlay nil)
15221 (defvar org-dcst nil) ; dynamically scoped
15222 (defvar org-read-date-history nil)
15223 (defvar org-read-date-final-answer nil)
15224 (defvar org-read-date-analyze-futurep nil)
15225 (defvar org-read-date-analyze-forced-year nil)
15226 (defvar org-read-date-inactive)
15228 (defun org-read-date (&optional org-with-time to-time from-string prompt
15229 default-time default-input inactive)
15230 "Read a date, possibly a time, and make things smooth for the user.
15231 The prompt will suggest to enter an ISO date, but you can also enter anything
15232 which will at least partially be understood by `parse-time-string'.
15233 Unrecognized parts of the date will default to the current day, month, year,
15234 hour and minute. If this command is called to replace a timestamp at point,
15235 or to enter the second timestamp of a range, the default time is taken
15236 from the existing stamp. Furthermore, the command prefers the future,
15237 so if you are giving a date where the year is not given, and the day-month
15238 combination is already past in the current year, it will assume you
15239 mean next year. For details, see the manual. A few examples:
15241 3-2-5 --> 2003-02-05
15242 feb 15 --> currentyear-02-15
15243 2/15 --> currentyear-02-15
15244 sep 12 9 --> 2009-09-12
15245 12:45 --> today 12:45
15246 22 sept 0:34 --> currentyear-09-22 0:34
15247 12 --> currentyear-currentmonth-12
15248 Fri --> nearest Friday (today or later)
15249 etc.
15251 Furthermore you can specify a relative date by giving, as the *first* thing
15252 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15253 change in days weeks, months, years.
15254 With a single plus or minus, the date is relative to today. With a double
15255 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15256 +4d --> four days from today
15257 +4 --> same as above
15258 +2w --> two weeks from today
15259 ++5 --> five days from default date
15261 The function understands only English month and weekday abbreviations.
15263 While prompting, a calendar is popped up - you can also select the
15264 date with the mouse (button 1). The calendar shows a period of three
15265 months. To scroll it to other months, use the keys `>' and `<'.
15266 If you don't like the calendar, turn it off with
15267 \(setq org-read-date-popup-calendar nil)
15269 With optional argument TO-TIME, the date will immediately be converted
15270 to an internal time.
15271 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15272 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15273 still enter a time, and this function will inform the calling routine
15274 about this change. The calling routine may then choose to change the
15275 format used to insert the time stamp into the buffer to include the time.
15276 With optional argument FROM-STRING, read from this string instead from
15277 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15278 the time/date that is used for everything that is not specified by the
15279 user."
15280 (require 'parse-time)
15281 (let* ((org-time-stamp-rounding-minutes
15282 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15283 (org-dcst org-display-custom-times)
15284 (ct (org-current-time))
15285 (org-def (or org-overriding-default-time default-time ct))
15286 (org-defdecode (decode-time org-def))
15287 (dummy (progn
15288 (when (< (nth 2 org-defdecode) org-extend-today-until)
15289 (setcar (nthcdr 2 org-defdecode) -1)
15290 (setcar (nthcdr 1 org-defdecode) 59)
15291 (setq org-def (apply 'encode-time org-defdecode)
15292 org-defdecode (decode-time org-def)))))
15293 (calendar-frame-setup nil)
15294 (calendar-setup nil)
15295 (calendar-move-hook nil)
15296 (calendar-view-diary-initially-flag nil)
15297 (calendar-view-holidays-initially-flag nil)
15298 (timestr (format-time-string
15299 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15300 (prompt (concat (if prompt (concat prompt " ") "")
15301 (format "Date+time [%s]: " timestr)))
15302 ans (org-ans0 "") org-ans1 org-ans2 final)
15304 (cond
15305 (from-string (setq ans from-string))
15306 (org-read-date-popup-calendar
15307 (save-excursion
15308 (save-window-excursion
15309 (calendar)
15310 (org-eval-in-calendar '(setq cursor-type nil) t)
15311 (unwind-protect
15312 (progn
15313 (calendar-forward-day (- (time-to-days org-def)
15314 (calendar-absolute-from-gregorian
15315 (calendar-current-date))))
15316 (org-eval-in-calendar nil t)
15317 (let* ((old-map (current-local-map))
15318 (map (copy-keymap calendar-mode-map))
15319 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15320 (org-defkey map (kbd "RET") 'org-calendar-select)
15321 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15322 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15323 (org-defkey minibuffer-local-map [(meta shift left)]
15324 (lambda () (interactive)
15325 (org-eval-in-calendar '(calendar-backward-month 1))))
15326 (org-defkey minibuffer-local-map [(meta shift right)]
15327 (lambda () (interactive)
15328 (org-eval-in-calendar '(calendar-forward-month 1))))
15329 (org-defkey minibuffer-local-map [(meta shift up)]
15330 (lambda () (interactive)
15331 (org-eval-in-calendar '(calendar-backward-year 1))))
15332 (org-defkey minibuffer-local-map [(meta shift down)]
15333 (lambda () (interactive)
15334 (org-eval-in-calendar '(calendar-forward-year 1))))
15335 (org-defkey minibuffer-local-map [?\e (shift left)]
15336 (lambda () (interactive)
15337 (org-eval-in-calendar '(calendar-backward-month 1))))
15338 (org-defkey minibuffer-local-map [?\e (shift right)]
15339 (lambda () (interactive)
15340 (org-eval-in-calendar '(calendar-forward-month 1))))
15341 (org-defkey minibuffer-local-map [?\e (shift up)]
15342 (lambda () (interactive)
15343 (org-eval-in-calendar '(calendar-backward-year 1))))
15344 (org-defkey minibuffer-local-map [?\e (shift down)]
15345 (lambda () (interactive)
15346 (org-eval-in-calendar '(calendar-forward-year 1))))
15347 (org-defkey minibuffer-local-map [(shift up)]
15348 (lambda () (interactive)
15349 (org-eval-in-calendar '(calendar-backward-week 1))))
15350 (org-defkey minibuffer-local-map [(shift down)]
15351 (lambda () (interactive)
15352 (org-eval-in-calendar '(calendar-forward-week 1))))
15353 (org-defkey minibuffer-local-map [(shift left)]
15354 (lambda () (interactive)
15355 (org-eval-in-calendar '(calendar-backward-day 1))))
15356 (org-defkey minibuffer-local-map [(shift right)]
15357 (lambda () (interactive)
15358 (org-eval-in-calendar '(calendar-forward-day 1))))
15359 (org-defkey minibuffer-local-map ">"
15360 (lambda () (interactive)
15361 (org-eval-in-calendar '(scroll-calendar-left 1))))
15362 (org-defkey minibuffer-local-map "<"
15363 (lambda () (interactive)
15364 (org-eval-in-calendar '(scroll-calendar-right 1))))
15365 (org-defkey minibuffer-local-map "\C-v"
15366 (lambda () (interactive)
15367 (org-eval-in-calendar
15368 '(calendar-scroll-left-three-months 1))))
15369 (org-defkey minibuffer-local-map "\M-v"
15370 (lambda () (interactive)
15371 (org-eval-in-calendar
15372 '(calendar-scroll-right-three-months 1))))
15373 (run-hooks 'org-read-date-minibuffer-setup-hook)
15374 (unwind-protect
15375 (progn
15376 (use-local-map map)
15377 (setq org-read-date-inactive inactive)
15378 (add-hook 'post-command-hook 'org-read-date-display)
15379 (setq org-ans0 (read-string prompt default-input
15380 'org-read-date-history nil))
15381 ;; org-ans0: from prompt
15382 ;; org-ans1: from mouse click
15383 ;; org-ans2: from calendar motion
15384 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15385 (remove-hook 'post-command-hook 'org-read-date-display)
15386 (use-local-map old-map)
15387 (when org-read-date-overlay
15388 (delete-overlay org-read-date-overlay)
15389 (setq org-read-date-overlay nil)))))
15390 (bury-buffer "*Calendar*")))))
15392 (t ; Naked prompt only
15393 (unwind-protect
15394 (setq ans (read-string prompt default-input
15395 'org-read-date-history timestr))
15396 (when org-read-date-overlay
15397 (delete-overlay org-read-date-overlay)
15398 (setq org-read-date-overlay nil)))))
15400 (setq final (org-read-date-analyze ans org-def org-defdecode))
15402 (when org-read-date-analyze-forced-year
15403 (message "Year was forced into %s"
15404 (if org-read-date-force-compatible-dates
15405 "compatible range (1970-2037)"
15406 "range representable on this machine"))
15407 (ding))
15409 ;; One round trip to get rid of 34th of August and stuff like that....
15410 (setq final (decode-time (apply 'encode-time final)))
15412 (setq org-read-date-final-answer ans)
15414 (if to-time
15415 (apply 'encode-time final)
15416 (if (and (boundp 'org-time-was-given) org-time-was-given)
15417 (format "%04d-%02d-%02d %02d:%02d"
15418 (nth 5 final) (nth 4 final) (nth 3 final)
15419 (nth 2 final) (nth 1 final))
15420 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15422 (defvar org-def)
15423 (defvar org-defdecode)
15424 (defvar org-with-time)
15425 (defun org-read-date-display ()
15426 "Display the current date prompt interpretation in the minibuffer."
15427 (when org-read-date-display-live
15428 (when org-read-date-overlay
15429 (delete-overlay org-read-date-overlay))
15430 (when (minibufferp (current-buffer))
15431 (save-excursion
15432 (end-of-line 1)
15433 (while (not (equal (buffer-substring
15434 (max (point-min) (- (point) 4)) (point))
15435 " "))
15436 (insert " ")))
15437 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15438 " " (or org-ans1 org-ans2)))
15439 (org-end-time-was-given nil)
15440 (f (org-read-date-analyze ans org-def org-defdecode))
15441 (fmts (if org-dcst
15442 org-time-stamp-custom-formats
15443 org-time-stamp-formats))
15444 (fmt (if (or org-with-time
15445 (and (boundp 'org-time-was-given) org-time-was-given))
15446 (cdr fmts)
15447 (car fmts)))
15448 (txt (format-time-string fmt (apply 'encode-time f)))
15449 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15450 (txt (concat "=> " txt)))
15451 (when (and org-end-time-was-given
15452 (string-match org-plain-time-of-day-regexp txt))
15453 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15454 org-end-time-was-given
15455 (substring txt (match-end 0)))))
15456 (when org-read-date-analyze-futurep
15457 (setq txt (concat txt " (=>F)")))
15458 (setq org-read-date-overlay
15459 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15460 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15462 (defun org-read-date-analyze (ans org-def org-defdecode)
15463 "Analyze the combined answer of the date prompt."
15464 ;; FIXME: cleanup and comment
15465 (let ((nowdecode (decode-time (current-time)))
15466 delta deltan deltaw deltadef year month day
15467 hour minute second wday pm h2 m2 tl wday1
15468 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15469 (setq org-read-date-analyze-futurep nil
15470 org-read-date-analyze-forced-year nil)
15471 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15472 (setq ans "+0"))
15474 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15475 (setq ans (replace-match "" t t ans)
15476 deltan (car delta)
15477 deltaw (nth 1 delta)
15478 deltadef (nth 2 delta)))
15480 ;; Check if there is an iso week date in there. If yes, store the
15481 ;; info and postpone interpreting it until the rest of the parsing
15482 ;; is done.
15483 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15484 (setq iso-year (if (match-end 1)
15485 (org-small-year-to-year
15486 (string-to-number (match-string 1 ans))))
15487 iso-weekday (if (match-end 3)
15488 (string-to-number (match-string 3 ans)))
15489 iso-week (string-to-number (match-string 2 ans)))
15490 (setq ans (replace-match "" t t ans)))
15492 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15493 (when (string-match
15494 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15495 (setq year (if (match-end 2)
15496 (string-to-number (match-string 2 ans))
15497 (progn (setq kill-year t)
15498 (string-to-number (format-time-string "%Y"))))
15499 month (string-to-number (match-string 3 ans))
15500 day (string-to-number (match-string 4 ans)))
15501 (if (< year 100) (setq year (+ 2000 year)))
15502 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15503 t nil ans)))
15505 ;; Help matching dotted european dates
15506 (when (string-match
15507 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15508 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15509 (setq kill-year t)
15510 (string-to-number (format-time-string "%Y")))
15511 day (string-to-number (match-string 1 ans))
15512 month (string-to-number (match-string 2 ans))
15513 ans (replace-match (format "%04d-%02d-%02d" year month day)
15514 t nil ans)))
15516 ;; Help matching american dates, like 5/30 or 5/30/7
15517 (when (string-match
15518 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15519 (setq year (if (match-end 4)
15520 (string-to-number (match-string 4 ans))
15521 (progn (setq kill-year t)
15522 (string-to-number (format-time-string "%Y"))))
15523 month (string-to-number (match-string 1 ans))
15524 day (string-to-number (match-string 2 ans)))
15525 (if (< year 100) (setq year (+ 2000 year)))
15526 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15527 t nil ans)))
15528 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15529 ;; If there is a time with am/pm, and *no* time without it, we convert
15530 ;; so that matching will be successful.
15531 (loop for i from 1 to 2 do ; twice, for end time as well
15532 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15533 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15534 (setq hour (string-to-number (match-string 1 ans))
15535 minute (if (match-end 3)
15536 (string-to-number (match-string 3 ans))
15538 pm (equal ?p
15539 (string-to-char (downcase (match-string 4 ans)))))
15540 (if (and (= hour 12) (not pm))
15541 (setq hour 0)
15542 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15543 (setq ans (replace-match (format "%02d:%02d" hour minute)
15544 t t ans))))
15546 ;; Check if a time range is given as a duration
15547 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15548 (setq hour (string-to-number (match-string 1 ans))
15549 h2 (+ hour (string-to-number (match-string 3 ans)))
15550 minute (string-to-number (match-string 2 ans))
15551 m2 (+ minute (if (match-end 5) (string-to-number
15552 (match-string 5 ans))0)))
15553 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15554 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15555 t t ans)))
15557 ;; Check if there is a time range
15558 (when (boundp 'org-end-time-was-given)
15559 (setq org-time-was-given nil)
15560 (when (and (string-match org-plain-time-of-day-regexp ans)
15561 (match-end 8))
15562 (setq org-end-time-was-given (match-string 8 ans))
15563 (setq ans (concat (substring ans 0 (match-beginning 7))
15564 (substring ans (match-end 7))))))
15566 (setq tl (parse-time-string ans)
15567 day (or (nth 3 tl) (nth 3 org-defdecode))
15568 month (or (nth 4 tl)
15569 (if (and org-read-date-prefer-future
15570 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15571 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15572 (nth 4 org-defdecode)))
15573 year (or (and (not kill-year) (nth 5 tl))
15574 (if (and org-read-date-prefer-future
15575 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15576 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15577 (nth 5 org-defdecode)))
15578 hour (or (nth 2 tl) (nth 2 org-defdecode))
15579 minute (or (nth 1 tl) (nth 1 org-defdecode))
15580 second (or (nth 0 tl) 0)
15581 wday (nth 6 tl))
15583 (when (and (eq org-read-date-prefer-future 'time)
15584 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15585 (equal day (nth 3 nowdecode))
15586 (equal month (nth 4 nowdecode))
15587 (equal year (nth 5 nowdecode))
15588 (nth 2 tl)
15589 (or (< (nth 2 tl) (nth 2 nowdecode))
15590 (and (= (nth 2 tl) (nth 2 nowdecode))
15591 (nth 1 tl)
15592 (< (nth 1 tl) (nth 1 nowdecode)))))
15593 (setq day (1+ day)
15594 futurep t))
15596 ;; Special date definitions below
15597 (cond
15598 (iso-week
15599 ;; There was an iso week
15600 (require 'cal-iso)
15601 (setq futurep nil)
15602 (setq year (or iso-year year)
15603 day (or iso-weekday wday 1)
15604 wday nil ; to make sure that the trigger below does not match
15605 iso-date (calendar-gregorian-from-absolute
15606 (calendar-absolute-from-iso
15607 (list iso-week day year))))
15608 ; FIXME: Should we also push ISO weeks into the future?
15609 ; (when (and org-read-date-prefer-future
15610 ; (not iso-year)
15611 ; (< (calendar-absolute-from-gregorian iso-date)
15612 ; (time-to-days (current-time))))
15613 ; (setq year (1+ year)
15614 ; iso-date (calendar-gregorian-from-absolute
15615 ; (calendar-absolute-from-iso
15616 ; (list iso-week day year)))))
15617 (setq month (car iso-date)
15618 year (nth 2 iso-date)
15619 day (nth 1 iso-date)))
15620 (deltan
15621 (setq futurep nil)
15622 (unless deltadef
15623 (let ((now (decode-time (current-time))))
15624 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15625 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15626 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15627 ((equal deltaw "m") (setq month (+ month deltan)))
15628 ((equal deltaw "y") (setq year (+ year deltan)))))
15629 ((and wday (not (nth 3 tl)))
15630 ;; Weekday was given, but no day, so pick that day in the week
15631 ;; on or after the derived date.
15632 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15633 (unless (equal wday wday1)
15634 (setq day (+ day (% (- wday wday1 -7) 7))))))
15635 (if (and (boundp 'org-time-was-given)
15636 (nth 2 tl))
15637 (setq org-time-was-given t))
15638 (if (< year 100) (setq year (+ 2000 year)))
15639 ;; Check of the date is representable
15640 (if org-read-date-force-compatible-dates
15641 (progn
15642 (if (< year 1970)
15643 (setq year 1970 org-read-date-analyze-forced-year t))
15644 (if (> year 2037)
15645 (setq year 2037 org-read-date-analyze-forced-year t)))
15646 (condition-case nil
15647 (ignore (encode-time second minute hour day month year))
15648 (error
15649 (setq year (nth 5 org-defdecode))
15650 (setq org-read-date-analyze-forced-year t))))
15651 (setq org-read-date-analyze-futurep futurep)
15652 (list second minute hour day month year)))
15654 (defvar parse-time-weekdays)
15655 (defun org-read-date-get-relative (s today default)
15656 "Check string S for special relative date string.
15657 TODAY and DEFAULT are internal times, for today and for a default.
15658 Return shift list (N what def-flag)
15659 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15660 N is the number of WHATs to shift.
15661 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15662 the DEFAULT date rather than TODAY."
15663 (require 'parse-time)
15664 (when (and
15665 (string-match
15666 (concat
15667 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15668 "\\([0-9]+\\)?"
15669 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15670 "\\([ \t]\\|$\\)") s)
15671 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15672 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15673 (string-to-char (substring (match-string 1 s) -1))
15674 ?+))
15675 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15676 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15677 (what (if (match-end 3) (match-string 3 s) "d"))
15678 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15679 (date (if rel default today))
15680 (wday (nth 6 (decode-time date)))
15681 delta)
15682 (if wday1
15683 (progn
15684 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15685 (if (= dir ?-) (setq delta (- delta 7)))
15686 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15687 (list delta "d" rel))
15688 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15690 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15691 "Turn a user-specified date into the internal representation.
15692 The internal representation needed by the calendar is (month day year).
15693 This is a wrapper to handle the brain-dead convention in calendar that
15694 user function argument order change dependent on argument order."
15695 (if (boundp 'calendar-date-style)
15696 (cond
15697 ((eq calendar-date-style 'american)
15698 (list arg1 arg2 arg3))
15699 ((eq calendar-date-style 'european)
15700 (list arg2 arg1 arg3))
15701 ((eq calendar-date-style 'iso)
15702 (list arg2 arg3 arg1)))
15703 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15704 (if (org-bound-and-true-p european-calendar-style)
15705 (list arg2 arg1 arg3)
15706 (list arg1 arg2 arg3)))))
15708 (defun org-eval-in-calendar (form &optional keepdate)
15709 "Eval FORM in the calendar window and return to current window.
15710 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15711 otherwise stick to the current value of `org-ans2'."
15712 (let ((sf (selected-frame))
15713 (sw (selected-window)))
15714 (select-window (get-buffer-window "*Calendar*" t))
15715 (eval form)
15716 (when (and (not keepdate) (calendar-cursor-to-date))
15717 (let* ((date (calendar-cursor-to-date))
15718 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15719 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15720 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15721 (select-window sw)
15722 (org-select-frame-set-input-focus sf)))
15724 (defun org-calendar-select ()
15725 "Return to `org-read-date' with the date currently selected.
15726 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15727 (interactive)
15728 (when (calendar-cursor-to-date)
15729 (let* ((date (calendar-cursor-to-date))
15730 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15731 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15732 (if (active-minibuffer-window) (exit-minibuffer))))
15734 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15735 "Insert a date stamp for the date given by the internal TIME.
15736 WITH-HM means use the stamp format that includes the time of the day.
15737 INACTIVE means use square brackets instead of angular ones, so that the
15738 stamp will not contribute to the agenda.
15739 PRE and POST are optional strings to be inserted before and after the
15740 stamp.
15741 The command returns the inserted time stamp."
15742 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15743 stamp)
15744 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15745 (insert-before-markers (or pre ""))
15746 (when (listp extra)
15747 (setq extra (car extra))
15748 (if (and (stringp extra)
15749 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15750 (setq extra (format "-%02d:%02d"
15751 (string-to-number (match-string 1 extra))
15752 (string-to-number (match-string 2 extra))))
15753 (setq extra nil)))
15754 (when extra
15755 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15756 (insert-before-markers (setq stamp (format-time-string fmt time)))
15757 (insert-before-markers (or post ""))
15758 (setq org-last-inserted-timestamp stamp)))
15760 (defun org-toggle-time-stamp-overlays ()
15761 "Toggle the use of custom time stamp formats."
15762 (interactive)
15763 (setq org-display-custom-times (not org-display-custom-times))
15764 (unless org-display-custom-times
15765 (let ((p (point-min)) (bmp (buffer-modified-p)))
15766 (while (setq p (next-single-property-change p 'display))
15767 (if (and (get-text-property p 'display)
15768 (eq (get-text-property p 'face) 'org-date))
15769 (remove-text-properties
15770 p (setq p (next-single-property-change p 'display))
15771 '(display t))))
15772 (set-buffer-modified-p bmp)))
15773 (if (featurep 'xemacs)
15774 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15775 (org-restart-font-lock)
15776 (setq org-table-may-need-update t)
15777 (if org-display-custom-times
15778 (message "Time stamps are overlaid with custom format")
15779 (message "Time stamp overlays removed")))
15781 (defun org-display-custom-time (beg end)
15782 "Overlay modified time stamp format over timestamp between BEG and END."
15783 (let* ((ts (buffer-substring beg end))
15784 t1 w1 with-hm tf time str w2 (off 0))
15785 (save-match-data
15786 (setq t1 (org-parse-time-string ts t))
15787 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15788 (setq off (- (match-end 0) (match-beginning 0)))))
15789 (setq end (- end off))
15790 (setq w1 (- end beg)
15791 with-hm (and (nth 1 t1) (nth 2 t1))
15792 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15793 time (org-fix-decoded-time t1)
15794 str (org-add-props
15795 (format-time-string
15796 (substring tf 1 -1) (apply 'encode-time time))
15797 nil 'mouse-face 'highlight)
15798 w2 (length str))
15799 (if (not (= w2 w1))
15800 (add-text-properties (1+ beg) (+ 2 beg)
15801 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15802 (if (featurep 'xemacs)
15803 (progn
15804 (put-text-property beg end 'invisible t)
15805 (put-text-property beg end 'end-glyph (make-glyph str)))
15806 (put-text-property beg end 'display str))))
15808 (defun org-translate-time (string)
15809 "Translate all timestamps in STRING to custom format.
15810 But do this only if the variable `org-display-custom-times' is set."
15811 (when org-display-custom-times
15812 (save-match-data
15813 (let* ((start 0)
15814 (re org-ts-regexp-both)
15815 t1 with-hm inactive tf time str beg end)
15816 (while (setq start (string-match re string start))
15817 (setq beg (match-beginning 0)
15818 end (match-end 0)
15819 t1 (save-match-data
15820 (org-parse-time-string (substring string beg end) t))
15821 with-hm (and (nth 1 t1) (nth 2 t1))
15822 inactive (equal (substring string beg (1+ beg)) "[")
15823 tf (funcall (if with-hm 'cdr 'car)
15824 org-time-stamp-custom-formats)
15825 time (org-fix-decoded-time t1)
15826 str (format-time-string
15827 (concat
15828 (if inactive "[" "<") (substring tf 1 -1)
15829 (if inactive "]" ">"))
15830 (apply 'encode-time time))
15831 string (replace-match str t t string)
15832 start (+ start (length str)))))))
15833 string)
15835 (defun org-fix-decoded-time (time)
15836 "Set 0 instead of nil for the first 6 elements of time.
15837 Don't touch the rest."
15838 (let ((n 0))
15839 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15841 (defun org-days-to-time (timestamp-string)
15842 "Difference between TIMESTAMP-STRING and now in days."
15843 (- (time-to-days (org-time-string-to-time timestamp-string))
15844 (time-to-days (current-time))))
15846 (defun org-deadline-close (timestamp-string &optional ndays)
15847 "Is the time in TIMESTAMP-STRING close to the current date?"
15848 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15849 (and (< (org-days-to-time timestamp-string) ndays)
15850 (not (org-entry-is-done-p))))
15852 (defun org-get-wdays (ts)
15853 "Get the deadline lead time appropriate for timestring TS."
15854 (cond
15855 ((<= org-deadline-warning-days 0)
15856 ;; 0 or negative, enforce this value no matter what
15857 (- org-deadline-warning-days))
15858 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15859 ;; lead time is specified.
15860 (floor (* (string-to-number (match-string 1 ts))
15861 (cdr (assoc (match-string 2 ts)
15862 '(("d" . 1) ("w" . 7)
15863 ("m" . 30.4) ("y" . 365.25)))))))
15864 ;; go for the default.
15865 (t org-deadline-warning-days)))
15867 (defun org-calendar-select-mouse (ev)
15868 "Return to `org-read-date' with the date currently selected.
15869 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15870 (interactive "e")
15871 (mouse-set-point ev)
15872 (when (calendar-cursor-to-date)
15873 (let* ((date (calendar-cursor-to-date))
15874 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15875 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15876 (if (active-minibuffer-window) (exit-minibuffer))))
15878 (defun org-check-deadlines (ndays)
15879 "Check if there are any deadlines due or past due.
15880 A deadline is considered due if it happens within `org-deadline-warning-days'
15881 days from today's date. If the deadline appears in an entry marked DONE,
15882 it is not shown. The prefix arg NDAYS can be used to test that many
15883 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15884 (interactive "P")
15885 (let* ((org-warn-days
15886 (cond
15887 ((equal ndays '(4)) 100000)
15888 (ndays (prefix-numeric-value ndays))
15889 (t (abs org-deadline-warning-days))))
15890 (case-fold-search nil)
15891 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15892 (callback
15893 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15895 (message "%d deadlines past-due or due within %d days"
15896 (org-occur regexp nil callback)
15897 org-warn-days)))
15899 (defsubst org-re-timestamp (type)
15900 "Return a regexp for timestamp TYPE.
15901 Allowed values for TYPE are:
15903 all: all timestamps
15904 active: only active timestamps (<...>)
15905 inactive: only inactive timestamps ([...])
15906 scheduled: only scheduled timestamps
15907 deadline: only deadline timestamps
15909 When TYPE is nil, fall back on returning a regexp that matches
15910 both scheduled and deadline timestamps."
15911 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15912 ((eq type 'active) org-ts-regexp)
15913 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15914 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15915 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15916 ((eq type 'scheduled-or-deadline)
15917 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15919 (defun org-check-before-date (date)
15920 "Check if there are deadlines or scheduled entries before DATE."
15921 (interactive (list (org-read-date)))
15922 (let ((case-fold-search nil)
15923 (regexp (org-re-timestamp org-ts-type))
15924 (callback
15925 (lambda () (time-less-p
15926 (org-time-string-to-time (match-string 1))
15927 (org-time-string-to-time date)))))
15928 (message "%d entries before %s"
15929 (org-occur regexp nil callback) date)))
15931 (defun org-check-after-date (date)
15932 "Check if there are deadlines or scheduled entries after DATE."
15933 (interactive (list (org-read-date)))
15934 (let ((case-fold-search nil)
15935 (regexp (org-re-timestamp org-ts-type))
15936 (callback
15937 (lambda () (not
15938 (time-less-p
15939 (org-time-string-to-time (match-string 1))
15940 (org-time-string-to-time date))))))
15941 (message "%d entries after %s"
15942 (org-occur regexp nil callback) date)))
15944 (defun org-check-dates-range (start-date end-date)
15945 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15946 (interactive (list (org-read-date nil nil nil "Range starts")
15947 (org-read-date nil nil nil "Range end")))
15948 (let ((case-fold-search nil)
15949 (regexp (org-re-timestamp org-ts-type))
15950 (callback
15951 (lambda ()
15952 (let ((match (match-string 1)))
15953 (and
15954 (not (time-less-p
15955 (org-time-string-to-time match)
15956 (org-time-string-to-time start-date)))
15957 (time-less-p
15958 (org-time-string-to-time match)
15959 (org-time-string-to-time end-date)))))))
15960 (message "%d entries between %s and %s"
15961 (org-occur regexp nil callback) start-date end-date)))
15963 (defun org-evaluate-time-range (&optional to-buffer)
15964 "Evaluate a time range by computing the difference between start and end.
15965 Normally the result is just printed in the echo area, but with prefix arg
15966 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15967 If the time range is actually in a table, the result is inserted into the
15968 next column.
15969 For time difference computation, a year is assumed to be exactly 365
15970 days in order to avoid rounding problems."
15971 (interactive "P")
15973 (org-clock-update-time-maybe)
15974 (save-excursion
15975 (unless (org-at-date-range-p t)
15976 (goto-char (point-at-bol))
15977 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15978 (if (not (org-at-date-range-p t))
15979 (error "Not at a time-stamp range, and none found in current line")))
15980 (let* ((ts1 (match-string 1))
15981 (ts2 (match-string 2))
15982 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15983 (match-end (match-end 0))
15984 (time1 (org-time-string-to-time ts1))
15985 (time2 (org-time-string-to-time ts2))
15986 (t1 (org-float-time time1))
15987 (t2 (org-float-time time2))
15988 (diff (abs (- t2 t1)))
15989 (negative (< (- t2 t1) 0))
15990 ;; (ys (floor (* 365 24 60 60)))
15991 (ds (* 24 60 60))
15992 (hs (* 60 60))
15993 (fy "%dy %dd %02d:%02d")
15994 (fy1 "%dy %dd")
15995 (fd "%dd %02d:%02d")
15996 (fd1 "%dd")
15997 (fh "%02d:%02d")
15998 y d h m align)
15999 (if havetime
16000 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16002 d (floor (/ diff ds)) diff (mod diff ds)
16003 h (floor (/ diff hs)) diff (mod diff hs)
16004 m (floor (/ diff 60)))
16005 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16007 d (floor (+ (/ diff ds) 0.5))
16008 h 0 m 0))
16009 (if (not to-buffer)
16010 (message "%s" (org-make-tdiff-string y d h m))
16011 (if (org-at-table-p)
16012 (progn
16013 (goto-char match-end)
16014 (setq align t)
16015 (and (looking-at " *|") (goto-char (match-end 0))))
16016 (goto-char match-end))
16017 (if (looking-at
16018 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16019 (replace-match ""))
16020 (if negative (insert " -"))
16021 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16022 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16023 (insert " " (format fh h m))))
16024 (if align (org-table-align))
16025 (message "Time difference inserted")))))
16027 (defun org-make-tdiff-string (y d h m)
16028 (let ((fmt "")
16029 (l nil))
16030 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16031 l (push y l)))
16032 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16033 l (push d l)))
16034 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16035 l (push h l)))
16036 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16037 l (push m l)))
16038 (apply 'format fmt (nreverse l))))
16040 (defun org-time-string-to-time (s &optional buffer pos)
16041 "Convert a timestamp string into internal time."
16042 (condition-case errdata
16043 (apply 'encode-time (org-parse-time-string s))
16044 (error (error "Bad timestamp `%s'%s\nError was: %s"
16045 s (if (not (and buffer pos))
16047 (format " at %d in buffer `%s'" pos buffer))
16048 (cdr errdata)))))
16050 (defun org-time-string-to-seconds (s)
16051 "Convert a timestamp string to a number of seconds."
16052 (org-float-time (org-time-string-to-time s)))
16054 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16055 "Convert a time stamp to an absolute day number.
16056 If there is a specifier for a cyclic time stamp, get the closest date to
16057 DAYNR.
16058 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16059 The variable date is bound by the calendar when this is called."
16060 (cond
16061 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16062 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16063 daynr
16064 (+ daynr 1000)))
16065 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16066 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16067 (time-to-days (current-time))) (match-string 0 s)
16068 prefer show-all))
16069 (t (time-to-days
16070 (condition-case errdata
16071 (apply 'encode-time (org-parse-time-string s))
16072 (error (error "Bad timestamp `%s'%s\nError was: %s"
16073 s (if (not (and buffer pos))
16075 (format " at %d in buffer `%s'" pos buffer))
16076 (cdr errdata))))))))
16078 (defun org-days-to-iso-week (days)
16079 "Return the iso week number."
16080 (require 'cal-iso)
16081 (car (calendar-iso-from-absolute days)))
16083 (defun org-small-year-to-year (year)
16084 "Convert 2-digit years into 4-digit years.
16085 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16086 The year 2000 cannot be abbreviated. Any year larger than 99
16087 is returned unchanged."
16088 (if (< year 38)
16089 (setq year (+ 2000 year))
16090 (if (< year 100)
16091 (setq year (+ 1900 year))))
16092 year)
16094 (defun org-time-from-absolute (d)
16095 "Return the time corresponding to date D.
16096 D may be an absolute day number, or a calendar-type list (month day year)."
16097 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16098 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16100 (defun org-calendar-holiday ()
16101 "List of holidays, for Diary display in Org-mode."
16102 (require 'holidays)
16103 (let ((hl (funcall
16104 (if (fboundp 'calendar-check-holidays)
16105 'calendar-check-holidays 'check-calendar-holidays) date)))
16106 (if hl (mapconcat 'identity hl "; "))))
16108 (defun org-diary-sexp-entry (sexp entry date)
16109 "Process a SEXP diary ENTRY for DATE."
16110 (require 'diary-lib)
16111 (let ((result (if calendar-debug-sexp
16112 (let ((stack-trace-on-error t))
16113 (eval (car (read-from-string sexp))))
16114 (condition-case nil
16115 (eval (car (read-from-string sexp)))
16116 (error
16117 (beep)
16118 (message "Bad sexp at line %d in %s: %s"
16119 (org-current-line)
16120 (buffer-file-name) sexp)
16121 (sleep-for 2))))))
16122 (cond ((stringp result) (split-string result "; "))
16123 ((and (consp result)
16124 (not (consp (cdr result)))
16125 (stringp (cdr result))) (cdr result))
16126 ((and (consp result)
16127 (stringp (car result))) result)
16128 (result entry))))
16130 (defun org-diary-to-ical-string (frombuf)
16131 "Get iCalendar entries from diary entries in buffer FROMBUF.
16132 This uses the icalendar.el library."
16133 (let* ((tmpdir (if (featurep 'xemacs)
16134 (temp-directory)
16135 temporary-file-directory))
16136 (tmpfile (make-temp-name
16137 (expand-file-name "orgics" tmpdir)))
16138 buf rtn b e)
16139 (with-current-buffer frombuf
16140 (icalendar-export-region (point-min) (point-max) tmpfile)
16141 (setq buf (find-buffer-visiting tmpfile))
16142 (set-buffer buf)
16143 (goto-char (point-min))
16144 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16145 (setq b (match-beginning 0)))
16146 (goto-char (point-max))
16147 (if (re-search-backward "^END:VEVENT" nil t)
16148 (setq e (match-end 0)))
16149 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16150 (kill-buffer buf)
16151 (delete-file tmpfile)
16152 rtn))
16154 (defun org-closest-date (start current change prefer show-all)
16155 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16156 When PREFER is `past', return a date that is either CURRENT or past.
16157 When PREFER is `future', return a date that is either CURRENT or future.
16158 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16159 ;; Make the proper lists from the dates
16160 (catch 'exit
16161 (let ((a1 '(("h" . hour)
16162 ("d" . day)
16163 ("w" . week)
16164 ("m" . month)
16165 ("y" . year)))
16166 (shour (nth 2 (org-parse-time-string start)))
16167 dn dw sday cday n1 n2 n0
16168 d m y y1 y2 date1 date2 nmonths nm ny m2)
16170 (setq start (org-date-to-gregorian start)
16171 current (org-date-to-gregorian
16172 (if show-all
16173 current
16174 (time-to-days (current-time))))
16175 sday (calendar-absolute-from-gregorian start)
16176 cday (calendar-absolute-from-gregorian current))
16178 (if (<= cday sday) (throw 'exit sday))
16180 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16181 (setq dn (string-to-number (match-string 1 change))
16182 dw (cdr (assoc (match-string 2 change) a1)))
16183 (error "Invalid change specifier: %s" change))
16184 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16185 (cond
16186 ((eq dw 'hour)
16187 (let ((missing-hours
16188 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16189 dn)))
16190 (setq n1 (if (zerop missing-hours) cday
16191 (- cday (1+ (floor (/ missing-hours 24)))))
16192 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16193 ((eq dw 'day)
16194 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16195 n2 (+ n1 dn)))
16196 ((eq dw 'year)
16197 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16198 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16199 (setq date1 (list m d y1)
16200 n1 (calendar-absolute-from-gregorian date1)
16201 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16202 n2 (calendar-absolute-from-gregorian date2)))
16203 ((eq dw 'month)
16204 ;; approx number of month between the two dates
16205 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16206 ;; How often does dn fit in there?
16207 (setq d (nth 1 start) m (car start) y (nth 2 start)
16208 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16209 m (+ m nm)
16210 ny (floor (/ m 12))
16211 y (+ y ny)
16212 m (- m (* ny 12)))
16213 (while (> m 12) (setq m (- m 12) y (1+ y)))
16214 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16215 (setq m2 (+ m dn) y2 y)
16216 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16217 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16218 (while (<= n2 cday)
16219 (setq n1 n2 m m2 y y2)
16220 (setq m2 (+ m dn) y2 y)
16221 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16222 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16223 ;; Make sure n1 is the earlier date
16224 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16225 (if show-all
16226 (cond
16227 ((eq prefer 'past) (if (= cday n2) n2 n1))
16228 ((eq prefer 'future) (if (= cday n1) n1 n2))
16229 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16230 (cond
16231 ((eq prefer 'past) (if (= cday n2) n2 n1))
16232 ((eq prefer 'future) (if (= cday n1) n1 n2))
16233 (t (if (= cday n1) n1 n2)))))))
16235 (defun org-date-to-gregorian (date)
16236 "Turn any specification of DATE into a Gregorian date for the calendar."
16237 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16238 ((and (listp date) (= (length date) 3)) date)
16239 ((stringp date)
16240 (setq date (org-parse-time-string date))
16241 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16242 ((listp date)
16243 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16245 (defun org-parse-time-string (s &optional nodefault)
16246 "Parse the standard Org-mode time string.
16247 This should be a lot faster than the normal `parse-time-string'.
16248 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16249 hour and minute fields will be nil if not given."
16250 (if (string-match org-ts-regexp0 s)
16251 (list 0
16252 (if (or (match-beginning 8) (not nodefault))
16253 (string-to-number (or (match-string 8 s) "0")))
16254 (if (or (match-beginning 7) (not nodefault))
16255 (string-to-number (or (match-string 7 s) "0")))
16256 (string-to-number (match-string 4 s))
16257 (string-to-number (match-string 3 s))
16258 (string-to-number (match-string 2 s))
16259 nil nil nil)
16260 (error "Not a standard Org-mode time string: %s" s)))
16262 (defun org-timestamp-up (&optional arg)
16263 "Increase the date item at the cursor by one.
16264 If the cursor is on the year, change the year. If it is on the month,
16265 the day or the time, change that.
16266 With prefix ARG, change by that many units."
16267 (interactive "p")
16268 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16270 (defun org-timestamp-down (&optional arg)
16271 "Decrease the date item at the cursor by one.
16272 If the cursor is on the year, change the year. If it is on the month,
16273 the day or the time, change that.
16274 With prefix ARG, change by that many units."
16275 (interactive "p")
16276 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16278 (defun org-timestamp-up-day (&optional arg)
16279 "Increase the date in the time stamp by one day.
16280 With prefix ARG, change that many days."
16281 (interactive "p")
16282 (if (and (not (org-at-timestamp-p t))
16283 (org-at-heading-p))
16284 (org-todo 'up)
16285 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16287 (defun org-timestamp-down-day (&optional arg)
16288 "Decrease the date in the time stamp by one day.
16289 With prefix ARG, change that many days."
16290 (interactive "p")
16291 (if (and (not (org-at-timestamp-p t))
16292 (org-at-heading-p))
16293 (org-todo 'down)
16294 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16296 (defun org-at-timestamp-p (&optional inactive-ok)
16297 "Determine if the cursor is in or at a timestamp."
16298 (interactive)
16299 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16300 (pos (point))
16301 (ans (or (looking-at tsr)
16302 (save-excursion
16303 (skip-chars-backward "^[<\n\r\t")
16304 (if (> (point) (point-min)) (backward-char 1))
16305 (and (looking-at tsr)
16306 (> (- (match-end 0) pos) -1))))))
16307 (and ans
16308 (boundp 'org-ts-what)
16309 (setq org-ts-what
16310 (cond
16311 ((= pos (match-beginning 0)) 'bracket)
16312 ;; Point is considered to be "on the bracket" whether
16313 ;; it's really on it or right after it.
16314 ((= pos (1- (match-end 0))) 'bracket)
16315 ((= pos (match-end 0)) 'after)
16316 ((org-pos-in-match-range pos 2) 'year)
16317 ((org-pos-in-match-range pos 3) 'month)
16318 ((org-pos-in-match-range pos 7) 'hour)
16319 ((org-pos-in-match-range pos 8) 'minute)
16320 ((or (org-pos-in-match-range pos 4)
16321 (org-pos-in-match-range pos 5)) 'day)
16322 ((and (> pos (or (match-end 8) (match-end 5)))
16323 (< pos (match-end 0)))
16324 (- pos (or (match-end 8) (match-end 5))))
16325 (t 'day))))
16326 ans))
16328 (defun org-toggle-timestamp-type ()
16329 "Toggle the type (<active> or [inactive]) of a time stamp."
16330 (interactive)
16331 (when (org-at-timestamp-p t)
16332 (let ((beg (match-beginning 0)) (end (match-end 0))
16333 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16334 (save-excursion
16335 (goto-char beg)
16336 (while (re-search-forward "[][<>]" end t)
16337 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16338 t t)))
16339 (message "Timestamp is now %sactive"
16340 (if (equal (char-after beg) ?<) "" "in")))))
16342 (defvar org-clock-history) ; defined in org-clock.el
16343 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16344 (defun org-timestamp-change (n &optional what updown)
16345 "Change the date in the time stamp at point.
16346 The date will be changed by N times WHAT. WHAT can be `day', `month',
16347 `year', `minute', `second'. If WHAT is not given, the cursor position
16348 in the timestamp determines what will be changed."
16349 (let ((origin (point)) origin-cat
16350 with-hm inactive
16351 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16352 org-ts-what
16353 extra rem
16354 ts time time0 fixnext clrgx)
16355 (if (not (org-at-timestamp-p t))
16356 (error "Not at a timestamp"))
16357 (if (and (not what) (eq org-ts-what 'bracket))
16358 (org-toggle-timestamp-type)
16359 ;; Point isn't on brackets. Remember the part of the time-stamp
16360 ;; the point was in. Indeed, size of time-stamps may change,
16361 ;; but point must be kept in the same category nonetheless.
16362 (setq origin-cat org-ts-what)
16363 (if (and (not what) (not (eq org-ts-what 'day))
16364 org-display-custom-times
16365 (get-text-property (point) 'display)
16366 (not (get-text-property (1- (point)) 'display)))
16367 (setq org-ts-what 'day))
16368 (setq org-ts-what (or what org-ts-what)
16369 inactive (= (char-after (match-beginning 0)) ?\[)
16370 ts (match-string 0))
16371 (replace-match "")
16372 (if (string-match
16373 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16375 (setq extra (match-string 1 ts)))
16376 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16377 (setq with-hm t))
16378 (setq time0 (org-parse-time-string ts))
16379 (when (and updown
16380 (eq org-ts-what 'minute)
16381 (not current-prefix-arg))
16382 ;; This looks like s-up and s-down. Change by one rounding step.
16383 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16384 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16385 (setcar (cdr time0) (+ (nth 1 time0)
16386 (if (> n 0) (- rem) (- dm rem))))))
16387 (setq time
16388 (encode-time (or (car time0) 0)
16389 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16390 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16391 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16392 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16393 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16394 (nthcdr 6 time0)))
16395 (when (and (member org-ts-what '(hour minute))
16396 extra
16397 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16398 (setq extra (org-modify-ts-extra
16399 extra
16400 (if (eq org-ts-what 'hour) 2 5)
16401 n dm)))
16402 (when (integerp org-ts-what)
16403 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16404 (if (eq what 'calendar)
16405 (let ((cal-date (org-get-date-from-calendar)))
16406 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16407 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16408 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16409 (setcar time0 (or (car time0) 0))
16410 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16411 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16412 (setq time (apply 'encode-time time0))))
16413 ;; Insert the new time-stamp, and ensure point stays in the same
16414 ;; category as before (i.e. not after the last position in that
16415 ;; category).
16416 (let ((pos (point)))
16417 ;; Stay before inserted string. `save-excursion' is of no use.
16418 (setq org-last-changed-timestamp
16419 (org-insert-time-stamp time with-hm inactive nil nil extra))
16420 (goto-char pos))
16421 (save-match-data
16422 (looking-at org-ts-regexp3)
16423 (goto-char (cond
16424 ;; `day' category ends before `hour' if any, or at
16425 ;; the end of the day name.
16426 ((eq origin-cat 'day)
16427 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16428 ((eq origin-cat 'hour) (min (match-end 7) origin))
16429 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16430 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16431 ;; `year' and `month' have both fixed size: point
16432 ;; couldn't have moved into another part.
16433 (t origin))))
16434 ;; Update clock if on a CLOCK line.
16435 (org-clock-update-time-maybe)
16436 ;; Maybe adjust the closest clock in `org-clock-history'
16437 (when org-clock-adjust-closest
16438 (if (not (and (org-at-clock-log-p)
16439 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16440 org-clock-history))))))
16441 (message "No clock to adjust")
16442 (cond ((save-excursion ; fix previous clock?
16443 (re-search-backward org-ts-regexp0 nil t)
16444 (org-looking-back (concat org-clock-string " \\[")))
16445 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16446 ((save-excursion ; fix next clock?
16447 (re-search-backward org-ts-regexp0 nil t)
16448 (looking-at (concat org-ts-regexp0 "\\] =>")))
16449 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16450 (save-window-excursion
16451 ;; Find closest clock to point, adjust the previous/next one in history
16452 (let* ((p (save-excursion (org-back-to-heading t)))
16453 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16454 (clfixnth
16455 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16456 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16457 (if (not clfixpos)
16458 (message "No clock to adjust")
16459 (save-excursion
16460 (org-goto-marker-or-bmk clfixpos)
16461 (org-show-subtree)
16462 (when (re-search-forward clrgx nil t)
16463 (goto-char (match-beginning 1))
16464 (let (org-clock-adjust-closest)
16465 (org-timestamp-change n org-ts-what updown))
16466 (message "Clock adjusted in %s for heading: %s"
16467 (file-name-nondirectory (buffer-file-name))
16468 (org-get-heading t t)))))))))
16469 ;; Try to recenter the calendar window, if any.
16470 (if (and org-calendar-follow-timestamp-change
16471 (get-buffer-window "*Calendar*" t)
16472 (memq org-ts-what '(day month year)))
16473 (org-recenter-calendar (time-to-days time))))))
16475 (defun org-modify-ts-extra (s pos n dm)
16476 "Change the different parts of the lead-time and repeat fields in timestamp."
16477 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16478 ng h m new rem)
16479 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16480 (cond
16481 ((or (org-pos-in-match-range pos 2)
16482 (org-pos-in-match-range pos 3))
16483 (setq m (string-to-number (match-string 3 s))
16484 h (string-to-number (match-string 2 s)))
16485 (if (org-pos-in-match-range pos 2)
16486 (setq h (+ h n))
16487 (setq n (* dm (org-no-warnings (signum n))))
16488 (when (not (= 0 (setq rem (% m dm))))
16489 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16490 (setq m (+ m n)))
16491 (if (< m 0) (setq m (+ m 60) h (1- h)))
16492 (if (> m 59) (setq m (- m 60) h (1+ h)))
16493 (setq h (min 24 (max 0 h)))
16494 (setq ng 1 new (format "-%02d:%02d" h m)))
16495 ((org-pos-in-match-range pos 6)
16496 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16497 ((org-pos-in-match-range pos 5)
16498 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16500 ((org-pos-in-match-range pos 9)
16501 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16502 ((org-pos-in-match-range pos 8)
16503 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16505 (when ng
16506 (setq s (concat
16507 (substring s 0 (match-beginning ng))
16509 (substring s (match-end ng))))))
16512 (defun org-recenter-calendar (date)
16513 "If the calendar is visible, recenter it to DATE."
16514 (let ((cwin (get-buffer-window "*Calendar*" t)))
16515 (when cwin
16516 (let ((calendar-move-hook nil))
16517 (with-selected-window cwin
16518 (calendar-goto-date (if (listp date) date
16519 (calendar-gregorian-from-absolute date))))))))
16521 (defun org-goto-calendar (&optional arg)
16522 "Go to the Emacs calendar at the current date.
16523 If there is a time stamp in the current line, go to that date.
16524 A prefix ARG can be used to force the current date."
16525 (interactive "P")
16526 (let ((tsr org-ts-regexp) diff
16527 (calendar-move-hook nil)
16528 (calendar-view-holidays-initially-flag nil)
16529 (calendar-view-diary-initially-flag nil))
16530 (if (or (org-at-timestamp-p)
16531 (save-excursion
16532 (beginning-of-line 1)
16533 (looking-at (concat ".*" tsr))))
16534 (let ((d1 (time-to-days (current-time)))
16535 (d2 (time-to-days
16536 (org-time-string-to-time (match-string 1)))))
16537 (setq diff (- d2 d1))))
16538 (calendar)
16539 (calendar-goto-today)
16540 (if (and diff (not arg)) (calendar-forward-day diff))))
16542 (defun org-get-date-from-calendar ()
16543 "Return a list (month day year) of date at point in calendar."
16544 (with-current-buffer "*Calendar*"
16545 (save-match-data
16546 (calendar-cursor-to-date))))
16548 (defun org-date-from-calendar ()
16549 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16550 If there is already a time stamp at the cursor position, update it."
16551 (interactive)
16552 (if (org-at-timestamp-p t)
16553 (org-timestamp-change 0 'calendar)
16554 (let ((cal-date (org-get-date-from-calendar)))
16555 (org-insert-time-stamp
16556 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16558 (defun org-minutes-to-hh:mm-string (m)
16559 "Compute H:MM from a number of minutes."
16560 (let ((h (/ m 60)))
16561 (setq m (- m (* 60 h)))
16562 (format org-time-clocksum-format h m)))
16564 (defun org-hh:mm-string-to-minutes (s)
16565 "Convert a string H:MM to a number of minutes.
16566 If the string is just a number, interpret it as minutes.
16567 In fact, the first hh:mm or number in the string will be taken,
16568 there can be extra stuff in the string.
16569 If no number is found, the return value is 0."
16570 (cond
16571 ((integerp s) s)
16572 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16573 (+ (* (string-to-number (match-string 1 s)) 60)
16574 (string-to-number (match-string 2 s))))
16575 ((string-match "\\([0-9]+\\)" s)
16576 (string-to-number (match-string 1 s)))
16577 (t 0)))
16579 (defcustom org-effort-durations
16580 `(("h" . 60)
16581 ("d" . ,(* 60 8))
16582 ("w" . ,(* 60 8 5))
16583 ("m" . ,(* 60 8 5 4))
16584 ("y" . ,(* 60 8 5 40)))
16585 "Conversion factor to minutes for an effort modifier.
16587 Each entry has the form (MODIFIER . MINUTES).
16589 In an effort string, a number followed by MODIFIER is multiplied
16590 by the specified number of MINUTES to obtain an effort in
16591 minutes.
16593 For example, if the value of this variable is ((\"hours\" . 60)), then an
16594 effort string \"2hours\" is equivalent to 120 minutes."
16595 :group 'org-agenda
16596 :version "24.1"
16597 :type '(alist :key-type (string :tag "Modifier")
16598 :value-type (number :tag "Minutes")))
16600 (defun org-duration-string-to-minutes (s &optional output-to-string)
16601 "Convert a duration string S to minutes.
16603 A bare number is interpreted as minutes, modifiers can be set by
16604 customizing `org-effort-durations' (which see).
16606 Entries containing a colon are interpreted as H:MM by
16607 `org-hh:mm-string-to-minutes'."
16608 (let ((result 0)
16609 (re (concat "\\([0-9.]+\\) *\\("
16610 (regexp-opt (mapcar 'car org-effort-durations))
16611 "\\)")))
16612 (while (string-match re s)
16613 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16614 (string-to-number (match-string 1 s))))
16615 (setq s (replace-match "" nil t s)))
16616 (setq result (floor result))
16617 (incf result (org-hh:mm-string-to-minutes s))
16618 (if output-to-string (number-to-string result) result)))
16620 ;;;; Files
16622 (defun org-save-all-org-buffers ()
16623 "Save all Org-mode buffers without user confirmation."
16624 (interactive)
16625 (message "Saving all Org-mode buffers...")
16626 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16627 (when (featurep 'org-id) (org-id-locations-save))
16628 (message "Saving all Org-mode buffers... done"))
16630 (defun org-revert-all-org-buffers ()
16631 "Revert all Org-mode buffers.
16632 Prompt for confirmation when there are unsaved changes.
16633 Be sure you know what you are doing before letting this function
16634 overwrite your changes.
16636 This function is useful in a setup where one tracks org files
16637 with a version control system, to revert on one machine after pulling
16638 changes from another. I believe the procedure must be like this:
16640 1. M-x org-save-all-org-buffers
16641 2. Pull changes from the other machine, resolve conflicts
16642 3. M-x org-revert-all-org-buffers"
16643 (interactive)
16644 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16645 (error "Abort"))
16646 (save-excursion
16647 (save-window-excursion
16648 (mapc
16649 (lambda (b)
16650 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16651 (with-current-buffer b buffer-file-name))
16652 (org-pop-to-buffer-same-window b)
16653 (revert-buffer t 'no-confirm)))
16654 (buffer-list))
16655 (when (and (featurep 'org-id) org-id-track-globally)
16656 (org-id-locations-load)))))
16658 ;;;; Agenda files
16660 ;;;###autoload
16661 (defun org-switchb (&optional arg)
16662 "Switch between Org buffers.
16663 With one prefix argument, restrict available buffers to files.
16664 With two prefix arguments, restrict available buffers to agenda files.
16666 Defaults to `iswitchb' for buffer name completion.
16667 Set `org-completion-use-ido' to make it use ido instead."
16668 (interactive "P")
16669 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16670 ((equal arg '(16)) (org-buffer-list 'agenda))
16671 (t (org-buffer-list))))
16672 (org-completion-use-iswitchb org-completion-use-iswitchb)
16673 (org-completion-use-ido org-completion-use-ido))
16674 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16675 (setq org-completion-use-iswitchb t))
16676 (org-pop-to-buffer-same-window
16677 (org-icompleting-read "Org buffer: "
16678 (mapcar 'list (mapcar 'buffer-name blist))
16679 nil t))))
16681 ;;; Define some older names previously used for this functionality
16682 ;;;###autoload
16683 (defalias 'org-ido-switchb 'org-switchb)
16684 ;;;###autoload
16685 (defalias 'org-iswitchb 'org-switchb)
16687 (defun org-buffer-list (&optional predicate exclude-tmp)
16688 "Return a list of Org buffers.
16689 PREDICATE can be `export', `files' or `agenda'.
16691 export restrict the list to Export buffers.
16692 files restrict the list to buffers visiting Org files.
16693 agenda restrict the list to buffers visiting agenda files.
16695 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16696 (let* ((bfn nil)
16697 (agenda-files (and (eq predicate 'agenda)
16698 (mapcar 'file-truename (org-agenda-files t))))
16699 (filter
16700 (cond
16701 ((eq predicate 'files)
16702 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16703 ((eq predicate 'export)
16704 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16705 ((eq predicate 'agenda)
16706 (lambda (b)
16707 (with-current-buffer b
16708 (and (derived-mode-p 'org-mode)
16709 (setq bfn (buffer-file-name b))
16710 (member (file-truename bfn) agenda-files)))))
16711 (t (lambda (b) (with-current-buffer b
16712 (or (derived-mode-p 'org-mode)
16713 (string-match "\*Org .*Export"
16714 (buffer-name b)))))))))
16715 (delq nil
16716 (mapcar
16717 (lambda(b)
16718 (if (and (funcall filter b)
16719 (or (not exclude-tmp)
16720 (not (string-match "tmp" (buffer-name b)))))
16722 nil))
16723 (buffer-list)))))
16725 (defun org-agenda-files (&optional unrestricted archives)
16726 "Get the list of agenda files.
16727 Optional UNRESTRICTED means return the full list even if a restriction
16728 is currently in place.
16729 When ARCHIVES is t, include all archive files that are really being
16730 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16731 `org-agenda-archives-mode' is t."
16732 (let ((files
16733 (cond
16734 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16735 ((stringp org-agenda-files) (org-read-agenda-file-list))
16736 ((listp org-agenda-files) org-agenda-files)
16737 (t (error "Invalid value of `org-agenda-files'")))))
16738 (setq files (apply 'append
16739 (mapcar (lambda (f)
16740 (if (file-directory-p f)
16741 (directory-files
16742 f t org-agenda-file-regexp)
16743 (list f)))
16744 files)))
16745 (when org-agenda-skip-unavailable-files
16746 (setq files (delq nil
16747 (mapcar (function
16748 (lambda (file)
16749 (and (file-readable-p file) file)))
16750 files))))
16751 (when (or (eq archives t)
16752 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16753 (setq files (org-add-archive-files files)))
16754 files))
16756 (defun org-agenda-file-p (&optional file)
16757 "Return non-nil, if FILE is an agenda file.
16758 If FILE is omitted, use the file associated with the current
16759 buffer."
16760 (member (or file (buffer-file-name))
16761 (org-agenda-files t)))
16763 (defun org-edit-agenda-file-list ()
16764 "Edit the list of agenda files.
16765 Depending on setup, this either uses customize to edit the variable
16766 `org-agenda-files', or it visits the file that is holding the list. In the
16767 latter case, the buffer is set up in a way that saving it automatically kills
16768 the buffer and restores the previous window configuration."
16769 (interactive)
16770 (if (stringp org-agenda-files)
16771 (let ((cw (current-window-configuration)))
16772 (find-file org-agenda-files)
16773 (org-set-local 'org-window-configuration cw)
16774 (org-add-hook 'after-save-hook
16775 (lambda ()
16776 (set-window-configuration
16777 (prog1 org-window-configuration
16778 (kill-buffer (current-buffer))))
16779 (org-install-agenda-files-menu)
16780 (message "New agenda file list installed"))
16781 nil 'local)
16782 (message "%s" (substitute-command-keys
16783 "Edit list and finish with \\[save-buffer]")))
16784 (customize-variable 'org-agenda-files)))
16786 (defun org-store-new-agenda-file-list (list)
16787 "Set new value for the agenda file list and save it correctly."
16788 (if (stringp org-agenda-files)
16789 (let ((fe (org-read-agenda-file-list t)) b u)
16790 (while (setq b (find-buffer-visiting org-agenda-files))
16791 (kill-buffer b))
16792 (with-temp-file org-agenda-files
16793 (insert
16794 (mapconcat
16795 (lambda (f) ;; Keep un-expanded entries.
16796 (if (setq u (assoc f fe))
16797 (cdr u)
16799 list "\n")
16800 "\n")))
16801 (let ((org-mode-hook nil) (org-inhibit-startup t)
16802 (org-insert-mode-line-in-empty-file nil))
16803 (setq org-agenda-files list)
16804 (customize-save-variable 'org-agenda-files org-agenda-files))))
16806 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16807 "Read the list of agenda files from a file.
16808 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16809 filenames, used by `org-store-new-agenda-file-list' to write back
16810 un-expanded file names."
16811 (when (file-directory-p org-agenda-files)
16812 (error "`org-agenda-files' cannot be a single directory"))
16813 (when (stringp org-agenda-files)
16814 (with-temp-buffer
16815 (insert-file-contents org-agenda-files)
16816 (mapcar
16817 (lambda (f)
16818 (let ((e (expand-file-name (substitute-in-file-name f)
16819 org-directory)))
16820 (if pair-with-expansion
16821 (cons e f)
16822 e)))
16823 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16825 ;;;###autoload
16826 (defun org-cycle-agenda-files ()
16827 "Cycle through the files in `org-agenda-files'.
16828 If the current buffer visits an agenda file, find the next one in the list.
16829 If the current buffer does not, find the first agenda file."
16830 (interactive)
16831 (let* ((fs (org-agenda-files t))
16832 (files (append fs (list (car fs))))
16833 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16834 file)
16835 (unless files (error "No agenda files"))
16836 (catch 'exit
16837 (while (setq file (pop files))
16838 (if (equal (file-truename file) tcf)
16839 (when (car files)
16840 (find-file (car files))
16841 (throw 'exit t))))
16842 (find-file (car fs)))
16843 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16845 (defun org-agenda-file-to-front (&optional to-end)
16846 "Move/add the current file to the top of the agenda file list.
16847 If the file is not present in the list, it is added to the front. If it is
16848 present, it is moved there. With optional argument TO-END, add/move to the
16849 end of the list."
16850 (interactive "P")
16851 (let ((org-agenda-skip-unavailable-files nil)
16852 (file-alist (mapcar (lambda (x)
16853 (cons (file-truename x) x))
16854 (org-agenda-files t)))
16855 (ctf (file-truename
16856 (or buffer-file-name
16857 (error "Please save the current buffer to a file"))))
16858 x had)
16859 (setq x (assoc ctf file-alist) had x)
16861 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16862 (if to-end
16863 (setq file-alist (append (delq x file-alist) (list x)))
16864 (setq file-alist (cons x (delq x file-alist))))
16865 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16866 (org-install-agenda-files-menu)
16867 (message "File %s to %s of agenda file list"
16868 (if had "moved" "added") (if to-end "end" "front"))))
16870 (defun org-remove-file (&optional file)
16871 "Remove current file from the list of files in variable `org-agenda-files'.
16872 These are the files which are being checked for agenda entries.
16873 Optional argument FILE means use this file instead of the current."
16874 (interactive)
16875 (let* ((org-agenda-skip-unavailable-files nil)
16876 (file (or file buffer-file-name
16877 (error "Current buffer does not visit a file")))
16878 (true-file (file-truename file))
16879 (afile (abbreviate-file-name file))
16880 (files (delq nil (mapcar
16881 (lambda (x)
16882 (if (equal true-file
16883 (file-truename x))
16884 nil x))
16885 (org-agenda-files t)))))
16886 (if (not (= (length files) (length (org-agenda-files t))))
16887 (progn
16888 (org-store-new-agenda-file-list files)
16889 (org-install-agenda-files-menu)
16890 (message "Removed file: %s" afile))
16891 (message "File was not in list: %s (not removed)" afile))))
16893 (defun org-file-menu-entry (file)
16894 (vector file (list 'find-file file) t))
16896 (defun org-check-agenda-file (file)
16897 "Make sure FILE exists. If not, ask user what to do."
16898 (when (not (file-exists-p file))
16899 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16900 (abbreviate-file-name file))
16901 (let ((r (downcase (read-char-exclusive))))
16902 (cond
16903 ((equal r ?r)
16904 (org-remove-file file)
16905 (throw 'nextfile t))
16906 (t (error "Abort"))))))
16908 (defun org-get-agenda-file-buffer (file)
16909 "Get a buffer visiting FILE. If the buffer needs to be created, add
16910 it to the list of buffers which might be released later."
16911 (let ((buf (org-find-base-buffer-visiting file)))
16912 (if buf
16913 buf ; just return it
16914 ;; Make a new buffer and remember it
16915 (setq buf (find-file-noselect file))
16916 (if buf (push buf org-agenda-new-buffers))
16917 buf)))
16919 (defun org-release-buffers (blist)
16920 "Release all buffers in list, asking the user for confirmation when needed.
16921 When a buffer is unmodified, it is just killed. When modified, it is saved
16922 \(if the user agrees) and then killed."
16923 (let (buf file)
16924 (while (setq buf (pop blist))
16925 (setq file (buffer-file-name buf))
16926 (when (and (buffer-modified-p buf)
16927 file
16928 (y-or-n-p (format "Save file %s? " file)))
16929 (with-current-buffer buf (save-buffer)))
16930 (kill-buffer buf))))
16932 (defun org-agenda-prepare-buffers (files)
16933 "Create buffers for all agenda files, protect archived trees and comments."
16934 (interactive)
16935 (let ((pa '(:org-archived t))
16936 (pc '(:org-comment t))
16937 (pall '(:org-archived t :org-comment t))
16938 (inhibit-read-only t)
16939 (rea (concat ":" org-archive-tag ":"))
16940 bmp file re)
16941 (save-excursion
16942 (save-restriction
16943 (while (setq file (pop files))
16944 (catch 'nextfile
16945 (if (bufferp file)
16946 (set-buffer file)
16947 (org-check-agenda-file file)
16948 (set-buffer (org-get-agenda-file-buffer file)))
16949 (widen)
16950 (setq bmp (buffer-modified-p))
16951 (org-refresh-category-properties)
16952 (setq org-todo-keywords-for-agenda
16953 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16954 (setq org-done-keywords-for-agenda
16955 (append org-done-keywords-for-agenda org-done-keywords))
16956 (setq org-todo-keyword-alist-for-agenda
16957 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16958 (setq org-drawers-for-agenda
16959 (append org-drawers-for-agenda org-drawers))
16960 (setq org-tag-alist-for-agenda
16961 (append org-tag-alist-for-agenda org-tag-alist))
16963 (save-excursion
16964 (remove-text-properties (point-min) (point-max) pall)
16965 (when org-agenda-skip-archived-trees
16966 (goto-char (point-min))
16967 (while (re-search-forward rea nil t)
16968 (if (org-at-heading-p t)
16969 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16970 (goto-char (point-min))
16971 (setq re (format org-heading-keyword-regexp-format
16972 org-comment-string))
16973 (while (re-search-forward re nil t)
16974 (add-text-properties
16975 (match-beginning 0) (org-end-of-subtree t) pc)))
16976 (set-buffer-modified-p bmp)))))
16977 (setq org-todo-keywords-for-agenda
16978 (org-uniquify org-todo-keywords-for-agenda))
16979 (setq org-todo-keyword-alist-for-agenda
16980 (org-uniquify org-todo-keyword-alist-for-agenda)
16981 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16983 ;;;; Embedded LaTeX
16985 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16986 "Keymap for the minor `org-cdlatex-mode'.")
16988 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16989 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16990 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16991 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16992 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16994 (defvar org-cdlatex-texmathp-advice-is-done nil
16995 "Flag remembering if we have applied the advice to texmathp already.")
16997 (define-minor-mode org-cdlatex-mode
16998 "Toggle the minor `org-cdlatex-mode'.
16999 This mode supports entering LaTeX environment and math in LaTeX fragments
17000 in Org-mode.
17001 \\{org-cdlatex-mode-map}"
17002 nil " OCDL" nil
17003 (when org-cdlatex-mode
17004 (require 'cdlatex)
17005 (run-hooks 'cdlatex-mode-hook)
17006 (cdlatex-compute-tables))
17007 (unless org-cdlatex-texmathp-advice-is-done
17008 (setq org-cdlatex-texmathp-advice-is-done t)
17009 (defadvice texmathp (around org-math-always-on activate)
17010 "Always return t in org-mode buffers.
17011 This is because we want to insert math symbols without dollars even outside
17012 the LaTeX math segments. If Orgmode thinks that point is actually inside
17013 an embedded LaTeX fragment, let texmathp do its job.
17014 \\[org-cdlatex-mode-map]"
17015 (interactive)
17016 (let (p)
17017 (cond
17018 ((not (derived-mode-p 'org-mode)) ad-do-it)
17019 ((eq this-command 'cdlatex-math-symbol)
17020 (setq ad-return-value t
17021 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17023 (let ((p (org-inside-LaTeX-fragment-p)))
17024 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17025 (setq ad-return-value t
17026 texmathp-why '("Org-mode embedded math" . 0))
17027 (if p ad-do-it)))))))))
17029 (defun turn-on-org-cdlatex ()
17030 "Unconditionally turn on `org-cdlatex-mode'."
17031 (org-cdlatex-mode 1))
17033 (defun org-inside-LaTeX-fragment-p ()
17034 "Test if point is inside a LaTeX fragment.
17035 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17036 sequence appearing also before point.
17037 Even though the matchers for math are configurable, this function assumes
17038 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17039 delimiters are skipped when they have been removed by customization.
17040 The return value is nil, or a cons cell with the delimiter and the
17041 position of this delimiter.
17043 This function does a reasonably good job, but can locally be fooled by
17044 for example currency specifications. For example it will assume being in
17045 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17046 fragments that are properly closed, but during editing, we have to live
17047 with the uncertainty caused by missing closing delimiters. This function
17048 looks only before point, not after."
17049 (catch 'exit
17050 (let ((pos (point))
17051 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17052 (lim (progn
17053 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17054 (point)))
17055 dd-on str (start 0) m re)
17056 (goto-char pos)
17057 (when dodollar
17058 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17059 re (nth 1 (assoc "$" org-latex-regexps)))
17060 (while (string-match re str start)
17061 (cond
17062 ((= (match-end 0) (length str))
17063 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17064 ((= (match-end 0) (- (length str) 5))
17065 (throw 'exit nil))
17066 (t (setq start (match-end 0))))))
17067 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17068 (goto-char pos)
17069 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17070 (and (match-beginning 2) (throw 'exit nil))
17071 ;; count $$
17072 (while (re-search-backward "\\$\\$" lim t)
17073 (setq dd-on (not dd-on)))
17074 (goto-char pos)
17075 (if dd-on (cons "$$" m))))))
17077 (defun org-inside-latex-macro-p ()
17078 "Is point inside a LaTeX macro or its arguments?"
17079 (save-match-data
17080 (org-in-regexp
17081 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17083 (defun org-try-cdlatex-tab ()
17084 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17085 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17086 - inside a LaTeX fragment, or
17087 - after the first word in a line, where an abbreviation expansion could
17088 insert a LaTeX environment."
17089 (when org-cdlatex-mode
17090 (cond
17091 ;; Before any word on the line: No expansion possible.
17092 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17093 ;; Just after first word on the line: Expand it. Make sure it
17094 ;; cannot happen on headlines, though.
17095 ((save-excursion
17096 (skip-chars-backward "a-zA-Z0-9*")
17097 (skip-chars-backward " \t")
17098 (and (bolp) (not (org-at-heading-p))))
17099 (cdlatex-tab) t)
17100 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17102 (defun org-cdlatex-underscore-caret (&optional arg)
17103 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17104 Revert to the normal definition outside of these fragments."
17105 (interactive "P")
17106 (if (org-inside-LaTeX-fragment-p)
17107 (call-interactively 'cdlatex-sub-superscript)
17108 (let (org-cdlatex-mode)
17109 (call-interactively (key-binding (vector last-input-event))))))
17111 (defun org-cdlatex-math-modify (&optional arg)
17112 "Execute `cdlatex-math-modify' in LaTeX fragments.
17113 Revert to the normal definition outside of these fragments."
17114 (interactive "P")
17115 (if (org-inside-LaTeX-fragment-p)
17116 (call-interactively 'cdlatex-math-modify)
17117 (let (org-cdlatex-mode)
17118 (call-interactively (key-binding (vector last-input-event))))))
17120 (defvar org-latex-fragment-image-overlays nil
17121 "List of overlays carrying the images of latex fragments.")
17122 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17124 (defun org-remove-latex-fragment-image-overlays ()
17125 "Remove all overlays with LaTeX fragment images in current buffer."
17126 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17127 (setq org-latex-fragment-image-overlays nil))
17129 (defun org-preview-latex-fragment (&optional subtree)
17130 "Preview the LaTeX fragment at point, or all locally or globally.
17131 If the cursor is in a LaTeX fragment, create the image and overlay
17132 it over the source code. If there is no fragment at point, display
17133 all fragments in the current text, from one headline to the next. With
17134 prefix SUBTREE, display all fragments in the current subtree. With a
17135 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17136 the cursor is before the first headline,
17137 display all fragments in the buffer.
17138 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17139 (interactive "P")
17140 (unless buffer-file-name
17141 (error "Can't preview LaTeX fragment in a non-file buffer"))
17142 (org-remove-latex-fragment-image-overlays)
17143 (save-excursion
17144 (save-restriction
17145 (let (beg end at msg)
17146 (cond
17147 ((or (equal subtree '(16))
17148 (not (save-excursion
17149 (re-search-backward org-outline-regexp-bol nil t))))
17150 (setq beg (point-min) end (point-max)
17151 msg "Creating images for buffer...%s"))
17152 ((equal subtree '(4))
17153 (org-back-to-heading)
17154 (setq beg (point) end (org-end-of-subtree t)
17155 msg "Creating images for subtree...%s"))
17157 (if (setq at (org-inside-LaTeX-fragment-p))
17158 (goto-char (max (point-min) (- (cdr at) 2)))
17159 (org-back-to-heading))
17160 (setq beg (point) end (progn (outline-next-heading) (point))
17161 msg (if at "Creating image...%s"
17162 "Creating images for entry...%s"))))
17163 (message msg "")
17164 (narrow-to-region beg end)
17165 (goto-char beg)
17166 (org-format-latex
17167 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17168 (file-name-nondirectory
17169 buffer-file-name)))
17170 default-directory 'overlays msg at 'forbuffer
17171 org-latex-create-formula-image-program)
17172 (message msg "done. Use `C-c C-c' to remove images.")))))
17174 (defvar org-latex-regexps
17175 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17176 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17177 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17178 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17179 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17180 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17181 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17182 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17183 "Regular expressions for matching embedded LaTeX.")
17185 (defvar org-export-have-math nil) ;; dynamic scoping
17186 (defun org-format-latex (prefix &optional dir overlays msg at
17187 forbuffer processing-type)
17188 "Replace LaTeX fragments with links to an image, and produce images.
17189 Some of the options can be changed using the variable
17190 `org-format-latex-options'."
17191 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17192 (let* ((prefixnodir (file-name-nondirectory prefix))
17193 (absprefix (expand-file-name prefix dir))
17194 (todir (file-name-directory absprefix))
17195 (opt org-format-latex-options)
17196 (matchers (plist-get opt :matchers))
17197 (re-list org-latex-regexps)
17198 (org-format-latex-header-extra
17199 (plist-get (org-infile-export-plist) :latex-header-extra))
17200 (cnt 0) txt hash link beg end re e checkdir
17201 executables-checked string
17202 m n block-type block linkfile movefile ov)
17203 ;; Check the different regular expressions
17204 (while (setq e (pop re-list))
17205 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17206 block (if block-type "\n\n" ""))
17207 (when (member m matchers)
17208 (goto-char (point-min))
17209 (while (re-search-forward re nil t)
17210 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17211 (not (get-text-property (match-beginning n)
17212 'org-protected))
17213 (or (not overlays)
17214 (not (eq (get-char-property (match-beginning n)
17215 'org-overlay-type)
17216 'org-latex-overlay))))
17217 (setq org-export-have-math t)
17218 (cond
17219 ((eq processing-type 'verbatim)
17220 ;; Leave the text verbatim, just protect it
17221 (add-text-properties (match-beginning n) (match-end n)
17222 '(org-protected t)))
17223 ((eq processing-type 'mathjax)
17224 ;; Prepare for MathJax processing
17225 (setq string (match-string n))
17226 (if (member m '("$" "$1"))
17227 (save-excursion
17228 (delete-region (match-beginning n) (match-end n))
17229 (goto-char (match-beginning n))
17230 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17231 "\\)")
17232 '(org-protected t))))
17233 (add-text-properties (match-beginning n) (match-end n)
17234 '(org-protected t))))
17235 ((or (eq processing-type 'dvipng)
17236 (eq processing-type 'imagemagick))
17237 ;; Process to an image
17238 (setq txt (match-string n)
17239 beg (match-beginning n) end (match-end n)
17240 cnt (1+ cnt))
17241 (let (print-length print-level) ; make sure full list is printed
17242 (setq hash (sha1 (prin1-to-string
17243 (list org-format-latex-header
17244 org-format-latex-header-extra
17245 org-export-latex-default-packages-alist
17246 org-export-latex-packages-alist
17247 org-format-latex-options
17248 forbuffer txt)))
17249 linkfile (format "%s_%s.png" prefix hash)
17250 movefile (format "%s_%s.png" absprefix hash)))
17251 (setq link (concat block "[[file:" linkfile "]]" block))
17252 (if msg (message msg cnt))
17253 (goto-char beg)
17254 (unless checkdir ; make sure the directory exists
17255 (setq checkdir t)
17256 (or (file-directory-p todir) (make-directory todir t)))
17257 (cond
17258 ((eq processing-type 'dvipng)
17259 (unless executables-checked
17260 (org-check-external-command
17261 "latex" "needed to convert LaTeX fragments to images")
17262 (org-check-external-command
17263 "dvipng" "needed to convert LaTeX fragments to images")
17264 (setq executables-checked t))
17265 (unless (file-exists-p movefile)
17266 (org-create-formula-image-with-dvipng
17267 txt movefile opt forbuffer)))
17268 ((eq processing-type 'imagemagick)
17269 (unless executables-checked
17270 (org-check-external-command
17271 "convert" "you need to install imagemagick")
17272 (setq executables-checked t))
17273 (unless (file-exists-p movefile)
17274 (org-create-formula-image-with-imagemagick
17275 txt movefile opt forbuffer))))
17276 (if overlays
17277 (progn
17278 (mapc (lambda (o)
17279 (if (eq (overlay-get o 'org-overlay-type)
17280 'org-latex-overlay)
17281 (delete-overlay o)))
17282 (overlays-in beg end))
17283 (setq ov (make-overlay beg end))
17284 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17285 (if (featurep 'xemacs)
17286 (progn
17287 (overlay-put ov 'invisible t)
17288 (overlay-put
17289 ov 'end-glyph
17290 (make-glyph (vector 'png :file movefile))))
17291 (overlay-put
17292 ov 'display
17293 (list 'image :type 'png :file movefile :ascent 'center)))
17294 (push ov org-latex-fragment-image-overlays)
17295 (goto-char end))
17296 (delete-region beg end)
17297 (insert (org-add-props link
17298 (list 'org-latex-src
17299 (replace-regexp-in-string
17300 "\"" "" txt)
17301 'org-latex-src-embed-type
17302 (if block-type 'paragraph 'character))))))
17303 ((eq processing-type 'mathml)
17304 ;; Process to MathML
17305 (unless executables-checked
17306 (unless (save-match-data (org-format-latex-mathml-available-p))
17307 (error "LaTeX to MathML converter not configured"))
17308 (setq executables-checked t))
17309 (setq txt (match-string n)
17310 beg (match-beginning n) end (match-end n)
17311 cnt (1+ cnt))
17312 (if msg (message msg cnt))
17313 (goto-char beg)
17314 (delete-region beg end)
17315 (insert (org-format-latex-as-mathml
17316 txt block-type prefix dir)))
17318 (error "Unknown conversion type %s for latex fragments"
17319 processing-type)))))))))
17321 (defun org-create-math-formula (latex-frag &optional mathml-file)
17322 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17323 Use `org-latex-to-mathml-convert-command'. If the conversion is
17324 sucessful, return the portion between \"<math...> </math>\"
17325 elements otherwise return nil. When MATHML-FILE is specified,
17326 write the results in to that file. When invoked as an
17327 interactive command, prompt for LATEX-FRAG, with initial value
17328 set to the current active region and echo the results for user
17329 inspection."
17330 (interactive (list (let ((frag (when (org-region-active-p)
17331 (buffer-substring-no-properties
17332 (region-beginning) (region-end)))))
17333 (read-string "LaTeX Fragment: " frag nil frag))))
17334 (unless latex-frag (error "Invalid latex-frag"))
17335 (let* ((tmp-in-file (file-relative-name
17336 (make-temp-name (expand-file-name "ltxmathml-in"))))
17337 (ignore (write-region latex-frag nil tmp-in-file))
17338 (tmp-out-file (file-relative-name
17339 (make-temp-name (expand-file-name "ltxmathml-out"))))
17340 (cmd (format-spec
17341 org-latex-to-mathml-convert-command
17342 `((?j . ,(shell-quote-argument
17343 (expand-file-name org-latex-to-mathml-jar-file)))
17344 (?I . ,(shell-quote-argument tmp-in-file))
17345 (?o . ,(shell-quote-argument tmp-out-file)))))
17346 mathml shell-command-output)
17347 (when (org-called-interactively-p 'any)
17348 (unless (org-format-latex-mathml-available-p)
17349 (error "LaTeX to MathML converter not configured")))
17350 (message "Running %s" cmd)
17351 (setq shell-command-output (shell-command-to-string cmd))
17352 (setq mathml
17353 (when (file-readable-p tmp-out-file)
17354 (with-current-buffer (find-file-noselect tmp-out-file t)
17355 (goto-char (point-min))
17356 (when (re-search-forward
17357 (concat
17358 (regexp-quote
17359 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17360 "\\(.\\|\n\\)*"
17361 (regexp-quote "</math>")) nil t)
17362 (prog1 (match-string 0) (kill-buffer))))))
17363 (cond
17364 (mathml
17365 (setq mathml
17366 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17367 (when mathml-file
17368 (write-region mathml nil mathml-file))
17369 (when (org-called-interactively-p 'any)
17370 (message mathml)))
17371 ((message "LaTeX to MathML conversion failed")
17372 (message shell-command-output)))
17373 (delete-file tmp-in-file)
17374 (when (file-exists-p tmp-out-file)
17375 (delete-file tmp-out-file))
17376 mathml))
17378 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17379 prefix &optional dir)
17380 "Use `org-create-math-formula' but check local cache first."
17381 (let* ((absprefix (expand-file-name prefix dir))
17382 (print-length nil) (print-level nil)
17383 (formula-id (concat
17384 "formula-"
17385 (sha1
17386 (prin1-to-string
17387 (list latex-frag
17388 org-latex-to-mathml-convert-command)))))
17389 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17390 (formula-cache-dir (file-name-directory formula-cache)))
17392 (unless (file-directory-p formula-cache-dir)
17393 (make-directory formula-cache-dir t))
17395 (unless (file-exists-p formula-cache)
17396 (org-create-math-formula latex-frag formula-cache))
17398 (if (file-exists-p formula-cache)
17399 ;; Successful conversion. Return the link to MathML file.
17400 (org-add-props
17401 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17402 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17403 'org-latex-src-embed-type (if latex-frag-type
17404 'paragraph 'character)))
17405 ;; Failed conversion. Return the LaTeX fragment verbatim
17406 (add-text-properties
17407 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17408 latex-frag)))
17410 ;; This function borrows from Ganesh Swami's latex2png.el
17411 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17412 "This calls dvipng."
17413 (require 'org-latex)
17414 (let* ((tmpdir (if (featurep 'xemacs)
17415 (temp-directory)
17416 temporary-file-directory))
17417 (texfilebase (make-temp-name
17418 (expand-file-name "orgtex" tmpdir)))
17419 (texfile (concat texfilebase ".tex"))
17420 (dvifile (concat texfilebase ".dvi"))
17421 (pngfile (concat texfilebase ".png"))
17422 (fnh (if (featurep 'xemacs)
17423 (font-height (face-font 'default))
17424 (face-attribute 'default :height nil)))
17425 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17426 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17427 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17428 "Black"))
17429 (bg (or (plist-get options (if buffer :background :html-background))
17430 "Transparent")))
17431 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17432 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17433 (with-temp-file texfile
17434 (insert (org-splice-latex-header
17435 org-format-latex-header
17436 org-export-latex-default-packages-alist
17437 org-export-latex-packages-alist t
17438 org-format-latex-header-extra))
17439 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17440 (require 'org-latex)
17441 (org-export-latex-fix-inputenc))
17442 (let ((dir default-directory))
17443 (condition-case nil
17444 (progn
17445 (cd tmpdir)
17446 (call-process "latex" nil nil nil texfile))
17447 (error nil))
17448 (cd dir))
17449 (if (not (file-exists-p dvifile))
17450 (progn (message "Failed to create dvi file from %s" texfile) nil)
17451 (condition-case nil
17452 (if (featurep 'xemacs)
17453 (call-process "dvipng" nil nil nil
17454 "-fg" fg "-bg" bg
17455 "-T" "tight"
17456 "-o" pngfile
17457 dvifile)
17458 (call-process "dvipng" nil nil nil
17459 "-fg" fg "-bg" bg
17460 "-D" dpi
17461 ;;"-x" scale "-y" scale
17462 "-T" "tight"
17463 "-o" pngfile
17464 dvifile))
17465 (error nil))
17466 (if (not (file-exists-p pngfile))
17467 (if org-format-latex-signal-error
17468 (error "Failed to create png file from %s" texfile)
17469 (message "Failed to create png file from %s" texfile)
17470 nil)
17471 ;; Use the requested file name and clean up
17472 (copy-file pngfile tofile 'replace)
17473 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17474 (if (file-exists-p (concat texfilebase e))
17475 (delete-file (concat texfilebase e))))
17476 pngfile))))
17478 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17479 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17480 "This calls convert, which is included into imagemagick."
17481 (require 'org-latex)
17482 (let* ((tmpdir (if (featurep 'xemacs)
17483 (temp-directory)
17484 temporary-file-directory))
17485 (texfilebase (make-temp-name
17486 (expand-file-name "orgtex" tmpdir)))
17487 (texfile (concat texfilebase ".tex"))
17488 (pdffile (concat texfilebase ".pdf"))
17489 (pngfile (concat texfilebase ".png"))
17490 (fnh (if (featurep 'xemacs)
17491 (font-height (face-font 'default))
17492 (face-attribute 'default :height nil)))
17493 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17494 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17495 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17496 "black"))
17497 (bg (or (plist-get options (if buffer :background :html-background))
17498 "white")))
17499 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17500 (setq fg (org-latex-color-format fg)))
17501 (if (eq bg 'default) (setq bg (org-latex-color :background))
17502 (setq bg (org-latex-color-format
17503 (if (string= bg "Transparent")(setq bg "white")))))
17504 (with-temp-file texfile
17505 (insert (org-splice-latex-header
17506 org-format-latex-header
17507 org-export-latex-default-packages-alist
17508 org-export-latex-packages-alist t
17509 org-format-latex-header-extra))
17510 (insert "\n\\begin{document}\n"
17511 "\\definecolor{fg}{rgb}{" fg "}\n"
17512 "\\definecolor{bg}{rgb}{" bg "}\n"
17513 "\n\\pagecolor{bg}\n"
17514 "\n{\\color{fg}\n"
17515 string
17516 "\n}\n"
17517 "\n\\end{document}\n" )
17518 (require 'org-latex)
17519 (org-export-latex-fix-inputenc))
17520 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17521 (condition-case nil
17522 (progn
17523 (cd tmpdir)
17524 (setq cmds org-latex-to-pdf-process)
17525 (while cmds
17526 (setq latex-frags-cmds (pop cmds))
17527 (if (listp latex-frags-cmds)
17528 (setq cmds nil)
17529 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17530 (while latex-frags-cmds
17531 (setq cmd (pop latex-frags-cmds))
17532 (while (string-match "%b" cmd)
17533 (setq cmd (replace-match
17534 (save-match-data
17535 (shell-quote-argument texfile))
17536 t t cmd)))
17537 (while (string-match "%f" cmd)
17538 (setq cmd (replace-match
17539 (save-match-data
17540 (shell-quote-argument (file-name-nondirectory texfile)))
17541 t t cmd)))
17542 (while (string-match "%o" cmd)
17543 (setq cmd (replace-match
17544 (save-match-data
17545 (shell-quote-argument (file-name-directory texfile)))
17546 t t cmd)))
17547 (setq cmd (split-string cmd))
17548 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17549 (error nil))
17550 (cd dir))
17551 (if (not (file-exists-p pdffile))
17552 (progn (message "Failed to create pdf file from %s" texfile) nil)
17553 (condition-case nil
17554 (if (featurep 'xemacs)
17555 (call-process "convert" nil nil nil
17556 "-density" "96"
17557 "-trim"
17558 "-antialias"
17559 pdffile
17560 "-quality" "100"
17561 ;; "-sharpen" "0x1.0"
17562 pngfile)
17563 (call-process "convert" nil nil nil
17564 "-density" dpi
17565 "-trim"
17566 "-antialias"
17567 pdffile
17568 "-quality" "100"
17569 ; "-sharpen" "0x1.0"
17570 pngfile))
17571 (error nil))
17572 (if (not (file-exists-p pngfile))
17573 (if org-format-latex-signal-error
17574 (error "Failed to create png file from %s" texfile)
17575 (message "Failed to create png file from %s" texfile)
17576 nil)
17577 ;; Use the requested file name and clean up
17578 (copy-file pngfile tofile 'replace)
17579 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17580 (if (file-exists-p (concat texfilebase e))
17581 (delete-file (concat texfilebase e))))
17582 pngfile))))
17584 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17585 "Fill a LaTeX header template TPL.
17586 In the template, the following place holders will be recognized:
17588 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17589 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17590 [PACKAGES] \\usepackage statements for PKG
17591 [NO-PACKAGES] do not include PKG
17592 [EXTRA] the string EXTRA
17593 [NO-EXTRA] do not include EXTRA
17595 For backward compatibility, if both the positive and the negative place
17596 holder is missing, the positive one (without the \"NO-\") will be
17597 assumed to be present at the end of the template.
17598 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17599 EXTRA is a string.
17600 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17601 (let (rpl (end ""))
17602 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17603 (setq rpl (if (or (match-end 1) (not def-pkg))
17604 "" (org-latex-packages-to-string def-pkg snippets-p t))
17605 tpl (replace-match rpl t t tpl))
17606 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17608 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17609 (setq rpl (if (or (match-end 1) (not pkg))
17610 "" (org-latex-packages-to-string pkg snippets-p t))
17611 tpl (replace-match rpl t t tpl))
17612 (if pkg (setq end
17613 (concat end "\n"
17614 (org-latex-packages-to-string pkg snippets-p)))))
17616 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17617 (setq rpl (if (or (match-end 1) (not extra))
17618 "" (concat extra "\n"))
17619 tpl (replace-match rpl t t tpl))
17620 (if (and extra (string-match "\\S-" extra))
17621 (setq end (concat end "\n" extra))))
17623 (if (string-match "\\S-" end)
17624 (concat tpl "\n" end)
17625 tpl)))
17627 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17628 "Turn an alist of packages into a string with the \\usepackage macros."
17629 (setq pkg (mapconcat (lambda(p)
17630 (cond
17631 ((stringp p) p)
17632 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17633 (format "%% Package %s omitted" (cadr p)))
17634 ((equal "" (car p))
17635 (format "\\usepackage{%s}" (cadr p)))
17637 (format "\\usepackage[%s]{%s}"
17638 (car p) (cadr p)))))
17640 "\n"))
17641 (if newline (concat pkg "\n") pkg))
17643 (defun org-dvipng-color (attr)
17644 "Return a RGB color specification for dvipng."
17645 (apply 'format "rgb %s %s %s"
17646 (mapcar 'org-normalize-color
17647 (if (featurep 'xemacs)
17648 (color-rgb-components
17649 (face-property 'default
17650 (cond ((eq attr :foreground) 'foreground)
17651 ((eq attr :background) 'background))))
17652 (color-values (face-attribute 'default attr nil))))))
17654 (defun org-latex-color (attr)
17655 "Return a RGB color for the LaTeX color package."
17656 (apply 'format "%s,%s,%s"
17657 (mapcar 'org-normalize-color
17658 (if (featurep 'xemacs)
17659 (color-rgb-components
17660 (face-property 'default
17661 (cond ((eq attr :foreground) 'foreground)
17662 ((eq attr :background) 'background))))
17663 (color-values (face-attribute 'default attr nil))))))
17665 (defun org-latex-color-format (color-name)
17666 "Convert COLOR-NAME to a RGB color value."
17667 (apply 'format "%s,%s,%s"
17668 (mapcar 'org-normalize-color
17669 (color-values color-name))))
17671 (defun org-normalize-color (value)
17672 "Return string to be used as color value for an RGB component."
17673 (format "%g" (/ value 65535.0)))
17675 ;; Image display
17678 (defvar org-inline-image-overlays nil)
17679 (make-variable-buffer-local 'org-inline-image-overlays)
17681 (defun org-toggle-inline-images (&optional include-linked)
17682 "Toggle the display of inline images.
17683 INCLUDE-LINKED is passed to `org-display-inline-images'."
17684 (interactive "P")
17685 (if org-inline-image-overlays
17686 (progn
17687 (org-remove-inline-images)
17688 (message "Inline image display turned off"))
17689 (org-display-inline-images include-linked)
17690 (if org-inline-image-overlays
17691 (message "%d images displayed inline"
17692 (length org-inline-image-overlays))
17693 (message "No images to display inline"))))
17695 (defun org-redisplay-inline-images ()
17696 "Refresh the display of inline images."
17697 (interactive)
17698 (if (not org-inline-image-overlays)
17699 (org-toggle-inline-images)
17700 (org-toggle-inline-images)
17701 (org-toggle-inline-images)))
17703 (defun org-display-inline-images (&optional include-linked refresh beg end)
17704 "Display inline images.
17705 Normally only links without a description part are inlined, because this
17706 is how it will work for export. When INCLUDE-LINKED is set, also links
17707 with a description part will be inlined. This can be nice for a quick
17708 look at those images, but it does not reflect what exported files will look
17709 like.
17710 When REFRESH is set, refresh existing images between BEG and END.
17711 This will create new image displays only if necessary.
17712 BEG and END default to the buffer boundaries."
17713 (interactive "P")
17714 (unless refresh
17715 (org-remove-inline-images)
17716 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17717 (save-excursion
17718 (save-restriction
17719 (widen)
17720 (setq beg (or beg (point-min)) end (or end (point-max)))
17721 (goto-char beg)
17722 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17723 (substring (org-image-file-name-regexp) 0 -2)
17724 "\\)\\]" (if include-linked "" "\\]")))
17725 old file ov img)
17726 (while (re-search-forward re end t)
17727 (setq old (get-char-property-and-overlay (match-beginning 1)
17728 'org-image-overlay))
17729 (setq file (expand-file-name
17730 (concat (or (match-string 3) "") (match-string 4))))
17731 (when (file-exists-p file)
17732 (if (and (car-safe old) refresh)
17733 (image-refresh (overlay-get (cdr old) 'display))
17734 (setq img (save-match-data (create-image file)))
17735 (when img
17736 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17737 (overlay-put ov 'display img)
17738 (overlay-put ov 'face 'default)
17739 (overlay-put ov 'org-image-overlay t)
17740 (overlay-put ov 'modification-hooks
17741 (list 'org-display-inline-remove-overlay))
17742 (push ov org-inline-image-overlays)))))))))
17744 (define-obsolete-function-alias
17745 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17747 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17748 "Remove inline-display overlay if a corresponding region is modified."
17749 (let ((inhibit-modification-hooks t))
17750 (when (and ov after)
17751 (delete ov org-inline-image-overlays)
17752 (delete-overlay ov))))
17754 (defun org-remove-inline-images ()
17755 "Remove inline display of images."
17756 (interactive)
17757 (mapc 'delete-overlay org-inline-image-overlays)
17758 (setq org-inline-image-overlays nil))
17760 ;;;; Key bindings
17762 ;; Outline functions from `outline-mode-prefix-map'
17763 ;; that can be remapped in Org:
17764 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17765 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17766 (define-key org-mode-map [remap outline-forward-same-level]
17767 'org-forward-heading-same-level)
17768 (define-key org-mode-map [remap outline-backward-same-level]
17769 'org-backward-heading-same-level)
17770 (define-key org-mode-map [remap show-branches]
17771 'org-kill-note-or-show-branches)
17772 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17773 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17774 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17776 ;; Outline functions from `outline-mode-prefix-map' that can not
17777 ;; be remapped in Org:
17779 ;; - the column "key binding" shows whether the Outline function is still
17780 ;; available in Org mode on the same key that it has been bound to in
17781 ;; Outline mode:
17782 ;; - "overridden": key used for a different functionality in Org mode
17783 ;; - else: key still bound to the same Outline function in Org mode
17785 ;; | Outline function | key binding | Org replacement |
17786 ;; |------------------------------------+-------------+-----------------------|
17787 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17788 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17789 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17790 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17791 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17792 ;; | `show-entry' | overridden | no replacement |
17793 ;; | `show-children' | `C-c C-i' | visibility cycling |
17794 ;; | `show-branches' | `C-c C-k' | still same function |
17795 ;; | `show-subtree' | overridden | visibility cycling |
17796 ;; | `show-all' | overridden | no replacement |
17797 ;; | `hide-subtree' | overridden | visibility cycling |
17798 ;; | `hide-body' | overridden | no replacement |
17799 ;; | `hide-entry' | overridden | visibility cycling |
17800 ;; | `hide-leaves' | overridden | no replacement |
17801 ;; | `hide-sublevels' | overridden | no replacement |
17802 ;; | `hide-other' | overridden | no replacement |
17804 ;; Make `C-c C-x' a prefix key
17805 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17807 ;; TAB key with modifiers
17808 (org-defkey org-mode-map "\C-i" 'org-cycle)
17809 (org-defkey org-mode-map [(tab)] 'org-cycle)
17810 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17811 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17812 ;; The following line is necessary under Suse GNU/Linux
17813 (unless (featurep 'xemacs)
17814 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17815 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17816 (define-key org-mode-map [backtab] 'org-shifttab)
17818 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17819 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17820 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17822 ;; Cursor keys with modifiers
17823 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17824 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17825 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17826 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17828 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17829 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17830 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17831 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17833 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17834 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17835 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17836 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17838 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17839 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17840 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17841 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17843 ;; Babel keys
17844 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17845 (mapc (lambda (pair)
17846 (define-key org-babel-map (car pair) (cdr pair)))
17847 org-babel-key-bindings)
17849 ;;; Extra keys for tty access.
17850 ;; We only set them when really needed because otherwise the
17851 ;; menus don't show the simple keys
17853 (when (or org-use-extra-keys
17854 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17855 (not window-system))
17856 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17857 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17858 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17859 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17860 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17861 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17862 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17863 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17864 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17865 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17866 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17867 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17868 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17869 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17870 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17871 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17872 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17873 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17874 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17875 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17876 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17877 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17878 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17879 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17880 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17881 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17882 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17883 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17885 ;; All the other keys
17887 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17888 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17889 (if (boundp 'narrow-map)
17890 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17891 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17892 (if (boundp 'narrow-map)
17893 (org-defkey narrow-map "b" 'org-narrow-to-block)
17894 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17895 (if (boundp 'narrow-map)
17896 (org-defkey narrow-map "e" 'org-narrow-to-element)
17897 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17898 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17899 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17900 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17901 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17902 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17903 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17904 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17905 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17906 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17907 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17908 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17909 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17910 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17911 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17912 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17913 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17914 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17915 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17916 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17917 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17918 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17919 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17920 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17921 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17922 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17923 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17924 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17925 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17926 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17927 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17928 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17929 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17930 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17931 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17932 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17933 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17934 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17935 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17936 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17937 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17938 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17939 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17940 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17941 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17942 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17943 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17944 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17945 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17946 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17947 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17948 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17949 (org-defkey org-mode-map "\C-c^" 'org-sort)
17950 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17951 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17952 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17953 (org-defkey org-mode-map "\C-m" 'org-return)
17954 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17955 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17956 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17957 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17958 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17959 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17960 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17961 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17962 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17963 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17964 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17965 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17966 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17967 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17968 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17969 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17970 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17971 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17972 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17973 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17974 (org-defkey org-mode-map "\M-h" 'org-mark-element)
17975 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17976 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17978 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17979 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17980 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17982 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17983 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17984 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
17985 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
17986 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17987 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17988 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
17989 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17990 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17991 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17992 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17993 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17994 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
17995 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17996 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17997 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17998 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17999 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18000 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18001 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18002 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18003 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18005 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18006 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18007 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18008 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18009 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18011 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18013 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18015 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18016 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18018 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18021 (when (featurep 'xemacs)
18022 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18025 (defconst org-speed-commands-default
18027 ("Outline Navigation")
18028 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18029 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18030 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18031 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18032 ("u" . (org-speed-move-safe 'outline-up-heading))
18033 ("j" . org-goto)
18034 ("g" . (org-refile t))
18035 ("Outline Visibility")
18036 ("c" . org-cycle)
18037 ("C" . org-shifttab)
18038 (" " . org-display-outline-path)
18039 (":" . org-columns)
18040 ("Outline Structure Editing")
18041 ("U" . org-shiftmetaup)
18042 ("D" . org-shiftmetadown)
18043 ("r" . org-metaright)
18044 ("l" . org-metaleft)
18045 ("R" . org-shiftmetaright)
18046 ("L" . org-shiftmetaleft)
18047 ("i" . (progn (forward-char 1) (call-interactively
18048 'org-insert-heading-respect-content)))
18049 ("^" . org-sort)
18050 ("w" . org-refile)
18051 ("a" . org-archive-subtree-default-with-confirmation)
18052 ("." . org-mark-subtree)
18053 ("#" . org-toggle-comment)
18054 ("Clock Commands")
18055 ("I" . org-clock-in)
18056 ("O" . org-clock-out)
18057 ("Meta Data Editing")
18058 ("t" . org-todo)
18059 ("," . (org-priority))
18060 ("0" . (org-priority ?\ ))
18061 ("1" . (org-priority ?A))
18062 ("2" . (org-priority ?B))
18063 ("3" . (org-priority ?C))
18064 (";" . org-set-tags-command)
18065 ("e" . org-set-effort)
18066 ("E" . org-inc-effort)
18067 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18068 (org-entry-put (point) "APPT_WARNTIME" m)))
18069 ("Agenda Views etc")
18070 ("v" . org-agenda)
18071 ("/" . org-sparse-tree)
18072 ("Misc")
18073 ("o" . org-open-at-point)
18074 ("?" . org-speed-command-help)
18075 ("<" . (org-agenda-set-restriction-lock 'subtree))
18076 (">" . (org-agenda-remove-restriction-lock))
18078 "The default speed commands.")
18080 (defun org-print-speed-command (e)
18081 (if (> (length (car e)) 1)
18082 (progn
18083 (princ "\n")
18084 (princ (car e))
18085 (princ "\n")
18086 (princ (make-string (length (car e)) ?-))
18087 (princ "\n"))
18088 (princ (car e))
18089 (princ " ")
18090 (if (symbolp (cdr e))
18091 (princ (symbol-name (cdr e)))
18092 (prin1 (cdr e)))
18093 (princ "\n")))
18095 (defun org-speed-command-help ()
18096 "Show the available speed commands."
18097 (interactive)
18098 (if (not org-use-speed-commands)
18099 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18100 (with-output-to-temp-buffer "*Help*"
18101 (princ "User-defined Speed commands\n===========================\n")
18102 (mapc 'org-print-speed-command org-speed-commands-user)
18103 (princ "\n")
18104 (princ "Built-in Speed commands\n=======================\n")
18105 (mapc 'org-print-speed-command org-speed-commands-default))
18106 (with-current-buffer "*Help*"
18107 (setq truncate-lines t))))
18109 (defun org-speed-move-safe (cmd)
18110 "Execute CMD, but make sure that the cursor always ends up in a headline.
18111 If not, return to the original position and throw an error."
18112 (interactive)
18113 (let ((pos (point)))
18114 (call-interactively cmd)
18115 (unless (and (bolp) (org-at-heading-p))
18116 (goto-char pos)
18117 (error "Boundary reached while executing %s" cmd))))
18119 (defvar org-self-insert-command-undo-counter 0)
18121 (defvar org-table-auto-blank-field) ; defined in org-table.el
18122 (defvar org-speed-command nil)
18124 (define-obsolete-function-alias
18125 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18127 (defun org-speed-command-activate (keys)
18128 "Hook for activating single-letter speed commands.
18129 `org-speed-commands-default' specifies a minimal command set.
18130 Use `org-speed-commands-user' for further customization."
18131 (when (or (and (bolp) (looking-at org-outline-regexp))
18132 (and (functionp org-use-speed-commands)
18133 (funcall org-use-speed-commands)))
18134 (cdr (assoc keys (append org-speed-commands-user
18135 org-speed-commands-default)))))
18137 (define-obsolete-function-alias
18138 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18140 (defun org-babel-speed-command-activate (keys)
18141 "Hook for activating single-letter code block commands."
18142 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18143 (cdr (assoc keys org-babel-key-bindings))))
18145 (defcustom org-speed-command-hook
18146 '(org-speed-command-default-hook org-babel-speed-command-hook)
18147 "Hook for activating speed commands at strategic locations.
18148 Hook functions are called in sequence until a valid handler is
18149 found.
18151 Each hook takes a single argument, a user-pressed command key
18152 which is also a `self-insert-command' from the global map.
18154 Within the hook, examine the cursor position and the command key
18155 and return nil or a valid handler as appropriate. Handler could
18156 be one of an interactive command, a function, or a form.
18158 Set `org-use-speed-commands' to non-nil value to enable this
18159 hook. The default setting is `org-speed-command-activate'."
18160 :group 'org-structure
18161 :version "24.1"
18162 :type 'hook)
18164 (defun org-self-insert-command (N)
18165 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18166 If the cursor is in a table looking at whitespace, the whitespace is
18167 overwritten, and the table is not marked as requiring realignment."
18168 (interactive "p")
18169 (org-check-before-invisible-edit 'insert)
18170 (cond
18171 ((and org-use-speed-commands
18172 (setq org-speed-command
18173 (run-hook-with-args-until-success
18174 'org-speed-command-hook (this-command-keys))))
18175 (cond
18176 ((commandp org-speed-command)
18177 (setq this-command org-speed-command)
18178 (call-interactively org-speed-command))
18179 ((functionp org-speed-command)
18180 (funcall org-speed-command))
18181 ((and org-speed-command (listp org-speed-command))
18182 (eval org-speed-command))
18183 (t (let (org-use-speed-commands)
18184 (call-interactively 'org-self-insert-command)))))
18185 ((and
18186 (org-table-p)
18187 (progn
18188 ;; check if we blank the field, and if that triggers align
18189 (and (featurep 'org-table) org-table-auto-blank-field
18190 (member last-command
18191 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18192 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18193 ;; got extra space, this field does not determine column width
18194 (let (org-table-may-need-update) (org-table-blank-field))
18195 ;; no extra space, this field may determine column width
18196 (org-table-blank-field)))
18198 (eq N 1)
18199 (looking-at "[^|\n]* |"))
18200 (let (org-table-may-need-update)
18201 (goto-char (1- (match-end 0)))
18202 (backward-delete-char 1)
18203 (goto-char (match-beginning 0))
18204 (self-insert-command N)))
18206 (setq org-table-may-need-update t)
18207 (self-insert-command N)
18208 (org-fix-tags-on-the-fly)
18209 (if org-self-insert-cluster-for-undo
18210 (if (not (eq last-command 'org-self-insert-command))
18211 (setq org-self-insert-command-undo-counter 1)
18212 (if (>= org-self-insert-command-undo-counter 20)
18213 (setq org-self-insert-command-undo-counter 1)
18214 (and (> org-self-insert-command-undo-counter 0)
18215 buffer-undo-list (listp buffer-undo-list)
18216 (not (cadr buffer-undo-list)) ; remove nil entry
18217 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18218 (setq org-self-insert-command-undo-counter
18219 (1+ org-self-insert-command-undo-counter))))))))
18221 (defun org-check-before-invisible-edit (kind)
18222 "Check is editing if kind KIND would be dangerous with invisible text around.
18223 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18224 ;; First, try to get out of here as quickly as possible, to reduce overhead
18225 (if (and org-catch-invisible-edits
18226 (or (not (boundp 'visible-mode)) (not visible-mode))
18227 (or (get-char-property (point) 'invisible)
18228 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18229 ;; OK, we need to take a closer look
18230 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18231 (invisible-before-point (if (bobp) nil (get-char-property
18232 (1- (point)) 'invisible)))
18233 (border-and-ok-direction
18235 ;; Check if we are acting predictably before invisible text
18236 (and invisible-at-point (not invisible-before-point)
18237 (memq kind '(insert delete-backward)))
18238 ;; Check if we are acting predictably after invisible text
18239 ;; This works not well, and I have turned it off. It seems
18240 ;; better to always show and stop after invisible text.
18241 ;; (and (not invisible-at-point) invisible-before-point
18242 ;; (memq kind '(insert delete)))
18244 (when (or (memq invisible-at-point '(outline org-hide-block t))
18245 (memq invisible-before-point '(outline org-hide-block t)))
18246 (if (eq org-catch-invisible-edits 'error)
18247 (error "Editing in invisible areas is prohibited - make visible first"))
18248 (if (and org-custom-properties-overlays
18249 (y-or-n-p "Display invisible properties in this buffer? "))
18250 (org-toggle-custom-properties-visibility)
18251 ;; Make the area visible
18252 (save-excursion
18253 (if invisible-before-point
18254 (goto-char (previous-single-char-property-change
18255 (point) 'invisible)))
18256 (org-cycle))
18257 (cond
18258 ((eq org-catch-invisible-edits 'show)
18259 ;; That's it, we do the edit after showing
18260 (message
18261 "Unfolding invisible region around point before editing")
18262 (sit-for 1))
18263 ((and (eq org-catch-invisible-edits 'smart)
18264 border-and-ok-direction)
18265 (message "Unfolding invisible region around point before editing"))
18267 ;; Don't do the edit, make the user repeat it in full visibility
18268 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18270 (defun org-fix-tags-on-the-fly ()
18271 (when (and (equal (char-after (point-at-bol)) ?*)
18272 (org-at-heading-p))
18273 (org-align-tags-here org-tags-column)))
18275 (defun org-delete-backward-char (N)
18276 "Like `delete-backward-char', insert whitespace at field end in tables.
18277 When deleting backwards, in tables this function will insert whitespace in
18278 front of the next \"|\" separator, to keep the table aligned. The table will
18279 still be marked for re-alignment if the field did fill the entire column,
18280 because, in this case the deletion might narrow the column."
18281 (interactive "p")
18282 (org-check-before-invisible-edit 'delete-backward)
18283 (if (and (org-table-p)
18284 (eq N 1)
18285 (string-match "|" (buffer-substring (point-at-bol) (point)))
18286 (looking-at ".*?|"))
18287 (let ((pos (point))
18288 (noalign (looking-at "[^|\n\r]* |"))
18289 (c org-table-may-need-update))
18290 (backward-delete-char N)
18291 (if (not overwrite-mode)
18292 (progn
18293 (skip-chars-forward "^|")
18294 (insert " ")
18295 (goto-char (1- pos))))
18296 ;; noalign: if there were two spaces at the end, this field
18297 ;; does not determine the width of the column.
18298 (if noalign (setq org-table-may-need-update c)))
18299 (backward-delete-char N)
18300 (org-fix-tags-on-the-fly)))
18302 (defun org-delete-char (N)
18303 "Like `delete-char', but insert whitespace at field end in tables.
18304 When deleting characters, in tables this function will insert whitespace in
18305 front of the next \"|\" separator, to keep the table aligned. The table will
18306 still be marked for re-alignment if the field did fill the entire column,
18307 because, in this case the deletion might narrow the column."
18308 (interactive "p")
18309 (org-check-before-invisible-edit 'delete)
18310 (if (and (org-table-p)
18311 (not (bolp))
18312 (not (= (char-after) ?|))
18313 (eq N 1))
18314 (if (looking-at ".*?|")
18315 (let ((pos (point))
18316 (noalign (looking-at "[^|\n\r]* |"))
18317 (c org-table-may-need-update))
18318 (replace-match (concat
18319 (substring (match-string 0) 1 -1)
18320 " |"))
18321 (goto-char pos)
18322 ;; noalign: if there were two spaces at the end, this field
18323 ;; does not determine the width of the column.
18324 (if noalign (setq org-table-may-need-update c)))
18325 (delete-char N))
18326 (delete-char N)
18327 (org-fix-tags-on-the-fly)))
18329 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18330 (put 'org-self-insert-command 'delete-selection t)
18331 (put 'orgtbl-self-insert-command 'delete-selection t)
18332 (put 'org-delete-char 'delete-selection 'supersede)
18333 (put 'org-delete-backward-char 'delete-selection 'supersede)
18334 (put 'org-yank 'delete-selection 'yank)
18336 ;; Make `flyspell-mode' delay after some commands
18337 (put 'org-self-insert-command 'flyspell-delayed t)
18338 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18339 (put 'org-delete-char 'flyspell-delayed t)
18340 (put 'org-delete-backward-char 'flyspell-delayed t)
18342 ;; Make pabbrev-mode expand after org-mode commands
18343 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18344 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18346 ;; How to do this: Measure non-white length of current string
18347 ;; If equal to column width, we should realign.
18349 (defun org-remap (map &rest commands)
18350 "In MAP, remap the functions given in COMMANDS.
18351 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18352 (let (new old)
18353 (while commands
18354 (setq old (pop commands) new (pop commands))
18355 (if (fboundp 'command-remapping)
18356 (org-defkey map (vector 'remap old) new)
18357 (substitute-key-definition old new map global-map)))))
18359 (when (eq org-enable-table-editor 'optimized)
18360 ;; If the user wants maximum table support, we need to hijack
18361 ;; some standard editing functions
18362 (org-remap org-mode-map
18363 'self-insert-command 'org-self-insert-command
18364 'delete-char 'org-delete-char
18365 'delete-backward-char 'org-delete-backward-char)
18366 (org-defkey org-mode-map "|" 'org-force-self-insert))
18368 (defvar org-ctrl-c-ctrl-c-hook nil
18369 "Hook for functions attaching themselves to `C-c C-c'.
18371 This can be used to add additional functionality to the C-c C-c
18372 key which executes context-dependent commands. This hook is run
18373 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18374 run after the last test.
18376 Each function will be called with no arguments. The function
18377 must check if the context is appropriate for it to act. If yes,
18378 it should do its thing and then return a non-nil value. If the
18379 context is wrong, just do nothing and return nil.")
18381 (defvar org-ctrl-c-ctrl-c-final-hook nil
18382 "Hook for functions attaching themselves to `C-c C-c'.
18384 This can be used to add additional functionality to the C-c C-c
18385 key which executes context-dependent commands. This hook is run
18386 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18387 before the first test.
18389 Each function will be called with no arguments. The function
18390 must check if the context is appropriate for it to act. If yes,
18391 it should do its thing and then return a non-nil value. If the
18392 context is wrong, just do nothing and return nil.")
18394 (defvar org-tab-first-hook nil
18395 "Hook for functions to attach themselves to TAB.
18396 See `org-ctrl-c-ctrl-c-hook' for more information.
18397 This hook runs as the first action when TAB is pressed, even before
18398 `org-cycle' messes around with the `outline-regexp' to cater for
18399 inline tasks and plain list item folding.
18400 If any function in this hook returns t, any other actions that
18401 would have been caused by TAB (such as table field motion or visibility
18402 cycling) will not occur.")
18404 (defvar org-tab-after-check-for-table-hook nil
18405 "Hook for functions to attach themselves to TAB.
18406 See `org-ctrl-c-ctrl-c-hook' for more information.
18407 This hook runs after it has been established that the cursor is not in a
18408 table, but before checking if the cursor is in a headline or if global cycling
18409 should be done.
18410 If any function in this hook returns t, not other actions like visibility
18411 cycling will be done.")
18413 (defvar org-tab-after-check-for-cycling-hook nil
18414 "Hook for functions to attach themselves to TAB.
18415 See `org-ctrl-c-ctrl-c-hook' for more information.
18416 This hook runs after it has been established that not table field motion and
18417 not visibility should be done because of current context. This is probably
18418 the place where a package like yasnippets can hook in.")
18420 (defvar org-tab-before-tab-emulation-hook nil
18421 "Hook for functions to attach themselves to TAB.
18422 See `org-ctrl-c-ctrl-c-hook' for more information.
18423 This hook runs after every other options for TAB have been exhausted, but
18424 before indentation and \t insertion takes place.")
18426 (defvar org-metaleft-hook nil
18427 "Hook for functions attaching themselves to `M-left'.
18428 See `org-ctrl-c-ctrl-c-hook' for more information.")
18429 (defvar org-metaright-hook nil
18430 "Hook for functions attaching themselves to `M-right'.
18431 See `org-ctrl-c-ctrl-c-hook' for more information.")
18432 (defvar org-metaup-hook nil
18433 "Hook for functions attaching themselves to `M-up'.
18434 See `org-ctrl-c-ctrl-c-hook' for more information.")
18435 (defvar org-metadown-hook nil
18436 "Hook for functions attaching themselves to `M-down'.
18437 See `org-ctrl-c-ctrl-c-hook' for more information.")
18438 (defvar org-shiftmetaleft-hook nil
18439 "Hook for functions attaching themselves to `M-S-left'.
18440 See `org-ctrl-c-ctrl-c-hook' for more information.")
18441 (defvar org-shiftmetaright-hook nil
18442 "Hook for functions attaching themselves to `M-S-right'.
18443 See `org-ctrl-c-ctrl-c-hook' for more information.")
18444 (defvar org-shiftmetaup-hook nil
18445 "Hook for functions attaching themselves to `M-S-up'.
18446 See `org-ctrl-c-ctrl-c-hook' for more information.")
18447 (defvar org-shiftmetadown-hook nil
18448 "Hook for functions attaching themselves to `M-S-down'.
18449 See `org-ctrl-c-ctrl-c-hook' for more information.")
18450 (defvar org-metareturn-hook nil
18451 "Hook for functions attaching themselves to `M-RET'.
18452 See `org-ctrl-c-ctrl-c-hook' for more information.")
18453 (defvar org-shiftup-hook nil
18454 "Hook for functions attaching themselves to `S-up'.
18455 See `org-ctrl-c-ctrl-c-hook' for more information.")
18456 (defvar org-shiftup-final-hook nil
18457 "Hook for functions attaching themselves to `S-up'.
18458 This one runs after all other options except shift-select have been excluded.
18459 See `org-ctrl-c-ctrl-c-hook' for more information.")
18460 (defvar org-shiftdown-hook nil
18461 "Hook for functions attaching themselves to `S-down'.
18462 See `org-ctrl-c-ctrl-c-hook' for more information.")
18463 (defvar org-shiftdown-final-hook nil
18464 "Hook for functions attaching themselves to `S-down'.
18465 This one runs after all other options except shift-select have been excluded.
18466 See `org-ctrl-c-ctrl-c-hook' for more information.")
18467 (defvar org-shiftleft-hook nil
18468 "Hook for functions attaching themselves to `S-left'.
18469 See `org-ctrl-c-ctrl-c-hook' for more information.")
18470 (defvar org-shiftleft-final-hook nil
18471 "Hook for functions attaching themselves to `S-left'.
18472 This one runs after all other options except shift-select have been excluded.
18473 See `org-ctrl-c-ctrl-c-hook' for more information.")
18474 (defvar org-shiftright-hook nil
18475 "Hook for functions attaching themselves to `S-right'.
18476 See `org-ctrl-c-ctrl-c-hook' for more information.")
18477 (defvar org-shiftright-final-hook nil
18478 "Hook for functions attaching themselves to `S-right'.
18479 This one runs after all other options except shift-select have been excluded.
18480 See `org-ctrl-c-ctrl-c-hook' for more information.")
18482 (defun org-modifier-cursor-error ()
18483 "Throw an error, a modified cursor command was applied in wrong context."
18484 (error "This command is active in special context like tables, headlines or items"))
18486 (defun org-shiftselect-error ()
18487 "Throw an error because Shift-Cursor command was applied in wrong context."
18488 (if (and (boundp 'shift-select-mode) shift-select-mode)
18489 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18490 (error "This command works only in special context like headlines or timestamps")))
18492 (defun org-call-for-shift-select (cmd)
18493 (let ((this-command-keys-shift-translated t))
18494 (call-interactively cmd)))
18496 (defun org-shifttab (&optional arg)
18497 "Global visibility cycling or move to previous table field.
18498 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18499 on context.
18500 See the individual commands for more information."
18501 (interactive "P")
18502 (cond
18503 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18504 ((integerp arg)
18505 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18506 (message "Content view to level: %d" arg)
18507 (org-content (prefix-numeric-value arg2))
18508 (setq org-cycle-global-status 'overview)))
18509 (t (call-interactively 'org-global-cycle))))
18511 (defun org-shiftmetaleft ()
18512 "Promote subtree or delete table column.
18513 Calls `org-promote-subtree', `org-outdent-item-tree', or
18514 `org-table-delete-column', depending on context. See the
18515 individual commands for more information."
18516 (interactive)
18517 (cond
18518 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18519 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18520 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18521 ((if (not (org-region-active-p)) (org-at-item-p)
18522 (save-excursion (goto-char (region-beginning))
18523 (org-at-item-p)))
18524 (call-interactively 'org-outdent-item-tree))
18525 (t (org-modifier-cursor-error))))
18527 (defun org-shiftmetaright ()
18528 "Demote subtree or insert table column.
18529 Calls `org-demote-subtree', `org-indent-item-tree', or
18530 `org-table-insert-column', depending on context. See the
18531 individual commands for more information."
18532 (interactive)
18533 (cond
18534 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18535 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18536 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18537 ((if (not (org-region-active-p)) (org-at-item-p)
18538 (save-excursion (goto-char (region-beginning))
18539 (org-at-item-p)))
18540 (call-interactively 'org-indent-item-tree))
18541 (t (org-modifier-cursor-error))))
18543 (defun org-shiftmetaup (&optional arg)
18544 "Move subtree up or kill table row.
18545 Calls `org-move-subtree-up' or `org-table-kill-row' or
18546 `org-move-item-up' or `org-timestamp-up', depending on context.
18547 See the individual commands for more information."
18548 (interactive "P")
18549 (cond
18550 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18551 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18552 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18553 ((org-at-item-p) (call-interactively 'org-move-item-up))
18554 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18555 (call-interactively 'org-timestamp-up)))
18556 (t (org-modifier-cursor-error))))
18558 (defun org-shiftmetadown (&optional arg)
18559 "Move subtree down or insert table row.
18560 Calls `org-move-subtree-down' or `org-table-insert-row' or
18561 `org-move-item-down' or `org-timestamp-up', depending on context.
18562 See the individual commands for more information."
18563 (interactive "P")
18564 (cond
18565 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18566 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18567 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18568 ((org-at-item-p) (call-interactively 'org-move-item-down))
18569 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18570 (call-interactively 'org-timestamp-down)))
18571 (t (org-modifier-cursor-error))))
18573 (defsubst org-hidden-tree-error ()
18574 (error
18575 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18577 (defun org-metaleft (&optional arg)
18578 "Promote heading or move table column to left.
18579 Calls `org-do-promote' or `org-table-move-column', depending on context.
18580 With no specific context, calls the Emacs default `backward-word'.
18581 See the individual commands for more information."
18582 (interactive "P")
18583 (cond
18584 ((run-hook-with-args-until-success 'org-metaleft-hook))
18585 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18586 ((org-with-limited-levels
18587 (or (org-at-heading-p)
18588 (and (org-region-active-p)
18589 (save-excursion
18590 (goto-char (region-beginning))
18591 (org-at-heading-p)))))
18592 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18593 (call-interactively 'org-do-promote))
18594 ;; At an inline task.
18595 ((org-at-heading-p)
18596 (call-interactively 'org-inlinetask-promote))
18597 ((or (org-at-item-p)
18598 (and (org-region-active-p)
18599 (save-excursion
18600 (goto-char (region-beginning))
18601 (org-at-item-p))))
18602 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18603 (call-interactively 'org-outdent-item))
18604 (t (call-interactively 'backward-word))))
18606 (defun org-metaright (&optional arg)
18607 "Demote a subtree, a list item or move table column to right.
18608 In front of a drawer or a block keyword, indent it correctly.
18609 With no specific context, calls the Emacs default `forward-word'.
18610 See the individual commands for more information."
18611 (interactive "P")
18612 (cond
18613 ((run-hook-with-args-until-success 'org-metaright-hook))
18614 ((org-at-table-p) (call-interactively 'org-table-move-column))
18615 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18616 ((org-at-block-p) (call-interactively 'org-indent-block))
18617 ((org-with-limited-levels
18618 (or (org-at-heading-p)
18619 (and (org-region-active-p)
18620 (save-excursion
18621 (goto-char (region-beginning))
18622 (org-at-heading-p)))))
18623 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18624 (call-interactively 'org-do-demote))
18625 ;; At an inline task.
18626 ((org-at-heading-p)
18627 (call-interactively 'org-inlinetask-demote))
18628 ((or (org-at-item-p)
18629 (and (org-region-active-p)
18630 (save-excursion
18631 (goto-char (region-beginning))
18632 (org-at-item-p))))
18633 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18634 (call-interactively 'org-indent-item))
18635 (t (call-interactively 'forward-word))))
18637 (defun org-check-for-hidden (what)
18638 "Check if there are hidden headlines/items in the current visual line.
18639 WHAT can be either `headlines' or `items'. If the current line is
18640 an outline or item heading and it has a folded subtree below it,
18641 this function returns t, nil otherwise."
18642 (let ((re (cond
18643 ((eq what 'headlines) org-outline-regexp-bol)
18644 ((eq what 'items) (org-item-beginning-re))
18645 (t (error "This should not happen"))))
18646 beg end)
18647 (save-excursion
18648 (catch 'exit
18649 (unless (org-region-active-p)
18650 (setq beg (point-at-bol))
18651 (beginning-of-line 2)
18652 (while (and (not (eobp)) ;; this is like `next-line'
18653 (get-char-property (1- (point)) 'invisible))
18654 (beginning-of-line 2))
18655 (setq end (point))
18656 (goto-char beg)
18657 (goto-char (point-at-eol))
18658 (setq end (max end (point)))
18659 (while (re-search-forward re end t)
18660 (if (get-char-property (match-beginning 0) 'invisible)
18661 (throw 'exit t))))
18662 nil))))
18664 (autoload 'org-element-at-point "org-element")
18665 (autoload 'org-element-type "org-element")
18667 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18668 (declare-function org-element-type "org-element" (element))
18669 (declare-function org-element-contents "org-element" (element))
18670 (declare-function org-element-property "org-element" (property element))
18671 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18672 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18673 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18674 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18675 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18677 (defun org-metaup (&optional arg)
18678 "Move subtree up or move table row up.
18679 Calls `org-move-subtree-up' or `org-table-move-row' or
18680 `org-move-item-up', depending on context. See the individual commands
18681 for more information."
18682 (interactive "P")
18683 (cond
18684 ((run-hook-with-args-until-success 'org-metaup-hook))
18685 ((org-region-active-p)
18686 (let* ((a (min (region-beginning) (region-end)))
18687 (b (1- (max (region-beginning) (region-end))))
18688 (c (save-excursion (goto-char a)
18689 (move-beginning-of-line 0)))
18690 (d (save-excursion (goto-char a)
18691 (move-end-of-line 0) (point))))
18692 (transpose-regions a b c d)
18693 (goto-char c)))
18694 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18695 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18696 ((org-at-item-p) (call-interactively 'org-move-item-up))
18697 (t (org-drag-element-backward))))
18699 (defun org-metadown (&optional arg)
18700 "Move subtree down or move table row down.
18701 Calls `org-move-subtree-down' or `org-table-move-row' or
18702 `org-move-item-down', depending on context. See the individual
18703 commands for more information."
18704 (interactive "P")
18705 (cond
18706 ((run-hook-with-args-until-success 'org-metadown-hook))
18707 ((org-region-active-p)
18708 (let* ((a (min (region-beginning) (region-end)))
18709 (b (max (region-beginning) (region-end)))
18710 (c (save-excursion (goto-char b)
18711 (move-beginning-of-line 1)))
18712 (d (save-excursion (goto-char b)
18713 (move-end-of-line 1) (1+ (point)))))
18714 (transpose-regions a b c d)
18715 (goto-char d)))
18716 ((org-at-table-p) (call-interactively 'org-table-move-row))
18717 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18718 ((org-at-item-p) (call-interactively 'org-move-item-down))
18719 (t (org-drag-element-forward))))
18721 (defun org-shiftup (&optional arg)
18722 "Increase item in timestamp or increase priority of current headline.
18723 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18724 depending on context. See the individual commands for more information."
18725 (interactive "P")
18726 (cond
18727 ((run-hook-with-args-until-success 'org-shiftup-hook))
18728 ((and org-support-shift-select (org-region-active-p))
18729 (org-call-for-shift-select 'previous-line))
18730 ((org-at-timestamp-p t)
18731 (call-interactively (if org-edit-timestamp-down-means-later
18732 'org-timestamp-down 'org-timestamp-up)))
18733 ((and (not (eq org-support-shift-select 'always))
18734 org-enable-priority-commands
18735 (org-at-heading-p))
18736 (call-interactively 'org-priority-up))
18737 ((and (not org-support-shift-select) (org-at-item-p))
18738 (call-interactively 'org-previous-item))
18739 ((org-clocktable-try-shift 'up arg))
18740 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18741 (org-support-shift-select
18742 (org-call-for-shift-select 'previous-line))
18743 (t (org-shiftselect-error))))
18745 (defun org-shiftdown (&optional arg)
18746 "Decrease item in timestamp or decrease priority of current headline.
18747 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18748 depending on context. See the individual commands for more information."
18749 (interactive "P")
18750 (cond
18751 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18752 ((and org-support-shift-select (org-region-active-p))
18753 (org-call-for-shift-select 'next-line))
18754 ((org-at-timestamp-p t)
18755 (call-interactively (if org-edit-timestamp-down-means-later
18756 'org-timestamp-up 'org-timestamp-down)))
18757 ((and (not (eq org-support-shift-select 'always))
18758 org-enable-priority-commands
18759 (org-at-heading-p))
18760 (call-interactively 'org-priority-down))
18761 ((and (not org-support-shift-select) (org-at-item-p))
18762 (call-interactively 'org-next-item))
18763 ((org-clocktable-try-shift 'down arg))
18764 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18765 (org-support-shift-select
18766 (org-call-for-shift-select 'next-line))
18767 (t (org-shiftselect-error))))
18769 (defun org-shiftright (&optional arg)
18770 "Cycle the thing at point or in the current line, depending on context.
18771 Depending on context, this does one of the following:
18773 - switch a timestamp at point one day into the future
18774 - on a headline, switch to the next TODO keyword.
18775 - on an item, switch entire list to the next bullet type
18776 - on a property line, switch to the next allowed value
18777 - on a clocktable definition line, move time block into the future"
18778 (interactive "P")
18779 (cond
18780 ((run-hook-with-args-until-success 'org-shiftright-hook))
18781 ((and org-support-shift-select (org-region-active-p))
18782 (org-call-for-shift-select 'forward-char))
18783 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18784 ((and (not (eq org-support-shift-select 'always))
18785 (org-at-heading-p))
18786 (let ((org-inhibit-logging
18787 (not org-treat-S-cursor-todo-selection-as-state-change))
18788 (org-inhibit-blocking
18789 (not org-treat-S-cursor-todo-selection-as-state-change)))
18790 (org-call-with-arg 'org-todo 'right)))
18791 ((or (and org-support-shift-select
18792 (not (eq org-support-shift-select 'always))
18793 (org-at-item-bullet-p))
18794 (and (not org-support-shift-select) (org-at-item-p)))
18795 (org-call-with-arg 'org-cycle-list-bullet nil))
18796 ((and (not (eq org-support-shift-select 'always))
18797 (org-at-property-p))
18798 (call-interactively 'org-property-next-allowed-value))
18799 ((org-clocktable-try-shift 'right arg))
18800 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18801 (org-support-shift-select
18802 (org-call-for-shift-select 'forward-char))
18803 (t (org-shiftselect-error))))
18805 (defun org-shiftleft (&optional arg)
18806 "Cycle the thing at point or in the current line, depending on context.
18807 Depending on context, this does one of the following:
18809 - switch a timestamp at point one day into the past
18810 - on a headline, switch to the previous TODO keyword.
18811 - on an item, switch entire list to the previous bullet type
18812 - on a property line, switch to the previous allowed value
18813 - on a clocktable definition line, move time block into the past"
18814 (interactive "P")
18815 (cond
18816 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18817 ((and org-support-shift-select (org-region-active-p))
18818 (org-call-for-shift-select 'backward-char))
18819 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18820 ((and (not (eq org-support-shift-select 'always))
18821 (org-at-heading-p))
18822 (let ((org-inhibit-logging
18823 (not org-treat-S-cursor-todo-selection-as-state-change))
18824 (org-inhibit-blocking
18825 (not org-treat-S-cursor-todo-selection-as-state-change)))
18826 (org-call-with-arg 'org-todo 'left)))
18827 ((or (and org-support-shift-select
18828 (not (eq org-support-shift-select 'always))
18829 (org-at-item-bullet-p))
18830 (and (not org-support-shift-select) (org-at-item-p)))
18831 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18832 ((and (not (eq org-support-shift-select 'always))
18833 (org-at-property-p))
18834 (call-interactively 'org-property-previous-allowed-value))
18835 ((org-clocktable-try-shift 'left arg))
18836 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18837 (org-support-shift-select
18838 (org-call-for-shift-select 'backward-char))
18839 (t (org-shiftselect-error))))
18841 (defun org-shiftcontrolright ()
18842 "Switch to next TODO set."
18843 (interactive)
18844 (cond
18845 ((and org-support-shift-select (org-region-active-p))
18846 (org-call-for-shift-select 'forward-word))
18847 ((and (not (eq org-support-shift-select 'always))
18848 (org-at-heading-p))
18849 (org-call-with-arg 'org-todo 'nextset))
18850 (org-support-shift-select
18851 (org-call-for-shift-select 'forward-word))
18852 (t (org-shiftselect-error))))
18854 (defun org-shiftcontrolleft ()
18855 "Switch to previous TODO set."
18856 (interactive)
18857 (cond
18858 ((and org-support-shift-select (org-region-active-p))
18859 (org-call-for-shift-select 'backward-word))
18860 ((and (not (eq org-support-shift-select 'always))
18861 (org-at-heading-p))
18862 (org-call-with-arg 'org-todo 'previousset))
18863 (org-support-shift-select
18864 (org-call-for-shift-select 'backward-word))
18865 (t (org-shiftselect-error))))
18867 (defun org-shiftcontrolup ()
18868 "Change timestamps synchronously up in CLOCK log lines."
18869 (interactive)
18870 (cond ((and (not org-support-shift-select)
18871 (org-at-clock-log-p)
18872 (org-at-timestamp-p t))
18873 (org-clock-timestamps-up))
18874 (t (org-shiftselect-error))))
18876 (defun org-shiftcontroldown ()
18877 "Change timestamps synchronously down in CLOCK log lines."
18878 (interactive)
18879 (cond ((and (not org-support-shift-select)
18880 (org-at-clock-log-p)
18881 (org-at-timestamp-p t))
18882 (org-clock-timestamps-down))
18883 (t (org-shiftselect-error))))
18885 (defun org-ctrl-c-ret ()
18886 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18887 (interactive)
18888 (cond
18889 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18890 (t (call-interactively 'org-insert-heading))))
18892 (defun org-find-visible ()
18893 (let ((s (point)))
18894 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18895 (get-char-property s 'invisible)))
18897 (defun org-find-invisible ()
18898 (let ((s (point)))
18899 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18900 (not (get-char-property s 'invisible))))
18903 (defun org-copy-visible (beg end)
18904 "Copy the visible parts of the region."
18905 (interactive "r")
18906 (let (snippets s)
18907 (save-excursion
18908 (save-restriction
18909 (narrow-to-region beg end)
18910 (setq s (goto-char (point-min)))
18911 (while (not (= (point) (point-max)))
18912 (goto-char (org-find-invisible))
18913 (push (buffer-substring s (point)) snippets)
18914 (setq s (goto-char (org-find-visible))))))
18915 (kill-new (apply 'concat (nreverse snippets)))))
18917 (defun org-copy-special ()
18918 "Copy region in table or copy current subtree.
18919 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18920 See the individual commands for more information."
18921 (interactive)
18922 (call-interactively
18923 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18925 (defun org-cut-special ()
18926 "Cut region in table or cut current subtree.
18927 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18928 See the individual commands for more information."
18929 (interactive)
18930 (call-interactively
18931 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18933 (defun org-paste-special (arg)
18934 "Paste rectangular region into table, or past subtree relative to level.
18935 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18936 See the individual commands for more information."
18937 (interactive "P")
18938 (if (org-at-table-p)
18939 (org-table-paste-rectangle)
18940 (org-paste-subtree arg)))
18942 (defun org-edit-special (&optional arg)
18943 "Call a special editor for the stuff at point.
18944 When at a table, call the formula editor with `org-table-edit-formulas'.
18945 When at the first line of an src example, call `org-edit-src-code'.
18946 When in an #+include line, visit the include file. Otherwise call
18947 `ffap' to visit the file at point."
18948 (interactive)
18949 ;; possibly prep session before editing source
18950 (when arg
18951 (let* ((info (org-babel-get-src-block-info))
18952 (lang (nth 0 info))
18953 (params (nth 2 info))
18954 (session (cdr (assoc :session params))))
18955 (when (and info session) ;; we are in a source-code block with a session
18956 (funcall
18957 (intern (concat "org-babel-prep-session:" lang)) session params))))
18958 (cond ;; proceed with `org-edit-special'
18959 ((save-excursion
18960 (beginning-of-line 1)
18961 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18962 (find-file (org-trim (match-string 1))))
18963 ((org-edit-src-code))
18964 ((org-edit-fixed-width-region))
18965 ((org-at-table.el-p)
18966 (org-edit-src-code))
18967 ((or (org-at-table-p)
18968 (save-excursion
18969 (beginning-of-line 1)
18970 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18971 (call-interactively 'org-table-edit-formulas))
18972 (t (call-interactively 'ffap))))
18974 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18975 (defun org-ctrl-c-ctrl-c (&optional arg)
18976 "Set tags in headline, or update according to changed information at point.
18978 This command does many different things, depending on context:
18980 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18981 this is what we do.
18983 - If the cursor is on a statistics cookie, update it.
18985 - If the cursor is in a headline, prompt for tags and insert them
18986 into the current line, aligned to `org-tags-column'. When called
18987 with prefix arg, realign all tags in the current buffer.
18989 - If the cursor is in one of the special #+KEYWORD lines, this
18990 triggers scanning the buffer for these lines and updating the
18991 information.
18993 - If the cursor is inside a table, realign the table. This command
18994 works even if the automatic table editor has been turned off.
18996 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18997 the entire table.
18999 - If the cursor is at a footnote reference or definition, jump to
19000 the corresponding definition or references, respectively.
19002 - If the cursor is a the beginning of a dynamic block, update it.
19004 - If the current buffer is a capture buffer, close note and file it.
19006 - If the cursor is on a <<<target>>>, update radio targets and
19007 corresponding links in this buffer.
19009 - If the cursor is on a numbered item in a plain list, renumber the
19010 ordered list.
19012 - If the cursor is on a checkbox, toggle it.
19014 - If the cursor is on a code block, evaluate it. The variable
19015 `org-confirm-babel-evaluate' can be used to control prompting
19016 before code block evaluation, by default every code block
19017 evaluation requires confirmation. Code block evaluation can be
19018 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19019 (interactive "P")
19020 (let ((org-enable-table-editor t))
19021 (cond
19022 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19023 org-occur-highlights
19024 org-latex-fragment-image-overlays)
19025 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19026 (org-remove-occur-highlights)
19027 (org-remove-latex-fragment-image-overlays)
19028 (message "Temporary highlights/overlays removed from current buffer"))
19029 ((and (local-variable-p 'org-finish-function (current-buffer))
19030 (fboundp org-finish-function))
19031 (funcall org-finish-function))
19032 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19033 ((org-in-regexp org-ts-regexp-both)
19034 (org-timestamp-change 0 'day))
19035 ((or (looking-at org-property-start-re)
19036 (org-at-property-p))
19037 (call-interactively 'org-property-action))
19038 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19039 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19040 (or (org-at-heading-p) (org-at-item-p)))
19041 (call-interactively 'org-update-statistics-cookies))
19042 ((org-at-heading-p) (call-interactively 'org-set-tags))
19043 ((org-at-table.el-p)
19044 (message "Use C-c ' to edit table.el tables"))
19045 ((org-at-table-p)
19046 (org-table-maybe-eval-formula)
19047 (if arg
19048 (call-interactively 'org-table-recalculate)
19049 (org-table-maybe-recalculate-line))
19050 (call-interactively 'org-table-align)
19051 (orgtbl-send-table 'maybe))
19052 ((or (org-footnote-at-reference-p)
19053 (org-footnote-at-definition-p))
19054 (call-interactively 'org-footnote-action))
19055 ((org-at-item-checkbox-p)
19056 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19057 ;; list only if at top item.
19058 (let* ((cbox (match-string 1))
19059 (struct (org-list-struct))
19060 (old-struct (copy-tree struct))
19061 (parents (org-list-parents-alist struct))
19062 (orderedp (org-entry-get nil "ORDERED"))
19063 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19064 block-item)
19065 ;; Use a light version of `org-toggle-checkbox' to avoid
19066 ;; computing list structure twice.
19067 (let ((new-box (cond
19068 ((equal arg '(16)) "[-]")
19069 ((equal arg '(4)) nil)
19070 ((equal "[X]" cbox) "[ ]")
19071 (t "[X]"))))
19072 (if (and firstp arg)
19073 ;; If at first item of sub-list, remove check-box from
19074 ;; every item at the same level.
19075 (mapc
19076 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19077 (org-list-get-all-items
19078 (point-at-bol) struct (org-list-prevs-alist struct)))
19079 (org-list-set-checkbox (point-at-bol) struct new-box)))
19080 ;; Replicate `org-list-write-struct', while grabbing a return
19081 ;; value from `org-list-struct-fix-box'.
19082 (org-list-struct-fix-ind struct parents 2)
19083 (org-list-struct-fix-item-end struct)
19084 (let ((prevs (org-list-prevs-alist struct)))
19085 (org-list-struct-fix-bul struct prevs)
19086 (org-list-struct-fix-ind struct parents)
19087 (setq block-item
19088 (org-list-struct-fix-box struct parents prevs orderedp)))
19089 (org-list-struct-apply-struct struct old-struct)
19090 (org-update-checkbox-count-maybe)
19091 (when block-item
19092 (message
19093 "Checkboxes were removed due to unchecked box at line %d"
19094 (org-current-line block-item)))
19095 (when firstp (org-list-send-list 'maybe))))
19096 ((org-at-item-p)
19097 ;; Cursor at an item: repair list. Do checkbox related actions
19098 ;; only if function was called with an argument. Send list only
19099 ;; if at top item.
19100 (let* ((struct (org-list-struct))
19101 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19102 old-struct)
19103 (when arg
19104 (setq old-struct (copy-tree struct))
19105 (if firstp
19106 ;; If at first item of sub-list, add check-box to every
19107 ;; item at the same level.
19108 (mapc
19109 (lambda (pos)
19110 (unless (org-list-get-checkbox pos struct)
19111 (org-list-set-checkbox pos struct "[ ]")))
19112 (org-list-get-all-items
19113 (point-at-bol) struct (org-list-prevs-alist struct)))
19114 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19115 (org-list-write-struct
19116 struct (org-list-parents-alist struct) old-struct)
19117 (when arg (org-update-checkbox-count-maybe))
19118 (when firstp (org-list-send-list 'maybe))))
19119 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19120 ;; Dynamic block
19121 (beginning-of-line 1)
19122 (save-excursion (org-update-dblock)))
19123 ((save-excursion
19124 (let ((case-fold-search t))
19125 (beginning-of-line 1)
19126 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19127 (cond
19128 ((or (equal (match-string 1) "TBLFM")
19129 (equal (match-string 1) "tblfm"))
19130 ;; Recalculate the table before this line
19131 (save-excursion
19132 (beginning-of-line 1)
19133 (skip-chars-backward " \r\n\t")
19134 (if (org-at-table-p)
19135 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19137 (let ((org-inhibit-startup-visibility-stuff t)
19138 (org-startup-align-all-tables nil))
19139 (when (boundp 'org-table-coordinate-overlays)
19140 (mapc 'delete-overlay org-table-coordinate-overlays)
19141 (setq org-table-coordinate-overlays nil))
19142 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19143 (message "Local setup has been refreshed"))))
19144 ((org-clock-update-time-maybe))
19146 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19147 (error "C-c C-c can do nothing useful at this location"))))))
19149 (defun org-mode-restart ()
19150 "Restart Org-mode, to scan again for special lines.
19151 Also updates the keyword regular expressions."
19152 (interactive)
19153 (org-mode)
19154 (message "Org-mode restarted"))
19156 (defun org-kill-note-or-show-branches ()
19157 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19158 (interactive)
19159 (if (not org-finish-function)
19160 (progn
19161 (hide-subtree)
19162 (call-interactively 'show-branches))
19163 (let ((org-note-abort t))
19164 (funcall org-finish-function))))
19166 (defun org-return (&optional indent)
19167 "Goto next table row or insert a newline.
19168 Calls `org-table-next-row' or `newline', depending on context.
19169 See the individual commands for more information."
19170 (interactive)
19171 (let (org-ts-what)
19172 (cond
19173 ((or (bobp) (org-in-src-block-p))
19174 (if indent (newline-and-indent) (newline)))
19175 ((org-at-table-p)
19176 (org-table-justify-field-maybe)
19177 (call-interactively 'org-table-next-row))
19178 ;; when `newline-and-indent' is called within a list, make sure
19179 ;; text moved stays inside the item.
19180 ((and (org-in-item-p) indent)
19181 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19182 (progn
19183 (save-match-data (newline))
19184 (org-indent-line-to (length (match-string 0))))
19185 (let ((ind (org-get-indentation)))
19186 (newline)
19187 (if (org-looking-back org-list-end-re)
19188 (org-indent-line)
19189 (org-indent-line-to ind)))))
19190 ((and org-return-follows-link
19191 (org-at-timestamp-p t)
19192 (not (eq org-ts-what 'after)))
19193 (org-follow-timestamp-link))
19194 ((and org-return-follows-link
19195 (let ((tprop (get-text-property (point) 'face)))
19196 (or (eq tprop 'org-link)
19197 (and (listp tprop) (memq 'org-link tprop)))))
19198 (call-interactively 'org-open-at-point))
19199 ((and (org-at-heading-p)
19200 (looking-at
19201 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19202 (org-show-entry)
19203 (end-of-line 1)
19204 (newline))
19205 (t (if indent (newline-and-indent) (newline))))))
19207 (defun org-return-indent ()
19208 "Goto next table row or insert a newline and indent.
19209 Calls `org-table-next-row' or `newline-and-indent', depending on
19210 context. See the individual commands for more information."
19211 (interactive)
19212 (org-return t))
19214 (defun org-ctrl-c-star ()
19215 "Compute table, or change heading status of lines.
19216 Calls `org-table-recalculate' or `org-toggle-heading',
19217 depending on context."
19218 (interactive)
19219 (cond
19220 ((org-at-table-p)
19221 (call-interactively 'org-table-recalculate))
19223 ;; Convert all lines in region to list items
19224 (call-interactively 'org-toggle-heading))))
19226 (defun org-ctrl-c-minus ()
19227 "Insert separator line in table or modify bullet status of line.
19228 Also turns a plain line or a region of lines into list items.
19229 Calls `org-table-insert-hline', `org-toggle-item', or
19230 `org-cycle-list-bullet', depending on context."
19231 (interactive)
19232 (cond
19233 ((org-at-table-p)
19234 (call-interactively 'org-table-insert-hline))
19235 ((org-region-active-p)
19236 (call-interactively 'org-toggle-item))
19237 ((org-in-item-p)
19238 (call-interactively 'org-cycle-list-bullet))
19240 (call-interactively 'org-toggle-item))))
19242 (defun org-toggle-item (arg)
19243 "Convert headings or normal lines to items, items to normal lines.
19244 If there is no active region, only the current line is considered.
19246 If the first non blank line in the region is an headline, convert
19247 all headlines to items, shifting text accordingly.
19249 If it is an item, convert all items to normal lines.
19251 If it is normal text, change region into an item. With a prefix
19252 argument ARG, change each line in region into an item."
19253 (interactive "P")
19254 (let ((shift-text
19255 (function
19256 ;; Shift text in current section to IND, from point to END.
19257 ;; The function leaves point to END line.
19258 (lambda (ind end)
19259 (let ((min-i 1000) (end (copy-marker end)))
19260 ;; First determine the minimum indentation (MIN-I) of
19261 ;; the text.
19262 (save-excursion
19263 (catch 'exit
19264 (while (< (point) end)
19265 (let ((i (org-get-indentation)))
19266 (cond
19267 ;; Skip blank lines and inline tasks.
19268 ((looking-at "^[ \t]*$"))
19269 ((looking-at org-outline-regexp-bol))
19270 ;; We can't find less than 0 indentation.
19271 ((zerop i) (throw 'exit (setq min-i 0)))
19272 ((< i min-i) (setq min-i i))))
19273 (forward-line))))
19274 ;; Then indent each line so that a line indented to
19275 ;; MIN-I becomes indented to IND. Ignore blank lines
19276 ;; and inline tasks in the process.
19277 (let ((delta (- ind min-i)))
19278 (while (< (point) end)
19279 (unless (or (looking-at "^[ \t]*$")
19280 (looking-at org-outline-regexp-bol))
19281 (org-indent-line-to (+ (org-get-indentation) delta)))
19282 (forward-line)))))))
19283 (skip-blanks
19284 (function
19285 ;; Return beginning of first non-blank line, starting from
19286 ;; line at POS.
19287 (lambda (pos)
19288 (save-excursion
19289 (goto-char pos)
19290 (skip-chars-forward " \r\t\n")
19291 (point-at-bol)))))
19292 beg end)
19293 ;; Determine boundaries of changes.
19294 (if (org-region-active-p)
19295 (setq beg (funcall skip-blanks (region-beginning))
19296 end (copy-marker (region-end)))
19297 (setq beg (funcall skip-blanks (point-at-bol))
19298 end (copy-marker (point-at-eol))))
19299 ;; Depending on the starting line, choose an action on the text
19300 ;; between BEG and END.
19301 (org-with-limited-levels
19302 (save-excursion
19303 (goto-char beg)
19304 (cond
19305 ;; Case 1. Start at an item: de-itemize. Note that it only
19306 ;; happens when a region is active: `org-ctrl-c-minus'
19307 ;; would call `org-cycle-list-bullet' otherwise.
19308 ((org-at-item-p)
19309 (while (< (point) end)
19310 (when (org-at-item-p)
19311 (skip-chars-forward " \t")
19312 (delete-region (point) (match-end 0)))
19313 (forward-line)))
19314 ;; Case 2. Start at an heading: convert to items.
19315 ((org-at-heading-p)
19316 (let* ((bul (org-list-bullet-string "-"))
19317 (bul-len (length bul))
19318 ;; Indentation of the first heading. It should be
19319 ;; relative to the indentation of its parent, if any.
19320 (start-ind (save-excursion
19321 (cond
19322 ((not org-adapt-indentation) 0)
19323 ((not (outline-previous-heading)) 0)
19324 (t (length (match-string 0))))))
19325 ;; Level of first heading. Further headings will be
19326 ;; compared to it to determine hierarchy in the list.
19327 (ref-level (org-reduced-level (org-outline-level))))
19328 (while (< (point) end)
19329 (let* ((level (org-reduced-level (org-outline-level)))
19330 (delta (max 0 (- level ref-level))))
19331 ;; If current headline is less indented than the first
19332 ;; one, set it as reference, in order to preserve
19333 ;; subtrees.
19334 (when (< level ref-level) (setq ref-level level))
19335 (replace-match bul t t)
19336 (org-indent-line-to (+ start-ind (* delta bul-len)))
19337 ;; Ensure all text down to END (or SECTION-END) belongs
19338 ;; to the newly created item.
19339 (let ((section-end (save-excursion
19340 (or (outline-next-heading) (point)))))
19341 (forward-line)
19342 (funcall shift-text
19343 (+ start-ind (* (1+ delta) bul-len))
19344 (min end section-end)))))))
19345 ;; Case 3. Normal line with ARG: turn each non-item line into
19346 ;; an item.
19347 (arg
19348 (while (< (point) end)
19349 (unless (or (org-at-heading-p) (org-at-item-p))
19350 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19351 (replace-match
19352 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19353 (forward-line)))
19354 ;; Case 4. Normal line without ARG: make the first line of
19355 ;; region an item, and shift indentation of others
19356 ;; lines to set them as item's body.
19357 (t (let* ((bul (org-list-bullet-string "-"))
19358 (bul-len (length bul))
19359 (ref-ind (org-get-indentation)))
19360 (skip-chars-forward " \t")
19361 (insert bul)
19362 (forward-line)
19363 (while (< (point) end)
19364 ;; Ensure that lines less indented than first one
19365 ;; still get included in item body.
19366 (funcall shift-text
19367 (+ ref-ind bul-len)
19368 (min end (save-excursion (or (outline-next-heading)
19369 (point)))))
19370 (forward-line)))))))))
19372 (defun org-toggle-heading (&optional nstars)
19373 "Convert headings to normal text, or items or text to headings.
19374 If there is no active region, only the current line is considered.
19376 With a \\[universal-argument] prefix, convert the whole list at
19377 point into heading.
19379 In a region:
19381 - If the first non blank line is an headline, remove the stars
19382 from all headlines in the region.
19384 - If it is a normal line turn each and every normal line (i.e. not an
19385 heading or an item) in the region into a heading.
19387 - If it is a plain list item, turn all plain list items into headings.
19389 When converting a line into a heading, the number of stars is chosen
19390 such that the lines become children of the current entry. However,
19391 when a prefix argument is given, its value determines the number of
19392 stars to add."
19393 (interactive "P")
19394 (let ((skip-blanks
19395 (function
19396 ;; Return beginning of first non-blank line, starting from
19397 ;; line at POS.
19398 (lambda (pos)
19399 (save-excursion
19400 (goto-char pos)
19401 (while (org-at-comment-p) (forward-line))
19402 (skip-chars-forward " \r\t\n")
19403 (point-at-bol)))))
19404 beg end toggled)
19405 ;; Determine boundaries of changes. If a universal prefix has
19406 ;; been given, put the list in a region. If region ends at a bol,
19407 ;; do not consider the last line to be in the region.
19409 (when (and current-prefix-arg (org-at-item-p))
19410 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19411 (org-mark-element))
19413 (if (org-region-active-p)
19414 (setq beg (funcall skip-blanks (region-beginning))
19415 end (copy-marker (save-excursion
19416 (goto-char (region-end))
19417 (if (bolp) (point) (point-at-eol)))))
19418 (setq beg (funcall skip-blanks (point-at-bol))
19419 end (copy-marker (point-at-eol))))
19420 ;; Ensure inline tasks don't count as headings.
19421 (org-with-limited-levels
19422 (save-excursion
19423 (goto-char beg)
19424 (cond
19425 ;; Case 1. Started at an heading: de-star headings.
19426 ((org-at-heading-p)
19427 (while (< (point) end)
19428 (when (org-at-heading-p t)
19429 (looking-at org-outline-regexp) (replace-match "")
19430 (setq toggled t))
19431 (forward-line)))
19432 ;; Case 2. Started at an item: change items into headlines.
19433 ;; One star will be added by `org-list-to-subtree'.
19434 ((org-at-item-p)
19435 (let* ((stars (make-string
19436 (if nstars
19437 ;; subtract the star that will be added again by
19438 ;; `org-list-to-subtree'
19439 (1- (prefix-numeric-value current-prefix-arg))
19440 (or (org-current-level) 0))
19441 ?*))
19442 (add-stars
19443 (cond (nstars "") ; stars from prefix only
19444 ((equal stars "") "") ; before first heading
19445 (org-odd-levels-only "*") ; inside heading, odd
19446 (t "")))) ; inside heading, oddeven
19447 (while (< (point) end)
19448 (when (org-at-item-p)
19449 ;; Pay attention to cases when region ends before list.
19450 (let* ((struct (org-list-struct))
19451 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19452 (save-restriction
19453 (narrow-to-region (point) list-end)
19454 (insert
19455 (org-list-to-subtree
19456 (org-list-parse-list t)
19457 '(:istart (concat stars add-stars (funcall get-stars depth))
19458 :icount (concat stars add-stars (funcall get-stars depth)))))))
19459 (setq toggled t))
19460 (forward-line))))
19461 ;; Case 3. Started at normal text: make every line an heading,
19462 ;; skipping headlines and items.
19463 (t (let* ((stars (make-string
19464 (if nstars
19465 (prefix-numeric-value current-prefix-arg)
19466 (or (org-current-level) 0))
19467 ?*))
19468 (add-stars
19469 (cond (nstars "") ; stars from prefix only
19470 ((equal stars "") "*") ; before first heading
19471 (org-odd-levels-only "**") ; inside heading, odd
19472 (t "*"))) ; inside heading, oddeven
19473 (rpl (concat stars add-stars " ")))
19474 (while (< (point) end)
19475 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19476 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19477 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19478 (forward-line)))))))
19479 (unless toggled (message "Cannot toggle heading from here"))))
19481 (defun org-meta-return (&optional arg)
19482 "Insert a new heading or wrap a region in a table.
19483 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19484 See the individual commands for more information."
19485 (interactive "P")
19486 (cond
19487 ((run-hook-with-args-until-success 'org-metareturn-hook))
19488 ((or (org-at-drawer-p) (org-at-property-p))
19489 (newline-and-indent))
19490 ((org-at-table-p)
19491 (call-interactively 'org-table-wrap-region))
19492 (t (call-interactively 'org-insert-heading))))
19494 ;;; Menu entries
19496 (defsubst org-in-subtree-not-table-p ()
19497 "Are we in a subtree and not in a table?"
19498 (and (not (org-before-first-heading-p))
19499 (not (org-at-table-p))))
19501 ;; Define the Org-mode menus
19502 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19503 '("Tbl"
19504 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19505 ["Next Field" org-cycle (org-at-table-p)]
19506 ["Previous Field" org-shifttab (org-at-table-p)]
19507 ["Next Row" org-return (org-at-table-p)]
19508 "--"
19509 ["Blank Field" org-table-blank-field (org-at-table-p)]
19510 ["Edit Field" org-table-edit-field (org-at-table-p)]
19511 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19512 "--"
19513 ("Column"
19514 ["Move Column Left" org-metaleft (org-at-table-p)]
19515 ["Move Column Right" org-metaright (org-at-table-p)]
19516 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19517 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19518 ("Row"
19519 ["Move Row Up" org-metaup (org-at-table-p)]
19520 ["Move Row Down" org-metadown (org-at-table-p)]
19521 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19522 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19523 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19524 "--"
19525 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19526 ("Rectangle"
19527 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19528 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19529 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19530 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19531 "--"
19532 ("Calculate"
19533 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19534 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19535 ["Edit Formulas" org-edit-special (org-at-table-p)]
19536 "--"
19537 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19538 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19539 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19540 "--"
19541 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19542 "--"
19543 ["Sum Column/Rectangle" org-table-sum
19544 (or (org-at-table-p) (org-region-active-p))]
19545 ["Which Column?" org-table-current-column (org-at-table-p)])
19546 ["Debug Formulas"
19547 org-table-toggle-formula-debugger
19548 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19549 ["Show Col/Row Numbers"
19550 org-table-toggle-coordinate-overlays
19551 :style toggle
19552 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19553 "--"
19554 ["Create" org-table-create (and (not (org-at-table-p))
19555 org-enable-table-editor)]
19556 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19557 ["Import from File" org-table-import (not (org-at-table-p))]
19558 ["Export to File" org-table-export (org-at-table-p)]
19559 "--"
19560 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19562 (easy-menu-define org-org-menu org-mode-map "Org menu"
19563 '("Org"
19564 ("Show/Hide"
19565 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19566 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19567 ["Sparse Tree..." org-sparse-tree t]
19568 ["Reveal Context" org-reveal t]
19569 ["Show All" show-all t]
19570 "--"
19571 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19572 "--"
19573 ["New Heading" org-insert-heading t]
19574 ("Navigate Headings"
19575 ["Up" outline-up-heading t]
19576 ["Next" outline-next-visible-heading t]
19577 ["Previous" outline-previous-visible-heading t]
19578 ["Next Same Level" outline-forward-same-level t]
19579 ["Previous Same Level" outline-backward-same-level t]
19580 "--"
19581 ["Jump" org-goto t])
19582 ("Edit Structure"
19583 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19584 "--"
19585 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19586 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19587 "--"
19588 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19589 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19590 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19591 "--"
19592 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19593 "--"
19594 ["Copy visible text" org-copy-visible t]
19595 "--"
19596 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19597 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19598 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19599 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19600 "--"
19601 ["Sort Region/Children" org-sort t]
19602 "--"
19603 ["Convert to odd levels" org-convert-to-odd-levels t]
19604 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19605 ("Editing"
19606 ["Emphasis..." org-emphasize t]
19607 ["Edit Source Example" org-edit-special t]
19608 "--"
19609 ["Footnote new/jump" org-footnote-action t]
19610 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19611 ("Archive"
19612 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19613 "--"
19614 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19615 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19616 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19618 "--"
19619 ("Hyperlinks"
19620 ["Store Link (Global)" org-store-link t]
19621 ["Find existing link to here" org-occur-link-in-agenda-files t]
19622 ["Insert Link" org-insert-link t]
19623 ["Follow Link" org-open-at-point t]
19624 "--"
19625 ["Next link" org-next-link t]
19626 ["Previous link" org-previous-link t]
19627 "--"
19628 ["Descriptive Links"
19629 org-toggle-link-display
19630 :style radio
19631 :selected org-descriptive-links
19633 ["Literal Links"
19634 org-toggle-link-display
19635 :style radio
19636 :selected (not org-descriptive-links)])
19637 "--"
19638 ("TODO Lists"
19639 ["TODO/DONE/-" org-todo t]
19640 ("Select keyword"
19641 ["Next keyword" org-shiftright (org-at-heading-p)]
19642 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19643 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19644 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19645 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19646 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19647 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19648 "--"
19649 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19650 :selected org-enforce-todo-dependencies :style toggle :active t]
19651 "Settings for tree at point"
19652 ["Do Children sequentially" org-toggle-ordered-property :style radio
19653 :selected (org-entry-get nil "ORDERED")
19654 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19655 ["Do Children parallel" org-toggle-ordered-property :style radio
19656 :selected (not (org-entry-get nil "ORDERED"))
19657 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19658 "--"
19659 ["Set Priority" org-priority t]
19660 ["Priority Up" org-shiftup t]
19661 ["Priority Down" org-shiftdown t]
19662 "--"
19663 ["Get news from all feeds" org-feed-update-all t]
19664 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19665 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19666 ("TAGS and Properties"
19667 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19668 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19669 "--"
19670 ["Set property" org-set-property (not (org-before-first-heading-p))]
19671 ["Column view of properties" org-columns t]
19672 ["Insert Column View DBlock" org-insert-columns-dblock t])
19673 ("Dates and Scheduling"
19674 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19675 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19676 ("Change Date"
19677 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19678 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19679 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19680 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19681 ["Compute Time Range" org-evaluate-time-range t]
19682 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19683 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19684 "--"
19685 ["Custom time format" org-toggle-time-stamp-overlays
19686 :style radio :selected org-display-custom-times]
19687 "--"
19688 ["Goto Calendar" org-goto-calendar t]
19689 ["Date from Calendar" org-date-from-calendar t]
19690 "--"
19691 ["Start/Restart Timer" org-timer-start t]
19692 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19693 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19694 ["Insert Timer String" org-timer t]
19695 ["Insert Timer Item" org-timer-item t])
19696 ("Logging work"
19697 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19698 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19699 ["Clock out" org-clock-out t]
19700 ["Clock cancel" org-clock-cancel t]
19701 "--"
19702 ["Mark as default task" org-clock-mark-default-task t]
19703 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19704 ["Goto running clock" org-clock-goto t]
19705 "--"
19706 ["Display times" org-clock-display t]
19707 ["Create clock table" org-clock-report t]
19708 "--"
19709 ["Record DONE time"
19710 (progn (setq org-log-done (not org-log-done))
19711 (message "Switching to %s will %s record a timestamp"
19712 (car org-done-keywords)
19713 (if org-log-done "automatically" "not")))
19714 :style toggle :selected org-log-done])
19715 "--"
19716 ["Agenda Command..." org-agenda t]
19717 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19718 ("File List for Agenda")
19719 ("Special views current file"
19720 ["TODO Tree" org-show-todo-tree t]
19721 ["Check Deadlines" org-check-deadlines t]
19722 ["Timeline" org-timeline t]
19723 ["Tags/Property tree" org-match-sparse-tree t])
19724 "--"
19725 ["Export/Publish..." org-export t]
19726 ("LaTeX"
19727 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19728 :selected org-cdlatex-mode]
19729 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19730 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19731 ["Modify math symbol" org-cdlatex-math-modify
19732 (org-inside-LaTeX-fragment-p)]
19733 ["Insert citation" org-reftex-citation t]
19734 "--"
19735 ["Template for BEAMER" (progn (require 'org-beamer)
19736 (org-insert-beamer-options-template)) t])
19737 "--"
19738 ("MobileOrg"
19739 ["Push Files and Views" org-mobile-push t]
19740 ["Get Captured and Flagged" org-mobile-pull t]
19741 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19742 "--"
19743 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19744 "--"
19745 ("Documentation"
19746 ["Show Version" org-version t]
19747 ["Info Documentation" org-info t])
19748 ("Customize"
19749 ["Browse Org Group" org-customize t]
19750 "--"
19751 ["Expand This Menu" org-create-customize-menu
19752 (fboundp 'customize-menu-create)])
19753 ["Send bug report" org-submit-bug-report t]
19754 "--"
19755 ("Refresh/Reload"
19756 ["Refresh setup current buffer" org-mode-restart t]
19757 ["Reload Org (after update)" org-reload t]
19758 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19761 (defun org-info (&optional node)
19762 "Read documentation for Org-mode in the info system.
19763 With optional NODE, go directly to that node."
19764 (interactive)
19765 (info (format "(org)%s" (or node ""))))
19767 ;;;###autoload
19768 (defun org-submit-bug-report ()
19769 "Submit a bug report on Org-mode via mail.
19771 Don't hesitate to report any problems or inaccurate documentation.
19773 If you don't have setup sending mail from (X)Emacs, please copy the
19774 output buffer into your mail program, as it gives us important
19775 information about your Org-mode version and configuration."
19776 (interactive)
19777 (require 'reporter)
19778 (org-load-modules-maybe)
19779 (org-require-autoloaded-modules)
19780 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19781 (reporter-submit-bug-report
19782 "emacs-orgmode@gnu.org"
19783 (org-version nil 'full)
19784 (let (list)
19785 (save-window-excursion
19786 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19787 (delete-other-windows)
19788 (erase-buffer)
19789 (insert "You are about to submit a bug report to the Org-mode mailing list.
19791 We would like to add your full Org-mode and Outline configuration to the
19792 bug report. This greatly simplifies the work of the maintainer and
19793 other experts on the mailing list.
19795 HOWEVER, some variables you have customized may contain private
19796 information. The names of customers, colleagues, or friends, might
19797 appear in the form of file names, tags, todo states, or search strings.
19798 If you answer yes to the prompt, you might want to check and remove
19799 such private information before sending the email.")
19800 (add-text-properties (point-min) (point-max) '(face org-warning))
19801 (when (yes-or-no-p "Include your Org-mode configuration ")
19802 (mapatoms
19803 (lambda (v)
19804 (and (boundp v)
19805 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19806 (or (and (symbol-value v)
19807 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19808 (and
19809 (get v 'custom-type) (get v 'standard-value)
19810 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19811 (push v list)))))
19812 (kill-buffer (get-buffer "*Warn about privacy*"))
19813 list))
19814 nil nil
19815 "Remember to cover the basics, that is, what you expected to happen and
19816 what in fact did happen. You don't know how to make a good report? See
19818 http://orgmode.org/manual/Feedback.html#Feedback
19820 Your bug report will be posted to the Org-mode mailing list.
19821 ------------------------------------------------------------------------")
19822 (save-excursion
19823 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19824 (replace-match "\\1Bug: \\3 [\\2]")))))
19827 (defun org-install-agenda-files-menu ()
19828 (let ((bl (buffer-list)))
19829 (save-excursion
19830 (while bl
19831 (set-buffer (pop bl))
19832 (if (derived-mode-p 'org-mode) (setq bl nil)))
19833 (when (derived-mode-p 'org-mode)
19834 (easy-menu-change
19835 '("Org") "File List for Agenda"
19836 (append
19837 (list
19838 ["Edit File List" (org-edit-agenda-file-list) t]
19839 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19840 ["Remove Current File from List" org-remove-file t]
19841 ["Cycle through agenda files" org-cycle-agenda-files t]
19842 ["Occur in all agenda files" org-occur-in-agenda-files t]
19843 "--")
19844 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19846 ;;;; Documentation
19848 (defun org-require-autoloaded-modules ()
19849 (interactive)
19850 (mapc 'require
19851 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19852 org-docbook org-exp org-html org-icalendar
19853 org-id org-latex
19854 org-publish org-remember org-table
19855 org-timer org-xoxo)))
19857 ;;;###autoload
19858 (defun org-reload (&optional uncompiled)
19859 "Reload all org lisp files.
19860 With prefix arg UNCOMPILED, load the uncompiled versions."
19861 (interactive "P")
19862 (require 'find-func)
19863 (let* ((file-re "^org\\(-.*\\)?\\.el")
19864 (dir-org (file-name-directory (org-find-library-dir "org")))
19865 (dir-org-contrib (ignore-errors
19866 (file-name-directory
19867 (org-find-library-dir "org-contribdir"))))
19868 (babel-files
19869 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19870 (append (list nil "comint" "eval" "exp" "keys"
19871 "lob" "ref" "table" "tangle")
19872 (delq nil
19873 (mapcar
19874 (lambda (lang)
19875 (when (cdr lang) (symbol-name (car lang))))
19876 org-babel-load-languages)))))
19877 (files
19878 (append babel-files
19879 (and dir-org-contrib
19880 (directory-files dir-org-contrib t file-re))
19881 (directory-files dir-org t file-re)))
19882 (remove-re (concat (if (featurep 'xemacs)
19883 "org-colview" "org-colview-xemacs")
19884 "\\'")))
19885 (setq files (mapcar 'file-name-sans-extension files))
19886 (setq files (mapcar
19887 (lambda (x) (if (string-match remove-re x) nil x))
19888 files))
19889 (setq files (delq nil files))
19890 (mapc
19891 (lambda (f)
19892 (when (featurep (intern (file-name-nondirectory f)))
19893 (if (and (not uncompiled)
19894 (file-exists-p (concat f ".elc")))
19895 (load (concat f ".elc") nil nil 'nosuffix)
19896 (load (concat f ".el") nil nil 'nosuffix))))
19897 files)
19898 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19899 (org-version nil 'full 'message))
19901 ;;;###autoload
19902 (defun org-customize ()
19903 "Call the customize function with org as argument."
19904 (interactive)
19905 (org-load-modules-maybe)
19906 (org-require-autoloaded-modules)
19907 (customize-browse 'org))
19909 (defun org-create-customize-menu ()
19910 "Create a full customization menu for Org-mode, insert it into the menu."
19911 (interactive)
19912 (org-load-modules-maybe)
19913 (org-require-autoloaded-modules)
19914 (if (fboundp 'customize-menu-create)
19915 (progn
19916 (easy-menu-change
19917 '("Org") "Customize"
19918 `(["Browse Org group" org-customize t]
19919 "--"
19920 ,(customize-menu-create 'org)
19921 ["Set" Custom-set t]
19922 ["Save" Custom-save t]
19923 ["Reset to Current" Custom-reset-current t]
19924 ["Reset to Saved" Custom-reset-saved t]
19925 ["Reset to Standard Settings" Custom-reset-standard t]))
19926 (message "\"Org\"-menu now contains full customization menu"))
19927 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19929 ;;;; Miscellaneous stuff
19931 ;;; Generally useful functions
19933 (defun org-get-at-bol (property)
19934 "Get text property PROPERTY at beginning of line."
19935 (get-text-property (point-at-bol) property))
19937 (defun org-find-text-property-in-string (prop s)
19938 "Return the first non-nil value of property PROP in string S."
19939 (or (get-text-property 0 prop s)
19940 (get-text-property (or (next-single-property-change 0 prop s) 0)
19941 prop s)))
19943 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19944 "Display the given MESSAGE as a warning."
19945 (if (fboundp 'display-warning)
19946 (display-warning 'org message
19947 (if (featurep 'xemacs) 'warning :warning))
19948 (let ((buf (get-buffer-create "*Org warnings*")))
19949 (with-current-buffer buf
19950 (goto-char (point-max))
19951 (insert "Warning (Org): " message)
19952 (unless (bolp)
19953 (newline)))
19954 (display-buffer buf)
19955 (sit-for 0))))
19957 (defun org-eval (form)
19958 "Eval FORM and return result."
19959 (condition-case error
19960 (eval form)
19961 (error (format "%%![Error: %s]" error))))
19963 (defun org-in-clocktable-p ()
19964 "Check if the cursor is in a clocktable."
19965 (let ((pos (point)) start)
19966 (save-excursion
19967 (end-of-line 1)
19968 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19969 (setq start (match-beginning 0))
19970 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19971 (>= (match-end 0) pos)
19972 start))))
19974 (defun org-in-commented-line ()
19975 "Is point in a line starting with `#'?"
19976 (equal (char-after (point-at-bol)) ?#))
19978 (defun org-in-indented-comment-line ()
19979 "Is point in a line starting with `#' after some white space?"
19980 (save-excursion
19981 (save-match-data
19982 (goto-char (point-at-bol))
19983 (looking-at "[ \t]*#"))))
19985 (defun org-in-verbatim-emphasis ()
19986 (save-match-data
19987 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19989 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19990 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19991 (if (and marker (marker-buffer marker)
19992 (buffer-live-p (marker-buffer marker)))
19993 (progn
19994 (org-pop-to-buffer-same-window (marker-buffer marker))
19995 (if (or (> marker (point-max)) (< marker (point-min)))
19996 (widen))
19997 (goto-char marker)
19998 (org-show-context 'org-goto))
19999 (if bookmark
20000 (bookmark-jump bookmark)
20001 (error "Cannot find location"))))
20003 (defun org-quote-csv-field (s)
20004 "Quote field for inclusion in CSV material."
20005 (if (string-match "[\",]" s)
20006 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20009 (defun org-force-self-insert (N)
20010 "Needed to enforce self-insert under remapping."
20011 (interactive "p")
20012 (self-insert-command N))
20014 (defun org-string-width (s)
20015 "Compute width of string, ignoring invisible characters.
20016 This ignores character with invisibility property `org-link', and also
20017 characters with property `org-cwidth', because these will become invisible
20018 upon the next fontification round."
20019 (let (b l)
20020 (when (or (eq t buffer-invisibility-spec)
20021 (assq 'org-link buffer-invisibility-spec))
20022 (while (setq b (text-property-any 0 (length s)
20023 'invisible 'org-link s))
20024 (setq s (concat (substring s 0 b)
20025 (substring s (or (next-single-property-change
20026 b 'invisible s) (length s)))))))
20027 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20028 (setq s (concat (substring s 0 b)
20029 (substring s (or (next-single-property-change
20030 b 'org-cwidth s) (length s))))))
20031 (setq l (string-width s) b -1)
20032 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20033 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20036 (defun org-shorten-string (s maxlength)
20037 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20038 If the string is shorter or has length MAXLENGTH, just return the
20039 original string. If it is longer, the functions finds a space in the
20040 string, breaks this string off at that locations and adds three dots
20041 as ellipsis. Including the ellipsis, the string will not be longer
20042 than MAXLENGTH. If finding a good breaking point in the string does
20043 not work, the string is just chopped off in the middle of a word
20044 if necessary."
20045 (if (<= (length s) maxlength)
20047 (let* ((n (max (- maxlength 4) 1))
20048 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20049 (if (string-match re s)
20050 (concat (match-string 1 s) "...")
20051 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20053 (defun org-get-indentation (&optional line)
20054 "Get the indentation of the current line, interpreting tabs.
20055 When LINE is given, assume it represents a line and compute its indentation."
20056 (if line
20057 (if (string-match "^ *" (org-remove-tabs line))
20058 (match-end 0))
20059 (save-excursion
20060 (beginning-of-line 1)
20061 (skip-chars-forward " \t")
20062 (current-column))))
20064 (defun org-get-string-indentation (s)
20065 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20066 (let ((n -1) (i 0) (w tab-width) c)
20067 (catch 'exit
20068 (while (< (setq n (1+ n)) (length s))
20069 (setq c (aref s n))
20070 (cond ((= c ?\ ) (setq i (1+ i)))
20071 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20072 (t (throw 'exit t)))))
20075 (defun org-remove-tabs (s &optional width)
20076 "Replace tabulators in S with spaces.
20077 Assumes that s is a single line, starting in column 0."
20078 (setq width (or width tab-width))
20079 (while (string-match "\t" s)
20080 (setq s (replace-match
20081 (make-string
20082 (- (* width (/ (+ (match-beginning 0) width) width))
20083 (match-beginning 0)) ?\ )
20084 t t s)))
20087 (defun org-fix-indentation (line ind)
20088 "Fix indentation in LINE.
20089 IND is a cons cell with target and minimum indentation.
20090 If the current indentation in LINE is smaller than the minimum,
20091 leave it alone. If it is larger than ind, set it to the target."
20092 (let* ((l (org-remove-tabs line))
20093 (i (org-get-indentation l))
20094 (i1 (car ind)) (i2 (cdr ind)))
20095 (if (>= i i2) (setq l (substring line i2)))
20096 (if (> i1 0)
20097 (concat (make-string i1 ?\ ) l)
20098 l)))
20100 (defun org-remove-indentation (code &optional n)
20101 "Remove the maximum common indentation from the lines in CODE.
20102 N may optionally be the number of spaces to remove."
20103 (with-temp-buffer
20104 (insert code)
20105 (org-do-remove-indentation n)
20106 (buffer-string)))
20108 (defun org-do-remove-indentation (&optional n)
20109 "Remove the maximum common indentation from the buffer."
20110 (untabify (point-min) (point-max))
20111 (let ((min 10000) re)
20112 (if n
20113 (setq min n)
20114 (goto-char (point-min))
20115 (while (re-search-forward "^ *[^ \n]" nil t)
20116 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20117 (unless (or (= min 0) (= min 10000))
20118 (setq re (format "^ \\{%d\\}" min))
20119 (goto-char (point-min))
20120 (while (re-search-forward re nil t)
20121 (replace-match "")
20122 (end-of-line 1))
20123 min)))
20125 (defun org-fill-template (template alist)
20126 "Find each %key of ALIST in TEMPLATE and replace it."
20127 (let ((case-fold-search nil)
20128 entry key value)
20129 (setq alist (sort (copy-sequence alist)
20130 (lambda (a b) (< (length (car a)) (length (car b))))))
20131 (while (setq entry (pop alist))
20132 (setq template
20133 (replace-regexp-in-string
20134 (concat "%" (regexp-quote (car entry)))
20135 (or (cdr entry) "") template t t)))
20136 template))
20138 (defun org-base-buffer (buffer)
20139 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20140 (if (not buffer)
20141 buffer
20142 (or (buffer-base-buffer buffer)
20143 buffer)))
20145 (defun org-trim (s)
20146 "Remove whitespace at beginning and end of string."
20147 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20148 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20151 (defun org-wrap (string &optional width lines)
20152 "Wrap string to either a number of lines, or a width in characters.
20153 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20154 that costs. If there is a word longer than WIDTH, the text is actually
20155 wrapped to the length of that word.
20156 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20157 many lines, whatever width that takes.
20158 The return value is a list of lines, without newlines at the end."
20159 (let* ((words (org-split-string string "[ \t\n]+"))
20160 (maxword (apply 'max (mapcar 'org-string-width words)))
20161 w ll)
20162 (cond (width
20163 (org-do-wrap words (max maxword width)))
20164 (lines
20165 (setq w maxword)
20166 (setq ll (org-do-wrap words maxword))
20167 (if (<= (length ll) lines)
20169 (setq ll words)
20170 (while (> (length ll) lines)
20171 (setq w (1+ w))
20172 (setq ll (org-do-wrap words w)))
20173 ll))
20174 (t (error "Cannot wrap this")))))
20176 (defun org-do-wrap (words width)
20177 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20178 (let (lines line)
20179 (while words
20180 (setq line (pop words))
20181 (while (and words (< (+ (length line) (length (car words))) width))
20182 (setq line (concat line " " (pop words))))
20183 (setq lines (push line lines)))
20184 (nreverse lines)))
20186 (defun org-split-string (string &optional separators)
20187 "Splits STRING into substrings at SEPARATORS.
20188 No empty strings are returned if there are matches at the beginning
20189 and end of string."
20190 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20191 (start 0)
20192 notfirst
20193 (list nil))
20194 (while (and (string-match rexp string
20195 (if (and notfirst
20196 (= start (match-beginning 0))
20197 (< start (length string)))
20198 (1+ start) start))
20199 (< (match-beginning 0) (length string)))
20200 (setq notfirst t)
20201 (or (eq (match-beginning 0) 0)
20202 (and (eq (match-beginning 0) (match-end 0))
20203 (eq (match-beginning 0) start))
20204 (setq list
20205 (cons (substring string start (match-beginning 0))
20206 list)))
20207 (setq start (match-end 0)))
20208 (or (eq start (length string))
20209 (setq list
20210 (cons (substring string start)
20211 list)))
20212 (nreverse list)))
20214 (defun org-quote-vert (s)
20215 "Replace \"|\" with \"\\vert\"."
20216 (while (string-match "|" s)
20217 (setq s (replace-match "\\vert" t t s)))
20220 (defun org-uuidgen-p (s)
20221 "Is S an ID created by UUIDGEN?"
20222 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20224 (defun org-in-src-block-p nil
20225 "Whether point is in a code source block."
20226 (let (ov)
20227 (when (setq ov (overlays-at (point)))
20228 (memq 'org-block-background
20229 (overlay-properties
20230 (car ov))))))
20232 (defun org-context ()
20233 "Return a list of contexts of the current cursor position.
20234 If several contexts apply, all are returned.
20235 Each context entry is a list with a symbol naming the context, and
20236 two positions indicating start and end of the context. Possible
20237 contexts are:
20239 :headline anywhere in a headline
20240 :headline-stars on the leading stars in a headline
20241 :todo-keyword on a TODO keyword (including DONE) in a headline
20242 :tags on the TAGS in a headline
20243 :priority on the priority cookie in a headline
20244 :item on the first line of a plain list item
20245 :item-bullet on the bullet/number of a plain list item
20246 :checkbox on the checkbox in a plain list item
20247 :table in an org-mode table
20248 :table-special on a special filed in a table
20249 :table-table in a table.el table
20250 :clocktable in a clocktable
20251 :src-block in a source block
20252 :link on a hyperlink
20253 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20254 :target on a <<target>>
20255 :radio-target on a <<<radio-target>>>
20256 :latex-fragment on a LaTeX fragment
20257 :latex-preview on a LaTeX fragment with overlaid preview image
20259 This function expects the position to be visible because it uses font-lock
20260 faces as a help to recognize the following contexts: :table-special, :link,
20261 and :keyword."
20262 (let* ((f (get-text-property (point) 'face))
20263 (faces (if (listp f) f (list f)))
20264 (case-fold-search t)
20265 (p (point)) clist o)
20266 ;; First the large context
20267 (cond
20268 ((org-at-heading-p t)
20269 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20270 (when (progn
20271 (beginning-of-line 1)
20272 (looking-at org-todo-line-tags-regexp))
20273 (push (org-point-in-group p 1 :headline-stars) clist)
20274 (push (org-point-in-group p 2 :todo-keyword) clist)
20275 (push (org-point-in-group p 4 :tags) clist))
20276 (goto-char p)
20277 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20278 (if (looking-at "\\[#[A-Z0-9]\\]")
20279 (push (org-point-in-group p 0 :priority) clist)))
20281 ((org-at-item-p)
20282 (push (org-point-in-group p 2 :item-bullet) clist)
20283 (push (list :item (point-at-bol)
20284 (save-excursion (org-end-of-item) (point)))
20285 clist)
20286 (and (org-at-item-checkbox-p)
20287 (push (org-point-in-group p 0 :checkbox) clist)))
20289 ((org-at-table-p)
20290 (push (list :table (org-table-begin) (org-table-end)) clist)
20291 (if (memq 'org-formula faces)
20292 (push (list :table-special
20293 (previous-single-property-change p 'face)
20294 (next-single-property-change p 'face)) clist)))
20295 ((org-at-table-p 'any)
20296 (push (list :table-table) clist)))
20297 (goto-char p)
20299 (let ((case-fold-search t))
20300 ;; New the "medium" contexts: clocktables, source blocks
20301 (cond ((org-in-clocktable-p)
20302 (push (list :clocktable
20303 (and (or (looking-at "#\\+BEGIN: clocktable")
20304 (search-backward "#+BEGIN: clocktable" nil t))
20305 (match-beginning 0))
20306 (and (re-search-forward "#\\+END:?" nil t)
20307 (match-end 0))) clist))
20308 ((org-in-src-block-p)
20309 (push (list :src-block
20310 (and (or (looking-at "#\\+BEGIN_SRC")
20311 (search-backward "#+BEGIN_SRC" nil t))
20312 (match-beginning 0))
20313 (and (search-forward "#+END_SRC" nil t)
20314 (match-beginning 0))) clist))))
20315 (goto-char p)
20317 ;; Now the small context
20318 (cond
20319 ((org-at-timestamp-p)
20320 (push (org-point-in-group p 0 :timestamp) clist))
20321 ((memq 'org-link faces)
20322 (push (list :link
20323 (previous-single-property-change p 'face)
20324 (next-single-property-change p 'face)) clist))
20325 ((memq 'org-special-keyword faces)
20326 (push (list :keyword
20327 (previous-single-property-change p 'face)
20328 (next-single-property-change p 'face)) clist))
20329 ((org-at-target-p)
20330 (push (org-point-in-group p 0 :target) clist)
20331 (goto-char (1- (match-beginning 0)))
20332 (if (looking-at org-radio-target-regexp)
20333 (push (org-point-in-group p 0 :radio-target) clist))
20334 (goto-char p))
20335 ((setq o (car (delq nil
20336 (mapcar
20337 (lambda (x)
20338 (if (memq x org-latex-fragment-image-overlays) x))
20339 (overlays-at (point))))))
20340 (push (list :latex-fragment
20341 (overlay-start o) (overlay-end o)) clist)
20342 (push (list :latex-preview
20343 (overlay-start o) (overlay-end o)) clist))
20344 ((org-inside-LaTeX-fragment-p)
20345 ;; FIXME: positions wrong.
20346 (push (list :latex-fragment (point) (point)) clist)))
20348 (setq clist (nreverse (delq nil clist)))
20349 clist))
20351 ;; FIXME: Compare with at-regexp-p Do we need both?
20352 (defun org-in-regexp (re &optional nlines visually)
20353 "Check if point is inside a match of regexp.
20354 Normally only the current line is checked, but you can include NLINES extra
20355 lines both before and after point into the search.
20356 If VISUALLY is set, require that the cursor is not after the match but
20357 really on, so that the block visually is on the match."
20358 (catch 'exit
20359 (let ((pos (point))
20360 (eol (point-at-eol (+ 1 (or nlines 0))))
20361 (inc (if visually 1 0)))
20362 (save-excursion
20363 (beginning-of-line (- 1 (or nlines 0)))
20364 (while (re-search-forward re eol t)
20365 (if (and (<= (match-beginning 0) pos)
20366 (>= (+ inc (match-end 0)) pos))
20367 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20369 (defun org-at-regexp-p (regexp)
20370 "Is point inside a match of REGEXP in the current line?"
20371 (catch 'exit
20372 (save-excursion
20373 (let ((pos (point)) (end (point-at-eol)))
20374 (beginning-of-line 1)
20375 (while (re-search-forward regexp end t)
20376 (if (and (<= (match-beginning 0) pos)
20377 (>= (match-end 0) pos))
20378 (throw 'exit t)))
20379 nil))))
20381 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20382 "Non-nil when point is between matches of START-RE and END-RE.
20384 Also return a non-nil value when point is on one of the matches.
20386 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20387 buffer positions. Default values are the positions of headlines
20388 surrounding the point.
20390 The functions returns a cons cell whose car (resp. cdr) is the
20391 position before START-RE (resp. after END-RE)."
20392 (save-match-data
20393 (let ((pos (point))
20394 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20395 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20396 beg end)
20397 (save-excursion
20398 ;; Point is on a block when on START-RE or if START-RE can be
20399 ;; found before it...
20400 (and (or (org-at-regexp-p start-re)
20401 (re-search-backward start-re limit-up t))
20402 (setq beg (match-beginning 0))
20403 ;; ... and END-RE after it...
20404 (goto-char (match-end 0))
20405 (re-search-forward end-re limit-down t)
20406 (> (setq end (match-end 0)) pos)
20407 ;; ... without another START-RE in-between.
20408 (goto-char (match-beginning 0))
20409 (not (re-search-backward start-re (1+ beg) t))
20410 ;; Return value.
20411 (cons beg end))))))
20413 (defun org-in-block-p (names)
20414 "Non-nil when point belongs to a block whose name belongs to NAMES.
20416 NAMES is a list of strings containing names of blocks.
20418 Return first block name matched, or nil. Beware that in case of
20419 nested blocks, the returned name may not belong to the closest
20420 block from point."
20421 (save-match-data
20422 (catch 'exit
20423 (let ((case-fold-search t)
20424 (lim-up (save-excursion (outline-previous-heading)))
20425 (lim-down (save-excursion (outline-next-heading))))
20426 (mapc (lambda (name)
20427 (let ((n (regexp-quote name)))
20428 (when (org-between-regexps-p
20429 (concat "^[ \t]*#\\+begin_" n)
20430 (concat "^[ \t]*#\\+end_" n)
20431 lim-up lim-down)
20432 (throw 'exit n))))
20433 names))
20434 nil)))
20436 (defun org-occur-in-agenda-files (regexp &optional nlines)
20437 "Call `multi-occur' with buffers for all agenda files."
20438 (interactive "sOrg-files matching: \np")
20439 (let* ((files (org-agenda-files))
20440 (tnames (mapcar 'file-truename files))
20441 (extra org-agenda-text-search-extra-files)
20443 (when (eq (car extra) 'agenda-archives)
20444 (setq extra (cdr extra))
20445 (setq files (org-add-archive-files files)))
20446 (while (setq f (pop extra))
20447 (unless (member (file-truename f) tnames)
20448 (add-to-list 'files f 'append)
20449 (add-to-list 'tnames (file-truename f) 'append)))
20450 (multi-occur
20451 (mapcar (lambda (x)
20452 (with-current-buffer
20453 (or (get-file-buffer x) (find-file-noselect x))
20454 (widen)
20455 (current-buffer)))
20456 files)
20457 regexp)))
20459 (if (boundp 'occur-mode-find-occurrence-hook)
20460 ;; Emacs 23
20461 (add-hook 'occur-mode-find-occurrence-hook
20462 (lambda ()
20463 (when (derived-mode-p 'org-mode)
20464 (org-reveal))))
20465 ;; Emacs 22
20466 (defadvice occur-mode-goto-occurrence
20467 (after org-occur-reveal activate)
20468 (and (derived-mode-p 'org-mode) (org-reveal)))
20469 (defadvice occur-mode-goto-occurrence-other-window
20470 (after org-occur-reveal activate)
20471 (and (derived-mode-p 'org-mode) (org-reveal)))
20472 (defadvice occur-mode-display-occurrence
20473 (after org-occur-reveal activate)
20474 (when (derived-mode-p 'org-mode)
20475 (let ((pos (occur-mode-find-occurrence)))
20476 (with-current-buffer (marker-buffer pos)
20477 (save-excursion
20478 (goto-char pos)
20479 (org-reveal)))))))
20481 (defun org-occur-link-in-agenda-files ()
20482 "Create a link and search for it in the agendas.
20483 The link is not stored in `org-stored-links', it is just created
20484 for the search purpose."
20485 (interactive)
20486 (let ((link (condition-case nil
20487 (org-store-link nil)
20488 (error "Unable to create a link to here"))))
20489 (org-occur-in-agenda-files (regexp-quote link))))
20491 (defun org-uniquify (list)
20492 "Remove duplicate elements from LIST."
20493 (let (res)
20494 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20495 res))
20497 (defun org-delete-all (elts list)
20498 "Remove all elements in ELTS from LIST."
20499 (while elts
20500 (setq list (delete (pop elts) list)))
20501 list)
20503 (defun org-count (cl-item cl-seq)
20504 "Count the number of occurrences of ITEM in SEQ.
20505 Taken from `count' in cl-seq.el with all keyword arguments removed."
20506 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20507 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20508 (while (< cl-start cl-end)
20509 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20510 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20511 (setq cl-start (1+ cl-start)))
20512 cl-count))
20514 (defun org-remove-if (predicate seq)
20515 "Remove everything from SEQ that fulfills PREDICATE."
20516 (let (res e)
20517 (while seq
20518 (setq e (pop seq))
20519 (if (not (funcall predicate e)) (push e res)))
20520 (nreverse res)))
20522 (defun org-remove-if-not (predicate seq)
20523 "Remove everything from SEQ that does not fulfill PREDICATE."
20524 (let (res e)
20525 (while seq
20526 (setq e (pop seq))
20527 (if (funcall predicate e) (push e res)))
20528 (nreverse res)))
20530 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20531 "Reduce two-argument FUNCTION across SEQ.
20532 Taken from `reduce' in cl-seq.el with all keyword arguments but
20533 \":initial-value\" removed."
20534 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20535 (cadr (memq :initial-value cl-keys)))
20536 (cl-seq (pop cl-seq))
20537 (t (funcall cl-func)))))
20538 (while cl-seq
20539 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20540 cl-accum))
20542 (defun org-back-over-empty-lines ()
20543 "Move backwards over whitespace, to the beginning of the first empty line.
20544 Returns the number of empty lines passed."
20545 (let ((pos (point)))
20546 (if (cdr (assoc 'heading org-blank-before-new-entry))
20547 (skip-chars-backward " \t\n\r")
20548 (unless (eobp)
20549 (forward-line -1)))
20550 (beginning-of-line 2)
20551 (goto-char (min (point) pos))
20552 (count-lines (point) pos)))
20554 (defun org-skip-whitespace ()
20555 (skip-chars-forward " \t\n\r"))
20557 (defun org-point-in-group (point group &optional context)
20558 "Check if POINT is in match-group GROUP.
20559 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20560 match. If the match group does not exist or point is not inside it,
20561 return nil."
20562 (and (match-beginning group)
20563 (>= point (match-beginning group))
20564 (<= point (match-end group))
20565 (if context
20566 (list context (match-beginning group) (match-end group))
20567 t)))
20569 (defun org-switch-to-buffer-other-window (&rest args)
20570 "Switch to buffer in a second window on the current frame.
20571 In particular, do not allow pop-up frames.
20572 Returns the newly created buffer."
20573 (let (pop-up-frames special-display-buffer-names special-display-regexps
20574 special-display-function)
20575 (apply 'switch-to-buffer-other-window args)))
20577 (defun org-combine-plists (&rest plists)
20578 "Create a single property list from all plists in PLISTS.
20579 The process starts by copying the first list, and then setting properties
20580 from the other lists. Settings in the last list are the most significant
20581 ones and overrule settings in the other lists."
20582 (let ((rtn (copy-sequence (pop plists)))
20583 p v ls)
20584 (while plists
20585 (setq ls (pop plists))
20586 (while ls
20587 (setq p (pop ls) v (pop ls))
20588 (setq rtn (plist-put rtn p v))))
20589 rtn))
20591 (defun org-replace-escapes (string table)
20592 "Replace %-escapes in STRING with values in TABLE.
20593 TABLE is an association list with keys like \"%a\" and string values.
20594 The sequences in STRING may contain normal field width and padding information,
20595 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20596 so values can contain further %-escapes if they are define later in TABLE."
20597 (let ((tbl (copy-alist table))
20598 (case-fold-search nil)
20599 (pchg 0)
20600 e re rpl)
20601 (while (setq e (pop tbl))
20602 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20603 (when (and (cdr e) (string-match re (cdr e)))
20604 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20605 (safe "SREF"))
20606 (add-text-properties 0 3 (list 'sref sref) safe)
20607 (setcdr e (replace-match safe t t (cdr e)))))
20608 (while (string-match re string)
20609 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20610 (cdr e)))
20611 (setq string (replace-match rpl t t string))))
20612 (while (setq pchg (next-property-change pchg string))
20613 (let ((sref (get-text-property pchg 'sref string)))
20614 (when (and sref (string-match "SREF" string pchg))
20615 (setq string (replace-match sref t t string)))))
20616 string))
20618 (defun org-sublist (list start end)
20619 "Return a section of LIST, from START to END.
20620 Counting starts at 1."
20621 (let (rtn (c start))
20622 (setq list (nthcdr (1- start) list))
20623 (while (and list (<= c end))
20624 (push (pop list) rtn)
20625 (setq c (1+ c)))
20626 (nreverse rtn)))
20628 (defun org-find-base-buffer-visiting (file)
20629 "Like `find-buffer-visiting' but always return the base buffer and
20630 not an indirect buffer."
20631 (let ((buf (or (get-file-buffer file)
20632 (find-buffer-visiting file))))
20633 (if buf
20634 (or (buffer-base-buffer buf) buf)
20635 nil)))
20637 (defun org-image-file-name-regexp (&optional extensions)
20638 "Return regexp matching the file names of images.
20639 If EXTENSIONS is given, only match these."
20640 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20641 (image-file-name-regexp)
20642 (let ((image-file-name-extensions
20643 (or extensions
20644 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20645 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20646 (concat "\\."
20647 (regexp-opt (nconc (mapcar 'upcase
20648 image-file-name-extensions)
20649 image-file-name-extensions)
20651 "\\'"))))
20653 (defun org-file-image-p (file &optional extensions)
20654 "Return non-nil if FILE is an image."
20655 (save-match-data
20656 (string-match (org-image-file-name-regexp extensions) file)))
20658 (defun org-get-cursor-date ()
20659 "Return the date at cursor in as a time.
20660 This works in the calendar and in the agenda, anywhere else it just
20661 returns the current time."
20662 (let (date day defd)
20663 (cond
20664 ((eq major-mode 'calendar-mode)
20665 (setq date (calendar-cursor-to-date)
20666 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20667 ((eq major-mode 'org-agenda-mode)
20668 (setq day (get-text-property (point) 'day))
20669 (if day
20670 (setq date (calendar-gregorian-from-absolute day)
20671 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20672 (nth 2 date))))))
20673 (or defd (current-time))))
20675 (defun org-mark-subtree (&optional up)
20676 "Mark the current subtree.
20677 This puts point at the start of the current subtree, and mark at
20678 the end. If a numeric prefix UP is given, move up into the
20679 hierarchy of headlines by UP levels before marking the subtree."
20680 (interactive "P")
20681 (org-with-limited-levels
20682 (cond ((org-at-heading-p) (beginning-of-line))
20683 ((org-before-first-heading-p) (error "Not in a subtree"))
20684 (t (outline-previous-visible-heading 1))))
20685 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20686 (if (org-called-interactively-p 'any)
20687 (call-interactively 'org-mark-element)
20688 (org-mark-element)))
20690 ;;; Indentation
20692 (defun org-indent-line ()
20693 "Indent line depending on context."
20694 (interactive)
20695 (let* ((pos (point))
20696 (itemp (org-at-item-p))
20697 (case-fold-search t)
20698 (org-drawer-regexp (or org-drawer-regexp "\000"))
20699 (inline-task-p (and (featurep 'org-inlinetask)
20700 (org-inlinetask-in-task-p)))
20701 (inline-re (and inline-task-p
20702 (org-inlinetask-outline-regexp)))
20703 column)
20704 (if (and orgstruct-is-++ (eq pos (point)))
20705 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20706 (indent-according-to-mode))
20707 (beginning-of-line 1)
20708 (cond
20709 ;; Headings
20710 ((looking-at org-outline-regexp) (setq column 0))
20711 ;; Included files
20712 ((looking-at "#\\+include:") (setq column 0))
20713 ;; Footnote definition
20714 ((looking-at org-footnote-definition-re) (setq column 0))
20715 ;; Literal examples
20716 ((looking-at "[ \t]*:\\( \\|$\\)")
20717 (setq column (org-get-indentation))) ; do nothing
20718 ;; Lists
20719 ((ignore-errors (goto-char (org-in-item-p)))
20720 (setq column (if itemp
20721 (org-get-indentation)
20722 (org-list-item-body-column (point))))
20723 (goto-char pos))
20724 ;; Drawers
20725 ((and (looking-at "[ \t]*:END:")
20726 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20727 (save-excursion
20728 (goto-char (1- (match-beginning 1)))
20729 (setq column (current-column))))
20730 ;; Special blocks
20731 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20732 (save-excursion
20733 (re-search-backward
20734 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20735 (setq column (org-get-indentation (match-string 0))))
20736 ((and (not (looking-at "[ \t]*#\\+begin_"))
20737 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20738 (save-excursion
20739 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20740 (setq column
20741 (cond ((equal (downcase (match-string 1)) "src")
20742 ;; src blocks: let `org-edit-src-exit' handle them
20743 (org-get-indentation))
20744 ((equal (downcase (match-string 1)) "example")
20745 (max (org-get-indentation)
20746 (org-get-indentation (match-string 0))))
20748 (org-get-indentation (match-string 0))))))
20749 ;; This line has nothing special, look at the previous relevant
20750 ;; line to compute indentation
20752 (beginning-of-line 0)
20753 (while (and (not (bobp))
20754 (not (looking-at org-drawer-regexp))
20755 ;; When point started in an inline task, do not move
20756 ;; above task starting line.
20757 (not (and inline-task-p (looking-at inline-re)))
20758 ;; Skip drawers, blocks, empty lines, verbatim,
20759 ;; comments, tables, footnotes definitions, lists,
20760 ;; inline tasks.
20761 (or (and (looking-at "[ \t]*:END:")
20762 (re-search-backward org-drawer-regexp nil t))
20763 (and (looking-at "[ \t]*#\\+end_")
20764 (re-search-backward "[ \t]*#\\+begin_"nil t))
20765 (looking-at "[ \t]*[\n:#|]")
20766 (looking-at org-footnote-definition-re)
20767 (and (ignore-errors (goto-char (org-in-item-p)))
20768 (goto-char
20769 (org-list-get-top-point (org-list-struct))))
20770 (and (not inline-task-p)
20771 (featurep 'org-inlinetask)
20772 (org-inlinetask-in-task-p)
20773 (or (org-inlinetask-goto-beginning) t))))
20774 (beginning-of-line 0))
20775 (cond
20776 ;; There was an heading above.
20777 ((looking-at "\\*+[ \t]+")
20778 (if (not org-adapt-indentation)
20779 (setq column 0)
20780 (goto-char (match-end 0))
20781 (setq column (current-column))))
20782 ;; A drawer had started and is unfinished
20783 ((looking-at org-drawer-regexp)
20784 (goto-char (1- (match-beginning 1)))
20785 (setq column (current-column)))
20786 ;; Else, nothing noticeable found: get indentation and go on.
20787 (t (setq column (org-get-indentation))))))
20788 ;; Now apply indentation and move cursor accordingly
20789 (goto-char pos)
20790 (if (<= (current-column) (current-indentation))
20791 (org-indent-line-to column)
20792 (save-excursion (org-indent-line-to column)))
20793 ;; Special polishing for properties, see `org-property-format'
20794 (setq column (current-column))
20795 (beginning-of-line 1)
20796 (if (looking-at
20797 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20798 (replace-match (concat (match-string 1)
20799 (format org-property-format
20800 (match-string 2) (match-string 3)))
20801 t t))
20802 (org-move-to-column column))))
20804 (defun org-indent-drawer ()
20805 "Indent the drawer at point."
20806 (interactive)
20807 (let ((p (point))
20808 (e (and (save-excursion (re-search-forward ":END:" nil t))
20809 (match-end 0)))
20810 (folded
20811 (save-excursion
20812 (end-of-line)
20813 (when (overlays-at (point))
20814 (member 'invisible (overlay-properties
20815 (car (overlays-at (point)))))))))
20816 (when folded (org-cycle))
20817 (indent-for-tab-command)
20818 (while (and (move-beginning-of-line 2) (< (point) e))
20819 (indent-for-tab-command))
20820 (goto-char p)
20821 (when folded (org-cycle)))
20822 (message "Drawer at point indented"))
20824 (defun org-indent-block ()
20825 "Indent the block at point."
20826 (interactive)
20827 (let ((p (point))
20828 (case-fold-search t)
20829 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20830 (match-end 0)))
20831 (folded
20832 (save-excursion
20833 (end-of-line)
20834 (when (overlays-at (point))
20835 (member 'invisible (overlay-properties
20836 (car (overlays-at (point)))))))))
20837 (when folded (org-cycle))
20838 (indent-for-tab-command)
20839 (while (and (move-beginning-of-line 2) (< (point) e))
20840 (indent-for-tab-command))
20841 (goto-char p)
20842 (when folded (org-cycle)))
20843 (message "Block at point indented"))
20845 (defun org-indent-region (start end)
20846 "Indent region."
20847 (interactive "r")
20848 (save-excursion
20849 (let ((line-end (org-current-line end)))
20850 (goto-char start)
20851 (while (< (org-current-line) line-end)
20852 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20853 (t (call-interactively 'org-indent-line)))
20854 (move-beginning-of-line 2)))))
20857 ;;; Filling
20859 ;; We use our own fill-paragraph and auto-fill functions.
20861 ;; `org-fill-paragraph' relies on adaptive filling and context
20862 ;; checking. Appropriate `fill-prefix' is computed with
20863 ;; `org-adaptive-fill-function'.
20865 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20866 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20867 ;; `org-adaptive-fill-function' value. Internally,
20868 ;; `org-comment-line-break-function' breaks the line.
20870 ;; `org-setup-filling' installs filling and auto-filling related
20871 ;; variables during `org-mode' initialization.
20873 (defun org-setup-filling ()
20874 (interactive)
20875 ;; Prevent auto-fill from inserting unwanted new items.
20876 (when (boundp 'fill-nobreak-predicate)
20877 (org-set-local
20878 'fill-nobreak-predicate
20879 (org-uniquify
20880 (append fill-nobreak-predicate
20881 '(org-fill-paragraph-separate-nobreak-p
20882 org-fill-line-break-nobreak-p)))))
20883 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20884 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20885 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20886 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20888 (defvar org-element-paragraph-separate) ; org-element.el
20889 (defun org-fill-paragraph-separate-nobreak-p ()
20890 "Non-nil when a line break at point would insert a new item."
20891 (looking-at (substring org-element-paragraph-separate 1)))
20893 (defun org-fill-line-break-nobreak-p ()
20894 "Non-nil when a line break at point would create an Org line break."
20895 (save-excursion
20896 (skip-chars-backward "[ \t]")
20897 (skip-chars-backward "\\\\")
20898 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20900 (declare-function message-in-body-p "message" ())
20901 (defvar org-element--affiliated-re) ; From org-element.el
20902 (defun org-adaptive-fill-function ()
20903 "Compute a fill prefix for the current line.
20904 Return fill prefix, as a string, or nil if current line isn't
20905 meant to be filled."
20906 (org-with-wide-buffer
20907 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
20908 ;; FIXME: This is really the job of orgstruct++-mode
20909 (let* ((p (line-beginning-position))
20910 (element (save-excursion (beginning-of-line)
20911 (org-element-at-point)))
20912 (type (org-element-type element))
20913 (post-affiliated
20914 (save-excursion
20915 (goto-char (org-element-property :begin element))
20916 (while (looking-at org-element--affiliated-re) (forward-line))
20917 (point))))
20918 (unless (< p post-affiliated)
20919 (case type
20920 (comment (looking-at "[ \t]*# ?") (match-string 0))
20921 (footnote-definition "")
20922 ((item plain-list)
20923 (make-string (org-list-item-body-column post-affiliated) ? ))
20924 (paragraph
20925 ;; Fill prefix is usually the same as the current line,
20926 ;; except if the paragraph is at the beginning of an item.
20927 (let ((parent (org-element-property :parent element)))
20928 (cond ((eq (org-element-type parent) 'item)
20929 (make-string (org-list-item-body-column
20930 (org-element-property :begin parent))
20931 ? ))
20932 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20933 (match-string 0))
20934 (t ""))))
20935 (comment-block
20936 ;; Only fill contents if P is within block boundaries.
20937 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20938 (forward-line)
20939 (point)))
20940 (cend (save-excursion
20941 (goto-char (org-element-property :end element))
20942 (skip-chars-backward " \r\t\n")
20943 (line-beginning-position))))
20944 (when (and (>= p cbeg) (< p cend))
20945 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20946 (match-string 0)
20947 ""))))))))))
20949 (declare-function message-goto-body "message" ())
20950 (defvar message-cite-prefix-regexp) ; From message.el
20951 (defvar org-element-all-objects) ; From org-element.el
20952 (defun org-fill-paragraph (&optional justify)
20953 "Fill element at point, when applicable.
20955 This function only applies to comment blocks, comments, example
20956 blocks and paragraphs. Also, as a special case, re-align table
20957 when point is at one.
20959 If JUSTIFY is non-nil (interactively, with prefix argument),
20960 justify as well. If `sentence-end-double-space' is non-nil, then
20961 period followed by one space does not end a sentence, so don't
20962 break a line there. The variable `fill-column' controls the
20963 width for filling.
20965 For convenience, when point is at a plain list, an item or
20966 a footnote definition, try to fill the first paragraph within."
20967 ;; Falls back on message-fill-paragraph when necessary
20968 (interactive)
20969 (if (and (derived-mode-p 'message-mode)
20970 (or (not (message-in-body-p))
20971 (save-excursion (move-beginning-of-line 1)
20972 (looking-at message-cite-prefix-regexp))))
20973 (let ((fill-paragraph-function
20974 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
20975 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
20976 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
20977 (paragraph-separate
20978 (cadadr (assoc 'paragraph-separate org-fb-vars))))
20979 (fill-paragraph nil))
20980 (save-excursion
20981 ;; Move to end of line in order to get the first paragraph
20982 ;; within a plain list or a footnote definition.
20983 (end-of-line)
20984 (let ((element (org-element-at-point)))
20985 ;; First check if point is in a blank line at the beginning of
20986 ;; the buffer. In that case, ignore filling.
20987 (if (< (point) (org-element-property :begin element)) t
20988 (case (org-element-type element)
20989 ;; Align Org tables, leave table.el tables as-is.
20990 (table-row (org-table-align) t)
20991 (table
20992 (when (eq (org-element-property :type element) 'org)
20993 (org-table-align))
20995 (paragraph
20996 ;; Paragraphs may contain `line-break' type objects.
20997 (let ((beg (max (point-min)
20998 (org-element-property :contents-begin element)))
20999 (end (min (point-max)
21000 (org-element-property :contents-end element))))
21001 ;; Do nothing if point is at an affiliated keyword.
21002 (if (< (point) beg) t
21003 (when (derived-mode-p 'message-mode)
21004 ;; In `message-mode', do not fill following
21005 ;; citation in current paragraph nor text before
21006 ;; message body.
21007 (let ((body-start (save-excursion (message-goto-body))))
21008 (when body-start (setq beg (max body-start beg))))
21009 (when (save-excursion
21010 (re-search-forward
21011 (concat "^" message-cite-prefix-regexp) end t))
21012 (setq end (match-beginning 0))))
21013 ;; Fill paragraph, taking line breaks into
21014 ;; consideration. For that, slice the paragraph
21015 ;; using line breaks as separators, and fill the
21016 ;; parts in reverse order to avoid messing with
21017 ;; markers.
21018 (save-excursion
21019 (goto-char end)
21020 (mapc
21021 (lambda (pos)
21022 (fill-region-as-paragraph pos (point) justify)
21023 (goto-char pos))
21024 ;; Find the list of ending positions for line
21025 ;; breaks in the current paragraph. Add paragraph
21026 ;; beginning to include first slice.
21027 (nreverse
21028 (cons
21030 (org-element-map
21031 (org-element--parse-objects
21032 beg end nil org-element-all-objects)
21033 'line-break
21034 (lambda (lb) (org-element-property :end lb)))))))
21035 t)))
21036 ;; Contents of `comment-block' type elements should be
21037 ;; filled as plain text, but only if point is within block
21038 ;; markers.
21039 (comment-block
21040 (let* ((case-fold-search t)
21041 (beg (save-excursion
21042 (goto-char (org-element-property :begin element))
21043 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21044 (forward-line)
21045 (point)))
21046 (end (save-excursion
21047 (goto-char (org-element-property :end element))
21048 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21049 (line-beginning-position))))
21050 (when (and (>= (point) beg) (< (point) end))
21051 (fill-region-as-paragraph
21052 (save-excursion
21053 (end-of-line)
21054 (re-search-backward "^[ \t]*$" beg 'move)
21055 (line-beginning-position))
21056 (save-excursion
21057 (beginning-of-line)
21058 (re-search-forward "^[ \t]*$" end 'move)
21059 (line-beginning-position))
21060 justify)))
21062 ;; Fill comments.
21063 (comment (fill-comment-paragraph justify))
21064 ;; Ignore every other element.
21065 (otherwise t)))))))
21067 (defun org-auto-fill-function ()
21068 "Auto-fill function."
21069 ;; Check if auto-filling is meaningful.
21070 (let ((fc (current-fill-column)))
21071 (when (and fc (> (current-column) fc))
21072 (let* ((fill-prefix (org-adaptive-fill-function))
21073 ;; Enforce empty fill prefix, if required. Otherwise, it
21074 ;; will be computed again.
21075 (adaptive-fill-mode (not (equal fill-prefix ""))))
21076 (when fill-prefix (do-auto-fill))))))
21078 (defun org-comment-line-break-function (&optional soft)
21079 "Break line at point and indent, continuing comment if within one.
21080 The inserted newline is marked hard if variable
21081 `use-hard-newlines' is true, unless optional argument SOFT is
21082 non-nil."
21083 (if soft (insert-and-inherit ?\n) (newline 1))
21084 (save-excursion (forward-char -1) (delete-horizontal-space))
21085 (delete-horizontal-space)
21086 (indent-to-left-margin)
21087 (insert-before-markers-and-inherit fill-prefix))
21090 ;;; Comments
21092 ;; Org comments syntax is quite complex. It requires the entire line
21093 ;; to be just a comment. Also, even with the right syntax at the
21094 ;; beginning of line, some some elements (i.e. verse-block or
21095 ;; example-block) don't accept comments. Usual Emacs comment commands
21096 ;; cannot cope with those requirements. Therefore, Org replaces them.
21098 ;; Org still relies on `comment-dwim', but cannot trust
21099 ;; `comment-only-p'. So, `comment-region-function' and
21100 ;; `uncomment-region-function' both point
21101 ;; to`org-comment-or-uncomment-region'. Eventually,
21102 ;; `org-insert-comment' takes care of insertion of comments at the
21103 ;; beginning of line.
21105 ;; `org-setup-comments-handling' install comments related variables
21106 ;; during `org-mode' initialization.
21108 (defun org-setup-comments-handling ()
21109 (interactive)
21110 (org-set-local 'comment-use-syntax nil)
21111 (org-set-local 'comment-start "# ")
21112 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21113 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21114 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21115 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21117 (defun org-insert-comment ()
21118 "Insert an empty comment above current line.
21119 If the line is empty, insert comment at its beginning."
21120 (beginning-of-line)
21121 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21122 (org-indent-line)
21123 (insert "# "))
21125 (defvar comment-empty-lines) ; From newcomment.el.
21126 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21127 "Comment or uncomment each non-blank line in the region.
21128 Uncomment each non-blank line between BEG and END if it only
21129 contains commented lines. Otherwise, comment them."
21130 (save-restriction
21131 ;; Restrict region
21132 (narrow-to-region (save-excursion (goto-char beg)
21133 (skip-chars-forward " \r\t\n" end)
21134 (line-beginning-position))
21135 (save-excursion (goto-char end)
21136 (skip-chars-backward " \r\t\n" beg)
21137 (line-end-position)))
21138 (let ((uncommentp
21139 ;; UNCOMMENTP is non-nil when every non blank line between
21140 ;; BEG and END is a comment.
21141 (save-excursion
21142 (goto-char (point-min))
21143 (while (and (not (eobp))
21144 (let ((element (org-element-at-point)))
21145 (and (eq (org-element-type element) 'comment)
21146 (goto-char (min (point-max)
21147 (org-element-property
21148 :end element)))))))
21149 (eobp))))
21150 (if uncommentp
21151 ;; Only blank lines and comments in region: uncomment it.
21152 (save-excursion
21153 (goto-char (point-min))
21154 (while (not (eobp))
21155 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21156 (replace-match "" nil nil nil 1))
21157 (forward-line)))
21158 ;; Comment each line in region.
21159 (let ((min-indent (point-max)))
21160 ;; First find the minimum indentation across all lines.
21161 (save-excursion
21162 (goto-char (point-min))
21163 (while (and (not (eobp)) (not (zerop min-indent)))
21164 (unless (looking-at "[ \t]*$")
21165 (setq min-indent (min min-indent (current-indentation))))
21166 (forward-line)))
21167 ;; Then loop over all lines.
21168 (save-excursion
21169 (goto-char (point-min))
21170 (while (not (eobp))
21171 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21172 (org-move-to-column min-indent t)
21173 (insert comment-start))
21174 (forward-line))))))))
21177 ;;; Other stuff.
21179 (defun org-toggle-fixed-width-section (arg)
21180 "Toggle the fixed-width export.
21181 If there is no active region, the QUOTE keyword at the current headline is
21182 inserted or removed. When present, it causes the text between this headline
21183 and the next to be exported as fixed-width text, and unmodified.
21184 If there is an active region, this command adds or removes a colon as the
21185 first character of this line. If the first character of a line is a colon,
21186 this line is also exported in fixed-width font."
21187 (interactive "P")
21188 (let* ((cc 0)
21189 (regionp (org-region-active-p))
21190 (beg (if regionp (region-beginning) (point)))
21191 (end (if regionp (region-end)))
21192 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21193 (case-fold-search nil)
21194 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21195 off)
21196 (if regionp
21197 (save-excursion
21198 (goto-char beg)
21199 (setq cc (current-column))
21200 (beginning-of-line 1)
21201 (setq off (looking-at re))
21202 (while (> nlines 0)
21203 (setq nlines (1- nlines))
21204 (beginning-of-line 1)
21205 (cond
21206 (arg
21207 (org-move-to-column cc t)
21208 (insert ": \n")
21209 (forward-line -1))
21210 ((and off (looking-at re))
21211 (replace-match "" t t nil 1))
21212 ((not off) (org-move-to-column cc t) (insert ": ")))
21213 (forward-line 1)))
21214 (save-excursion
21215 (org-back-to-heading)
21216 (cond
21217 ((looking-at (format org-heading-keyword-regexp-format
21218 org-quote-string))
21219 (goto-char (match-end 1))
21220 (looking-at (concat " +" org-quote-string))
21221 (replace-match "" t t)
21222 (when (eolp) (insert " ")))
21223 ((looking-at org-outline-regexp)
21224 (goto-char (match-end 0))
21225 (insert org-quote-string " ")))))))
21227 (defun org-reftex-citation ()
21228 "Use reftex-citation to insert a citation into the buffer.
21229 This looks for a line like
21231 #+BIBLIOGRAPHY: foo plain option:-d
21233 and derives from it that foo.bib is the bibliography file relevant
21234 for this document. It then installs the necessary environment for RefTeX
21235 to work in this buffer and calls `reftex-citation' to insert a citation
21236 into the buffer.
21238 Export of such citations to both LaTeX and HTML is handled by the contributed
21239 package org-exp-bibtex by Taru Karttunen."
21240 (interactive)
21241 (let ((reftex-docstruct-symbol 'rds)
21242 (reftex-cite-format "\\cite{%l}")
21243 rds bib)
21244 (save-excursion
21245 (save-restriction
21246 (widen)
21247 (let ((case-fold-search t)
21248 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21249 (if (not (save-excursion
21250 (or (re-search-forward re nil t)
21251 (re-search-backward re nil t))))
21252 (error "No bibliography defined in file")
21253 (setq bib (concat (match-string 1) ".bib")
21254 rds (list (list 'bib bib)))))))
21255 (call-interactively 'reftex-citation)))
21257 ;;;; Functions extending outline functionality
21259 (defun org-beginning-of-line (&optional arg)
21260 "Go to the beginning of the current line. If that is invisible, continue
21261 to a visible line beginning. This makes the function of C-a more intuitive.
21262 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21263 first attempt, and only move to after the tags when the cursor is already
21264 beyond the end of the headline."
21265 (interactive "P")
21266 (let ((pos (point))
21267 (special (if (consp org-special-ctrl-a/e)
21268 (car org-special-ctrl-a/e)
21269 org-special-ctrl-a/e))
21270 refpos)
21271 (if (org-bound-and-true-p line-move-visual)
21272 (beginning-of-visual-line 1)
21273 (beginning-of-line 1))
21274 (if (and arg (fboundp 'move-beginning-of-line))
21275 (call-interactively 'move-beginning-of-line)
21276 (if (bobp)
21278 (backward-char 1)
21279 (if (org-truely-invisible-p)
21280 (while (and (not (bobp)) (org-truely-invisible-p))
21281 (backward-char 1)
21282 (beginning-of-line 1))
21283 (forward-char 1))))
21284 (when special
21285 (cond
21286 ((and (looking-at org-complex-heading-regexp)
21287 (= (char-after (match-end 1)) ?\ ))
21288 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21289 (point-at-eol)))
21290 (goto-char
21291 (if (eq special t)
21292 (cond ((> pos refpos) refpos)
21293 ((= pos (point)) refpos)
21294 (t (point)))
21295 (cond ((> pos (point)) (point))
21296 ((not (eq last-command this-command)) (point))
21297 (t refpos)))))
21298 ((org-at-item-p)
21299 ;; Being at an item and not looking at an the item means point
21300 ;; was previously moved to beginning of a visual line, which
21301 ;; doesn't contain the item. Therefore, do nothing special,
21302 ;; just stay here.
21303 (when (looking-at org-list-full-item-re)
21304 ;; Set special position at first white space character after
21305 ;; bullet, and check-box, if any.
21306 (let ((after-bullet
21307 (let ((box (match-end 3)))
21308 (if (not box) (match-end 1)
21309 (let ((after (char-after box)))
21310 (if (and after (= after ? )) (1+ box) box))))))
21311 ;; Special case: Move point to special position when
21312 ;; currently after it or at beginning of line.
21313 (if (eq special t)
21314 (when (or (> pos after-bullet) (= (point) pos))
21315 (goto-char after-bullet))
21316 ;; Reversed case: Move point to special position when
21317 ;; point was already at beginning of line and command is
21318 ;; repeated.
21319 (when (and (= (point) pos) (eq last-command this-command))
21320 (goto-char after-bullet))))))))
21321 (org-no-warnings
21322 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21324 (defun org-end-of-line (&optional arg)
21325 "Go to the end of the line.
21326 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21327 tags on the first attempt, and only move to after the tags when
21328 the cursor is already beyond the end of the headline."
21329 (interactive "P")
21330 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21331 org-special-ctrl-a/e))
21332 (type (org-element-type
21333 (save-excursion (beginning-of-line) (org-element-at-point)))))
21334 (cond
21335 ((or (not special) arg)
21336 (call-interactively
21337 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line)))
21338 ((memq type '(headline inlinetask))
21339 (let ((pos (point)))
21340 (beginning-of-line 1)
21341 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21342 (if (eq special t)
21343 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21344 (goto-char (match-beginning 1))
21345 (goto-char (match-end 0)))
21346 (if (or (< pos (match-end 0))
21347 (not (eq this-command last-command)))
21348 (goto-char (match-end 0))
21349 (goto-char (match-beginning 1))))
21350 (call-interactively
21351 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line)))))
21352 ((memq type
21353 '(center-block comment-block drawer dynamic-block example-block
21354 export-block item plain-list property-drawer
21355 quote-block special-block src-block verse-block))
21356 ;; Never move past the ellipsis.
21357 (or (eolp) (move-end-of-line 1))
21358 (when (org-invisible-p2) (backward-char)))
21360 (call-interactively
21361 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line))))
21362 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21364 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21365 (define-key org-mode-map "\C-e" 'org-end-of-line)
21367 (defun org-backward-sentence (&optional arg)
21368 "Go to beginning of sentence, or beginning of table field.
21369 This will call `backward-sentence' or `org-table-beginning-of-field',
21370 depending on context."
21371 (interactive "P")
21372 (cond
21373 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21374 (t (call-interactively 'backward-sentence))))
21376 (defun org-forward-sentence (&optional arg)
21377 "Go to end of sentence, or end of table field.
21378 This will call `forward-sentence' or `org-table-end-of-field',
21379 depending on context."
21380 (interactive "P")
21381 (cond
21382 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21383 (t (call-interactively 'forward-sentence))))
21385 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21386 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21388 (defun org-kill-line (&optional arg)
21389 "Kill line, to tags or end of line."
21390 (interactive "P")
21391 (cond
21392 ((or (not org-special-ctrl-k)
21393 (bolp)
21394 (not (org-at-heading-p)))
21395 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21396 org-ctrl-k-protect-subtree)
21397 (if (or (eq org-ctrl-k-protect-subtree 'error)
21398 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21399 (error "C-k aborted - would kill hidden subtree")))
21400 (call-interactively
21401 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21402 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21403 (kill-region (point) (match-beginning 1))
21404 (org-set-tags nil t))
21405 (t (kill-region (point) (point-at-eol)))))
21407 (define-key org-mode-map "\C-k" 'org-kill-line)
21409 (defun org-yank (&optional arg)
21410 "Yank. If the kill is a subtree, treat it specially.
21411 This command will look at the current kill and check if is a single
21412 subtree, or a series of subtrees[1]. If it passes the test, and if the
21413 cursor is at the beginning of a line or after the stars of a currently
21414 empty headline, then the yank is handled specially. How exactly depends
21415 on the value of the following variables, both set by default.
21417 org-yank-folded-subtrees
21418 When set, the subtree(s) will be folded after insertion, but only
21419 if doing so would now swallow text after the yanked text.
21421 org-yank-adjusted-subtrees
21422 When set, the subtree will be promoted or demoted in order to
21423 fit into the local outline tree structure, which means that the level
21424 will be adjusted so that it becomes the smaller one of the two
21425 *visible* surrounding headings.
21427 Any prefix to this command will cause `yank' to be called directly with
21428 no special treatment. In particular, a simple \\[universal-argument] prefix \
21429 will just
21430 plainly yank the text as it is.
21432 \[1] The test checks if the first non-white line is a heading
21433 and if there are no other headings with fewer stars."
21434 (interactive "P")
21435 (org-yank-generic 'yank arg))
21437 (defun org-yank-generic (command arg)
21438 "Perform some yank-like command.
21440 This function implements the behavior described in the `org-yank'
21441 documentation. However, it has been generalized to work for any
21442 interactive command with similar behavior."
21444 ;; pretend to be command COMMAND
21445 (setq this-command command)
21447 (if arg
21448 (call-interactively command)
21450 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21451 (and (org-kill-is-subtree-p)
21452 (or (bolp)
21453 (and (looking-at "[ \t]*$")
21454 (string-match
21455 "\\`\\*+\\'"
21456 (buffer-substring (point-at-bol) (point)))))))
21457 swallowp)
21458 (cond
21459 ((and subtreep org-yank-folded-subtrees)
21460 (let ((beg (point))
21461 end)
21462 (if (and subtreep org-yank-adjusted-subtrees)
21463 (org-paste-subtree nil nil 'for-yank)
21464 (call-interactively command))
21466 (setq end (point))
21467 (goto-char beg)
21468 (when (and (bolp) subtreep
21469 (not (setq swallowp
21470 (org-yank-folding-would-swallow-text beg end))))
21471 (org-with-limited-levels
21472 (or (looking-at org-outline-regexp)
21473 (re-search-forward org-outline-regexp-bol end t))
21474 (while (and (< (point) end) (looking-at org-outline-regexp))
21475 (hide-subtree)
21476 (org-cycle-show-empty-lines 'folded)
21477 (condition-case nil
21478 (outline-forward-same-level 1)
21479 (error (goto-char end))))))
21480 (when swallowp
21481 (message
21482 "Inserted text not folded because that would swallow text"))
21484 (goto-char end)
21485 (skip-chars-forward " \t\n\r")
21486 (beginning-of-line 1)
21487 (push-mark beg 'nomsg)))
21488 ((and subtreep org-yank-adjusted-subtrees)
21489 (let ((beg (point-at-bol)))
21490 (org-paste-subtree nil nil 'for-yank)
21491 (push-mark beg 'nomsg)))
21493 (call-interactively command))))))
21495 (defun org-yank-folding-would-swallow-text (beg end)
21496 "Would hide-subtree at BEG swallow any text after END?"
21497 (let (level)
21498 (org-with-limited-levels
21499 (save-excursion
21500 (goto-char beg)
21501 (when (or (looking-at org-outline-regexp)
21502 (re-search-forward org-outline-regexp-bol end t))
21503 (setq level (org-outline-level)))
21504 (goto-char end)
21505 (skip-chars-forward " \t\r\n\v\f")
21506 (if (or (eobp)
21507 (and (bolp) (looking-at org-outline-regexp)
21508 (<= (org-outline-level) level)))
21509 nil ; Nothing would be swallowed
21510 t))))) ; something would swallow
21512 (define-key org-mode-map "\C-y" 'org-yank)
21514 (defun org-truely-invisible-p ()
21515 "Check if point is at a character currently not visible.
21516 This version does not only check the character property, but also
21517 `visible-mode'."
21518 ;; Early versions of noutline don't have `outline-invisible-p'.
21519 (if (org-bound-and-true-p visible-mode)
21521 (outline-invisible-p)))
21523 (defun org-invisible-p2 ()
21524 "Check if point is at a character currently not visible."
21525 (save-excursion
21526 (if (and (eolp) (not (bobp))) (backward-char 1))
21527 ;; Early versions of noutline don't have `outline-invisible-p'.
21528 (outline-invisible-p)))
21530 (defun org-back-to-heading (&optional invisible-ok)
21531 "Call `outline-back-to-heading', but provide a better error message."
21532 (condition-case nil
21533 (outline-back-to-heading invisible-ok)
21534 (error (error "Before first headline at position %d in buffer %s"
21535 (point) (current-buffer)))))
21537 (defun org-before-first-heading-p ()
21538 "Before first heading?"
21539 (save-excursion
21540 (end-of-line)
21541 (null (re-search-backward org-outline-regexp-bol nil t))))
21543 (defun org-at-heading-p (&optional ignored)
21544 (outline-on-heading-p t))
21545 ;; Compatibility alias with Org versions < 7.8.03
21546 (defalias 'org-on-heading-p 'org-at-heading-p)
21548 (defun org-at-comment-p nil
21549 "Is cursor in a line starting with a # character?"
21550 (save-excursion
21551 (beginning-of-line)
21552 (looking-at "^#")))
21554 (defun org-at-drawer-p nil
21555 "Is cursor at a drawer keyword?"
21556 (save-excursion
21557 (move-beginning-of-line 1)
21558 (looking-at org-drawer-regexp)))
21560 (defun org-at-block-p nil
21561 "Is cursor at a block keyword?"
21562 (save-excursion
21563 (move-beginning-of-line 1)
21564 (looking-at org-block-regexp)))
21566 (defun org-point-at-end-of-empty-headline ()
21567 "If point is at the end of an empty headline, return t, else nil.
21568 If the heading only contains a TODO keyword, it is still still considered
21569 empty."
21570 (and (looking-at "[ \t]*$")
21571 (when org-todo-line-regexp
21572 (save-excursion
21573 (beginning-of-line 1)
21574 (let ((case-fold-search nil))
21575 (looking-at org-todo-line-regexp)
21576 (string= (match-string 3) ""))))))
21578 (defun org-at-heading-or-item-p ()
21579 (or (org-at-heading-p) (org-at-item-p)))
21581 (defun org-at-target-p ()
21582 (or (org-in-regexp org-radio-target-regexp)
21583 (org-in-regexp org-target-regexp)))
21584 ;; Compatibility alias with Org versions < 7.8.03
21585 (defalias 'org-on-target-p 'org-at-target-p)
21587 (defun org-up-heading-all (arg)
21588 "Move to the heading line of which the present line is a subheading.
21589 This function considers both visible and invisible heading lines.
21590 With argument, move up ARG levels."
21591 (if (fboundp 'outline-up-heading-all)
21592 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21593 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21595 (defun org-up-heading-safe ()
21596 "Move to the heading line of which the present line is a subheading.
21597 This version will not throw an error. It will return the level of the
21598 headline found, or nil if no higher level is found.
21600 Also, this function will be a lot faster than `outline-up-heading',
21601 because it relies on stars being the outline starters. This can really
21602 make a significant difference in outlines with very many siblings."
21603 (let (start-level re)
21604 (org-back-to-heading t)
21605 (setq start-level (funcall outline-level))
21606 (if (equal start-level 1)
21608 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21609 (if (re-search-backward re nil t)
21610 (funcall outline-level)))))
21612 (defun org-first-sibling-p ()
21613 "Is this heading the first child of its parents?"
21614 (interactive)
21615 (let ((re org-outline-regexp-bol)
21616 level l)
21617 (unless (org-at-heading-p t)
21618 (error "Not at a heading"))
21619 (setq level (funcall outline-level))
21620 (save-excursion
21621 (if (not (re-search-backward re nil t))
21623 (setq l (funcall outline-level))
21624 (< l level)))))
21626 (defun org-goto-sibling (&optional previous)
21627 "Goto the next sibling, even if it is invisible.
21628 When PREVIOUS is set, go to the previous sibling instead. Returns t
21629 when a sibling was found. When none is found, return nil and don't
21630 move point."
21631 (let ((fun (if previous 're-search-backward 're-search-forward))
21632 (pos (point))
21633 (re org-outline-regexp-bol)
21634 level l)
21635 (when (condition-case nil (org-back-to-heading t) (error nil))
21636 (setq level (funcall outline-level))
21637 (catch 'exit
21638 (or previous (forward-char 1))
21639 (while (funcall fun re nil t)
21640 (setq l (funcall outline-level))
21641 (when (< l level) (goto-char pos) (throw 'exit nil))
21642 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21643 (goto-char pos)
21644 nil))))
21646 (defun org-show-siblings ()
21647 "Show all siblings of the current headline."
21648 (save-excursion
21649 (while (org-goto-sibling) (org-flag-heading nil)))
21650 (save-excursion
21651 (while (org-goto-sibling 'previous)
21652 (org-flag-heading nil))))
21654 (defun org-goto-first-child ()
21655 "Goto the first child, even if it is invisible.
21656 Return t when a child was found. Otherwise don't move point and
21657 return nil."
21658 (let (level (pos (point)) (re org-outline-regexp-bol))
21659 (when (condition-case nil (org-back-to-heading t) (error nil))
21660 (setq level (outline-level))
21661 (forward-char 1)
21662 (if (and (re-search-forward re nil t) (> (outline-level) level))
21663 (progn (goto-char (match-beginning 0)) t)
21664 (goto-char pos) nil))))
21666 (defun org-show-hidden-entry ()
21667 "Show an entry where even the heading is hidden."
21668 (save-excursion
21669 (org-show-entry)))
21671 (defun org-flag-heading (flag &optional entry)
21672 "Flag the current heading. FLAG non-nil means make invisible.
21673 When ENTRY is non-nil, show the entire entry."
21674 (save-excursion
21675 (org-back-to-heading t)
21676 ;; Check if we should show the entire entry
21677 (if entry
21678 (progn
21679 (org-show-entry)
21680 (save-excursion
21681 (and (outline-next-heading)
21682 (org-flag-heading nil))))
21683 (outline-flag-region (max (point-min) (1- (point)))
21684 (save-excursion (outline-end-of-heading) (point))
21685 flag))))
21687 (defun org-get-next-sibling ()
21688 "Move to next heading of the same level, and return point.
21689 If there is no such heading, return nil.
21690 This is like outline-next-sibling, but invisible headings are ok."
21691 (let ((level (funcall outline-level)))
21692 (outline-next-heading)
21693 (while (and (not (eobp)) (> (funcall outline-level) level))
21694 (outline-next-heading))
21695 (if (or (eobp) (< (funcall outline-level) level))
21697 (point))))
21699 (defun org-get-last-sibling ()
21700 "Move to previous heading of the same level, and return point.
21701 If there is no such heading, return nil."
21702 (let ((opoint (point))
21703 (level (funcall outline-level)))
21704 (outline-previous-heading)
21705 (when (and (/= (point) opoint) (outline-on-heading-p t))
21706 (while (and (> (funcall outline-level) level)
21707 (not (bobp)))
21708 (outline-previous-heading))
21709 (if (< (funcall outline-level) level)
21711 (point)))))
21713 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21714 "Goto to the end of a subtree."
21715 ;; This contains an exact copy of the original function, but it uses
21716 ;; `org-back-to-heading', to make it work also in invisible
21717 ;; trees. And is uses an invisible-ok argument.
21718 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21719 ;; Furthermore, when used inside Org, finding the end of a large subtree
21720 ;; with many children and grandchildren etc, this can be much faster
21721 ;; than the outline version.
21722 (org-back-to-heading invisible-ok)
21723 (let ((first t)
21724 (level (funcall outline-level)))
21725 (if (and (derived-mode-p 'org-mode) (< level 1000))
21726 ;; A true heading (not a plain list item), in Org-mode
21727 ;; This means we can easily find the end by looking
21728 ;; only for the right number of stars. Using a regexp to do
21729 ;; this is so much faster than using a Lisp loop.
21730 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21731 (forward-char 1)
21732 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21733 ;; something else, do it the slow way
21734 (while (and (not (eobp))
21735 (or first (> (funcall outline-level) level)))
21736 (setq first nil)
21737 (outline-next-heading)))
21738 (unless to-heading
21739 (if (memq (preceding-char) '(?\n ?\^M))
21740 (progn
21741 ;; Go to end of line before heading
21742 (forward-char -1)
21743 (if (memq (preceding-char) '(?\n ?\^M))
21744 ;; leave blank line before heading
21745 (forward-char -1))))))
21746 (point))
21748 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21749 "Use Org version in org-mode, for dramatic speed-up."
21750 (if (derived-mode-p 'org-mode)
21751 (progn
21752 (org-end-of-subtree nil t)
21753 (unless (eobp) (backward-char 1)))
21754 ad-do-it))
21756 (defun org-end-of-meta-data-and-drawers ()
21757 "Jump to the first text after meta data and drawers in the current entry.
21758 This will move over empty lines, lines with planning time stamps,
21759 clocking lines, and drawers."
21760 (org-back-to-heading t)
21761 (let ((end (save-excursion (outline-next-heading) (point)))
21762 (re (concat "\\(" org-drawer-regexp "\\)"
21763 "\\|" "[ \t]*" org-keyword-time-regexp)))
21764 (forward-line 1)
21765 (while (re-search-forward re end t)
21766 (if (not (match-end 1))
21767 ;; empty or planning line
21768 (forward-line 1)
21769 ;; a drawer, find the end
21770 (re-search-forward "^[ \t]*:END:" end 'move)
21771 (forward-line 1)))
21772 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21773 (point)))
21775 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21776 "Move forward to the arg'th subheading at same level as this one.
21777 Stop at the first and last subheadings of a superior heading.
21778 Normally this only looks at visible headings, but when INVISIBLE-OK is
21779 non-nil it will also look at invisible ones."
21780 (interactive "p")
21781 (org-back-to-heading invisible-ok)
21782 (org-at-heading-p)
21783 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21784 (re (format "^\\*\\{1,%d\\} " level))
21786 (forward-char 1)
21787 (while (> arg 0)
21788 (while (and (re-search-forward re nil 'move)
21789 (setq l (- (match-end 0) (match-beginning 0) 1))
21790 (= l level)
21791 (not invisible-ok)
21792 (progn (backward-char 1) (outline-invisible-p)))
21793 (if (< l level) (setq arg 1)))
21794 (setq arg (1- arg)))
21795 (beginning-of-line 1)))
21797 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21798 "Move backward to the arg'th subheading at same level as this one.
21799 Stop at the first and last subheadings of a superior heading."
21800 (interactive "p")
21801 (org-back-to-heading)
21802 (org-at-heading-p)
21803 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21804 (re (format "^\\*\\{1,%d\\} " level))
21806 (while (> arg 0)
21807 (while (and (re-search-backward re nil 'move)
21808 (setq l (- (match-end 0) (match-beginning 0) 1))
21809 (= l level)
21810 (not invisible-ok)
21811 (outline-invisible-p))
21812 (if (< l level) (setq arg 1)))
21813 (setq arg (1- arg)))))
21815 (defun org-forward-element ()
21816 "Move forward by one element.
21817 Move to the next element at the same level, when possible."
21818 (interactive)
21819 (cond ((eobp) (error "Cannot move further down"))
21820 ((org-with-limited-levels (org-at-heading-p))
21821 (let ((origin (point)))
21822 (org-forward-heading-same-level 1)
21823 (unless (org-with-limited-levels (org-at-heading-p))
21824 (goto-char origin)
21825 (error "Cannot move further down"))))
21827 (let* ((elem (org-element-at-point))
21828 (end (org-element-property :end elem))
21829 (parent (org-element-property :parent elem)))
21830 (if (and parent (= (org-element-property :contents-end parent) end))
21831 (goto-char (org-element-property :end parent))
21832 (goto-char end))))))
21834 (defun org-backward-element ()
21835 "Move backward by one element.
21836 Move to the previous element at the same level, when possible."
21837 (interactive)
21838 (cond ((bobp) (error "Cannot move further up"))
21839 ((org-with-limited-levels (org-at-heading-p))
21840 ;; At an headline, move to the previous one, if any, or stay
21841 ;; here.
21842 (let ((origin (point)))
21843 (org-backward-heading-same-level 1)
21844 (unless (org-with-limited-levels (org-at-heading-p))
21845 (goto-char origin)
21846 (error "Cannot move further up"))))
21848 (let* ((trail (org-element-at-point 'keep-trail))
21849 (elem (car trail))
21850 (prev-elem (nth 1 trail))
21851 (beg (org-element-property :begin elem)))
21852 (cond
21853 ;; Move to beginning of current element if point isn't
21854 ;; there already.
21855 ((/= (point) beg) (goto-char beg))
21856 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21857 ((org-before-first-heading-p) (goto-char (point-min)))
21858 (t (org-back-to-heading)))))))
21860 (defun org-up-element ()
21861 "Move to upper element."
21862 (interactive)
21863 (if (org-with-limited-levels (org-at-heading-p))
21864 (unless (org-up-heading-safe) (error "No surrounding element"))
21865 (let* ((elem (org-element-at-point))
21866 (parent (org-element-property :parent elem)))
21867 (if parent (goto-char (org-element-property :begin parent))
21868 (if (org-with-limited-levels (org-before-first-heading-p))
21869 (error "No surrounding element")
21870 (org-with-limited-levels (org-back-to-heading)))))))
21872 (defvar org-element-greater-elements)
21873 (defun org-down-element ()
21874 "Move to inner element."
21875 (interactive)
21876 (let ((element (org-element-at-point)))
21877 (cond
21878 ((memq (org-element-type element) '(plain-list table))
21879 (goto-char (org-element-property :contents-begin element))
21880 (forward-char))
21881 ((memq (org-element-type element) org-element-greater-elements)
21882 ;; If contents are hidden, first disclose them.
21883 (when (org-element-property :hiddenp element) (org-cycle))
21884 (goto-char (or (org-element-property :contents-begin element)
21885 (error "No content for this element"))))
21886 (t (error "No inner element")))))
21888 (defun org-drag-element-backward ()
21889 "Move backward element at point."
21890 (interactive)
21891 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21892 (let* ((trail (org-element-at-point 'keep-trail))
21893 (elem (car trail))
21894 (prev-elem (nth 1 trail)))
21895 ;; Error out if no previous element or previous element is
21896 ;; a parent of the current one.
21897 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21898 (error "Cannot drag element backward")
21899 (let ((pos (point)))
21900 (org-element-swap-A-B prev-elem elem)
21901 (goto-char (+ (org-element-property :begin prev-elem)
21902 (- pos (org-element-property :begin elem)))))))))
21904 (defun org-drag-element-forward ()
21905 "Move forward element at point."
21906 (interactive)
21907 (let* ((pos (point))
21908 (elem (org-element-at-point)))
21909 (when (= (point-max) (org-element-property :end elem))
21910 (error "Cannot drag element forward"))
21911 (goto-char (org-element-property :end elem))
21912 (let ((next-elem (org-element-at-point)))
21913 (when (or (org-element-nested-p elem next-elem)
21914 (and (eq (org-element-type next-elem) 'headline)
21915 (not (eq (org-element-type elem) 'headline))))
21916 (goto-char pos)
21917 (error "Cannot drag element forward"))
21918 ;; Compute new position of point: it's shifted by NEXT-ELEM
21919 ;; body's length (without final blanks) and by the length of
21920 ;; blanks between ELEM and NEXT-ELEM.
21921 (let ((size-next (- (save-excursion
21922 (goto-char (org-element-property :end next-elem))
21923 (skip-chars-backward " \r\t\n")
21924 (forward-line)
21925 ;; Small correction if buffer doesn't end
21926 ;; with a newline character.
21927 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
21928 (org-element-property :begin next-elem)))
21929 (size-blank (- (org-element-property :end elem)
21930 (save-excursion
21931 (goto-char (org-element-property :end elem))
21932 (skip-chars-backward " \r\t\n")
21933 (forward-line)
21934 (point)))))
21935 (org-element-swap-A-B elem next-elem)
21936 (goto-char (+ pos size-next size-blank))))))
21938 (defun org-mark-element ()
21939 "Put point at beginning of this element, mark at end.
21941 Interactively, if this command is repeated or (in Transient Mark
21942 mode) if the mark is active, it marks the next element after the
21943 ones already marked."
21944 (interactive)
21945 (let (deactivate-mark)
21946 (if (and (org-called-interactively-p 'any)
21947 (or (and (eq last-command this-command) (mark t))
21948 (and transient-mark-mode mark-active)))
21949 (set-mark
21950 (save-excursion
21951 (goto-char (mark))
21952 (goto-char (org-element-property :end (org-element-at-point)))))
21953 (let ((element (org-element-at-point)))
21954 (end-of-line)
21955 (push-mark (org-element-property :end element) t t)
21956 (goto-char (org-element-property :begin element))))))
21958 (defun org-narrow-to-element ()
21959 "Narrow buffer to current element."
21960 (interactive)
21961 (let ((elem (org-element-at-point)))
21962 (cond
21963 ((eq (car elem) 'headline)
21964 (narrow-to-region
21965 (org-element-property :begin elem)
21966 (org-element-property :end elem)))
21967 ((memq (car elem) org-element-greater-elements)
21968 (narrow-to-region
21969 (org-element-property :contents-begin elem)
21970 (org-element-property :contents-end elem)))
21972 (narrow-to-region
21973 (org-element-property :begin elem)
21974 (org-element-property :end elem))))))
21976 (defun org-transpose-element ()
21977 "Transpose current and previous elements, keeping blank lines between.
21978 Point is moved after both elements."
21979 (interactive)
21980 (org-skip-whitespace)
21981 (let ((end (org-element-property :end (org-element-at-point))))
21982 (org-drag-element-backward)
21983 (goto-char end)))
21985 (defun org-unindent-buffer ()
21986 "Un-indent the visible part of the buffer.
21987 Relative indentation (between items, inside blocks, etc.) isn't
21988 modified."
21989 (interactive)
21990 (unless (eq major-mode 'org-mode)
21991 (error "Cannot un-indent a buffer not in Org mode"))
21992 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
21993 unindent-tree ; For byte-compiler.
21994 (unindent-tree
21995 (function
21996 (lambda (contents)
21997 (mapc
21998 (lambda (element)
21999 (if (memq (org-element-type element) '(headline section))
22000 (funcall unindent-tree (org-element-contents element))
22001 (save-excursion
22002 (save-restriction
22003 (narrow-to-region
22004 (org-element-property :begin element)
22005 (org-element-property :end element))
22006 (org-do-remove-indentation)))))
22007 (reverse contents))))))
22008 (funcall unindent-tree (org-element-contents parse-tree))))
22010 (defun org-show-subtree ()
22011 "Show everything after this heading at deeper levels."
22012 (interactive)
22013 (outline-flag-region
22014 (point)
22015 (save-excursion
22016 (org-end-of-subtree t t))
22017 nil))
22019 (defun org-show-entry ()
22020 "Show the body directly following this heading.
22021 Show the heading too, if it is currently invisible."
22022 (interactive)
22023 (save-excursion
22024 (condition-case nil
22025 (progn
22026 (org-back-to-heading t)
22027 (outline-flag-region
22028 (max (point-min) (1- (point)))
22029 (save-excursion
22030 (if (re-search-forward
22031 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22032 (match-beginning 1)
22033 (point-max)))
22034 nil)
22035 (org-cycle-hide-drawers 'children))
22036 (error nil))))
22038 (defun org-make-options-regexp (kwds &optional extra)
22039 "Make a regular expression for keyword lines."
22040 (concat
22041 "^#\\+\\("
22042 (mapconcat 'regexp-quote kwds "\\|")
22043 (if extra (concat "\\|" extra))
22044 "\\):[ \t]*\\(.*\\)"))
22046 ;; Make isearch reveal the necessary context
22047 (defun org-isearch-end ()
22048 "Reveal context after isearch exits."
22049 (when isearch-success ; only if search was successful
22050 (if (featurep 'xemacs)
22051 ;; Under XEmacs, the hook is run in the correct place,
22052 ;; we directly show the context.
22053 (org-show-context 'isearch)
22054 ;; In Emacs the hook runs *before* restoring the overlays.
22055 ;; So we have to use a one-time post-command-hook to do this.
22056 ;; (Emacs 22 has a special variable, see function `org-mode')
22057 (unless (and (boundp 'isearch-mode-end-hook-quit)
22058 isearch-mode-end-hook-quit)
22059 ;; Only when the isearch was not quitted.
22060 (org-add-hook 'post-command-hook 'org-isearch-post-command
22061 'append 'local)))))
22063 (defun org-isearch-post-command ()
22064 "Remove self from hook, and show context."
22065 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22066 (org-show-context 'isearch))
22069 ;;;; Integration with and fixes for other packages
22071 ;;; Imenu support
22073 (defvar org-imenu-markers nil
22074 "All markers currently used by Imenu.")
22075 (make-variable-buffer-local 'org-imenu-markers)
22077 (defun org-imenu-new-marker (&optional pos)
22078 "Return a new marker for use by Imenu, and remember the marker."
22079 (let ((m (make-marker)))
22080 (move-marker m (or pos (point)))
22081 (push m org-imenu-markers)
22084 (defun org-imenu-get-tree ()
22085 "Produce the index for Imenu."
22086 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22087 (setq org-imenu-markers nil)
22088 (let* ((n org-imenu-depth)
22089 (re (concat "^" (org-get-limited-outline-regexp)))
22090 (subs (make-vector (1+ n) nil))
22091 (last-level 0)
22092 m level head)
22093 (save-excursion
22094 (save-restriction
22095 (widen)
22096 (goto-char (point-max))
22097 (while (re-search-backward re nil t)
22098 (setq level (org-reduced-level (funcall outline-level)))
22099 (when (and (<= level n)
22100 (looking-at org-complex-heading-regexp))
22101 (setq head (org-link-display-format
22102 (org-match-string-no-properties 4))
22103 m (org-imenu-new-marker))
22104 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22105 (if (>= level last-level)
22106 (push (cons head m) (aref subs level))
22107 (push (cons head (aref subs (1+ level))) (aref subs level))
22108 (loop for i from (1+ level) to n do (aset subs i nil)))
22109 (setq last-level level)))))
22110 (aref subs 1)))
22112 (eval-after-load "imenu"
22113 '(progn
22114 (add-hook 'imenu-after-jump-hook
22115 (lambda ()
22116 (if (derived-mode-p 'org-mode)
22117 (org-show-context 'org-goto))))))
22119 (defun org-link-display-format (link)
22120 "Replace a link with either the description, or the link target
22121 if no description is present"
22122 (save-match-data
22123 (if (string-match org-bracket-link-analytic-regexp link)
22124 (replace-match (if (match-end 5)
22125 (match-string 5 link)
22126 (concat (match-string 1 link)
22127 (match-string 3 link)))
22128 nil t link)
22129 link)))
22131 (defun org-toggle-link-display ()
22132 "Toggle the literal or descriptive display of links."
22133 (interactive)
22134 (if org-descriptive-links
22135 (progn (org-remove-from-invisibility-spec '(org-link))
22136 (org-restart-font-lock)
22137 (setq org-descriptive-links nil))
22138 (progn (add-to-invisibility-spec '(org-link))
22139 (org-restart-font-lock)
22140 (setq org-descriptive-links t))))
22142 ;; Speedbar support
22144 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22145 "Overlay marking the agenda restriction line in speedbar.")
22146 (overlay-put org-speedbar-restriction-lock-overlay
22147 'face 'org-agenda-restriction-lock)
22148 (overlay-put org-speedbar-restriction-lock-overlay
22149 'help-echo "Agendas are currently limited to this item.")
22150 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22152 (defun org-speedbar-set-agenda-restriction ()
22153 "Restrict future agenda commands to the location at point in speedbar.
22154 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22155 (interactive)
22156 (require 'org-agenda)
22157 (let (p m tp np dir txt)
22158 (cond
22159 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22160 'org-imenu t))
22161 (setq m (get-text-property p 'org-imenu-marker))
22162 (with-current-buffer (marker-buffer m)
22163 (goto-char m)
22164 (org-agenda-set-restriction-lock 'subtree)))
22165 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22166 'speedbar-function 'speedbar-find-file))
22167 (setq tp (previous-single-property-change
22168 (1+ p) 'speedbar-function)
22169 np (next-single-property-change
22170 tp 'speedbar-function)
22171 dir (speedbar-line-directory)
22172 txt (buffer-substring-no-properties (or tp (point-min))
22173 (or np (point-max))))
22174 (with-current-buffer (find-file-noselect
22175 (let ((default-directory dir))
22176 (expand-file-name txt)))
22177 (unless (derived-mode-p 'org-mode)
22178 (error "Cannot restrict to non-Org-mode file"))
22179 (org-agenda-set-restriction-lock 'file)))
22180 (t (error "Don't know how to restrict Org-mode's agenda")))
22181 (move-overlay org-speedbar-restriction-lock-overlay
22182 (point-at-bol) (point-at-eol))
22183 (setq current-prefix-arg nil)
22184 (org-agenda-maybe-redo)))
22186 (eval-after-load "speedbar"
22187 '(progn
22188 (speedbar-add-supported-extension ".org")
22189 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22190 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22191 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22192 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22193 (add-hook 'speedbar-visiting-tag-hook
22194 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22196 ;;; Fixes and Hacks for problems with other packages
22198 ;; Make flyspell not check words in links, to not mess up our keymap
22199 (defun org-mode-flyspell-verify ()
22200 "Don't let flyspell put overlays at active buttons, or on
22201 {todo,all-time,additional-option-like}-keywords."
22202 (let ((pos (max (1- (point)) (point-min)))
22203 (word (thing-at-point 'word)))
22204 (and (not (get-text-property pos 'keymap))
22205 (not (get-text-property pos 'org-no-flyspell))
22206 (not (member word org-todo-keywords-1))
22207 (not (member word org-all-time-keywords))
22208 (not (member word org-options-keywords))
22209 (not (member word (mapcar 'car org-startup-options)))
22210 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22212 (defun org-remove-flyspell-overlays-in (beg end)
22213 "Remove flyspell overlays in region."
22214 (and (org-bound-and-true-p flyspell-mode)
22215 (fboundp 'flyspell-delete-region-overlays)
22216 (flyspell-delete-region-overlays beg end))
22217 (add-text-properties beg end '(org-no-flyspell t)))
22219 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22220 (eval-after-load "bookmark"
22221 '(if (boundp 'bookmark-after-jump-hook)
22222 ;; We can use the hook
22223 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22224 ;; Hook not available, use advice
22225 (defadvice bookmark-jump (after org-make-visible activate)
22226 "Make the position visible."
22227 (org-bookmark-jump-unhide))))
22229 ;; Make sure saveplace shows the location if it was hidden
22230 (eval-after-load "saveplace"
22231 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22232 "Make the position visible."
22233 (org-bookmark-jump-unhide)))
22235 ;; Make sure ecb shows the location if it was hidden
22236 (eval-after-load "ecb"
22237 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22238 "Make hierarchy visible when jumping into location from ECB tree buffer."
22239 (if (derived-mode-p 'org-mode)
22240 (org-show-context))))
22242 (defun org-bookmark-jump-unhide ()
22243 "Unhide the current position, to show the bookmark location."
22244 (and (derived-mode-p 'org-mode)
22245 (or (outline-invisible-p)
22246 (save-excursion (goto-char (max (point-min) (1- (point))))
22247 (outline-invisible-p)))
22248 (org-show-context 'bookmark-jump)))
22250 ;; Make session.el ignore our circular variable
22251 (eval-after-load "session"
22252 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22254 ;;;; Experimental code
22256 (defun org-closed-in-range ()
22257 "Sparse tree of items closed in a certain time range.
22258 Still experimental, may disappear in the future."
22259 (interactive)
22260 ;; Get the time interval from the user.
22261 (let* ((time1 (org-float-time
22262 (org-read-date nil 'to-time nil "Starting date: ")))
22263 (time2 (org-float-time
22264 (org-read-date nil 'to-time nil "End date:")))
22265 ;; callback function
22266 (callback (lambda ()
22267 (let ((time
22268 (org-float-time
22269 (apply 'encode-time
22270 (org-parse-time-string
22271 (match-string 1))))))
22272 ;; check if time in interval
22273 (and (>= time time1) (<= time time2))))))
22274 ;; make tree, check each match with the callback
22275 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22277 ;;;; Finish up
22279 (provide 'org)
22281 (run-hooks 'org-load-hook)
22283 ;;; org.el ends here