org-mac-iCal.el (org-mac-iCal): Support version 10.8.
[org-mode.git] / lisp / org.el
blob7b85a11c1e270a50c492b9ba67a74e72c093a543
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 t)))
2502 (cond
2503 ((not p) org-log-into-drawer)
2504 ((equal p "nil") nil)
2505 ((equal p "t") "LOGBOOK")
2506 (t p))))
2508 (defcustom org-log-state-notes-insert-after-drawers nil
2509 "Non-nil means insert state change notes after any drawers in entry.
2510 Only the drawers that *immediately* follow the headline and the
2511 deadline/scheduled line are skipped.
2512 When nil, insert notes right after the heading and perhaps the line
2513 with deadline/scheduling if present.
2515 This variable will have no effect if `org-log-into-drawer' is
2516 set."
2517 :group 'org-todo
2518 :group 'org-progress
2519 :type 'boolean)
2521 (defcustom org-log-states-order-reversed t
2522 "Non-nil means the latest state note will be directly after heading.
2523 When nil, the state change notes will be ordered according to time."
2524 :group 'org-todo
2525 :group 'org-progress
2526 :type 'boolean)
2528 (defcustom org-todo-repeat-to-state nil
2529 "The TODO state to which a repeater should return the repeating task.
2530 By default this is the first task in a TODO sequence, or the previous state
2531 in a TODO_TYP set. But you can specify another task here.
2532 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2533 :group 'org-todo
2534 :version "24.1"
2535 :type '(choice (const :tag "Head of sequence" nil)
2536 (string :tag "Specific state")))
2538 (defcustom org-log-repeat 'time
2539 "Non-nil means record moving through the DONE state when triggering repeat.
2540 An auto-repeating task is immediately switched back to TODO when
2541 marked DONE. If you are not logging state changes (by adding \"@\"
2542 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2543 record a closing note, there will be no record of the task moving
2544 through DONE. This variable forces taking a note anyway.
2546 nil Don't force a record
2547 time Record a time stamp
2548 note Prompt for a note and add it with template `org-log-note-headings'
2550 This option can also be set with on a per-file-basis with
2552 #+STARTUP: nologrepeat
2553 #+STARTUP: logrepeat
2554 #+STARTUP: lognoterepeat
2556 You can have local logging settings for a subtree by setting the LOGGING
2557 property to one or more of these keywords."
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type '(choice
2561 (const :tag "Don't force a record" nil)
2562 (const :tag "Force recording the DONE state" time)
2563 (const :tag "Force recording a note with the DONE state" note)))
2566 (defgroup org-priorities nil
2567 "Priorities in Org-mode."
2568 :tag "Org Priorities"
2569 :group 'org-todo)
2571 (defcustom org-enable-priority-commands t
2572 "Non-nil means priority commands are active.
2573 When nil, these commands will be disabled, so that you never accidentally
2574 set a priority."
2575 :group 'org-priorities
2576 :type 'boolean)
2578 (defcustom org-highest-priority ?A
2579 "The highest priority of TODO items. A character like ?A, ?B etc.
2580 Must have a smaller ASCII number than `org-lowest-priority'."
2581 :group 'org-priorities
2582 :type 'character)
2584 (defcustom org-lowest-priority ?C
2585 "The lowest priority of TODO items. A character like ?A, ?B etc.
2586 Must have a larger ASCII number than `org-highest-priority'."
2587 :group 'org-priorities
2588 :type 'character)
2590 (defcustom org-default-priority ?B
2591 "The default priority of TODO items.
2592 This is the priority an item gets if no explicit priority is given.
2593 When starting to cycle on an empty priority the first step in the cycle
2594 depends on `org-priority-start-cycle-with-default'. The resulting first
2595 step priority must not exceed the range from `org-highest-priority' to
2596 `org-lowest-priority' which means that `org-default-priority' has to be
2597 in this range exclusive or inclusive the range boundaries. Else the
2598 first step refuses to set the default and the second will fall back
2599 to (depending on the command used) the highest or lowest priority."
2600 :group 'org-priorities
2601 :type 'character)
2603 (defcustom org-priority-start-cycle-with-default t
2604 "Non-nil means start with default priority when starting to cycle.
2605 When this is nil, the first step in the cycle will be (depending on the
2606 command used) one higher or lower than the default priority.
2607 See also `org-default-priority'."
2608 :group 'org-priorities
2609 :type 'boolean)
2611 (defcustom org-get-priority-function nil
2612 "Function to extract the priority from a string.
2613 The string is normally the headline. If this is nil Org computes the
2614 priority from the priority cookie like [#A] in the headline. It returns
2615 an integer, increasing by 1000 for each priority level.
2616 The user can set a different function here, which should take a string
2617 as an argument and return the numeric priority."
2618 :group 'org-priorities
2619 :version "24.1"
2620 :type 'function)
2622 (defgroup org-time nil
2623 "Options concerning time stamps and deadlines in Org-mode."
2624 :tag "Org Time"
2625 :group 'org)
2627 (defcustom org-insert-labeled-timestamps-at-point nil
2628 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2629 When nil, these labeled time stamps are forces into the second line of an
2630 entry, just after the headline. When scheduling from the global TODO list,
2631 the time stamp will always be forced into the second line."
2632 :group 'org-time
2633 :type 'boolean)
2635 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2636 "Formats for `format-time-string' which are used for time stamps.
2637 It is not recommended to change this constant.")
2639 (defcustom org-time-stamp-rounding-minutes '(0 5)
2640 "Number of minutes to round time stamps to.
2641 These are two values, the first applies when first creating a time stamp.
2642 The second applies when changing it with the commands `S-up' and `S-down'.
2643 When changing the time stamp, this means that it will change in steps
2644 of N minutes, as given by the second value.
2646 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2647 numbers should be factors of 60, so for example 5, 10, 15.
2649 When this is larger than 1, you can still force an exact time stamp by using
2650 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2651 and by using a prefix arg to `S-up/down' to specify the exact number
2652 of minutes to shift."
2653 :group 'org-time
2654 :get #'(lambda (var) ; Make sure both elements are there
2655 (if (integerp (default-value var))
2656 (list (default-value var) 5)
2657 (default-value var)))
2658 :type '(list
2659 (integer :tag "when inserting times")
2660 (integer :tag "when modifying times")))
2662 ;; Normalize old customizations of this variable.
2663 (when (integerp org-time-stamp-rounding-minutes)
2664 (setq org-time-stamp-rounding-minutes
2665 (list org-time-stamp-rounding-minutes
2666 org-time-stamp-rounding-minutes)))
2668 (defcustom org-display-custom-times nil
2669 "Non-nil means overlay custom formats over all time stamps.
2670 The formats are defined through the variable `org-time-stamp-custom-formats'.
2671 To turn this on on a per-file basis, insert anywhere in the file:
2672 #+STARTUP: customtime"
2673 :group 'org-time
2674 :set 'set-default
2675 :type 'sexp)
2676 (make-variable-buffer-local 'org-display-custom-times)
2678 (defcustom org-time-stamp-custom-formats
2679 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2680 "Custom formats for time stamps. See `format-time-string' for the syntax.
2681 These are overlaid over the default ISO format if the variable
2682 `org-display-custom-times' is set. Time like %H:%M should be at the
2683 end of the second format. The custom formats are also honored by export
2684 commands, if custom time display is turned on at the time of export."
2685 :group 'org-time
2686 :type 'sexp)
2688 (defun org-time-stamp-format (&optional long inactive)
2689 "Get the right format for a time string."
2690 (let ((f (if long (cdr org-time-stamp-formats)
2691 (car org-time-stamp-formats))))
2692 (if inactive
2693 (concat "[" (substring f 1 -1) "]")
2694 f)))
2696 (defcustom org-time-clocksum-format "%d:%02d"
2697 "The format string used when creating CLOCKSUM lines.
2698 This is also used when org-mode generates a time duration."
2699 :group 'org-time
2700 :type 'string)
2702 (defcustom org-time-clocksum-use-fractional nil
2703 "If non-nil, \\[org-clock-display] uses fractional times.
2704 org-mode generates a time duration."
2705 :group 'org-time
2706 :type 'boolean)
2708 (defcustom org-time-clocksum-fractional-format "%.2f"
2709 "The format string used when creating CLOCKSUM lines, or when
2710 org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'string)
2714 (defcustom org-deadline-warning-days 14
2715 "No. of days before expiration during which a deadline becomes active.
2716 This variable governs the display in sparse trees and in the agenda.
2717 When 0 or negative, it means use this number (the absolute value of it)
2718 even if a deadline has a different individual lead time specified.
2720 Custom commands can set this variable in the options section."
2721 :group 'org-time
2722 :group 'org-agenda-daily/weekly
2723 :type 'integer)
2725 (defcustom org-read-date-prefer-future t
2726 "Non-nil means assume future for incomplete date input from user.
2727 This affects the following situations:
2728 1. The user gives a month but not a year.
2729 For example, if it is April and you enter \"feb 2\", this will be read
2730 as Feb 2, *next* year. \"May 5\", however, will be this year.
2731 2. The user gives a day, but no month.
2732 For example, if today is the 15th, and you enter \"3\", Org-mode will
2733 read this as the third of *next* month. However, if you enter \"17\",
2734 it will be considered as *this* month.
2736 If you set this variable to the symbol `time', then also the following
2737 will work:
2739 3. If the user gives a time.
2740 If the time is before now, it will be interpreted as tomorrow.
2742 Currently none of this works for ISO week specifications.
2744 When this option is nil, the current day, month and year will always be
2745 used as defaults.
2747 See also `org-agenda-jump-prefer-future'."
2748 :group 'org-time
2749 :type '(choice
2750 (const :tag "Never" nil)
2751 (const :tag "Check month and day" t)
2752 (const :tag "Check month, day, and time" time)))
2754 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2755 "Should the agenda jump command prefer the future for incomplete dates?
2756 The default is to do the same as configured in `org-read-date-prefer-future'.
2757 But you can also set a deviating value here.
2758 This may t or nil, or the symbol `org-read-date-prefer-future'."
2759 :group 'org-agenda
2760 :group 'org-time
2761 :version "24.1"
2762 :type '(choice
2763 (const :tag "Use org-read-date-prefer-future"
2764 org-read-date-prefer-future)
2765 (const :tag "Never" nil)
2766 (const :tag "Always" t)))
2768 (defcustom org-read-date-force-compatible-dates t
2769 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2771 Depending on the system Emacs is running on, certain dates cannot
2772 be represented with the type used internally to represent time.
2773 Dates between 1970-1-1 and 2038-1-1 can always be represented
2774 correctly. Some systems allow for earlier dates, some for later,
2775 some for both. One way to find out it to insert any date into an
2776 Org buffer, putting the cursor on the year and hitting S-up and
2777 S-down to test the range.
2779 When this variable is set to t, the date/time prompt will not let
2780 you specify dates outside the 1970-2037 range, so it is certain that
2781 these dates will work in whatever version of Emacs you are
2782 running, and also that you can move a file from one Emacs implementation
2783 to another. WHenever Org is forcing the year for you, it will display
2784 a message and beep.
2786 When this variable is nil, Org will check if the date is
2787 representable in the specific Emacs implementation you are using.
2788 If not, it will force a year, usually the current year, and beep
2789 to remind you. Currently this setting is not recommended because
2790 the likelihood that you will open your Org files in an Emacs that
2791 has limited date range is not negligible.
2793 A workaround for this problem is to use diary sexp dates for time
2794 stamps outside of this range."
2795 :group 'org-time
2796 :version "24.1"
2797 :type 'boolean)
2799 (defcustom org-read-date-display-live t
2800 "Non-nil means display current interpretation of date prompt live.
2801 This display will be in an overlay, in the minibuffer."
2802 :group 'org-time
2803 :type 'boolean)
2805 (defcustom org-read-date-popup-calendar t
2806 "Non-nil means pop up a calendar when prompting for a date.
2807 In the calendar, the date can be selected with mouse-1. However, the
2808 minibuffer will also be active, and you can simply enter the date as well.
2809 When nil, only the minibuffer will be available."
2810 :group 'org-time
2811 :type 'boolean)
2812 (if (fboundp 'defvaralias)
2813 (defvaralias 'org-popup-calendar-for-date-prompt
2814 'org-read-date-popup-calendar))
2816 (defcustom org-read-date-minibuffer-setup-hook nil
2817 "Hook to be used to set up keys for the date/time interface.
2818 Add key definitions to `minibuffer-local-map', which will be a temporary
2819 copy."
2820 :group 'org-time
2821 :type 'hook)
2823 (defcustom org-extend-today-until 0
2824 "The hour when your day really ends. Must be an integer.
2825 This has influence for the following applications:
2826 - When switching the agenda to \"today\". It it is still earlier than
2827 the time given here, the day recognized as TODAY is actually yesterday.
2828 - When a date is read from the user and it is still before the time given
2829 here, the current date and time will be assumed to be yesterday, 23:59.
2830 Also, timestamps inserted in capture templates follow this rule.
2832 IMPORTANT: This is a feature whose implementation is and likely will
2833 remain incomplete. Really, it is only here because past midnight seems to
2834 be the favorite working time of John Wiegley :-)"
2835 :group 'org-time
2836 :type 'integer)
2838 (defcustom org-use-effective-time nil
2839 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2840 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2841 \"effective time\" of any timestamps between midnight and 8am will be
2842 23:59 of the previous day."
2843 :group 'org-time
2844 :version "24.1"
2845 :type 'boolean)
2847 (defcustom org-edit-timestamp-down-means-later nil
2848 "Non-nil means S-down will increase the time in a time stamp.
2849 When nil, S-up will increase."
2850 :group 'org-time
2851 :type 'boolean)
2853 (defcustom org-calendar-follow-timestamp-change t
2854 "Non-nil means make the calendar window follow timestamp changes.
2855 When a timestamp is modified and the calendar window is visible, it will be
2856 moved to the new date."
2857 :group 'org-time
2858 :type 'boolean)
2860 (defgroup org-tags nil
2861 "Options concerning tags in Org-mode."
2862 :tag "Org Tags"
2863 :group 'org)
2865 (defcustom org-tag-alist nil
2866 "List of tags allowed in Org-mode files.
2867 When this list is nil, Org-mode will base TAG input on what is already in the
2868 buffer.
2869 The value of this variable is an alist, the car of each entry must be a
2870 keyword as a string, the cdr may be a character that is used to select
2871 that tag through the fast-tag-selection interface.
2872 See the manual for details."
2873 :group 'org-tags
2874 :type '(repeat
2875 (choice
2876 (cons (string :tag "Tag name")
2877 (character :tag "Access char"))
2878 (list :tag "Start radio group"
2879 (const :startgroup)
2880 (option (string :tag "Group description")))
2881 (list :tag "End radio group"
2882 (const :endgroup)
2883 (option (string :tag "Group description")))
2884 (const :tag "New line" (:newline)))))
2886 (defcustom org-tag-persistent-alist nil
2887 "List of tags that will always appear in all Org-mode files.
2888 This is in addition to any in buffer settings or customizations
2889 of `org-tag-alist'.
2890 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2891 The value of this variable is an alist, the car of each entry must be a
2892 keyword as a string, the cdr may be a character that is used to select
2893 that tag through the fast-tag-selection interface.
2894 See the manual for details.
2895 To disable these tags on a per-file basis, insert anywhere in the file:
2896 #+STARTUP: noptag"
2897 :group 'org-tags
2898 :type '(repeat
2899 (choice
2900 (cons (string :tag "Tag name")
2901 (character :tag "Access char"))
2902 (const :tag "Start radio group" (:startgroup))
2903 (const :tag "End radio group" (:endgroup))
2904 (const :tag "New line" (:newline)))))
2906 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2907 "If non-nil, always offer completion for all tags of all agenda files.
2908 Instead of customizing this variable directly, you might want to
2909 set it locally for capture buffers, because there no list of
2910 tags in that file can be created dynamically (there are none).
2912 (add-hook 'org-capture-mode-hook
2913 (lambda ()
2914 (set (make-local-variable
2915 'org-complete-tags-always-offer-all-agenda-tags)
2916 t)))"
2917 :group 'org-tags
2918 :version "24.1"
2919 :type 'boolean)
2921 (defvar org-file-tags nil
2922 "List of tags that can be inherited by all entries in the file.
2923 The tags will be inherited if the variable `org-use-tag-inheritance'
2924 says they should be.
2925 This variable is populated from #+FILETAGS lines.")
2927 (defcustom org-use-fast-tag-selection 'auto
2928 "Non-nil means use fast tag selection scheme.
2929 This is a special interface to select and deselect tags with single keys.
2930 When nil, fast selection is never used.
2931 When the symbol `auto', fast selection is used if and only if selection
2932 characters for tags have been configured, either through the variable
2933 `org-tag-alist' or through a #+TAGS line in the buffer.
2934 When t, fast selection is always used and selection keys are assigned
2935 automatically if necessary."
2936 :group 'org-tags
2937 :type '(choice
2938 (const :tag "Always" t)
2939 (const :tag "Never" nil)
2940 (const :tag "When selection characters are configured" 'auto)))
2942 (defcustom org-fast-tag-selection-single-key nil
2943 "Non-nil means fast tag selection exits after first change.
2944 When nil, you have to press RET to exit it.
2945 During fast tag selection, you can toggle this flag with `C-c'.
2946 This variable can also have the value `expert'. In this case, the window
2947 displaying the tags menu is not even shown, until you press C-c again."
2948 :group 'org-tags
2949 :type '(choice
2950 (const :tag "No" nil)
2951 (const :tag "Yes" t)
2952 (const :tag "Expert" expert)))
2954 (defvar org-fast-tag-selection-include-todo nil
2955 "Non-nil means fast tags selection interface will also offer TODO states.
2956 This is an undocumented feature, you should not rely on it.")
2958 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2959 "The column to which tags should be indented in a headline.
2960 If this number is positive, it specifies the column. If it is negative,
2961 it means that the tags should be flushright to that column. For example,
2962 -80 works well for a normal 80 character screen.
2963 When 0, place tags directly after headline text, with only one space in
2964 between."
2965 :group 'org-tags
2966 :type 'integer)
2968 (defcustom org-auto-align-tags t
2969 "Non-nil keeps tags aligned when modifying headlines.
2970 Some operations (i.e. demoting) change the length of a headline and
2971 therefore shift the tags around. With this option turned on, after
2972 each such operation the tags are again aligned to `org-tags-column'."
2973 :group 'org-tags
2974 :type 'boolean)
2976 (defcustom org-use-tag-inheritance t
2977 "Non-nil means tags in levels apply also for sublevels.
2978 When nil, only the tags directly given in a specific line apply there.
2979 This may also be a list of tags that should be inherited, or a regexp that
2980 matches tags that should be inherited. Additional control is possible
2981 with the variable `org-tags-exclude-from-inheritance' which gives an
2982 explicit list of tags to be excluded from inheritance., even if the value of
2983 `org-use-tag-inheritance' would select it for inheritance.
2985 If this option is t, a match early-on in a tree can lead to a large
2986 number of matches in the subtree when constructing the agenda or creating
2987 a sparse tree. If you only want to see the first match in a tree during
2988 a search, check out the variable `org-tags-match-list-sublevels'."
2989 :group 'org-tags
2990 :type '(choice
2991 (const :tag "Not" nil)
2992 (const :tag "Always" t)
2993 (repeat :tag "Specific tags" (string :tag "Tag"))
2994 (regexp :tag "Tags matched by regexp")))
2996 (defcustom org-tags-exclude-from-inheritance nil
2997 "List of tags that should never be inherited.
2998 This is a way to exclude a few tags from inheritance. For way to do
2999 the opposite, to actively allow inheritance for selected tags,
3000 see the variable `org-use-tag-inheritance'."
3001 :group 'org-tags
3002 :type '(repeat (string :tag "Tag")))
3004 (defun org-tag-inherit-p (tag)
3005 "Check if TAG is one that should be inherited."
3006 (cond
3007 ((member tag org-tags-exclude-from-inheritance) nil)
3008 ((eq org-use-tag-inheritance t) t)
3009 ((not org-use-tag-inheritance) nil)
3010 ((stringp org-use-tag-inheritance)
3011 (string-match org-use-tag-inheritance tag))
3012 ((listp org-use-tag-inheritance)
3013 (member tag org-use-tag-inheritance))
3014 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3016 (defcustom org-tags-match-list-sublevels t
3017 "Non-nil means list also sublevels of headlines matching a search.
3018 This variable applies to tags/property searches, and also to stuck
3019 projects because this search is based on a tags match as well.
3021 When set to the symbol `indented', sublevels are indented with
3022 leading dots.
3024 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3025 the sublevels of a headline matching a tag search often also match
3026 the same search. Listing all of them can create very long lists.
3027 Setting this variable to nil causes subtrees of a match to be skipped.
3029 This variable is semi-obsolete and probably should always be true. It
3030 is better to limit inheritance to certain tags using the variables
3031 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3032 :group 'org-tags
3033 :type '(choice
3034 (const :tag "No, don't list them" nil)
3035 (const :tag "Yes, do list them" t)
3036 (const :tag "List them, indented with leading dots" indented)))
3038 (defcustom org-tags-sort-function nil
3039 "When set, tags are sorted using this function as a comparator."
3040 :group 'org-tags
3041 :type '(choice
3042 (const :tag "No sorting" nil)
3043 (const :tag "Alphabetical" string<)
3044 (const :tag "Reverse alphabetical" string>)
3045 (function :tag "Custom function" nil)))
3047 (defvar org-tags-history nil
3048 "History of minibuffer reads for tags.")
3049 (defvar org-last-tags-completion-table nil
3050 "The last used completion table for tags.")
3051 (defvar org-after-tags-change-hook nil
3052 "Hook that is run after the tags in a line have changed.")
3054 (defgroup org-properties nil
3055 "Options concerning properties in Org-mode."
3056 :tag "Org Properties"
3057 :group 'org)
3059 (defcustom org-property-format "%-10s %s"
3060 "How property key/value pairs should be formatted by `indent-line'.
3061 When `indent-line' hits a property definition, it will format the line
3062 according to this format, mainly to make sure that the values are
3063 lined-up with respect to each other."
3064 :group 'org-properties
3065 :type 'string)
3067 (defcustom org-properties-postprocess-alist nil
3068 "Alist of properties and functions to adjust inserted values.
3069 Elements of this alist must be of the form
3071 ([string] [function])
3073 where [string] must be a property name and [function] must be a
3074 lambda expression: this lambda expression must take one argument,
3075 the value to adjust, and return the new value as a string.
3077 For example, this element will allow the property \"Remaining\"
3078 to be updated wrt the relation between the \"Effort\" property
3079 and the clock summary:
3081 ((\"Remaining\" (lambda(value)
3082 (let ((clocksum (org-clock-sum-current-item))
3083 (effort (org-duration-string-to-minutes
3084 (org-entry-get (point) \"Effort\"))))
3085 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3086 :group 'org-properties
3087 :version "24.1"
3088 :type '(alist :key-type (string :tag "Property")
3089 :value-type (function :tag "Function")))
3091 (defcustom org-use-property-inheritance nil
3092 "Non-nil means properties apply also for sublevels.
3094 This setting is chiefly used during property searches. Turning it on can
3095 cause significant overhead when doing a search, which is why it is not
3096 on by default.
3098 When nil, only the properties directly given in the current entry count.
3099 When t, every property is inherited. The value may also be a list of
3100 properties that should have inheritance, or a regular expression matching
3101 properties that should be inherited.
3103 However, note that some special properties use inheritance under special
3104 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3105 and the properties ending in \"_ALL\" when they are used as descriptor
3106 for valid values of a property.
3108 Note for programmers:
3109 When querying an entry with `org-entry-get', you can control if inheritance
3110 should be used. By default, `org-entry-get' looks only at the local
3111 properties. You can request inheritance by setting the inherit argument
3112 to t (to force inheritance) or to `selective' (to respect the setting
3113 in this variable)."
3114 :group 'org-properties
3115 :type '(choice
3116 (const :tag "Not" nil)
3117 (const :tag "Always" t)
3118 (repeat :tag "Specific properties" (string :tag "Property"))
3119 (regexp :tag "Properties matched by regexp")))
3121 (defun org-property-inherit-p (property)
3122 "Check if PROPERTY is one that should be inherited."
3123 (cond
3124 ((eq org-use-property-inheritance t) t)
3125 ((not org-use-property-inheritance) nil)
3126 ((stringp org-use-property-inheritance)
3127 (string-match org-use-property-inheritance property))
3128 ((listp org-use-property-inheritance)
3129 (member property org-use-property-inheritance))
3130 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3132 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3133 "The default column format, if no other format has been defined.
3134 This variable can be set on the per-file basis by inserting a line
3136 #+COLUMNS: %25ITEM ....."
3137 :group 'org-properties
3138 :type 'string)
3140 (defcustom org-columns-ellipses ".."
3141 "The ellipses to be used when a field in column view is truncated.
3142 When this is the empty string, as many characters as possible are shown,
3143 but then there will be no visual indication that the field has been truncated.
3144 When this is a string of length N, the last N characters of a truncated
3145 field are replaced by this string. If the column is narrower than the
3146 ellipses string, only part of the ellipses string will be shown."
3147 :group 'org-properties
3148 :type 'string)
3150 (defcustom org-columns-modify-value-for-display-function nil
3151 "Function that modifies values for display in column view.
3152 For example, it can be used to cut out a certain part from a time stamp.
3153 The function must take 2 arguments:
3155 column-title The title of the column (*not* the property name)
3156 value The value that should be modified.
3158 The function should return the value that should be displayed,
3159 or nil if the normal value should be used."
3160 :group 'org-properties
3161 :type 'function)
3163 (defcustom org-effort-property "Effort"
3164 "The property that is being used to keep track of effort estimates.
3165 Effort estimates given in this property need to have the format H:MM."
3166 :group 'org-properties
3167 :group 'org-progress
3168 :type '(string :tag "Property"))
3170 (defconst org-global-properties-fixed
3171 '(("VISIBILITY_ALL" . "folded children content all")
3172 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3173 "List of property/value pairs that can be inherited by any entry.
3175 These are fixed values, for the preset properties. The user variable
3176 that can be used to add to this list is `org-global-properties'.
3178 The entries in this list are cons cells where the car is a property
3179 name and cdr is a string with the value. If the value represents
3180 multiple items like an \"_ALL\" property, separate the items by
3181 spaces.")
3183 (defcustom org-global-properties nil
3184 "List of property/value pairs that can be inherited by any entry.
3186 This list will be combined with the constant `org-global-properties-fixed'.
3188 The entries in this list are cons cells where the car is a property
3189 name and cdr is a string with the value.
3191 You can set buffer-local values for the same purpose in the variable
3192 `org-file-properties' this by adding lines like
3194 #+PROPERTY: NAME VALUE"
3195 :group 'org-properties
3196 :type '(repeat
3197 (cons (string :tag "Property")
3198 (string :tag "Value"))))
3200 (defvar org-file-properties nil
3201 "List of property/value pairs that can be inherited by any entry.
3202 Valid for the current buffer.
3203 This variable is populated from #+PROPERTY lines.")
3204 (make-variable-buffer-local 'org-file-properties)
3206 (defgroup org-agenda nil
3207 "Options concerning agenda views in Org-mode."
3208 :tag "Org Agenda"
3209 :group 'org)
3211 (defvar org-category nil
3212 "Variable used by org files to set a category for agenda display.
3213 Such files should use a file variable to set it, for example
3215 # -*- mode: org; org-category: \"ELisp\"
3217 or contain a special line
3219 #+CATEGORY: ELisp
3221 If the file does not specify a category, then file's base name
3222 is used instead.")
3223 (make-variable-buffer-local 'org-category)
3224 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3226 (defcustom org-agenda-files nil
3227 "The files to be used for agenda display.
3228 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3229 \\[org-remove-file]. You can also use customize to edit the list.
3231 If an entry is a directory, all files in that directory that are matched by
3232 `org-agenda-file-regexp' will be part of the file list.
3234 If the value of the variable is not a list but a single file name, then
3235 the list of agenda files is actually stored and maintained in that file, one
3236 agenda file per line. In this file paths can be given relative to
3237 `org-directory'. Tilde expansion and environment variable substitution
3238 are also made."
3239 :group 'org-agenda
3240 :type '(choice
3241 (repeat :tag "List of files and directories" file)
3242 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3244 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3245 "Regular expression to match files for `org-agenda-files'.
3246 If any element in the list in that variable contains a directory instead
3247 of a normal file, all files in that directory that are matched by this
3248 regular expression will be included."
3249 :group 'org-agenda
3250 :type 'regexp)
3252 (defcustom org-agenda-text-search-extra-files nil
3253 "List of extra files to be searched by text search commands.
3254 These files will be search in addition to the agenda files by the
3255 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3256 Note that these files will only be searched for text search commands,
3257 not for the other agenda views like todo lists, tag searches or the weekly
3258 agenda. This variable is intended to list notes and possibly archive files
3259 that should also be searched by these two commands.
3260 In fact, if the first element in the list is the symbol `agenda-archives',
3261 than all archive files of all agenda files will be added to the search
3262 scope."
3263 :group 'org-agenda
3264 :type '(set :greedy t
3265 (const :tag "Agenda Archives" agenda-archives)
3266 (repeat :inline t (file))))
3268 (if (fboundp 'defvaralias)
3269 (defvaralias 'org-agenda-multi-occur-extra-files
3270 'org-agenda-text-search-extra-files))
3272 (defcustom org-agenda-skip-unavailable-files nil
3273 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3274 A nil value means to remove them, after a query, from the list."
3275 :group 'org-agenda
3276 :type 'boolean)
3278 (defcustom org-calendar-to-agenda-key [?c]
3279 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3280 The command `org-calendar-goto-agenda' will be bound to this key. The
3281 default is the character `c' because then `c' can be used to switch back and
3282 forth between agenda and calendar."
3283 :group 'org-agenda
3284 :type 'sexp)
3286 (defcustom org-calendar-insert-diary-entry-key [?i]
3287 "The key to be installed in `calendar-mode-map' for adding diary entries.
3288 This option is irrelevant until `org-agenda-diary-file' has been configured
3289 to point to an Org-mode file. When that is the case, the command
3290 `org-agenda-diary-entry' will be bound to the key given here, by default
3291 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3292 if you want to continue doing this, you need to change this to a different
3293 key."
3294 :group 'org-agenda
3295 :type 'sexp)
3297 (defcustom org-agenda-diary-file 'diary-file
3298 "File to which to add new entries with the `i' key in agenda and calendar.
3299 When this is the symbol `diary-file', the functionality in the Emacs
3300 calendar will be used to add entries to the `diary-file'. But when this
3301 points to a file, `org-agenda-diary-entry' will be used instead."
3302 :group 'org-agenda
3303 :type '(choice
3304 (const :tag "The standard Emacs diary file" diary-file)
3305 (file :tag "Special Org file diary entries")))
3307 (eval-after-load "calendar"
3308 '(progn
3309 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3310 'org-calendar-goto-agenda)
3311 (add-hook 'calendar-mode-hook
3312 (lambda ()
3313 (unless (eq org-agenda-diary-file 'diary-file)
3314 (define-key calendar-mode-map
3315 org-calendar-insert-diary-entry-key
3316 'org-agenda-diary-entry))))))
3318 (defgroup org-latex nil
3319 "Options for embedding LaTeX code into Org-mode."
3320 :tag "Org LaTeX"
3321 :group 'org)
3323 (defcustom org-format-latex-options
3324 '(:foreground default :background default :scale 1.0
3325 :html-foreground "Black" :html-background "Transparent"
3326 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3327 "Options for creating images from LaTeX fragments.
3328 This is a property list with the following properties:
3329 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3330 `default' means use the foreground of the default face.
3331 :background the background color, or \"Transparent\".
3332 `default' means use the background of the default face.
3333 :scale a scaling factor for the size of the images, to get more pixels
3334 :html-foreground, :html-background, :html-scale
3335 the same numbers for HTML export.
3336 :matchers a list indicating which matchers should be used to
3337 find LaTeX fragments. Valid members of this list are:
3338 \"begin\" find environments
3339 \"$1\" find single characters surrounded by $.$
3340 \"$\" find math expressions surrounded by $...$
3341 \"$$\" find math expressions surrounded by $$....$$
3342 \"\\(\" find math expressions surrounded by \\(...\\)
3343 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3344 :group 'org-latex
3345 :type 'plist)
3347 (defcustom org-format-latex-signal-error t
3348 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3349 When nil, just push out a message."
3350 :group 'org-latex
3351 :version "24.1"
3352 :type 'boolean)
3354 (defcustom org-latex-to-mathml-jar-file nil
3355 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3356 Use this to specify additional executable file say a jar file.
3358 When using MathToWeb as the converter, specify the full-path to
3359 your mathtoweb.jar file."
3360 :group 'org-latex
3361 :version "24.1"
3362 :type '(choice
3363 (const :tag "None" nil)
3364 (file :tag "JAR file" :must-match t)))
3366 (defcustom org-latex-to-mathml-convert-command nil
3367 "Command to convert LaTeX fragments to MathML.
3368 Replace format-specifiers in the command as noted below and use
3369 `shell-command' to convert LaTeX to MathML.
3370 %j: Executable file in fully expanded form as specified by
3371 `org-latex-to-mathml-jar-file'.
3372 %I: Input LaTeX file in fully expanded form
3373 %o: Output MathML file
3374 This command is used by `org-create-math-formula'.
3376 When using MathToWeb as the converter, set this to
3377 \"java -jar %j -unicode -force -df %o %I\"."
3378 :group 'org-latex
3379 :version "24.1"
3380 :type '(choice
3381 (const :tag "None" nil)
3382 (string :tag "\nShell command")))
3384 (defcustom org-latex-create-formula-image-program 'dvipng
3385 "Program to convert LaTeX fragments with.
3387 dvipng Process the LaTeX fragments to dvi file, then convert
3388 dvi files to png files using dvipng.
3389 This will also include processing of non-math environments.
3390 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3391 to convert pdf files to png files"
3392 :group 'org-latex
3393 :version "24.1"
3394 :type '(choice
3395 (const :tag "dvipng" dvipng)
3396 (const :tag "imagemagick" imagemagick)))
3398 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3399 "Path to store latex preview images. A relative path here creates many
3400 directories relative to the processed org files paths. An absolute path
3401 puts all preview images at the same place."
3402 :group 'org-latex
3403 :version "24.3"
3404 :type 'string)
3406 (defun org-format-latex-mathml-available-p ()
3407 "Return t if `org-latex-to-mathml-convert-command' is usable."
3408 (save-match-data
3409 (when (and (boundp 'org-latex-to-mathml-convert-command)
3410 org-latex-to-mathml-convert-command)
3411 (let ((executable (car (split-string
3412 org-latex-to-mathml-convert-command))))
3413 (when (executable-find executable)
3414 (if (string-match
3415 "%j" org-latex-to-mathml-convert-command)
3416 (file-readable-p org-latex-to-mathml-jar-file)
3417 t))))))
3419 (defcustom org-format-latex-header "\\documentclass{article}
3420 \\usepackage[usenames]{color}
3421 \\usepackage{amsmath}
3422 \\usepackage[mathscr]{eucal}
3423 \\pagestyle{empty} % do not remove
3424 \[PACKAGES]
3425 \[DEFAULT-PACKAGES]
3426 % The settings below are copied from fullpage.sty
3427 \\setlength{\\textwidth}{\\paperwidth}
3428 \\addtolength{\\textwidth}{-3cm}
3429 \\setlength{\\oddsidemargin}{1.5cm}
3430 \\addtolength{\\oddsidemargin}{-2.54cm}
3431 \\setlength{\\evensidemargin}{\\oddsidemargin}
3432 \\setlength{\\textheight}{\\paperheight}
3433 \\addtolength{\\textheight}{-\\headheight}
3434 \\addtolength{\\textheight}{-\\headsep}
3435 \\addtolength{\\textheight}{-\\footskip}
3436 \\addtolength{\\textheight}{-3cm}
3437 \\setlength{\\topmargin}{1.5cm}
3438 \\addtolength{\\topmargin}{-2.54cm}"
3439 "The document header used for processing LaTeX fragments.
3440 It is imperative that this header make sure that no page number
3441 appears on the page. The package defined in the variables
3442 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3443 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3444 will be appended."
3445 :group 'org-latex
3446 :type 'string)
3448 (defvar org-format-latex-header-extra nil)
3450 (defun org-set-packages-alist (var val)
3451 "Set the packages alist and make sure it has 3 elements per entry."
3452 (set var (mapcar (lambda (x)
3453 (if (and (consp x) (= (length x) 2))
3454 (list (car x) (nth 1 x) t)
3456 val)))
3458 (defun org-get-packages-alist (var)
3460 "Get the packages alist and make sure it has 3 elements per entry."
3461 (mapcar (lambda (x)
3462 (if (and (consp x) (= (length x) 2))
3463 (list (car x) (nth 1 x) t)
3465 (default-value var)))
3467 ;; The following variables are defined here because is it also used
3468 ;; when formatting latex fragments. Originally it was part of the
3469 ;; LaTeX exporter, which is why the name includes "export".
3470 (defcustom org-export-latex-default-packages-alist
3471 '(("AUTO" "inputenc" t)
3472 ("T1" "fontenc" t)
3473 ("" "fixltx2e" nil)
3474 ("" "graphicx" t)
3475 ("" "longtable" nil)
3476 ("" "float" nil)
3477 ("" "wrapfig" nil)
3478 ("" "soul" t)
3479 ("" "textcomp" t)
3480 ("" "marvosym" t)
3481 ("" "wasysym" t)
3482 ("" "latexsym" t)
3483 ("" "amssymb" t)
3484 ("" "hyperref" nil)
3485 "\\tolerance=1000"
3487 "Alist of default packages to be inserted in the header.
3488 Change this only if one of the packages here causes an incompatibility
3489 with another package you are using.
3490 The packages in this list are needed by one part or another of Org-mode
3491 to function properly.
3493 - inputenc, fontenc: for basic font and character selection
3494 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3495 for interpreting the entities in `org-entities'. You can skip some of these
3496 packages if you don't use any of the symbols in it.
3497 - graphicx: for including images
3498 - float, wrapfig: for figure placement
3499 - longtable: for long tables
3500 - hyperref: for cross references
3502 Therefore you should not modify this variable unless you know what you
3503 are doing. The one reason to change it anyway is that you might be loading
3504 some other package that conflicts with one of the default packages.
3505 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3506 If SNIPPET-FLAG is t, the package also needs to be included when
3507 compiling LaTeX snippets into images for inclusion into HTML."
3508 :group 'org-export-latex
3509 :set 'org-set-packages-alist
3510 :get 'org-get-packages-alist
3511 :version "24.1"
3512 :type '(repeat
3513 (choice
3514 (list :tag "options/package pair"
3515 (string :tag "options")
3516 (string :tag "package")
3517 (boolean :tag "Snippet"))
3518 (string :tag "A line of LaTeX"))))
3520 (defcustom org-export-latex-packages-alist nil
3521 "Alist of packages to be inserted in every LaTeX header.
3522 These will be inserted after `org-export-latex-default-packages-alist'.
3523 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3524 SNIPPET-FLAG, when t, indicates that this package is also needed when
3525 turning LaTeX snippets into images for inclusion into HTML.
3526 Make sure that you only list packages here which:
3527 - you want in every file
3528 - do not conflict with the default packages in
3529 `org-export-latex-default-packages-alist'
3530 - do not conflict with the setup in `org-format-latex-header'."
3531 :group 'org-export-latex
3532 :set 'org-set-packages-alist
3533 :get 'org-get-packages-alist
3534 :type '(repeat
3535 (choice
3536 (list :tag "options/package pair"
3537 (string :tag "options")
3538 (string :tag "package")
3539 (boolean :tag "Snippet"))
3540 (string :tag "A line of LaTeX"))))
3543 (defgroup org-appearance nil
3544 "Settings for Org-mode appearance."
3545 :tag "Org Appearance"
3546 :group 'org)
3548 (defcustom org-level-color-stars-only nil
3549 "Non-nil means fontify only the stars in each headline.
3550 When nil, the entire headline is fontified.
3551 Changing it requires restart of `font-lock-mode' to become effective
3552 also in regions already fontified."
3553 :group 'org-appearance
3554 :type 'boolean)
3556 (defcustom org-hide-leading-stars nil
3557 "Non-nil means hide the first N-1 stars in a headline.
3558 This works by using the face `org-hide' for these stars. This
3559 face is white for a light background, and black for a dark
3560 background. You may have to customize the face `org-hide' to
3561 make this work.
3562 Changing it requires restart of `font-lock-mode' to become effective
3563 also in regions already fontified.
3564 You may also set this on a per-file basis by adding one of the following
3565 lines to the buffer:
3567 #+STARTUP: hidestars
3568 #+STARTUP: showstars"
3569 :group 'org-appearance
3570 :type 'boolean)
3572 (defcustom org-hidden-keywords nil
3573 "List of symbols corresponding to keywords to be hidden the org buffer.
3574 For example, a value '(title) for this list will make the document's title
3575 appear in the buffer without the initial #+TITLE: keyword."
3576 :group 'org-appearance
3577 :version "24.1"
3578 :type '(set (const :tag "#+AUTHOR" author)
3579 (const :tag "#+DATE" date)
3580 (const :tag "#+EMAIL" email)
3581 (const :tag "#+TITLE" title)))
3583 (defcustom org-custom-properties nil
3584 "List of properties (as strings) with a special meaning.
3585 The default use of these custom properties is to let the user
3586 hide them with `org-toggle-custom-properties-visibility'."
3587 :group 'org-properties
3588 :group 'org-appearance
3589 :version "24.3"
3590 :type '(repeat (string :tag "Property Name")))
3592 (defcustom org-fontify-done-headline nil
3593 "Non-nil means change the face of a headline if it is marked DONE.
3594 Normally, only the TODO/DONE keyword indicates the state of a headline.
3595 When this is non-nil, the headline after the keyword is set to the
3596 `org-headline-done' as an additional indication."
3597 :group 'org-appearance
3598 :type 'boolean)
3600 (defcustom org-fontify-emphasized-text t
3601 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3602 Changing this variable requires a restart of Emacs to take effect."
3603 :group 'org-appearance
3604 :type 'boolean)
3606 (defcustom org-fontify-whole-heading-line nil
3607 "Non-nil means fontify the whole line for headings.
3608 This is useful when setting a background color for the
3609 org-level-* faces."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-highlight-latex-fragments-and-specials nil
3614 "Non-nil means fontify what is treated specially by the exporters."
3615 :group 'org-appearance
3616 :type 'boolean)
3618 (defcustom org-hide-emphasis-markers nil
3619 "Non-nil mean font-lock should hide the emphasis marker characters."
3620 :group 'org-appearance
3621 :type 'boolean)
3623 (defcustom org-pretty-entities nil
3624 "Non-nil means show entities as UTF8 characters.
3625 When nil, the \\name form remains in the buffer."
3626 :group 'org-appearance
3627 :version "24.1"
3628 :type 'boolean)
3630 (defcustom org-pretty-entities-include-sub-superscripts t
3631 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3632 :group 'org-appearance
3633 :version "24.1"
3634 :type 'boolean)
3636 (defvar org-emph-re nil
3637 "Regular expression for matching emphasis.
3638 After a match, the match groups contain these elements:
3639 0 The match of the full regular expression, including the characters
3640 before and after the proper match
3641 1 The character before the proper match, or empty at beginning of line
3642 2 The proper match, including the leading and trailing markers
3643 3 The leading marker like * or /, indicating the type of highlighting
3644 4 The text between the emphasis markers, not including the markers
3645 5 The character after the match, empty at the end of a line")
3646 (defvar org-verbatim-re nil
3647 "Regular expression for matching verbatim text.")
3648 (defvar org-emphasis-regexp-components) ; defined just below
3649 (defvar org-emphasis-alist) ; defined just below
3650 (defun org-set-emph-re (var val)
3651 "Set variable and compute the emphasis regular expression."
3652 (set var val)
3653 (when (and (boundp 'org-emphasis-alist)
3654 (boundp 'org-emphasis-regexp-components)
3655 org-emphasis-alist org-emphasis-regexp-components)
3656 (let* ((e org-emphasis-regexp-components)
3657 (pre (car e))
3658 (post (nth 1 e))
3659 (border (nth 2 e))
3660 (body (nth 3 e))
3661 (nl (nth 4 e))
3662 (body1 (concat body "*?"))
3663 (markers (mapconcat 'car org-emphasis-alist ""))
3664 (vmarkers (mapconcat
3665 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3666 org-emphasis-alist "")))
3667 ;; make sure special characters appear at the right position in the class
3668 (if (string-match "\\^" markers)
3669 (setq markers (concat (replace-match "" t t markers) "^")))
3670 (if (string-match "-" markers)
3671 (setq markers (concat (replace-match "" t t markers) "-")))
3672 (if (string-match "\\^" vmarkers)
3673 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3674 (if (string-match "-" vmarkers)
3675 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3676 (if (> nl 0)
3677 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3678 (int-to-string nl) "\\}")))
3679 ;; Make the regexp
3680 (setq org-emph-re
3681 (concat "\\([" pre "]\\|^\\)"
3682 "\\("
3683 "\\([" markers "]\\)"
3684 "\\("
3685 "[^" border "]\\|"
3686 "[^" border "]"
3687 body1
3688 "[^" border "]"
3689 "\\)"
3690 "\\3\\)"
3691 "\\([" post "]\\|$\\)"))
3692 (setq org-verbatim-re
3693 (concat "\\([" pre "]\\|^\\)"
3694 "\\("
3695 "\\([" vmarkers "]\\)"
3696 "\\("
3697 "[^" border "]\\|"
3698 "[^" border "]"
3699 body1
3700 "[^" border "]"
3701 "\\)"
3702 "\\3\\)"
3703 "\\([" post "]\\|$\\)")))))
3705 (defcustom org-emphasis-regexp-components
3706 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3707 "Components used to build the regular expression for emphasis.
3708 This is a list with five entries. Terminology: In an emphasis string
3709 like \" *strong word* \", we call the initial space PREMATCH, the final
3710 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3711 and \"trong wor\" is the body. The different components in this variable
3712 specify what is allowed/forbidden in each part:
3714 pre Chars allowed as prematch. Beginning of line will be allowed too.
3715 post Chars allowed as postmatch. End of line will be allowed too.
3716 border The chars *forbidden* as border characters.
3717 body-regexp A regexp like \".\" to match a body character. Don't use
3718 non-shy groups here, and don't allow newline here.
3719 newline The maximum number of newlines allowed in an emphasis exp.
3721 Use customize to modify this, or restart Emacs after changing it."
3722 :group 'org-appearance
3723 :set 'org-set-emph-re
3724 :type '(list
3725 (sexp :tag "Allowed chars in pre ")
3726 (sexp :tag "Allowed chars in post ")
3727 (sexp :tag "Forbidden chars in border ")
3728 (sexp :tag "Regexp for body ")
3729 (integer :tag "number of newlines allowed")
3730 (option (boolean :tag "Please ignore this button"))))
3732 (defcustom org-emphasis-alist
3733 `(("*" bold "<b>" "</b>")
3734 ("/" italic "<i>" "</i>")
3735 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3736 ("=" org-code "<code>" "</code>" verbatim)
3737 ("~" org-verbatim "<code>" "</code>" verbatim)
3738 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3739 "<del>" "</del>")
3741 "Special syntax for emphasized text.
3742 Text starting and ending with a special character will be emphasized, for
3743 example *bold*, _underlined_ and /italic/. This variable sets the marker
3744 characters, the face to be used by font-lock for highlighting in Org-mode
3745 Emacs buffers, and the HTML tags to be used for this.
3746 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3747 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3748 Use customize to modify this, or restart Emacs after changing it."
3749 :group 'org-appearance
3750 :set 'org-set-emph-re
3751 :type '(repeat
3752 (list
3753 (string :tag "Marker character")
3754 (choice
3755 (face :tag "Font-lock-face")
3756 (plist :tag "Face property list"))
3757 (string :tag "HTML start tag")
3758 (string :tag "HTML end tag")
3759 (option (const verbatim)))))
3761 (defvar org-protecting-blocks
3762 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3763 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3764 This is needed for font-lock setup.")
3766 ;;; Miscellaneous options
3768 (defgroup org-completion nil
3769 "Completion in Org-mode."
3770 :tag "Org Completion"
3771 :group 'org)
3773 (defcustom org-completion-use-ido nil
3774 "Non-nil means use ido completion wherever possible.
3775 Note that `ido-mode' must be active for this variable to be relevant.
3776 If you decide to turn this variable on, you might well want to turn off
3777 `org-outline-path-complete-in-steps'.
3778 See also `org-completion-use-iswitchb'."
3779 :group 'org-completion
3780 :type 'boolean)
3782 (defcustom org-completion-use-iswitchb nil
3783 "Non-nil means use iswitchb completion wherever possible.
3784 Note that `iswitchb-mode' must be active for this variable to be relevant.
3785 If you decide to turn this variable on, you might well want to turn off
3786 `org-outline-path-complete-in-steps'.
3787 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3788 :group 'org-completion
3789 :type 'boolean)
3791 (defcustom org-completion-fallback-command 'hippie-expand
3792 "The expansion command called by \\[pcomplete] in normal context.
3793 Normal means, no org-mode-specific context."
3794 :group 'org-completion
3795 :type 'function)
3797 ;;; Functions and variables from their packages
3798 ;; Declared here to avoid compiler warnings
3800 ;; XEmacs only
3801 (defvar outline-mode-menu-heading)
3802 (defvar outline-mode-menu-show)
3803 (defvar outline-mode-menu-hide)
3804 (defvar zmacs-regions) ; XEmacs regions
3806 ;; Emacs only
3807 (defvar mark-active)
3809 ;; Various packages
3810 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3811 (declare-function calendar-forward-day "cal-move" (arg))
3812 (declare-function calendar-goto-date "cal-move" (date))
3813 (declare-function calendar-goto-today "cal-move" ())
3814 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3815 (defvar calc-embedded-close-formula)
3816 (defvar calc-embedded-open-formula)
3817 (declare-function cdlatex-tab "ext:cdlatex" ())
3818 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3819 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3820 (defvar font-lock-unfontify-region-function)
3821 (declare-function iswitchb-read-buffer "iswitchb"
3822 (prompt &optional default require-match start matches-set))
3823 (defvar iswitchb-temp-buflist)
3824 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3825 (defvar org-agenda-tags-todo-honor-ignore-options)
3826 (declare-function org-agenda-skip "org-agenda" ())
3827 (declare-function
3828 org-agenda-format-item "org-agenda"
3829 (extra txt &optional category tags dotime noprefix remove-re habitp))
3830 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3831 (declare-function org-agenda-change-all-lines "org-agenda"
3832 (newhead hdmarker &optional fixface just-this))
3833 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3834 (declare-function org-agenda-maybe-redo "org-agenda" ())
3835 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3836 (beg end))
3837 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3838 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3839 "org-agenda" (&optional end))
3840 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3841 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3842 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3843 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3844 (declare-function org-indent-mode "org-indent" (&optional arg))
3845 (declare-function parse-time-string "parse-time" (string))
3846 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3847 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3848 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3849 (defvar remember-data-file)
3850 (defvar texmathp-why)
3851 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3852 (declare-function table--at-cell-p "table" (position &optional object at-column))
3854 (defvar w3m-current-url)
3855 (defvar w3m-current-title)
3857 (defvar org-latex-regexps)
3859 ;;; Autoload and prepare some org modules
3861 ;; Some table stuff that needs to be defined here, because it is used
3862 ;; by the functions setting up org-mode or checking for table context.
3864 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3865 "Detect an org-type or table-type table.")
3866 (defconst org-table-line-regexp "^[ \t]*|"
3867 "Detect an org-type table line.")
3868 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3869 "Detect an org-type table line.")
3870 (defconst org-table-hline-regexp "^[ \t]*|-"
3871 "Detect an org-type table hline.")
3872 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3873 "Detect a table-type table hline.")
3874 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3875 "Detect the first line outside a table when searching from within it.
3876 This works for both table types.")
3878 ;; Autoload the functions in org-table.el that are needed by functions here.
3880 (eval-and-compile
3881 (org-autoload "org-table"
3882 '(org-table-begin org-table-blank-field org-table-end)))
3884 ;;;###autoload
3885 (defun turn-on-orgtbl ()
3886 "Unconditionally turn on `orgtbl-mode'."
3887 (require 'org-table)
3888 (orgtbl-mode 1))
3890 (defun org-at-table-p (&optional table-type)
3891 "Return t if the cursor is inside an org-type table.
3892 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3893 (if org-enable-table-editor
3894 (save-excursion
3895 (beginning-of-line 1)
3896 (looking-at (if table-type org-table-any-line-regexp
3897 org-table-line-regexp)))
3898 nil))
3899 (defsubst org-table-p () (org-at-table-p))
3901 (defun org-at-table.el-p ()
3902 "Return t if and only if we are at a table.el table."
3903 (and (org-at-table-p 'any)
3904 (save-excursion
3905 (goto-char (org-table-begin 'any))
3906 (looking-at org-table1-hline-regexp))))
3907 (defun org-table-recognize-table.el ()
3908 "If there is a table.el table nearby, recognize it and move into it."
3909 (if org-table-tab-recognizes-table.el
3910 (if (org-at-table.el-p)
3911 (progn
3912 (beginning-of-line 1)
3913 (if (looking-at org-table-dataline-regexp)
3915 (if (looking-at org-table1-hline-regexp)
3916 (progn
3917 (beginning-of-line 2)
3918 (if (looking-at org-table-any-border-regexp)
3919 (beginning-of-line -1)))))
3920 (if (re-search-forward "|" (org-table-end t) t)
3921 (progn
3922 (require 'table)
3923 (if (table--at-cell-p (point))
3925 (message "recognizing table.el table...")
3926 (table-recognize-table)
3927 (message "recognizing table.el table...done")))
3928 (error "This should not happen"))
3930 nil)
3931 nil))
3933 (defun org-at-table-hline-p ()
3934 "Return t if the cursor is inside a hline in a table."
3935 (if org-enable-table-editor
3936 (save-excursion
3937 (beginning-of-line 1)
3938 (looking-at org-table-hline-regexp))
3939 nil))
3941 (defvar org-table-clean-did-remove-column nil)
3943 (defun org-table-map-tables (function &optional quietly)
3944 "Apply FUNCTION to the start of all tables in the buffer."
3945 (save-excursion
3946 (save-restriction
3947 (widen)
3948 (goto-char (point-min))
3949 (while (re-search-forward org-table-any-line-regexp nil t)
3950 (unless quietly
3951 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3952 (beginning-of-line 1)
3953 (when (and (looking-at org-table-line-regexp)
3954 ;; Exclude tables in src/example/verbatim/clocktable blocks
3955 (not (org-in-block-p '("src" "example"))))
3956 (save-excursion (funcall function))
3957 (or (looking-at org-table-line-regexp)
3958 (forward-char 1)))
3959 (re-search-forward org-table-any-border-regexp nil 1))))
3960 (unless quietly (message "Mapping tables: done")))
3962 ;; Declare and autoload functions from org-exp.el & Co
3964 (declare-function org-default-export-plist "org-exp")
3965 (declare-function org-infile-export-plist "org-exp")
3966 (declare-function org-get-current-options "org-exp")
3968 ;; Declare and autoload functions from org-agenda.el
3970 (eval-and-compile
3971 (org-autoload "org-agenda"
3972 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3974 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3975 (declare-function org-clock-update-mode-line "org-clock" ())
3976 (declare-function org-resolve-clocks "org-clock"
3977 (&optional also-non-dangling-p prompt last-valid))
3978 (defvar org-clock-start-time)
3979 (defvar org-clock-marker (make-marker)
3980 "Marker recording the last clock-in.")
3981 (defvar org-clock-hd-marker (make-marker)
3982 "Marker recording the last clock-in, but the headline position.")
3983 (defvar org-clock-heading ""
3984 "The heading of the current clock entry.")
3985 (defun org-clock-is-active ()
3986 "Return non-nil if clock is currently running.
3987 The return value is actually the clock marker."
3988 (marker-buffer org-clock-marker))
3990 (eval-and-compile
3991 (org-autoload "org-clock" '(org-clock-remove-overlays
3992 org-clock-update-time-maybe
3993 org-clocktable-shift)))
3995 (defun org-check-running-clock ()
3996 "Check if the current buffer contains the running clock.
3997 If yes, offer to stop it and to save the buffer with the changes."
3998 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3999 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4000 (buffer-name))))
4001 (org-clock-out)
4002 (when (y-or-n-p "Save changed buffer?")
4003 (save-buffer))))
4005 (defun org-clocktable-try-shift (dir n)
4006 "Check if this line starts a clock table, if yes, shift the time block."
4007 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4008 (org-clocktable-shift dir n)))
4010 ;;;###autoload
4011 (defun org-clock-persistence-insinuate ()
4012 "Set up hooks for clock persistence."
4013 (require 'org-clock)
4014 (add-hook 'org-mode-hook 'org-clock-load)
4015 (add-hook 'kill-emacs-hook 'org-clock-save))
4017 ;; Define the variable already here, to make sure we have it.
4018 (defvar org-indent-mode nil
4019 "Non-nil if Org-Indent mode is enabled.
4020 Use the command `org-indent-mode' to change this variable.")
4022 ;; Autoload archiving code
4023 ;; The stuff that is needed for cycling and tags has to be defined here.
4025 (defgroup org-archive nil
4026 "Options concerning archiving in Org-mode."
4027 :tag "Org Archive"
4028 :group 'org-structure)
4030 (defcustom org-archive-location "%s_archive::"
4031 "The location where subtrees should be archived.
4033 The value of this variable is a string, consisting of two parts,
4034 separated by a double-colon. The first part is a filename and
4035 the second part is a headline.
4037 When the filename is omitted, archiving happens in the same file.
4038 %s in the filename will be replaced by the current file
4039 name (without the directory part). Archiving to a different file
4040 is useful to keep archived entries from contributing to the
4041 Org-mode Agenda.
4043 The archived entries will be filed as subtrees of the specified
4044 headline. When the headline is omitted, the subtrees are simply
4045 filed away at the end of the file, as top-level entries. Also in
4046 the heading you can use %s to represent the file name, this can be
4047 useful when using the same archive for a number of different files.
4049 Here are a few examples:
4050 \"%s_archive::\"
4051 If the current file is Projects.org, archive in file
4052 Projects.org_archive, as top-level trees. This is the default.
4054 \"::* Archived Tasks\"
4055 Archive in the current file, under the top-level headline
4056 \"* Archived Tasks\".
4058 \"~/org/archive.org::\"
4059 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4061 \"~/org/archive.org::* From %s\"
4062 Archive in file ~/org/archive.org (absolute path), under headlines
4063 \"From FILENAME\" where file name is the current file name.
4065 \"~/org/datetree.org::datetree/* Finished Tasks\"
4066 The \"datetree/\" string is special, signifying to archive
4067 items to the datetree. Items are placed in either the CLOSED
4068 date of the item, or the current date if there is no CLOSED date.
4069 The heading will be a subentry to the current date. There doesn't
4070 need to be a heading, but there always needs to be a slash after
4071 datetree. For example, to store archived items directly in the
4072 datetree, use \"~/org/datetree.org::datetree/\".
4074 \"basement::** Finished Tasks\"
4075 Archive in file ./basement (relative path), as level 3 trees
4076 below the level 2 heading \"** Finished Tasks\".
4078 You may set this option on a per-file basis by adding to the buffer a
4079 line like
4081 #+ARCHIVE: basement::** Finished Tasks
4083 You may also define it locally for a subtree by setting an ARCHIVE property
4084 in the entry. If such a property is found in an entry, or anywhere up
4085 the hierarchy, it will be used."
4086 :group 'org-archive
4087 :type 'string)
4089 (defcustom org-archive-tag "ARCHIVE"
4090 "The tag that marks a subtree as archived.
4091 An archived subtree does not open during visibility cycling, and does
4092 not contribute to the agenda listings.
4093 After changing this, font-lock must be restarted in the relevant buffers to
4094 get the proper fontification."
4095 :group 'org-archive
4096 :group 'org-keywords
4097 :type 'string)
4099 (defcustom org-agenda-skip-archived-trees t
4100 "Non-nil means the agenda will skip any items located in archived trees.
4101 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4102 variable is no longer recommended, you should leave it at the value t.
4103 Instead, use the key `v' to cycle the archives-mode in the agenda."
4104 :group 'org-archive
4105 :group 'org-agenda-skip
4106 :type 'boolean)
4108 (defcustom org-columns-skip-archived-trees t
4109 "Non-nil means ignore archived trees when creating column view."
4110 :group 'org-archive
4111 :group 'org-properties
4112 :type 'boolean)
4114 (defcustom org-cycle-open-archived-trees nil
4115 "Non-nil means `org-cycle' will open archived trees.
4116 An archived tree is a tree marked with the tag ARCHIVE.
4117 When nil, archived trees will stay folded. You can still open them with
4118 normal outline commands like `show-all', but not with the cycling commands."
4119 :group 'org-archive
4120 :group 'org-cycle
4121 :type 'boolean)
4123 (defcustom org-sparse-tree-open-archived-trees nil
4124 "Non-nil means sparse tree construction shows matches in archived trees.
4125 When nil, matches in these trees are highlighted, but the trees are kept in
4126 collapsed state."
4127 :group 'org-archive
4128 :group 'org-sparse-trees
4129 :type 'boolean)
4131 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4132 "The default date type when building a sparse tree.
4133 When this is nil, a date is a scheduled or a deadline timestamp.
4134 Otherwise, these types are allowed:
4136 all: all timestamps
4137 active: only active timestamps (<...>)
4138 inactive: only inactive timestamps (<...)
4139 scheduled: only scheduled timestamps
4140 deadline: only deadline timestamps"
4141 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4142 (const :tag "All timestamps" all)
4143 (const :tag "Only active timestamps" active)
4144 (const :tag "Only inactive timestamps" inactive)
4145 (const :tag "Only scheduled timestamps" scheduled)
4146 (const :tag "Only deadline timestamps" deadline))
4147 :version "24.3"
4148 :group 'org-sparse-trees)
4150 (defun org-cycle-hide-archived-subtrees (state)
4151 "Re-hide all archived subtrees after a visibility state change."
4152 (when (and (not org-cycle-open-archived-trees)
4153 (not (memq state '(overview folded))))
4154 (save-excursion
4155 (let* ((globalp (memq state '(contents all)))
4156 (beg (if globalp (point-min) (point)))
4157 (end (if globalp (point-max) (org-end-of-subtree t))))
4158 (org-hide-archived-subtrees beg end)
4159 (goto-char beg)
4160 (if (looking-at (concat ".*:" org-archive-tag ":"))
4161 (message "%s" (substitute-command-keys
4162 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4164 (defun org-force-cycle-archived ()
4165 "Cycle subtree even if it is archived."
4166 (interactive)
4167 (setq this-command 'org-cycle)
4168 (let ((org-cycle-open-archived-trees t))
4169 (call-interactively 'org-cycle)))
4171 (defun org-hide-archived-subtrees (beg end)
4172 "Re-hide all archived subtrees after a visibility state change."
4173 (save-excursion
4174 (let* ((re (concat ":" org-archive-tag ":")))
4175 (goto-char beg)
4176 (while (re-search-forward re end t)
4177 (when (org-at-heading-p)
4178 (org-flag-subtree t)
4179 (org-end-of-subtree t))))))
4181 (declare-function outline-end-of-heading "outline" ())
4182 (declare-function outline-flag-region "outline" (from to flag))
4183 (defun org-flag-subtree (flag)
4184 (save-excursion
4185 (org-back-to-heading t)
4186 (outline-end-of-heading)
4187 (outline-flag-region (point)
4188 (progn (org-end-of-subtree t) (point))
4189 flag)))
4191 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4193 (eval-and-compile
4194 (org-autoload "org-archive"
4195 '(org-add-archive-files)))
4197 ;; Autoload Column View Code
4199 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4200 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4201 (declare-function org-columns-compute "org-colview" (property))
4203 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4204 '(org-columns-number-to-string
4205 org-columns-get-format-and-top-level
4206 org-columns-compute
4207 org-columns-remove-overlays))
4209 ;; Autoload ID code
4211 (declare-function org-id-store-link "org-id")
4212 (declare-function org-id-locations-load "org-id")
4213 (declare-function org-id-locations-save "org-id")
4214 (defvar org-id-track-globally)
4215 (org-autoload "org-id"
4216 '(org-id-new
4217 org-id-copy
4218 org-id-get-with-outline-path-completion
4219 org-id-get-with-outline-drilling))
4221 ;;; Variables for pre-computed regular expressions, all buffer local
4223 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4224 "Matches first line of a hidden block.")
4225 (make-variable-buffer-local 'org-drawer-regexp)
4226 (defvar org-todo-regexp nil
4227 "Matches any of the TODO state keywords.")
4228 (make-variable-buffer-local 'org-todo-regexp)
4229 (defvar org-not-done-regexp nil
4230 "Matches any of the TODO state keywords except the last one.")
4231 (make-variable-buffer-local 'org-not-done-regexp)
4232 (defvar org-not-done-heading-regexp nil
4233 "Matches a TODO headline that is not done.")
4234 (make-variable-buffer-local 'org-not-done-regexp)
4235 (defvar org-todo-line-regexp nil
4236 "Matches a headline and puts TODO state into group 2 if present.")
4237 (make-variable-buffer-local 'org-todo-line-regexp)
4238 (defvar org-complex-heading-regexp nil
4239 "Matches a headline and puts everything into groups:
4240 group 1: the stars
4241 group 2: The todo keyword, maybe
4242 group 3: Priority cookie
4243 group 4: True headline
4244 group 5: Tags")
4245 (make-variable-buffer-local 'org-complex-heading-regexp)
4246 (defvar org-complex-heading-regexp-format nil
4247 "Printf format to make regexp to match an exact headline.
4248 This regexp will match the headline of any node which has the
4249 exact headline text that is put into the format, but may have any
4250 TODO state, priority and tags.")
4251 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4252 (defvar org-todo-line-tags-regexp nil
4253 "Matches a headline and puts TODO state into group 2 if present.
4254 Also put tags into group 4 if tags are present.")
4255 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4256 (defvar org-ds-keyword-length 12
4257 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4258 (make-variable-buffer-local 'org-ds-keyword-length)
4259 (defvar org-deadline-regexp nil
4260 "Matches the DEADLINE keyword.")
4261 (make-variable-buffer-local 'org-deadline-regexp)
4262 (defvar org-deadline-time-regexp nil
4263 "Matches the DEADLINE keyword together with a time stamp.")
4264 (make-variable-buffer-local 'org-deadline-time-regexp)
4265 (defvar org-deadline-line-regexp nil
4266 "Matches the DEADLINE keyword and the rest of the line.")
4267 (make-variable-buffer-local 'org-deadline-line-regexp)
4268 (defvar org-scheduled-regexp nil
4269 "Matches the SCHEDULED keyword.")
4270 (make-variable-buffer-local 'org-scheduled-regexp)
4271 (defvar org-scheduled-time-regexp nil
4272 "Matches the SCHEDULED keyword together with a time stamp.")
4273 (make-variable-buffer-local 'org-scheduled-time-regexp)
4274 (defvar org-closed-time-regexp nil
4275 "Matches the CLOSED keyword together with a time stamp.")
4276 (make-variable-buffer-local 'org-closed-time-regexp)
4278 (defvar org-keyword-time-regexp nil
4279 "Matches any of the 4 keywords, together with the time stamp.")
4280 (make-variable-buffer-local 'org-keyword-time-regexp)
4281 (defvar org-keyword-time-not-clock-regexp nil
4282 "Matches any of the 3 keywords, together with the time stamp.")
4283 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4284 (defvar org-maybe-keyword-time-regexp nil
4285 "Matches a timestamp, possibly preceded by a keyword.")
4286 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4287 (defvar org-all-time-keywords nil
4288 "List of time keywords.")
4289 (make-variable-buffer-local 'org-all-time-keywords)
4291 (defconst org-plain-time-of-day-regexp
4292 (concat
4293 "\\(\\<[012]?[0-9]"
4294 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4295 "\\(--?"
4296 "\\(\\<[012]?[0-9]"
4297 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4298 "\\)?")
4299 "Regular expression to match a plain time or time range.
4300 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4301 groups carry important information:
4302 0 the full match
4303 1 the first time, range or not
4304 8 the second time, if it is a range.")
4306 (defconst org-plain-time-extension-regexp
4307 (concat
4308 "\\(\\<[012]?[0-9]"
4309 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4310 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4311 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4312 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4313 groups carry important information:
4314 0 the full match
4315 7 hours of duration
4316 9 minutes of duration")
4318 (defconst org-stamp-time-of-day-regexp
4319 (concat
4320 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4321 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4322 "\\(--?"
4323 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4324 "Regular expression to match a timestamp time or time range.
4325 After a match, the following groups carry important information:
4326 0 the full match
4327 1 date plus weekday, for back referencing to make sure both times are on the same day
4328 2 the first time, range or not
4329 4 the second time, if it is a range.")
4331 (defconst org-startup-options
4332 '(("fold" org-startup-folded t)
4333 ("overview" org-startup-folded t)
4334 ("nofold" org-startup-folded nil)
4335 ("showall" org-startup-folded nil)
4336 ("showeverything" org-startup-folded showeverything)
4337 ("content" org-startup-folded content)
4338 ("indent" org-startup-indented t)
4339 ("noindent" org-startup-indented nil)
4340 ("hidestars" org-hide-leading-stars t)
4341 ("showstars" org-hide-leading-stars nil)
4342 ("odd" org-odd-levels-only t)
4343 ("oddeven" org-odd-levels-only nil)
4344 ("align" org-startup-align-all-tables t)
4345 ("noalign" org-startup-align-all-tables nil)
4346 ("inlineimages" org-startup-with-inline-images t)
4347 ("noinlineimages" org-startup-with-inline-images nil)
4348 ("customtime" org-display-custom-times t)
4349 ("logdone" org-log-done time)
4350 ("lognotedone" org-log-done note)
4351 ("nologdone" org-log-done nil)
4352 ("lognoteclock-out" org-log-note-clock-out t)
4353 ("nolognoteclock-out" org-log-note-clock-out nil)
4354 ("logrepeat" org-log-repeat state)
4355 ("lognoterepeat" org-log-repeat note)
4356 ("nologrepeat" org-log-repeat nil)
4357 ("logreschedule" org-log-reschedule time)
4358 ("lognotereschedule" org-log-reschedule note)
4359 ("nologreschedule" org-log-reschedule nil)
4360 ("logredeadline" org-log-redeadline time)
4361 ("lognoteredeadline" org-log-redeadline note)
4362 ("nologredeadline" org-log-redeadline nil)
4363 ("logrefile" org-log-refile time)
4364 ("lognoterefile" org-log-refile note)
4365 ("nologrefile" org-log-refile nil)
4366 ("fninline" org-footnote-define-inline t)
4367 ("nofninline" org-footnote-define-inline nil)
4368 ("fnlocal" org-footnote-section nil)
4369 ("fnauto" org-footnote-auto-label t)
4370 ("fnprompt" org-footnote-auto-label nil)
4371 ("fnconfirm" org-footnote-auto-label confirm)
4372 ("fnplain" org-footnote-auto-label plain)
4373 ("fnadjust" org-footnote-auto-adjust t)
4374 ("nofnadjust" org-footnote-auto-adjust nil)
4375 ("constcgs" constants-unit-system cgs)
4376 ("constSI" constants-unit-system SI)
4377 ("noptag" org-tag-persistent-alist nil)
4378 ("hideblocks" org-hide-block-startup t)
4379 ("nohideblocks" org-hide-block-startup nil)
4380 ("beamer" org-startup-with-beamer-mode t)
4381 ("entitiespretty" org-pretty-entities t)
4382 ("entitiesplain" org-pretty-entities nil))
4383 "Variable associated with STARTUP options for org-mode.
4384 Each element is a list of three items: the startup options (as written
4385 in the #+STARTUP line), the corresponding variable, and the value to set
4386 this variable to if the option is found. An optional forth element PUSH
4387 means to push this value onto the list in the variable.")
4389 (defun org-update-property-plist (key val props)
4390 "Update PROPS with KEY and VAL."
4391 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4392 (key (if appending (substring key 0 (- (length key) 1)) key))
4393 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4394 (previous (cdr (assoc key props))))
4395 (if appending
4396 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4397 (cons (cons key val) remainder))))
4399 (defconst org-block-regexp
4400 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4401 "Regular expression for hiding blocks.")
4402 (defconst org-heading-keyword-regexp-format
4403 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4404 "Printf format for a regexp matching an headline with some keyword.
4405 This regexp will match the headline of any node which has the
4406 exact keyword that is put into the format. The keyword isn't in
4407 any group by default, but the stars and the body are.")
4408 (defconst org-heading-keyword-maybe-regexp-format
4409 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4410 "Printf format for a regexp matching an headline, possibly with some keyword.
4411 This regexp can match any headline with the specified keyword, or
4412 without a keyword. The keyword isn't in any group by default,
4413 but the stars and the body are.")
4415 (defun org-set-regexps-and-options ()
4416 "Precompute regular expressions for current buffer."
4417 (when (derived-mode-p 'org-mode)
4418 (org-set-local 'org-todo-kwd-alist nil)
4419 (org-set-local 'org-todo-key-alist nil)
4420 (org-set-local 'org-todo-key-trigger nil)
4421 (org-set-local 'org-todo-keywords-1 nil)
4422 (org-set-local 'org-done-keywords nil)
4423 (org-set-local 'org-todo-heads nil)
4424 (org-set-local 'org-todo-sets nil)
4425 (org-set-local 'org-todo-log-states nil)
4426 (org-set-local 'org-file-properties nil)
4427 (org-set-local 'org-file-tags nil)
4428 (let ((re (org-make-options-regexp
4429 '("CATEGORY" "TODO" "COLUMNS"
4430 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4431 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4432 "OPTIONS")
4433 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4434 (splitre "[ \t]+")
4435 (scripts org-use-sub-superscripts)
4436 kwds kws0 kwsa key log value cat arch tags const links hw dws
4437 tail sep kws1 prio props ftags drawers beamer-p
4438 ext-setup-or-nil setup-contents (start 0))
4439 (save-excursion
4440 (save-restriction
4441 (widen)
4442 (goto-char (point-min))
4443 (while (or (and ext-setup-or-nil
4444 (string-match re ext-setup-or-nil start)
4445 (setq start (match-end 0)))
4446 (and (setq ext-setup-or-nil nil start 0)
4447 (re-search-forward re nil t)))
4448 (setq key (upcase (match-string 1 ext-setup-or-nil))
4449 value (org-match-string-no-properties 2 ext-setup-or-nil))
4450 (if (stringp value) (setq value (org-trim value)))
4451 (cond
4452 ((equal key "CATEGORY")
4453 (setq cat value))
4454 ((member key '("SEQ_TODO" "TODO"))
4455 (push (cons 'sequence (org-split-string value splitre)) kwds))
4456 ((equal key "TYP_TODO")
4457 (push (cons 'type (org-split-string value splitre)) kwds))
4458 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4459 ;; general TODO-like setup
4460 (push (cons (intern (downcase (match-string 1 key)))
4461 (org-split-string value splitre)) kwds))
4462 ((equal key "TAGS")
4463 (setq tags (append tags (if tags '("\\n") nil)
4464 (org-split-string value splitre))))
4465 ((equal key "COLUMNS")
4466 (org-set-local 'org-columns-default-format value))
4467 ((equal key "LINK")
4468 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4469 (push (cons (match-string 1 value)
4470 (org-trim (match-string 2 value)))
4471 links)))
4472 ((equal key "PRIORITIES")
4473 (setq prio (org-split-string value " +")))
4474 ((equal key "PROPERTY")
4475 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4476 (setq props (org-update-property-plist (match-string 1 value)
4477 (match-string 2 value)
4478 props))))
4479 ((equal key "FILETAGS")
4480 (when (string-match "\\S-" value)
4481 (setq ftags
4482 (append
4483 ftags
4484 (apply 'append
4485 (mapcar (lambda (x) (org-split-string x ":"))
4486 (org-split-string value)))))))
4487 ((equal key "DRAWERS")
4488 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4489 ((equal key "CONSTANTS")
4490 (setq const (append const (org-split-string value splitre))))
4491 ((equal key "STARTUP")
4492 (let ((opts (org-split-string value splitre))
4493 l var val)
4494 (while (setq l (pop opts))
4495 (when (setq l (assoc l org-startup-options))
4496 (setq var (nth 1 l) val (nth 2 l))
4497 (if (not (nth 3 l))
4498 (set (make-local-variable var) val)
4499 (if (not (listp (symbol-value var)))
4500 (set (make-local-variable var) nil))
4501 (set (make-local-variable var) (symbol-value var))
4502 (add-to-list var val))))))
4503 ((equal key "ARCHIVE")
4504 (setq arch value)
4505 (remove-text-properties 0 (length arch)
4506 '(face t fontified t) arch))
4507 ((equal key "LATEX_CLASS")
4508 (setq beamer-p (equal value "beamer")))
4509 ((equal key "OPTIONS")
4510 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4511 (setq scripts (read (match-string 2 value)))))
4512 ((equal key "SETUPFILE")
4513 (setq setup-contents (org-file-contents
4514 (expand-file-name
4515 (org-remove-double-quotes value))
4516 'noerror))
4517 (if (not ext-setup-or-nil)
4518 (setq ext-setup-or-nil setup-contents start 0)
4519 (setq ext-setup-or-nil
4520 (concat (substring ext-setup-or-nil 0 start)
4521 "\n" setup-contents "\n"
4522 (substring ext-setup-or-nil start)))))))
4523 ;; search for property blocks
4524 (goto-char (point-min))
4525 (while (re-search-forward org-block-regexp nil t)
4526 (when (equal "PROPERTY" (upcase (match-string 1)))
4527 (setq value (replace-regexp-in-string
4528 "[\n\r]" " " (match-string 4)))
4529 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4530 (setq props (org-update-property-plist (match-string 1 value)
4531 (match-string 2 value)
4532 props)))))))
4533 (org-set-local 'org-use-sub-superscripts scripts)
4534 (when cat
4535 (org-set-local 'org-category (intern cat))
4536 (push (cons "CATEGORY" cat) props))
4537 (when prio
4538 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4539 (setq prio (mapcar 'string-to-char prio))
4540 (org-set-local 'org-highest-priority (nth 0 prio))
4541 (org-set-local 'org-lowest-priority (nth 1 prio))
4542 (org-set-local 'org-default-priority (nth 2 prio)))
4543 (and props (org-set-local 'org-file-properties (nreverse props)))
4544 (and ftags (org-set-local 'org-file-tags
4545 (mapcar 'org-add-prop-inherited ftags)))
4546 (and drawers (org-set-local 'org-drawers drawers))
4547 (and arch (org-set-local 'org-archive-location arch))
4548 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4549 ;; Process the TODO keywords
4550 (unless kwds
4551 ;; Use the global values as if they had been given locally.
4552 (setq kwds (default-value 'org-todo-keywords))
4553 (if (stringp (car kwds))
4554 (setq kwds (list (cons org-todo-interpretation
4555 (default-value 'org-todo-keywords)))))
4556 (setq kwds (reverse kwds)))
4557 (setq kwds (nreverse kwds))
4558 (let (inter kws kw)
4559 (while (setq kws (pop kwds))
4560 (let ((kws (or
4561 (run-hook-with-args-until-success
4562 'org-todo-setup-filter-hook kws)
4563 kws)))
4564 (setq inter (pop kws) sep (member "|" kws)
4565 kws0 (delete "|" (copy-sequence kws))
4566 kwsa nil
4567 kws1 (mapcar
4568 (lambda (x)
4569 ;; 1 2
4570 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4571 (progn
4572 (setq kw (match-string 1 x)
4573 key (and (match-end 2) (match-string 2 x))
4574 log (org-extract-log-state-settings x))
4575 (push (cons kw (and key (string-to-char key))) kwsa)
4576 (and log (push log org-todo-log-states))
4578 (error "Invalid TODO keyword %s" x)))
4579 kws0)
4580 kwsa (if kwsa (append '((:startgroup))
4581 (nreverse kwsa)
4582 '((:endgroup))))
4583 hw (car kws1)
4584 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4585 tail (list inter hw (car dws) (org-last dws))))
4586 (add-to-list 'org-todo-heads hw 'append)
4587 (push kws1 org-todo-sets)
4588 (setq org-done-keywords (append org-done-keywords dws nil))
4589 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4590 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4591 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4592 (setq org-todo-sets (nreverse org-todo-sets)
4593 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4594 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4595 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4596 ;; Process the constants
4597 (when const
4598 (let (e cst)
4599 (while (setq e (pop const))
4600 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4601 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4602 (setq org-table-formula-constants-local cst)))
4604 ;; Process the tags.
4605 (when tags
4606 (let (e tgs)
4607 (while (setq e (pop tags))
4608 (cond
4609 ((equal e "{") (push '(:startgroup) tgs))
4610 ((equal e "}") (push '(:endgroup) tgs))
4611 ((equal e "\\n") (push '(:newline) tgs))
4612 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4613 (push (cons (match-string 1 e)
4614 (string-to-char (match-string 2 e)))
4615 tgs))
4616 (t (push (list e) tgs))))
4617 (org-set-local 'org-tag-alist nil)
4618 (while (setq e (pop tgs))
4619 (or (and (stringp (car e))
4620 (assoc (car e) org-tag-alist))
4621 (push e org-tag-alist)))))
4623 ;; Compute the regular expressions and other local variables.
4624 ;; Using `org-outline-regexp-bol' would complicate them much,
4625 ;; because of the fixed white space at the end of that string.
4626 (if (not org-done-keywords)
4627 (setq org-done-keywords (and org-todo-keywords-1
4628 (list (org-last org-todo-keywords-1)))))
4629 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4630 (length org-scheduled-string)
4631 (length org-clock-string)
4632 (length org-closed-string)))
4633 org-drawer-regexp
4634 (concat "^[ \t]*:\\("
4635 (mapconcat 'regexp-quote org-drawers "\\|")
4636 "\\):[ \t]*$")
4637 org-not-done-keywords
4638 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4639 org-todo-regexp
4640 (concat "\\("
4641 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4642 "\\)")
4643 org-not-done-regexp
4644 (concat "\\("
4645 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4646 "\\)")
4647 org-not-done-heading-regexp
4648 (format org-heading-keyword-regexp-format org-not-done-regexp)
4649 org-todo-line-regexp
4650 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4651 org-complex-heading-regexp
4652 (concat "^\\(\\*+\\)"
4653 "\\(?: +" org-todo-regexp "\\)?"
4654 "\\(?: +\\(\\[#.\\]\\)\\)?"
4655 "\\(?: +\\(.*?\\)\\)??"
4656 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4657 "[ \t]*$")
4658 org-complex-heading-regexp-format
4659 (concat "^\\(\\*+\\)"
4660 "\\(?: +" org-todo-regexp "\\)?"
4661 "\\(?: +\\(\\[#.\\]\\)\\)?"
4662 "\\(?: +"
4663 ;; Stats cookies can be stuck to body.
4664 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4665 "\\(%s\\)"
4666 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4667 "\\)"
4668 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4669 "[ \t]*$")
4670 org-todo-line-tags-regexp
4671 (concat "^\\(\\*+\\)"
4672 "\\(?: +" org-todo-regexp "\\)?"
4673 "\\(?: +\\(.*?\\)\\)??"
4674 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4675 "[ \t]*$")
4676 org-deadline-regexp (concat "\\<" org-deadline-string)
4677 org-deadline-time-regexp
4678 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4679 org-deadline-line-regexp
4680 (concat "\\<\\(" org-deadline-string "\\).*")
4681 org-scheduled-regexp
4682 (concat "\\<" org-scheduled-string)
4683 org-scheduled-time-regexp
4684 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4685 org-closed-time-regexp
4686 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4687 org-keyword-time-regexp
4688 (concat "\\<\\(" org-scheduled-string
4689 "\\|" org-deadline-string
4690 "\\|" org-closed-string
4691 "\\|" org-clock-string "\\)"
4692 " *[[<]\\([^]>]+\\)[]>]")
4693 org-keyword-time-not-clock-regexp
4694 (concat "\\<\\(" org-scheduled-string
4695 "\\|" org-deadline-string
4696 "\\|" org-closed-string
4697 "\\)"
4698 " *[[<]\\([^]>]+\\)[]>]")
4699 org-maybe-keyword-time-regexp
4700 (concat "\\(\\<\\(" org-scheduled-string
4701 "\\|" org-deadline-string
4702 "\\|" org-closed-string
4703 "\\|" org-clock-string "\\)\\)?"
4704 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4705 org-all-time-keywords
4706 (mapcar (lambda (w) (substring w 0 -1))
4707 (list org-scheduled-string org-deadline-string
4708 org-clock-string org-closed-string))
4710 (org-compute-latex-and-specials-regexp)
4711 (org-set-font-lock-defaults))))
4713 (defun org-file-contents (file &optional noerror)
4714 "Return the contents of FILE, as a string."
4715 (if (or (not file)
4716 (not (file-readable-p file)))
4717 (if noerror
4718 (progn
4719 (message "Cannot read file \"%s\"" file)
4720 (ding) (sit-for 2)
4722 (error "Cannot read file \"%s\"" file))
4723 (with-temp-buffer
4724 (insert-file-contents file)
4725 (buffer-string))))
4727 (defun org-extract-log-state-settings (x)
4728 "Extract the log state setting from a TODO keyword string.
4729 This will extract info from a string like \"WAIT(w@/!)\"."
4730 (let (kw key log1 log2)
4731 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4732 (setq kw (match-string 1 x)
4733 key (and (match-end 2) (match-string 2 x))
4734 log1 (and (match-end 3) (match-string 3 x))
4735 log2 (and (match-end 4) (match-string 4 x)))
4736 (and (or log1 log2)
4737 (list kw
4738 (and log1 (if (equal log1 "!") 'time 'note))
4739 (and log2 (if (equal log2 "!") 'time 'note)))))))
4741 (defun org-remove-keyword-keys (list)
4742 "Remove a pair of parenthesis at the end of each string in LIST."
4743 (mapcar (lambda (x)
4744 (if (string-match "(.*)$" x)
4745 (substring x 0 (match-beginning 0))
4747 list))
4749 (defun org-assign-fast-keys (alist)
4750 "Assign fast keys to a keyword-key alist.
4751 Respect keys that are already there."
4752 (let (new e (alt ?0))
4753 (while (setq e (pop alist))
4754 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4755 (cdr e)) ;; Key already assigned.
4756 (push e new)
4757 (let ((clist (string-to-list (downcase (car e))))
4758 (used (append new alist)))
4759 (when (= (car clist) ?@)
4760 (pop clist))
4761 (while (and clist (rassoc (car clist) used))
4762 (pop clist))
4763 (unless clist
4764 (while (rassoc alt used)
4765 (incf alt)))
4766 (push (cons (car e) (or (car clist) alt)) new))))
4767 (nreverse new)))
4769 ;;; Some variables used in various places
4771 (defvar org-window-configuration nil
4772 "Used in various places to store a window configuration.")
4773 (defvar org-selected-window nil
4774 "Used in various places to store a window configuration.")
4775 (defvar org-finish-function nil
4776 "Function to be called when `C-c C-c' is used.
4777 This is for getting out of special buffers like capture.")
4780 ;; FIXME: Occasionally check by commenting these, to make sure
4781 ;; no other functions uses these, forgetting to let-bind them.
4782 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4783 (defvar org-last-state)
4784 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4786 ;; Defined somewhere in this file, but used before definition.
4787 (defvar org-entities) ;; defined in org-entities.el
4788 (defvar org-struct-menu)
4789 (defvar org-org-menu)
4790 (defvar org-tbl-menu)
4792 ;;;; Define the Org-mode
4794 ;; We use a before-change function to check if a table might need
4795 ;; an update.
4796 (defvar org-table-may-need-update t
4797 "Indicates that a table might need an update.
4798 This variable is set by `org-before-change-function'.
4799 `org-table-align' sets it back to nil.")
4800 (defun org-before-change-function (beg end)
4801 "Every change indicates that a table might need an update."
4802 (setq org-table-may-need-update t))
4803 (defvar org-mode-map)
4804 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4805 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4806 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4807 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4808 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4809 (defvar org-table-buffer-is-an nil)
4811 (defvar bidi-paragraph-direction)
4812 (defvar buffer-face-mode-face)
4814 (require 'outline)
4815 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4816 (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"))
4817 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4819 ;; Other stuff we need.
4820 (require 'time-date)
4821 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4822 (require 'easymenu)
4823 (require 'overlay)
4825 (require 'org-macs)
4826 (require 'org-entities)
4827 ;; (require 'org-compat) moved higher up in the file before it is first used
4828 (require 'org-faces)
4829 (require 'org-list)
4830 (require 'org-pcomplete)
4831 (require 'org-src)
4832 (require 'org-footnote)
4834 ;; babel
4835 (require 'ob)
4836 (require 'ob-table)
4837 (require 'ob-lob)
4838 (require 'ob-ref)
4839 (require 'ob-tangle)
4840 (require 'ob-comint)
4841 (require 'ob-keys)
4843 ;;;###autoload
4844 (define-derived-mode org-mode outline-mode "Org"
4845 "Outline-based notes management and organizer, alias
4846 \"Carsten's outline-mode for keeping track of everything.\"
4848 Org-mode develops organizational tasks around a NOTES file which
4849 contains information about projects as plain text. Org-mode is
4850 implemented on top of outline-mode, which is ideal to keep the content
4851 of large files well structured. It supports ToDo items, deadlines and
4852 time stamps, which magically appear in the diary listing of the Emacs
4853 calendar. Tables are easily created with a built-in table editor.
4854 Plain text URL-like links connect to websites, emails (VM), Usenet
4855 messages (Gnus), BBDB entries, and any files related to the project.
4856 For printing and sharing of notes, an Org-mode file (or a part of it)
4857 can be exported as a structured ASCII or HTML file.
4859 The following commands are available:
4861 \\{org-mode-map}"
4863 ;; Get rid of Outline menus, they are not needed
4864 ;; Need to do this here because define-derived-mode sets up
4865 ;; the keymap so late. Still, it is a waste to call this each time
4866 ;; we switch another buffer into org-mode.
4867 (if (featurep 'xemacs)
4868 (when (boundp 'outline-mode-menu-heading)
4869 ;; Assume this is Greg's port, it uses easymenu
4870 (easy-menu-remove outline-mode-menu-heading)
4871 (easy-menu-remove outline-mode-menu-show)
4872 (easy-menu-remove outline-mode-menu-hide))
4873 (define-key org-mode-map [menu-bar headings] 'undefined)
4874 (define-key org-mode-map [menu-bar hide] 'undefined)
4875 (define-key org-mode-map [menu-bar show] 'undefined))
4877 (org-load-modules-maybe)
4878 (easy-menu-add org-org-menu)
4879 (easy-menu-add org-tbl-menu)
4880 (org-install-agenda-files-menu)
4881 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4882 (add-to-invisibility-spec '(org-cwidth))
4883 (add-to-invisibility-spec '(org-hide-block . t))
4884 (when (featurep 'xemacs)
4885 (org-set-local 'line-move-ignore-invisible t))
4886 (org-set-local 'outline-regexp org-outline-regexp)
4887 (org-set-local 'outline-level 'org-outline-level)
4888 (setq bidi-paragraph-direction 'left-to-right)
4889 (when (and org-ellipsis
4890 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4891 (fboundp 'make-glyph-code))
4892 (unless org-display-table
4893 (setq org-display-table (make-display-table)))
4894 (set-display-table-slot
4895 org-display-table 4
4896 (vconcat (mapcar
4897 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4898 org-ellipsis)))
4899 (if (stringp org-ellipsis) org-ellipsis "..."))))
4900 (setq buffer-display-table org-display-table))
4901 (org-set-regexps-and-options)
4902 (when (and org-tag-faces (not org-tags-special-faces-re))
4903 ;; tag faces set outside customize.... force initialization.
4904 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4905 ;; Calc embedded
4906 (org-set-local 'calc-embedded-open-mode "# ")
4907 (modify-syntax-entry ?@ "w")
4908 (if org-startup-truncated (setq truncate-lines t))
4909 (org-set-local 'font-lock-unfontify-region-function
4910 'org-unfontify-region)
4911 ;; Activate before-change-function
4912 (org-set-local 'org-table-may-need-update t)
4913 (org-add-hook 'before-change-functions 'org-before-change-function nil
4914 'local)
4915 ;; Check for running clock before killing a buffer
4916 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4917 ;; Indentation.
4918 (org-set-local 'indent-line-function 'org-indent-line)
4919 (org-set-local 'indent-region-function 'org-indent-region)
4920 ;; Initialize radio targets.
4921 (org-update-radio-target-regexp)
4922 ;; Filling and auto-filling.
4923 (org-setup-filling)
4924 ;; Comments.
4925 (org-setup-comments-handling)
4926 ;; Beginning/end of defun
4927 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4928 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4929 ;; Next error for sparse trees
4930 (org-set-local 'next-error-function 'org-occur-next-match)
4931 ;; Make sure dependence stuff works reliably, even for users who set it
4932 ;; too late :-(
4933 (if org-enforce-todo-dependencies
4934 (add-hook 'org-blocker-hook
4935 'org-block-todo-from-children-or-siblings-or-parent)
4936 (remove-hook 'org-blocker-hook
4937 'org-block-todo-from-children-or-siblings-or-parent))
4938 (if org-enforce-todo-checkbox-dependencies
4939 (add-hook 'org-blocker-hook
4940 'org-block-todo-from-checkboxes)
4941 (remove-hook 'org-blocker-hook
4942 'org-block-todo-from-checkboxes))
4944 ;; Align options lines
4945 (org-set-local
4946 'align-mode-rules-list
4947 '((org-in-buffer-settings
4948 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4949 (modes . '(org-mode)))))
4951 ;; Imenu
4952 (org-set-local 'imenu-create-index-function
4953 'org-imenu-get-tree)
4955 ;; Make isearch reveal context
4956 (if (or (featurep 'xemacs)
4957 (not (boundp 'outline-isearch-open-invisible-function)))
4958 ;; Emacs 21 and XEmacs make use of the hook
4959 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4960 ;; Emacs 22 deals with this through a special variable
4961 (org-set-local 'outline-isearch-open-invisible-function
4962 (lambda (&rest ignore) (org-show-context 'isearch))))
4964 ;; Turn on org-beamer-mode?
4965 (and org-startup-with-beamer-mode (org-beamer-mode))
4967 ;; Setup the pcomplete hooks
4968 (set (make-local-variable 'pcomplete-command-completion-function)
4969 'org-pcomplete-initial)
4970 (set (make-local-variable 'pcomplete-command-name-function)
4971 'org-command-at-point)
4972 (set (make-local-variable 'pcomplete-default-completion-function)
4973 'ignore)
4974 (set (make-local-variable 'pcomplete-parse-arguments-function)
4975 'org-parse-arguments)
4976 (set (make-local-variable 'pcomplete-termination-string) "")
4977 (when (>= emacs-major-version 23)
4978 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4980 ;; If empty file that did not turn on org-mode automatically, make it to.
4981 (if (and org-insert-mode-line-in-empty-file
4982 (org-called-interactively-p 'any)
4983 (= (point-min) (point-max)))
4984 (insert "# -*- mode: org -*-\n\n"))
4985 (unless org-inhibit-startup
4986 (when org-startup-align-all-tables
4987 (let ((bmp (buffer-modified-p)))
4988 (org-table-map-tables 'org-table-align 'quietly)
4989 (set-buffer-modified-p bmp)))
4990 (when org-startup-with-inline-images
4991 (org-display-inline-images))
4992 (when org-startup-indented
4993 (require 'org-indent)
4994 (org-indent-mode 1))
4995 (unless org-inhibit-startup-visibility-stuff
4996 (org-set-startup-visibility)))
4997 ;; Try to set org-hide correctly
4998 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5000 (when (fboundp 'abbrev-table-put)
5001 (abbrev-table-put org-mode-abbrev-table
5002 :parents (list text-mode-abbrev-table)))
5004 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5007 (defun org-find-invisible-foreground ()
5008 (let ((candidates (remove
5009 "unspecified-bg"
5010 (list
5011 (face-background 'default)
5012 (face-background 'org-default)
5013 (cdr (assoc 'background-color default-frame-alist))
5014 (cdr (assoc 'background-color initial-frame-alist))
5015 (cdr (assoc 'background-color window-system-default-frame-alist))
5016 (face-foreground 'org-hide)))))
5017 (car (remove nil candidates))))
5019 (defun org-current-time ()
5020 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5021 (if (> (car org-time-stamp-rounding-minutes) 1)
5022 (let ((r (car org-time-stamp-rounding-minutes))
5023 (time (decode-time)))
5024 (apply 'encode-time
5025 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5026 (nthcdr 2 time))))
5027 (current-time)))
5029 (defun org-today ()
5030 "Return today date, considering `org-extend-today-until'."
5031 (time-to-days
5032 (time-subtract (current-time)
5033 (list 0 (* 3600 org-extend-today-until) 0))))
5035 ;;;; Font-Lock stuff, including the activators
5037 (defvar org-mouse-map (make-sparse-keymap))
5038 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5039 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5040 (when org-mouse-1-follows-link
5041 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5042 (when org-tab-follows-link
5043 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5044 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5046 (require 'font-lock)
5048 (defconst org-non-link-chars "]\t\n\r<>")
5049 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5050 "shell" "elisp" "doi" "message"))
5051 (defvar org-link-types-re nil
5052 "Matches a link that has a url-like prefix like \"http:\"")
5053 (defvar org-link-re-with-space nil
5054 "Matches a link with spaces, optional angular brackets around it.")
5055 (defvar org-link-re-with-space2 nil
5056 "Matches a link with spaces, optional angular brackets around it.")
5057 (defvar org-link-re-with-space3 nil
5058 "Matches a link with spaces, only for internal part in bracket links.")
5059 (defvar org-angle-link-re nil
5060 "Matches link with angular brackets, spaces are allowed.")
5061 (defvar org-plain-link-re nil
5062 "Matches plain link, without spaces.")
5063 (defvar org-bracket-link-regexp nil
5064 "Matches a link in double brackets.")
5065 (defvar org-bracket-link-analytic-regexp nil
5066 "Regular expression used to analyze links.
5067 Here is what the match groups contain after a match:
5068 1: http:
5069 2: http
5070 3: path
5071 4: [desc]
5072 5: desc")
5073 (defvar org-bracket-link-analytic-regexp++ nil
5074 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5075 (defvar org-any-link-re nil
5076 "Regular expression matching any link.")
5078 (defcustom org-match-sexp-depth 3
5079 "Number of stacked braces for sub/superscript matching.
5080 This has to be set before loading org.el to be effective."
5081 :group 'org-export-translation ; ??????????????????????????/
5082 :type 'integer)
5084 (defun org-create-multibrace-regexp (left right n)
5085 "Create a regular expression which will match a balanced sexp.
5086 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5087 as single character strings.
5088 The regexp returned will match the entire expression including the
5089 delimiters. It will also define a single group which contains the
5090 match except for the outermost delimiters. The maximum depth of
5091 stacked delimiters is N. Escaping delimiters is not possible."
5092 (let* ((nothing (concat "[^" left right "]*?"))
5093 (or "\\|")
5094 (re nothing)
5095 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5096 (while (> n 1)
5097 (setq n (1- n)
5098 re (concat re or next)
5099 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5100 (concat left "\\(" re "\\)" right)))
5102 (defvar org-match-substring-regexp
5103 (concat
5104 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5105 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5106 "\\|"
5107 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5108 "\\|"
5109 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5110 "The regular expression matching a sub- or superscript.")
5112 (defvar org-match-substring-with-braces-regexp
5113 (concat
5114 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5115 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5116 "\\)")
5117 "The regular expression matching a sub- or superscript, forcing braces.")
5119 (defun org-make-link-regexps ()
5120 "Update the link regular expressions.
5121 This should be called after the variable `org-link-types' has changed."
5122 (setq org-link-types-re
5123 (concat
5124 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5125 org-link-re-with-space
5126 (concat
5127 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5128 "\\([^" org-non-link-chars " ]"
5129 "[^" org-non-link-chars "]*"
5130 "[^" org-non-link-chars " ]\\)>?")
5131 org-link-re-with-space2
5132 (concat
5133 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5134 "\\([^" org-non-link-chars " ]"
5135 "[^\t\n\r]*"
5136 "[^" org-non-link-chars " ]\\)>?")
5137 org-link-re-with-space3
5138 (concat
5139 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5140 "\\([^" org-non-link-chars " ]"
5141 "[^\t\n\r]*\\)")
5142 org-angle-link-re
5143 (concat
5144 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5145 "\\([^" org-non-link-chars " ]"
5146 "[^" org-non-link-chars "]*"
5147 "\\)>")
5148 org-plain-link-re
5149 (concat
5150 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5151 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5152 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5153 org-bracket-link-regexp
5154 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5155 org-bracket-link-analytic-regexp
5156 (concat
5157 "\\[\\["
5158 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5159 "\\([^]]+\\)"
5160 "\\]"
5161 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5162 "\\]")
5163 org-bracket-link-analytic-regexp++
5164 (concat
5165 "\\[\\["
5166 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5167 "\\([^]]+\\)"
5168 "\\]"
5169 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5170 "\\]")
5171 org-any-link-re
5172 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5173 org-angle-link-re "\\)\\|\\("
5174 org-plain-link-re "\\)")))
5176 (org-make-link-regexps)
5178 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5179 "Regular expression for fast time stamp matching.")
5180 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5181 "Regular expression for fast time stamp matching.")
5182 (defconst org-ts-regexp0
5183 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5184 "Regular expression matching time strings for analysis.
5185 This one does not require the space after the date, so it can be used
5186 on a string that terminates immediately after the date.")
5187 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5188 "Regular expression matching time strings for analysis.")
5189 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5190 "Regular expression matching time stamps, with groups.")
5191 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5192 "Regular expression matching time stamps (also [..]), with groups.")
5193 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5194 "Regular expression matching a time stamp range.")
5195 (defconst org-tr-regexp-both
5196 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5197 "Regular expression matching a time stamp range.")
5198 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5199 org-ts-regexp "\\)?")
5200 "Regular expression matching a time stamp or time stamp range.")
5201 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5202 org-ts-regexp-both "\\)?")
5203 "Regular expression matching a time stamp or time stamp range.
5204 The time stamps may be either active or inactive.")
5206 (defvar org-emph-face nil)
5208 (defun org-do-emphasis-faces (limit)
5209 "Run through the buffer and add overlays to emphasized strings."
5210 (let (rtn a)
5211 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5212 (if (not (= (char-after (match-beginning 3))
5213 (char-after (match-beginning 4))))
5214 (progn
5215 (setq rtn t)
5216 (setq a (assoc (match-string 3) org-emphasis-alist))
5217 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5218 'face
5219 (nth 1 a))
5220 (and (nth 4 a)
5221 (org-remove-flyspell-overlays-in
5222 (match-beginning 0) (match-end 0)))
5223 (add-text-properties (match-beginning 2) (match-end 2)
5224 '(font-lock-multiline t org-emphasis t))
5225 (when org-hide-emphasis-markers
5226 (add-text-properties (match-end 4) (match-beginning 5)
5227 '(invisible org-link))
5228 (add-text-properties (match-beginning 3) (match-end 3)
5229 '(invisible org-link)))))
5230 (backward-char 1))
5231 rtn))
5233 (defun org-emphasize (&optional char)
5234 "Insert or change an emphasis, i.e. a font like bold or italic.
5235 If there is an active region, change that region to a new emphasis.
5236 If there is no region, just insert the marker characters and position
5237 the cursor between them.
5238 CHAR should be either the marker character, or the first character of the
5239 HTML tag associated with that emphasis. If CHAR is a space, the means
5240 to remove the emphasis of the selected region.
5241 If char is not given (for example in an interactive call) it
5242 will be prompted for."
5243 (interactive)
5244 (let ((eal org-emphasis-alist) e det
5245 (erc org-emphasis-regexp-components)
5246 (prompt "")
5247 (string "") beg end move tag c s)
5248 (if (org-region-active-p)
5249 (setq beg (region-beginning) end (region-end)
5250 string (buffer-substring beg end))
5251 (setq move t))
5253 (while (setq e (pop eal))
5254 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5255 c (aref tag 0))
5256 (push (cons c (string-to-char (car e))) det)
5257 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5258 (substring tag 1)))))
5259 (setq det (nreverse det))
5260 (unless char
5261 (message "%s" (concat "Emphasis marker or tag:" prompt))
5262 (setq char (read-char-exclusive)))
5263 (setq char (or (cdr (assoc char det)) char))
5264 (if (equal char ?\ )
5265 (setq s "" move nil)
5266 (unless (assoc (char-to-string char) org-emphasis-alist)
5267 (error "No such emphasis marker: \"%c\"" char))
5268 (setq s (char-to-string char)))
5269 (while (and (> (length string) 1)
5270 (equal (substring string 0 1) (substring string -1))
5271 (assoc (substring string 0 1) org-emphasis-alist))
5272 (setq string (substring string 1 -1)))
5273 (setq string (concat s string s))
5274 (if beg (delete-region beg end))
5275 (unless (or (bolp)
5276 (string-match (concat "[" (nth 0 erc) "\n]")
5277 (char-to-string (char-before (point)))))
5278 (insert " "))
5279 (unless (or (eobp)
5280 (string-match (concat "[" (nth 1 erc) "\n]")
5281 (char-to-string (char-after (point)))))
5282 (insert " ") (backward-char 1))
5283 (insert string)
5284 (and move (backward-char 1))))
5286 (defconst org-nonsticky-props
5287 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5289 (defsubst org-rear-nonsticky-at (pos)
5290 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5292 (defun org-activate-plain-links (limit)
5293 "Run through the buffer and add overlays to links."
5294 (catch 'exit
5295 (let (f)
5296 (when (re-search-forward (concat org-plain-link-re) limit t)
5297 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5298 (setq f (get-text-property (match-beginning 0) 'face))
5299 (if (or (eq f 'org-tag)
5300 (and (listp f) (memq 'org-tag f)))
5302 (add-text-properties (match-beginning 0) (match-end 0)
5303 (list 'mouse-face 'highlight
5304 'face 'org-link
5305 'keymap org-mouse-map))
5306 (org-rear-nonsticky-at (match-end 0)))
5307 t))))
5309 (defun org-activate-code (limit)
5310 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5311 (progn
5312 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5313 (remove-text-properties (match-beginning 0) (match-end 0)
5314 '(display t invisible t intangible t))
5315 t)))
5317 (defcustom org-src-fontify-natively nil
5318 "When non-nil, fontify code in code blocks."
5319 :type 'boolean
5320 :version "24.1"
5321 :group 'org-appearance
5322 :group 'org-babel)
5324 (defcustom org-allow-promoting-top-level-subtree nil
5325 "When non-nil, allow promoting a top level subtree.
5326 The leading star of the top level headline will be replaced
5327 by a #."
5328 :type 'boolean
5329 :version "24.1"
5330 :group 'org-appearance)
5332 (defun org-fontify-meta-lines-and-blocks (limit)
5333 (condition-case nil
5334 (org-fontify-meta-lines-and-blocks-1 limit)
5335 (error (message "org-mode fontification error"))))
5337 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5338 "Fontify #+ lines and blocks, in the correct ways."
5339 (let ((case-fold-search t))
5340 (if (re-search-forward
5341 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5342 limit t)
5343 (let ((beg (match-beginning 0))
5344 (block-start (match-end 0))
5345 (block-end nil)
5346 (lang (match-string 7))
5347 (beg1 (line-beginning-position 2))
5348 (dc1 (downcase (match-string 2)))
5349 (dc3 (downcase (match-string 3)))
5350 end end1 quoting block-type ovl)
5351 (cond
5352 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5353 ;; a single line of backend-specific content
5354 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5355 (remove-text-properties (match-beginning 0) (match-end 0)
5356 '(display t invisible t intangible t))
5357 (add-text-properties (match-beginning 1) (match-end 3)
5358 '(font-lock-fontified t face org-meta-line))
5359 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5360 '(font-lock-fontified t face org-block))
5361 ; for backend-specific code
5363 ((and (match-end 4) (equal dc3 "+begin"))
5364 ;; Truly a block
5365 (setq block-type (downcase (match-string 5))
5366 quoting (member block-type org-protecting-blocks))
5367 (when (re-search-forward
5368 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5369 nil t) ;; on purpose, we look further than LIMIT
5370 (setq end (min (point-max) (match-end 0))
5371 end1 (min (point-max) (1- (match-beginning 0))))
5372 (setq block-end (match-beginning 0))
5373 (when quoting
5374 (remove-text-properties beg end
5375 '(display t invisible t intangible t)))
5376 (add-text-properties
5377 beg end
5378 '(font-lock-fontified t font-lock-multiline t))
5379 (add-text-properties beg beg1 '(face org-meta-line))
5380 (add-text-properties end1 (min (point-max) (1+ end))
5381 '(face org-meta-line)) ; for end_src
5382 (cond
5383 ((and lang (not (string= lang "")) org-src-fontify-natively)
5384 (org-src-font-lock-fontify-block lang block-start block-end)
5385 ;; remove old background overlays
5386 (mapc (lambda (ov)
5387 (if (eq (overlay-get ov 'face) 'org-block-background)
5388 (delete-overlay ov)))
5389 (overlays-at (/ (+ beg1 block-end) 2)))
5390 ;; add a background overlay
5391 (setq ovl (make-overlay beg1 block-end))
5392 (overlay-put ovl 'face 'org-block-background)
5393 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5394 (quoting
5395 (add-text-properties beg1 (min (point-max) (1+ end1))
5396 '(face org-block))) ; end of source block
5397 ((not org-fontify-quote-and-verse-blocks))
5398 ((string= block-type "quote")
5399 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5400 ((string= block-type "verse")
5401 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5402 (add-text-properties beg beg1 '(face org-block-begin-line))
5403 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5404 '(face org-block-end-line))
5406 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5407 (add-text-properties
5408 beg (match-end 3)
5409 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5410 '(font-lock-fontified t invisible t)
5411 '(font-lock-fontified t face org-document-info-keyword)))
5412 (add-text-properties
5413 (match-beginning 6) (match-end 6)
5414 (if (string-equal dc1 "+title:")
5415 '(font-lock-fontified t face org-document-title)
5416 '(font-lock-fontified t face org-document-info))))
5417 ((or (equal dc1 "+results")
5418 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5419 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5420 "+call:" "+header:" "+headers:" "+name:"))
5421 (and (match-end 4) (equal dc3 "+attr")))
5422 (add-text-properties
5423 beg (match-end 0)
5424 '(font-lock-fontified t face org-meta-line))
5426 ((member dc3 '(" " ""))
5427 (add-text-properties
5428 beg (match-end 0)
5429 '(font-lock-fontified t face font-lock-comment-face)))
5430 ((not (member (char-after beg) '(?\ ?\t)))
5431 ;; just any other in-buffer setting, but not indented
5432 (add-text-properties
5433 beg (match-end 0)
5434 '(font-lock-fontified t face org-meta-line))
5436 (t nil))))))
5438 (defun org-activate-angle-links (limit)
5439 "Run through the buffer and add overlays to links."
5440 (if (re-search-forward org-angle-link-re limit t)
5441 (progn
5442 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5443 (add-text-properties (match-beginning 0) (match-end 0)
5444 (list 'mouse-face 'highlight
5445 'keymap org-mouse-map))
5446 (org-rear-nonsticky-at (match-end 0))
5447 t)))
5449 (defun org-activate-footnote-links (limit)
5450 "Run through the buffer and add overlays to footnotes."
5451 (let ((fn (org-footnote-next-reference-or-definition limit)))
5452 (when fn
5453 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5454 (org-remove-flyspell-overlays-in beg end)
5455 (add-text-properties beg end
5456 (list 'mouse-face 'highlight
5457 'keymap org-mouse-map
5458 'help-echo
5459 (if (= (point-at-bol) beg)
5460 "Footnote definition"
5461 "Footnote reference")
5462 'font-lock-fontified t
5463 'font-lock-multiline t
5464 'face 'org-footnote))))))
5466 (defun org-activate-bracket-links (limit)
5467 "Run through the buffer and add overlays to bracketed links."
5468 (if (re-search-forward org-bracket-link-regexp limit t)
5469 (let* ((help (concat "LINK: "
5470 (org-match-string-no-properties 1)))
5471 ;; FIXME: above we should remove the escapes.
5472 ;; but that requires another match, protecting match data,
5473 ;; a lot of overhead for font-lock.
5474 (ip (org-maybe-intangible
5475 (list 'invisible 'org-link
5476 'keymap org-mouse-map 'mouse-face 'highlight
5477 'font-lock-multiline t 'help-echo help)))
5478 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5479 'font-lock-multiline t 'help-echo help)))
5480 ;; We need to remove the invisible property here. Table narrowing
5481 ;; may have made some of this invisible.
5482 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5483 (remove-text-properties (match-beginning 0) (match-end 0)
5484 '(invisible nil))
5485 (if (match-end 3)
5486 (progn
5487 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5488 (org-rear-nonsticky-at (match-beginning 3))
5489 (add-text-properties (match-beginning 3) (match-end 3) vp)
5490 (org-rear-nonsticky-at (match-end 3))
5491 (add-text-properties (match-end 3) (match-end 0) ip)
5492 (org-rear-nonsticky-at (match-end 0)))
5493 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5494 (org-rear-nonsticky-at (match-beginning 1))
5495 (add-text-properties (match-beginning 1) (match-end 1) vp)
5496 (org-rear-nonsticky-at (match-end 1))
5497 (add-text-properties (match-end 1) (match-end 0) ip)
5498 (org-rear-nonsticky-at (match-end 0)))
5499 t)))
5501 (defun org-activate-dates (limit)
5502 "Run through the buffer and add overlays to dates."
5503 (if (re-search-forward org-tsr-regexp-both limit t)
5504 (progn
5505 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5506 (add-text-properties (match-beginning 0) (match-end 0)
5507 (list 'mouse-face 'highlight
5508 'keymap org-mouse-map))
5509 (org-rear-nonsticky-at (match-end 0))
5510 (when org-display-custom-times
5511 (if (match-end 3)
5512 (org-display-custom-time (match-beginning 3) (match-end 3)))
5513 (org-display-custom-time (match-beginning 1) (match-end 1)))
5514 t)))
5516 (defvar org-target-link-regexp nil
5517 "Regular expression matching radio targets in plain text.")
5518 (make-variable-buffer-local 'org-target-link-regexp)
5519 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5520 "Regular expression matching a link target.")
5521 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5522 "Regular expression matching a radio target.")
5523 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5524 "Regular expression matching any target.")
5526 (defun org-activate-target-links (limit)
5527 "Run through the buffer and add overlays to target matches."
5528 (when org-target-link-regexp
5529 (let ((case-fold-search t))
5530 (if (re-search-forward org-target-link-regexp limit t)
5531 (progn
5532 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5533 (add-text-properties (match-beginning 0) (match-end 0)
5534 (list 'mouse-face 'highlight
5535 'keymap org-mouse-map
5536 'help-echo "Radio target link"
5537 'org-linked-text t))
5538 (org-rear-nonsticky-at (match-end 0))
5539 t)))))
5541 (defun org-update-radio-target-regexp ()
5542 "Find all radio targets in this file and update the regular expression."
5543 (interactive)
5544 (when (memq 'radio org-activate-links)
5545 (setq org-target-link-regexp
5546 (org-make-target-link-regexp (org-all-targets 'radio)))
5547 (org-restart-font-lock)))
5549 (defun org-hide-wide-columns (limit)
5550 (let (s e)
5551 (setq s (text-property-any (point) (or limit (point-max))
5552 'org-cwidth t))
5553 (when s
5554 (setq e (next-single-property-change s 'org-cwidth))
5555 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5556 (goto-char e)
5557 t)))
5559 (defvar org-latex-and-specials-regexp nil
5560 "Regular expression for highlighting export special stuff.")
5561 (defvar org-match-substring-regexp)
5562 (defvar org-match-substring-with-braces-regexp)
5564 ;; This should be with the exporter code, but we also use if for font-locking
5565 (defconst org-export-html-special-string-regexps
5566 '(("\\\\-" . "&shy;")
5567 ("---\\([^-]\\)" . "&mdash;\\1")
5568 ("--\\([^-]\\)" . "&ndash;\\1")
5569 ("\\.\\.\\." . "&hellip;"))
5570 "Regular expressions for special string conversion.")
5573 (defun org-compute-latex-and-specials-regexp ()
5574 "Compute regular expression for stuff treated specially by exporters."
5575 (if (not org-highlight-latex-fragments-and-specials)
5576 (org-set-local 'org-latex-and-specials-regexp nil)
5577 (require 'org-exp)
5578 (let*
5579 ((matchers (plist-get org-format-latex-options :matchers))
5580 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5581 org-latex-regexps)))
5582 (org-export-allow-BIND nil)
5583 (options (org-combine-plists (org-default-export-plist)
5584 (org-infile-export-plist)))
5585 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5586 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5587 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5588 (org-export-html-expand (plist-get options :expand-quoted-html))
5589 (org-export-with-special-strings (plist-get options :special-strings))
5590 (re-sub
5591 (cond
5592 ((equal org-export-with-sub-superscripts '{})
5593 (list org-match-substring-with-braces-regexp))
5594 (org-export-with-sub-superscripts
5595 (list org-match-substring-regexp))))
5596 (re-latex
5597 (if org-export-with-LaTeX-fragments
5598 (mapcar (lambda (x) (nth 1 x)) latexs)))
5599 (re-macros
5600 (if org-export-with-TeX-macros
5601 (list (concat "\\\\"
5602 (regexp-opt
5603 (append
5605 (delq nil
5606 (mapcar 'car-safe
5607 (append org-entities-user
5608 org-entities)))
5609 (if (boundp 'org-latex-entities)
5610 (mapcar (lambda (x)
5611 (or (car-safe x) x))
5612 org-latex-entities)
5613 nil))
5614 'words))) ; FIXME
5616 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5617 (re-special (if org-export-with-special-strings
5618 (mapcar (lambda (x) (car x))
5619 org-export-html-special-string-regexps)))
5620 (re-rest
5621 (delq nil
5622 (list
5623 (if org-export-html-expand "@<[^>\n]+>")
5624 ))))
5625 (org-set-local
5626 'org-latex-and-specials-regexp
5627 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5628 re-rest) "\\|")))))
5630 (defun org-do-latex-and-special-faces (limit)
5631 "Run through the buffer and add overlays to links."
5632 (when org-latex-and-specials-regexp
5633 (let (rtn d)
5634 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5635 limit t))
5636 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5637 'face))
5638 '(org-code org-verbatim underline)))
5639 (progn
5640 (setq rtn t
5641 d (cond ((member (char-after (1+ (match-beginning 0)))
5642 '(?_ ?^)) 1)
5643 (t 0)))
5644 (font-lock-prepend-text-property
5645 (+ d (match-beginning 0)) (match-end 0)
5646 'face 'org-latex-and-export-specials)
5647 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5648 '(font-lock-multiline t)))))
5649 rtn)))
5651 (defun org-restart-font-lock ()
5652 "Restart `font-lock-mode', to force refontification."
5653 (when (and (boundp 'font-lock-mode) font-lock-mode)
5654 (font-lock-mode -1)
5655 (font-lock-mode 1)))
5657 (defun org-all-targets (&optional radio)
5658 "Return a list of all targets in this file.
5659 With optional argument RADIO, only find radio targets."
5660 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5661 rtn)
5662 (save-excursion
5663 (goto-char (point-min))
5664 (while (re-search-forward re nil t)
5665 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5666 rtn)))
5668 (defun org-make-target-link-regexp (targets)
5669 "Make regular expression matching all strings in TARGETS.
5670 The regular expression finds the targets also if there is a line break
5671 between words."
5672 (and targets
5673 (concat
5674 "\\<\\("
5675 (mapconcat
5676 (lambda (x)
5677 (setq x (regexp-quote x))
5678 (while (string-match " +" x)
5679 (setq x (replace-match "\\s-+" t t x)))
5681 targets
5682 "\\|")
5683 "\\)\\>")))
5685 (defun org-activate-tags (limit)
5686 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5687 (progn
5688 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5689 (add-text-properties (match-beginning 1) (match-end 1)
5690 (list 'mouse-face 'highlight
5691 'keymap org-mouse-map))
5692 (org-rear-nonsticky-at (match-end 1))
5693 t)))
5695 (defun org-outline-level ()
5696 "Compute the outline level of the heading at point.
5697 This function assumes that the cursor is at the beginning of a line matched
5698 by `outline-regexp'. Otherwise it returns garbage.
5699 If this is called at a normal headline, the level is the number of stars.
5700 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5701 (save-excursion
5702 (looking-at org-outline-regexp)
5703 (1- (- (match-end 0) (match-beginning 0)))))
5705 (defvar org-font-lock-keywords nil)
5707 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5708 "Regular expression matching a property line.")
5710 (defvar org-font-lock-hook nil
5711 "Functions to be called for special font lock stuff.")
5713 (defvar org-font-lock-set-keywords-hook nil
5714 "Functions that can manipulate `org-font-lock-extra-keywords'.
5715 This is called after `org-font-lock-extra-keywords' is defined, but before
5716 it is installed to be used by font lock. This can be useful if something
5717 needs to be inserted at a specific position in the font-lock sequence.")
5719 (defun org-font-lock-hook (limit)
5720 "Run `org-font-lock-hook' within LIMIT."
5721 (run-hook-with-args 'org-font-lock-hook limit))
5723 (defun org-set-font-lock-defaults ()
5724 "Set font lock defaults for the current buffer."
5725 (let* ((em org-fontify-emphasized-text)
5726 (lk org-activate-links)
5727 (org-font-lock-extra-keywords
5728 (list
5729 ;; Call the hook
5730 '(org-font-lock-hook)
5731 ;; Headlines
5732 `(,(if org-fontify-whole-heading-line
5733 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5734 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5735 (1 (org-get-level-face 1))
5736 (2 (org-get-level-face 2))
5737 (3 (org-get-level-face 3)))
5738 ;; Table lines
5739 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5740 (1 'org-table t))
5741 ;; Table internals
5742 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5743 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5744 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5745 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5746 ;; Drawers
5747 (list org-drawer-regexp '(0 'org-special-keyword t))
5748 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5749 ;; Properties
5750 (list org-property-re
5751 '(1 'org-special-keyword t)
5752 '(3 'org-property-value t))
5753 ;; Links
5754 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5755 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5756 (if (memq 'plain lk) '(org-activate-plain-links))
5757 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5758 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5759 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5760 (if (memq 'footnote lk) '(org-activate-footnote-links))
5761 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5762 '(org-hide-wide-columns (0 nil append))
5763 ;; TODO keyword
5764 (list (format org-heading-keyword-regexp-format
5765 org-todo-regexp)
5766 '(2 (org-get-todo-face 2) t))
5767 ;; DONE
5768 (if org-fontify-done-headline
5769 (list (format org-heading-keyword-regexp-format
5770 (concat
5771 "\\(?:"
5772 (mapconcat 'regexp-quote org-done-keywords "\\|")
5773 "\\)"))
5774 '(2 'org-headline-done t))
5775 nil)
5776 ;; Priorities
5777 '(org-font-lock-add-priority-faces)
5778 ;; Tags
5779 '(org-font-lock-add-tag-faces)
5780 ;; Special keywords
5781 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5782 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5783 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5784 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5785 ;; Emphasis
5786 (if em
5787 (if (featurep 'xemacs)
5788 '(org-do-emphasis-faces (0 nil append))
5789 '(org-do-emphasis-faces)))
5790 ;; Checkboxes
5791 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5792 1 'org-checkbox prepend)
5793 (if (cdr (assq 'checkbox org-list-automatic-rules))
5794 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5795 (0 (org-get-checkbox-statistics-face) t)))
5796 ;; Description list items
5797 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5798 1 'org-list-dt prepend)
5799 ;; ARCHIVEd headings
5800 (list (concat
5801 org-outline-regexp-bol
5802 "\\(.*:" org-archive-tag ":.*\\)")
5803 '(1 'org-archived prepend))
5804 ;; Specials
5805 '(org-do-latex-and-special-faces)
5806 '(org-fontify-entities)
5807 '(org-raise-scripts)
5808 ;; Code
5809 '(org-activate-code (1 'org-code t))
5810 ;; COMMENT
5811 (list (format org-heading-keyword-regexp-format
5812 (concat "\\("
5813 org-comment-string "\\|" org-quote-string
5814 "\\)"))
5815 '(2 'org-special-keyword t))
5816 ;; Blocks and meta lines
5817 '(org-fontify-meta-lines-and-blocks)
5819 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5820 (run-hooks 'org-font-lock-set-keywords-hook)
5821 ;; Now set the full font-lock-keywords
5822 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5823 (org-set-local 'font-lock-defaults
5824 '(org-font-lock-keywords t nil nil backward-paragraph))
5825 (kill-local-variable 'font-lock-keywords) nil))
5827 (defun org-toggle-pretty-entities ()
5828 "Toggle the composition display of entities as UTF8 characters."
5829 (interactive)
5830 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5831 (org-restart-font-lock)
5832 (if org-pretty-entities
5833 (message "Entities are displayed as UTF8 characters")
5834 (save-restriction
5835 (widen)
5836 (org-decompose-region (point-min) (point-max))
5837 (message "Entities are displayed plain"))))
5839 (defvar org-custom-properties-overlays nil
5840 "List of overlays used for custom properties.")
5841 (make-variable-buffer-local 'org-custom-properties-overlays)
5843 (defun org-toggle-custom-properties-visibility ()
5844 "Display or hide properties in `org-custom-properties'."
5845 (interactive)
5846 (if org-custom-properties-overlays
5847 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5848 (setq org-custom-properties-overlays nil))
5849 (unless (not org-custom-properties)
5850 (save-excursion
5851 (save-restriction
5852 (widen)
5853 (goto-char (point-min))
5854 (while (re-search-forward org-property-re nil t)
5855 (mapc (lambda(p)
5856 (when (equal p (substring (match-string 1) 1 -1))
5857 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5858 (overlay-put o 'invisible t)
5859 (overlay-put o 'org-custom-property t)
5860 (push o org-custom-properties-overlays))))
5861 org-custom-properties)))))))
5863 (defun org-fontify-entities (limit)
5864 "Find an entity to fontify."
5865 (let (ee)
5866 (when org-pretty-entities
5867 (catch 'match
5868 (while (re-search-forward
5869 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5870 limit t)
5871 (if (and (not (org-in-indented-comment-line))
5872 (setq ee (org-entity-get (match-string 1)))
5873 (= (length (nth 6 ee)) 1))
5874 (let*
5875 ((end (if (equal (match-string 2) "{}")
5876 (match-end 2)
5877 (match-end 1))))
5878 (add-text-properties
5879 (match-beginning 0) end
5880 (list 'font-lock-fontified t))
5881 (compose-region (match-beginning 0) end
5882 (nth 6 ee) nil)
5883 (backward-char 1)
5884 (throw 'match t))))
5885 nil))))
5887 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5888 "Fontify string S like in Org-mode."
5889 (with-temp-buffer
5890 (insert s)
5891 (let ((org-odd-levels-only odd-levels))
5892 (org-mode)
5893 (font-lock-fontify-buffer)
5894 (buffer-string))))
5896 (defvar org-m nil)
5897 (defvar org-l nil)
5898 (defvar org-f nil)
5899 (defun org-get-level-face (n)
5900 "Get the right face for match N in font-lock matching of headlines."
5901 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5902 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5903 (if org-cycle-level-faces
5904 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5905 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5906 (cond
5907 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5908 ((eq n 2) org-f)
5909 (t (if org-level-color-stars-only nil org-f))))
5912 (defun org-get-todo-face (kwd)
5913 "Get the right face for a TODO keyword KWD.
5914 If KWD is a number, get the corresponding match group."
5915 (if (numberp kwd) (setq kwd (match-string kwd)))
5916 (or (org-face-from-face-or-color
5917 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5918 (and (member kwd org-done-keywords) 'org-done)
5919 'org-todo))
5921 (defun org-face-from-face-or-color (context inherit face-or-color)
5922 "Create a face list that inherits INHERIT, but sets the foreground color.
5923 When FACE-OR-COLOR is not a string, just return it."
5924 (if (stringp face-or-color)
5925 (list :inherit inherit
5926 (cdr (assoc context org-faces-easy-properties))
5927 face-or-color)
5928 face-or-color))
5930 (defun org-font-lock-add-tag-faces (limit)
5931 "Add the special tag faces."
5932 (when (and org-tag-faces org-tags-special-faces-re)
5933 (while (re-search-forward org-tags-special-faces-re limit t)
5934 (add-text-properties (match-beginning 1) (match-end 1)
5935 (list 'face (org-get-tag-face 1)
5936 'font-lock-fontified t))
5937 (backward-char 1))))
5939 (defun org-font-lock-add-priority-faces (limit)
5940 "Add the special priority faces."
5941 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5942 (when (save-match-data (org-at-heading-p))
5943 (add-text-properties
5944 (match-beginning 0) (match-end 0)
5945 (list 'face (or (org-face-from-face-or-color
5946 'priority 'org-special-keyword
5947 (cdr (assoc (char-after (match-beginning 1))
5948 org-priority-faces)))
5949 'org-special-keyword)
5950 'font-lock-fontified t)))))
5952 (defun org-get-tag-face (kwd)
5953 "Get the right face for a TODO keyword KWD.
5954 If KWD is a number, get the corresponding match group."
5955 (if (numberp kwd) (setq kwd (match-string kwd)))
5956 (or (org-face-from-face-or-color
5957 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5958 'org-tag))
5960 (defun org-unfontify-region (beg end &optional maybe_loudly)
5961 "Remove fontification and activation overlays from links."
5962 (font-lock-default-unfontify-region beg end)
5963 (let* ((buffer-undo-list t)
5964 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5965 (inhibit-modification-hooks t)
5966 deactivate-mark buffer-file-name buffer-file-truename)
5967 (org-decompose-region beg end)
5968 (remove-text-properties beg end
5969 '(mouse-face t keymap t org-linked-text t
5970 invisible t intangible t
5971 org-no-flyspell t org-emphasis t))
5972 (org-remove-font-lock-display-properties beg end)))
5974 (defconst org-script-display '(((raise -0.3) (height 0.7))
5975 ((raise 0.3) (height 0.7))
5976 ((raise -0.5))
5977 ((raise 0.5)))
5978 "Display properties for showing superscripts and subscripts.")
5980 (defun org-remove-font-lock-display-properties (beg end)
5981 "Remove specific display properties that have been added by font lock.
5982 The will remove the raise properties that are used to show superscripts
5983 and subscripts."
5984 (let (next prop)
5985 (while (< beg end)
5986 (setq next (next-single-property-change beg 'display nil end)
5987 prop (get-text-property beg 'display))
5988 (if (member prop org-script-display)
5989 (put-text-property beg next 'display nil))
5990 (setq beg next))))
5992 (defun org-raise-scripts (limit)
5993 "Add raise properties to sub/superscripts."
5994 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5995 (if (re-search-forward
5996 (if (eq org-use-sub-superscripts t)
5997 org-match-substring-regexp
5998 org-match-substring-with-braces-regexp)
5999 limit t)
6000 (let* ((pos (point)) table-p comment-p
6001 (mpos (match-beginning 3))
6002 (emph-p (get-text-property mpos 'org-emphasis))
6003 (link-p (get-text-property mpos 'mouse-face))
6004 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6005 (goto-char (point-at-bol))
6006 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6007 comment-p (org-looking-at-p "[ \t]*#"))
6008 (goto-char pos)
6009 ;; FIXME: Should we go back one character here, for a_b^c
6010 ;; (goto-char (1- pos)) ;????????????????????
6011 (if (or comment-p emph-p link-p keyw-p)
6013 (put-text-property (match-beginning 3) (match-end 0)
6014 'display
6015 (if (equal (char-after (match-beginning 2)) ?^)
6016 (nth (if table-p 3 1) org-script-display)
6017 (nth (if table-p 2 0) org-script-display)))
6018 (add-text-properties (match-beginning 2) (match-end 2)
6019 (list 'invisible t
6020 'org-dwidth t 'org-dwidth-n 1))
6021 (if (and (eq (char-after (match-beginning 3)) ?{)
6022 (eq (char-before (match-end 3)) ?}))
6023 (progn
6024 (add-text-properties
6025 (match-beginning 3) (1+ (match-beginning 3))
6026 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6027 (add-text-properties
6028 (1- (match-end 3)) (match-end 3)
6029 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6030 t)))))
6032 ;;;; Visibility cycling, including org-goto and indirect buffer
6034 ;;; Cycling
6036 (defvar org-cycle-global-status nil)
6037 (make-variable-buffer-local 'org-cycle-global-status)
6038 (defvar org-cycle-subtree-status nil)
6039 (make-variable-buffer-local 'org-cycle-subtree-status)
6041 (defvar org-inlinetask-min-level)
6043 ;;;###autoload
6044 (defun org-cycle (&optional arg)
6045 "TAB-action and visibility cycling for Org-mode.
6047 This is the command invoked in Org-mode by the TAB key. Its main purpose
6048 is outline visibility cycling, but it also invokes other actions
6049 in special contexts.
6051 - When this function is called with a prefix argument, rotate the entire
6052 buffer through 3 states (global cycling)
6053 1. OVERVIEW: Show only top-level headlines.
6054 2. CONTENTS: Show all headlines of all levels, but no body text.
6055 3. SHOW ALL: Show everything.
6056 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6057 determined by the variable `org-startup-folded', and by any VISIBILITY
6058 properties in the buffer.
6059 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6060 including any drawers.
6062 - When inside a table, re-align the table and move to the next field.
6064 - When point is at the beginning of a headline, rotate the subtree started
6065 by this line through 3 different states (local cycling)
6066 1. FOLDED: Only the main headline is shown.
6067 2. CHILDREN: The main headline and the direct children are shown.
6068 From this state, you can move to one of the children
6069 and zoom in further.
6070 3. SUBTREE: Show the entire subtree, including body text.
6071 If there is no subtree, switch directly from CHILDREN to FOLDED.
6073 - When point is at the beginning of an empty headline and the variable
6074 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6075 of the headline by demoting and promoting it to likely levels. This
6076 speeds up creation document structure by pressing TAB once or several
6077 times right after creating a new headline.
6079 - When there is a numeric prefix, go up to a heading with level ARG, do
6080 a `show-subtree' and return to the previous cursor position. If ARG
6081 is negative, go up that many levels.
6083 - When point is not at the beginning of a headline, execute the global
6084 binding for TAB, which is re-indenting the line. See the option
6085 `org-cycle-emulate-tab' for details.
6087 - Special case: if point is at the beginning of the buffer and there is
6088 no headline in line 1, this function will act as if called with prefix arg
6089 (C-u TAB, same as S-TAB) also when called without prefix arg.
6090 But only if also the variable `org-cycle-global-at-bob' is t."
6091 (interactive "P")
6092 (org-load-modules-maybe)
6093 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6094 (and org-cycle-level-after-item/entry-creation
6095 (or (org-cycle-level)
6096 (org-cycle-item-indentation))))
6097 (let* ((limit-level
6098 (or org-cycle-max-level
6099 (and (boundp 'org-inlinetask-min-level)
6100 org-inlinetask-min-level
6101 (1- org-inlinetask-min-level))))
6102 (nstars (and limit-level
6103 (if org-odd-levels-only
6104 (and limit-level (1- (* limit-level 2)))
6105 limit-level)))
6106 (org-outline-regexp
6107 (if (not (derived-mode-p 'org-mode))
6108 outline-regexp
6109 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6110 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6111 (not (looking-at org-outline-regexp))))
6112 (org-cycle-hook
6113 (if bob-special
6114 (delq 'org-optimize-window-after-visibility-change
6115 (copy-sequence org-cycle-hook))
6116 org-cycle-hook))
6117 (pos (point)))
6119 (if (or bob-special (equal arg '(4)))
6120 ;; special case: use global cycling
6121 (setq arg t))
6123 (cond
6125 ((equal arg '(16))
6126 (setq last-command 'dummy)
6127 (org-set-startup-visibility)
6128 (message "Startup visibility, plus VISIBILITY properties"))
6130 ((equal arg '(64))
6131 (show-all)
6132 (message "Entire buffer visible, including drawers"))
6134 ;; Table: enter it or move to the next field.
6135 ((org-at-table-p 'any)
6136 (if (org-at-table.el-p)
6137 (message "Use C-c ' to edit table.el tables")
6138 (if arg (org-table-edit-field t)
6139 (org-table-justify-field-maybe)
6140 (call-interactively 'org-table-next-field))))
6142 ((run-hook-with-args-until-success
6143 'org-tab-after-check-for-table-hook))
6145 ;; Global cycling: delegate to `org-cycle-internal-global'.
6146 ((eq arg t) (org-cycle-internal-global))
6148 ;; Drawers: delegate to `org-flag-drawer'.
6149 ((and org-drawers org-drawer-regexp
6150 (save-excursion
6151 (beginning-of-line 1)
6152 (looking-at org-drawer-regexp)))
6153 (org-flag-drawer ; toggle block visibility
6154 (not (get-char-property (match-end 0) 'invisible))))
6156 ;; Show-subtree, ARG levels up from here.
6157 ((integerp arg)
6158 (save-excursion
6159 (org-back-to-heading)
6160 (outline-up-heading (if (< arg 0) (- arg)
6161 (- (funcall outline-level) arg)))
6162 (org-show-subtree)))
6164 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6165 ((and (featurep 'org-inlinetask)
6166 (org-inlinetask-at-task-p)
6167 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6168 (org-inlinetask-toggle-visibility))
6170 ((org-try-cdlatex-tab))
6172 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6173 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6174 (save-excursion (beginning-of-line 1)
6175 (looking-at org-outline-regexp)))
6176 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6177 (org-cycle-internal-local))
6179 ;; From there: TAB emulation and template completion.
6180 (buffer-read-only (org-back-to-heading))
6182 ((run-hook-with-args-until-success
6183 'org-tab-after-check-for-cycling-hook))
6185 ((org-try-structure-completion))
6187 ((run-hook-with-args-until-success
6188 'org-tab-before-tab-emulation-hook))
6190 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6191 (or (not (bolp))
6192 (not (looking-at org-outline-regexp))))
6193 (call-interactively (global-key-binding "\t")))
6195 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6196 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6197 (or (and (eq org-cycle-emulate-tab 'white)
6198 (= (match-end 0) (point-at-eol)))
6199 (and (eq org-cycle-emulate-tab 'whitestart)
6200 (>= (match-end 0) pos))))
6202 (eq org-cycle-emulate-tab t))
6203 (call-interactively (global-key-binding "\t")))
6205 (t (save-excursion
6206 (org-back-to-heading)
6207 (org-cycle)))))))
6209 (defun org-cycle-internal-global ()
6210 "Do the global cycling action."
6211 ;; Hack to avoid display of messages for .org attachments in Gnus
6212 (let ((ga (string-match "\\*fontification" (buffer-name))))
6213 (cond
6214 ((and (eq last-command this-command)
6215 (eq org-cycle-global-status 'overview))
6216 ;; We just created the overview - now do table of contents
6217 ;; This can be slow in very large buffers, so indicate action
6218 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6219 (unless ga (message "CONTENTS..."))
6220 (org-content)
6221 (unless ga (message "CONTENTS...done"))
6222 (setq org-cycle-global-status 'contents)
6223 (run-hook-with-args 'org-cycle-hook 'contents))
6225 ((and (eq last-command this-command)
6226 (eq org-cycle-global-status 'contents))
6227 ;; We just showed the table of contents - now show everything
6228 (run-hook-with-args 'org-pre-cycle-hook 'all)
6229 (show-all)
6230 (unless ga (message "SHOW ALL"))
6231 (setq org-cycle-global-status 'all)
6232 (run-hook-with-args 'org-cycle-hook 'all))
6235 ;; Default action: go to overview
6236 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6237 (org-overview)
6238 (unless ga (message "OVERVIEW"))
6239 (setq org-cycle-global-status 'overview)
6240 (run-hook-with-args 'org-cycle-hook 'overview)))))
6242 (defun org-cycle-internal-local ()
6243 "Do the local cycling action."
6244 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6245 ;; First, determine end of headline (EOH), end of subtree or item
6246 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6247 (save-excursion
6248 (if (org-at-item-p)
6249 (progn
6250 (beginning-of-line)
6251 (setq struct (org-list-struct))
6252 (setq eoh (point-at-eol))
6253 (setq eos (org-list-get-item-end-before-blank (point) struct))
6254 (setq has-children (org-list-has-child-p (point) struct)))
6255 (org-back-to-heading)
6256 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6257 (setq eos (save-excursion
6258 (org-end-of-subtree t)
6259 (unless (eobp)
6260 (skip-chars-forward " \t\n"))
6261 (if (eobp) (point) (1- (point)))))
6262 (setq has-children
6263 (or (save-excursion
6264 (let ((level (funcall outline-level)))
6265 (outline-next-heading)
6266 (and (org-at-heading-p t)
6267 (> (funcall outline-level) level))))
6268 (save-excursion
6269 (org-list-search-forward (org-item-beginning-re) eos t)))))
6270 ;; Determine end invisible part of buffer (EOL)
6271 (beginning-of-line 2)
6272 ;; XEmacs doesn't have `next-single-char-property-change'
6273 (if (featurep 'xemacs)
6274 (while (and (not (eobp)) ;; this is like `next-line'
6275 (get-char-property (1- (point)) 'invisible))
6276 (beginning-of-line 2))
6277 (while (and (not (eobp)) ;; this is like `next-line'
6278 (get-char-property (1- (point)) 'invisible))
6279 (goto-char (next-single-char-property-change (point) 'invisible))
6280 (and (eolp) (beginning-of-line 2))))
6281 (setq eol (point)))
6282 ;; Find out what to do next and set `this-command'
6283 (cond
6284 ((= eos eoh)
6285 ;; Nothing is hidden behind this heading
6286 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6287 (message "EMPTY ENTRY")
6288 (setq org-cycle-subtree-status nil)
6289 (save-excursion
6290 (goto-char eos)
6291 (outline-next-heading)
6292 (if (outline-invisible-p) (org-flag-heading nil))))
6293 ((and (or (>= eol eos)
6294 (not (string-match "\\S-" (buffer-substring eol eos))))
6295 (or has-children
6296 (not (setq children-skipped
6297 org-cycle-skip-children-state-if-no-children))))
6298 ;; Entire subtree is hidden in one line: children view
6299 (run-hook-with-args 'org-pre-cycle-hook 'children)
6300 (if (org-at-item-p)
6301 (org-list-set-item-visibility (point-at-bol) struct 'children)
6302 (org-show-entry)
6303 (org-with-limited-levels (show-children))
6304 ;; FIXME: This slows down the func way too much.
6305 ;; How keep drawers hidden in subtree anyway?
6306 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6307 ;; (org-cycle-hide-drawers 'subtree))
6309 ;; Fold every list in subtree to top-level items.
6310 (when (eq org-cycle-include-plain-lists 'integrate)
6311 (save-excursion
6312 (org-back-to-heading)
6313 (while (org-list-search-forward (org-item-beginning-re) eos t)
6314 (beginning-of-line 1)
6315 (let* ((struct (org-list-struct))
6316 (prevs (org-list-prevs-alist struct))
6317 (end (org-list-get-bottom-point struct)))
6318 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6319 (org-list-get-all-items (point) struct prevs))
6320 (goto-char end))))))
6321 (message "CHILDREN")
6322 (save-excursion
6323 (goto-char eos)
6324 (outline-next-heading)
6325 (if (outline-invisible-p) (org-flag-heading nil)))
6326 (setq org-cycle-subtree-status 'children)
6327 (run-hook-with-args 'org-cycle-hook 'children))
6328 ((or children-skipped
6329 (and (eq last-command this-command)
6330 (eq org-cycle-subtree-status 'children)))
6331 ;; We just showed the children, or no children are there,
6332 ;; now show everything.
6333 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6334 (outline-flag-region eoh eos nil)
6335 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6336 (setq org-cycle-subtree-status 'subtree)
6337 (run-hook-with-args 'org-cycle-hook 'subtree))
6339 ;; Default action: hide the subtree.
6340 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6341 (outline-flag-region eoh eos t)
6342 (message "FOLDED")
6343 (setq org-cycle-subtree-status 'folded)
6344 (run-hook-with-args 'org-cycle-hook 'folded)))))
6346 ;;;###autoload
6347 (defun org-global-cycle (&optional arg)
6348 "Cycle the global visibility. For details see `org-cycle'.
6349 With \\[universal-argument] prefix arg, switch to startup visibility.
6350 With a numeric prefix, show all headlines up to that level."
6351 (interactive "P")
6352 (let ((org-cycle-include-plain-lists
6353 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6354 (cond
6355 ((integerp arg)
6356 (show-all)
6357 (hide-sublevels arg)
6358 (setq org-cycle-global-status 'contents))
6359 ((equal arg '(4))
6360 (org-set-startup-visibility)
6361 (message "Startup visibility, plus VISIBILITY properties."))
6363 (org-cycle '(4))))))
6365 (defun org-set-startup-visibility ()
6366 "Set the visibility required by startup options and properties."
6367 (cond
6368 ((eq org-startup-folded t)
6369 (org-cycle '(4)))
6370 ((eq org-startup-folded 'content)
6371 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6372 (org-cycle '(4)) (org-cycle '(4)))))
6373 (unless (eq org-startup-folded 'showeverything)
6374 (if org-hide-block-startup (org-hide-block-all))
6375 (org-set-visibility-according-to-property 'no-cleanup)
6376 (org-cycle-hide-archived-subtrees 'all)
6377 (org-cycle-hide-drawers 'all)
6378 (org-cycle-show-empty-lines t)))
6380 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6381 "Switch subtree visibilities according to :VISIBILITY: property."
6382 (interactive)
6383 (let (org-show-entry-below state)
6384 (save-excursion
6385 (goto-char (point-min))
6386 (while (re-search-forward
6387 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6388 nil t)
6389 (setq state (match-string 1))
6390 (save-excursion
6391 (org-back-to-heading t)
6392 (hide-subtree)
6393 (org-reveal)
6394 (cond
6395 ((equal state '("fold" "folded"))
6396 (hide-subtree))
6397 ((equal state "children")
6398 (org-show-hidden-entry)
6399 (show-children))
6400 ((equal state "content")
6401 (save-excursion
6402 (save-restriction
6403 (org-narrow-to-subtree)
6404 (org-content))))
6405 ((member state '("all" "showall"))
6406 (show-subtree)))))
6407 (unless no-cleanup
6408 (org-cycle-hide-archived-subtrees 'all)
6409 (org-cycle-hide-drawers 'all)
6410 (org-cycle-show-empty-lines 'all)))))
6412 ;; This function uses outline-regexp instead of the more fundamental
6413 ;; org-outline-regexp so that org-cycle-global works outside of Org
6414 ;; buffers, where outline-regexp is needed.
6415 (defun org-overview ()
6416 "Switch to overview mode, showing only top-level headlines.
6417 Really, this shows all headlines with level equal or greater than the level
6418 of the first headline in the buffer. This is important, because if the
6419 first headline is not level one, then (hide-sublevels 1) gives confusing
6420 results."
6421 (interactive)
6422 (let ((level (save-excursion
6423 (goto-char (point-min))
6424 (if (re-search-forward (concat "^" outline-regexp) nil t)
6425 (progn
6426 (goto-char (match-beginning 0))
6427 (funcall outline-level))))))
6428 (and level (hide-sublevels level))))
6430 (defun org-content (&optional arg)
6431 "Show all headlines in the buffer, like a table of contents.
6432 With numerical argument N, show content up to level N."
6433 (interactive "P")
6434 (save-excursion
6435 ;; Visit all headings and show their offspring
6436 (and (integerp arg) (org-overview))
6437 (goto-char (point-max))
6438 (catch 'exit
6439 (while (and (progn (condition-case nil
6440 (outline-previous-visible-heading 1)
6441 (error (goto-char (point-min))))
6443 (looking-at org-outline-regexp))
6444 (if (integerp arg)
6445 (show-children (1- arg))
6446 (show-branches))
6447 (if (bobp) (throw 'exit nil))))))
6450 (defun org-optimize-window-after-visibility-change (state)
6451 "Adjust the window after a change in outline visibility.
6452 This function is the default value of the hook `org-cycle-hook'."
6453 (when (get-buffer-window (current-buffer))
6454 (cond
6455 ((eq state 'content) nil)
6456 ((eq state 'all) nil)
6457 ((eq state 'folded) nil)
6458 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6459 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6461 (defun org-remove-empty-overlays-at (pos)
6462 "Remove outline overlays that do not contain non-white stuff."
6463 (mapc
6464 (lambda (o)
6465 (and (eq 'outline (overlay-get o 'invisible))
6466 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6467 (overlay-end o))))
6468 (delete-overlay o)))
6469 (overlays-at pos)))
6471 (defun org-clean-visibility-after-subtree-move ()
6472 "Fix visibility issues after moving a subtree."
6473 ;; First, find a reasonable region to look at:
6474 ;; Start two siblings above, end three below
6475 (let* ((beg (save-excursion
6476 (and (org-get-last-sibling)
6477 (org-get-last-sibling))
6478 (point)))
6479 (end (save-excursion
6480 (and (org-get-next-sibling)
6481 (org-get-next-sibling)
6482 (org-get-next-sibling))
6483 (if (org-at-heading-p)
6484 (point-at-eol)
6485 (point))))
6486 (level (looking-at "\\*+"))
6487 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6488 (save-excursion
6489 (save-restriction
6490 (narrow-to-region beg end)
6491 (when re
6492 ;; Properly fold already folded siblings
6493 (goto-char (point-min))
6494 (while (re-search-forward re nil t)
6495 (if (and (not (outline-invisible-p))
6496 (save-excursion
6497 (goto-char (point-at-eol)) (outline-invisible-p)))
6498 (hide-entry))))
6499 (org-cycle-show-empty-lines 'overview)
6500 (org-cycle-hide-drawers 'overview)))))
6502 (defun org-cycle-show-empty-lines (state)
6503 "Show empty lines above all visible headlines.
6504 The region to be covered depends on STATE when called through
6505 `org-cycle-hook'. Lisp program can use t for STATE to get the
6506 entire buffer covered. Note that an empty line is only shown if there
6507 are at least `org-cycle-separator-lines' empty lines before the headline."
6508 (when (not (= org-cycle-separator-lines 0))
6509 (save-excursion
6510 (let* ((n (abs org-cycle-separator-lines))
6511 (re (cond
6512 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6513 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6514 (t (let ((ns (number-to-string (- n 2))))
6515 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6516 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6517 beg end b e)
6518 (cond
6519 ((memq state '(overview contents t))
6520 (setq beg (point-min) end (point-max)))
6521 ((memq state '(children folded))
6522 (setq beg (point) end (progn (org-end-of-subtree t t)
6523 (beginning-of-line 2)
6524 (point)))))
6525 (when beg
6526 (goto-char beg)
6527 (while (re-search-forward re end t)
6528 (unless (get-char-property (match-end 1) 'invisible)
6529 (setq e (match-end 1))
6530 (if (< org-cycle-separator-lines 0)
6531 (setq b (save-excursion
6532 (goto-char (match-beginning 0))
6533 (org-back-over-empty-lines)
6534 (if (save-excursion
6535 (goto-char (max (point-min) (1- (point))))
6536 (org-at-heading-p))
6537 (1- (point))
6538 (point))))
6539 (setq b (match-beginning 1)))
6540 (outline-flag-region b e nil)))))))
6541 ;; Never hide empty lines at the end of the file.
6542 (save-excursion
6543 (goto-char (point-max))
6544 (outline-previous-heading)
6545 (outline-end-of-heading)
6546 (if (and (looking-at "[ \t\n]+")
6547 (= (match-end 0) (point-max)))
6548 (outline-flag-region (point) (match-end 0) nil))))
6550 (defun org-show-empty-lines-in-parent ()
6551 "Move to the parent and re-show empty lines before visible headlines."
6552 (save-excursion
6553 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6554 (org-cycle-show-empty-lines context))))
6556 (defun org-files-list ()
6557 "Return `org-agenda-files' list, plus all open org-mode files.
6558 This is useful for operations that need to scan all of a user's
6559 open and agenda-wise Org files."
6560 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6561 (dolist (buf (buffer-list))
6562 (with-current-buffer buf
6563 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6564 (let ((file (expand-file-name (buffer-file-name))))
6565 (unless (member file files)
6566 (push file files))))))
6567 files))
6569 (defsubst org-entry-beginning-position ()
6570 "Return the beginning position of the current entry."
6571 (save-excursion (outline-back-to-heading t) (point)))
6573 (defsubst org-entry-end-position ()
6574 "Return the end position of the current entry."
6575 (save-excursion (outline-next-heading) (point)))
6577 (defun org-cycle-hide-drawers (state)
6578 "Re-hide all drawers after a visibility state change."
6579 (when (and (derived-mode-p 'org-mode)
6580 (not (memq state '(overview folded contents))))
6581 (save-excursion
6582 (let* ((globalp (memq state '(contents all)))
6583 (beg (if globalp (point-min) (point)))
6584 (end (if globalp (point-max)
6585 (if (eq state 'children)
6586 (save-excursion (outline-next-heading) (point))
6587 (org-end-of-subtree t)))))
6588 (goto-char beg)
6589 (while (re-search-forward org-drawer-regexp end t)
6590 (org-flag-drawer t))))))
6592 (defun org-flag-drawer (flag)
6593 "When FLAG is non-nil, hide the drawer we are within.
6594 Otherwise make it visible."
6595 (save-excursion
6596 (beginning-of-line 1)
6597 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6598 (let ((b (match-end 0)))
6599 (if (re-search-forward
6600 "^[ \t]*:END:"
6601 (save-excursion (outline-next-heading) (point)) t)
6602 (outline-flag-region b (point-at-eol) flag)
6603 (error ":END: line missing at position %s" b))))))
6605 (defun org-subtree-end-visible-p ()
6606 "Is the end of the current subtree visible?"
6607 (pos-visible-in-window-p
6608 (save-excursion (org-end-of-subtree t) (point))))
6610 (defun org-first-headline-recenter (&optional N)
6611 "Move cursor to the first headline and recenter the headline.
6612 Optional argument N means put the headline into the Nth line of the window."
6613 (goto-char (point-min))
6614 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6615 (beginning-of-line)
6616 (recenter (prefix-numeric-value N))))
6618 ;;; Saving and restoring visibility
6620 (defun org-outline-overlay-data (&optional use-markers)
6621 "Return a list of the locations of all outline overlays.
6622 These are overlays with the `invisible' property value `outline'.
6623 The return value is a list of cons cells, with start and stop
6624 positions for each overlay.
6625 If USE-MARKERS is set, return the positions as markers."
6626 (let (beg end)
6627 (save-excursion
6628 (save-restriction
6629 (widen)
6630 (delq nil
6631 (mapcar (lambda (o)
6632 (when (eq (overlay-get o 'invisible) 'outline)
6633 (setq beg (overlay-start o)
6634 end (overlay-end o))
6635 (and beg end (> end beg)
6636 (if use-markers
6637 (cons (move-marker (make-marker) beg)
6638 (move-marker (make-marker) end))
6639 (cons beg end)))))
6640 (overlays-in (point-min) (point-max))))))))
6642 (defun org-set-outline-overlay-data (data)
6643 "Create visibility overlays for all positions in DATA.
6644 DATA should have been made by `org-outline-overlay-data'."
6645 (let (o)
6646 (save-excursion
6647 (save-restriction
6648 (widen)
6649 (show-all)
6650 (mapc (lambda (c)
6651 (outline-flag-region (car c) (cdr c) t))
6652 data)))))
6654 ;;; Folding of blocks
6656 (defvar org-hide-block-overlays nil
6657 "Overlays hiding blocks.")
6658 (make-variable-buffer-local 'org-hide-block-overlays)
6660 (defun org-block-map (function &optional start end)
6661 "Call FUNCTION at the head of all source blocks in the current buffer.
6662 Optional arguments START and END can be used to limit the range."
6663 (let ((start (or start (point-min)))
6664 (end (or end (point-max))))
6665 (save-excursion
6666 (goto-char start)
6667 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6668 (save-excursion
6669 (save-match-data
6670 (goto-char (match-beginning 0))
6671 (funcall function)))))))
6673 (defun org-hide-block-toggle-all ()
6674 "Toggle the visibility of all blocks in the current buffer."
6675 (org-block-map #'org-hide-block-toggle))
6677 (defun org-hide-block-all ()
6678 "Fold all blocks in the current buffer."
6679 (interactive)
6680 (org-show-block-all)
6681 (org-block-map #'org-hide-block-toggle-maybe))
6683 (defun org-show-block-all ()
6684 "Unfold all blocks in the current buffer."
6685 (interactive)
6686 (mapc 'delete-overlay org-hide-block-overlays)
6687 (setq org-hide-block-overlays nil))
6689 (defun org-hide-block-toggle-maybe ()
6690 "Toggle visibility of block at point."
6691 (interactive)
6692 (let ((case-fold-search t))
6693 (if (save-excursion
6694 (beginning-of-line 1)
6695 (looking-at org-block-regexp))
6696 (progn (org-hide-block-toggle)
6697 t) ;; to signal that we took action
6698 nil))) ;; to signal that we did not
6700 (defun org-hide-block-toggle (&optional force)
6701 "Toggle the visibility of the current block."
6702 (interactive)
6703 (save-excursion
6704 (beginning-of-line)
6705 (if (re-search-forward org-block-regexp nil t)
6706 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6707 (end (match-end 0)) ;; end of entire body
6709 (if (memq t (mapcar (lambda (overlay)
6710 (eq (overlay-get overlay 'invisible)
6711 'org-hide-block))
6712 (overlays-at start)))
6713 (if (or (not force) (eq force 'off))
6714 (mapc (lambda (ov)
6715 (when (member ov org-hide-block-overlays)
6716 (setq org-hide-block-overlays
6717 (delq ov org-hide-block-overlays)))
6718 (when (eq (overlay-get ov 'invisible)
6719 'org-hide-block)
6720 (delete-overlay ov)))
6721 (overlays-at start)))
6722 (setq ov (make-overlay start end))
6723 (overlay-put ov 'invisible 'org-hide-block)
6724 ;; make the block accessible to isearch
6725 (overlay-put
6726 ov 'isearch-open-invisible
6727 (lambda (ov)
6728 (when (member ov org-hide-block-overlays)
6729 (setq org-hide-block-overlays
6730 (delq ov org-hide-block-overlays)))
6731 (when (eq (overlay-get ov 'invisible)
6732 'org-hide-block)
6733 (delete-overlay ov))))
6734 (push ov org-hide-block-overlays)))
6735 (error "Not looking at a source block"))))
6737 ;; org-tab-after-check-for-cycling-hook
6738 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6739 ;; Remove overlays when changing major mode
6740 (add-hook 'org-mode-hook
6741 (lambda () (org-add-hook 'change-major-mode-hook
6742 'org-show-block-all 'append 'local)))
6744 ;;; Org-goto
6746 (defvar org-goto-window-configuration nil)
6747 (defvar org-goto-marker nil)
6748 (defvar org-goto-map
6749 (let ((map (make-sparse-keymap)))
6750 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6751 (while (setq cmd (pop cmds))
6752 (substitute-key-definition cmd cmd map global-map)))
6753 (suppress-keymap map)
6754 (org-defkey map "\C-m" 'org-goto-ret)
6755 (org-defkey map [(return)] 'org-goto-ret)
6756 (org-defkey map [(left)] 'org-goto-left)
6757 (org-defkey map [(right)] 'org-goto-right)
6758 (org-defkey map [(control ?g)] 'org-goto-quit)
6759 (org-defkey map "\C-i" 'org-cycle)
6760 (org-defkey map [(tab)] 'org-cycle)
6761 (org-defkey map [(down)] 'outline-next-visible-heading)
6762 (org-defkey map [(up)] 'outline-previous-visible-heading)
6763 (if org-goto-auto-isearch
6764 (if (fboundp 'define-key-after)
6765 (define-key-after map [t] 'org-goto-local-auto-isearch)
6766 nil)
6767 (org-defkey map "q" 'org-goto-quit)
6768 (org-defkey map "n" 'outline-next-visible-heading)
6769 (org-defkey map "p" 'outline-previous-visible-heading)
6770 (org-defkey map "f" 'outline-forward-same-level)
6771 (org-defkey map "b" 'outline-backward-same-level)
6772 (org-defkey map "u" 'outline-up-heading))
6773 (org-defkey map "/" 'org-occur)
6774 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6775 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6776 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6777 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6778 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6779 map))
6781 (defconst org-goto-help
6782 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6783 RET=jump to location [Q]uit and return to previous location
6784 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6786 (defvar org-goto-start-pos) ; dynamically scoped parameter
6788 ;; FIXME: Docstring does not mention both interfaces
6789 (defun org-goto (&optional alternative-interface)
6790 "Look up a different location in the current file, keeping current visibility.
6792 When you want look-up or go to a different location in a
6793 document, the fastest way is often to fold the entire buffer and
6794 then dive into the tree. This method has the disadvantage, that
6795 the previous location will be folded, which may not be what you
6796 want.
6798 This command works around this by showing a copy of the current
6799 buffer in an indirect buffer, in overview mode. You can dive
6800 into the tree in that copy, use org-occur and incremental search
6801 to find a location. When pressing RET or `Q', the command
6802 returns to the original buffer in which the visibility is still
6803 unchanged. After RET it will also jump to the location selected
6804 in the indirect buffer and expose the headline hierarchy above.
6806 With a prefix argument, use the alternative interface: e.g. if
6807 `org-goto-interface' is 'outline use 'outline-path-completion."
6808 (interactive "P")
6809 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6810 (org-refile-use-outline-path t)
6811 (org-refile-target-verify-function nil)
6812 (interface
6813 (if (not alternative-interface)
6814 org-goto-interface
6815 (if (eq org-goto-interface 'outline)
6816 'outline-path-completion
6817 'outline)))
6818 (org-goto-start-pos (point))
6819 (selected-point
6820 (if (eq interface 'outline)
6821 (car (org-get-location (current-buffer) org-goto-help))
6822 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6823 (org-refile-check-position pa)
6824 (nth 3 pa)))))
6825 (if selected-point
6826 (progn
6827 (org-mark-ring-push org-goto-start-pos)
6828 (goto-char selected-point)
6829 (if (or (outline-invisible-p) (org-invisible-p2))
6830 (org-show-context 'org-goto)))
6831 (message "Quit"))))
6833 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6834 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6835 (defvar org-goto-local-auto-isearch-map) ; defined below
6837 (defun org-get-location (buf help)
6838 "Let the user select a location in the Org-mode buffer BUF.
6839 This function uses a recursive edit. It returns the selected position
6840 or nil."
6841 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6842 (isearch-hide-immediately nil)
6843 (isearch-search-fun-function
6844 (lambda () 'org-goto-local-search-headings))
6845 (org-goto-selected-point org-goto-exit-command)
6846 (pop-up-frames nil)
6847 (special-display-buffer-names nil)
6848 (special-display-regexps nil)
6849 (special-display-function nil))
6850 (save-excursion
6851 (save-window-excursion
6852 (delete-other-windows)
6853 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6854 (org-pop-to-buffer-same-window
6855 (condition-case nil
6856 (make-indirect-buffer (current-buffer) "*org-goto*")
6857 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6858 (with-output-to-temp-buffer "*Help*"
6859 (princ help))
6860 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6861 (setq buffer-read-only nil)
6862 (let ((org-startup-truncated t)
6863 (org-startup-folded nil)
6864 (org-startup-align-all-tables nil))
6865 (org-mode)
6866 (org-overview))
6867 (setq buffer-read-only t)
6868 (if (and (boundp 'org-goto-start-pos)
6869 (integer-or-marker-p org-goto-start-pos))
6870 (let ((org-show-hierarchy-above t)
6871 (org-show-siblings t)
6872 (org-show-following-heading t))
6873 (goto-char org-goto-start-pos)
6874 (and (outline-invisible-p) (org-show-context)))
6875 (goto-char (point-min)))
6876 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6877 (message "Select location and press RET")
6878 (use-local-map org-goto-map)
6879 (recursive-edit)
6881 (kill-buffer "*org-goto*")
6882 (cons org-goto-selected-point org-goto-exit-command)))
6884 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6885 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6886 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6887 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6889 (defun org-goto-local-search-headings (string bound noerror)
6890 "Search and make sure that any matches are in headlines."
6891 (catch 'return
6892 (while (if isearch-forward
6893 (search-forward string bound noerror)
6894 (search-backward string bound noerror))
6895 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6896 (and (member :headline context)
6897 (not (member :tags context))))
6898 (throw 'return (point))))))
6900 (defun org-goto-local-auto-isearch ()
6901 "Start isearch."
6902 (interactive)
6903 (goto-char (point-min))
6904 (let ((keys (this-command-keys)))
6905 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6906 (isearch-mode t)
6907 (isearch-process-search-char (string-to-char keys)))))
6909 (defun org-goto-ret (&optional arg)
6910 "Finish `org-goto' by going to the new location."
6911 (interactive "P")
6912 (setq org-goto-selected-point (point)
6913 org-goto-exit-command 'return)
6914 (throw 'exit nil))
6916 (defun org-goto-left ()
6917 "Finish `org-goto' by going to the new location."
6918 (interactive)
6919 (if (org-at-heading-p)
6920 (progn
6921 (beginning-of-line 1)
6922 (setq org-goto-selected-point (point)
6923 org-goto-exit-command 'left)
6924 (throw 'exit nil))
6925 (error "Not on a heading")))
6927 (defun org-goto-right ()
6928 "Finish `org-goto' by going to the new location."
6929 (interactive)
6930 (if (org-at-heading-p)
6931 (progn
6932 (setq org-goto-selected-point (point)
6933 org-goto-exit-command 'right)
6934 (throw 'exit nil))
6935 (error "Not on a heading")))
6937 (defun org-goto-quit ()
6938 "Finish `org-goto' without cursor motion."
6939 (interactive)
6940 (setq org-goto-selected-point nil)
6941 (setq org-goto-exit-command 'quit)
6942 (throw 'exit nil))
6944 ;;; Indirect buffer display of subtrees
6946 (defvar org-indirect-dedicated-frame nil
6947 "This is the frame being used for indirect tree display.")
6948 (defvar org-last-indirect-buffer nil)
6950 (defun org-tree-to-indirect-buffer (&optional arg)
6951 "Create indirect buffer and narrow it to current subtree.
6952 With a numerical prefix ARG, go up to this level and then take that tree.
6953 If ARG is negative, go up that many levels.
6955 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6956 indirect buffer previously made with this command, to avoid proliferation of
6957 indirect buffers. However, when you call the command with a \
6958 \\[universal-argument] prefix, or
6959 when `org-indirect-buffer-display' is `new-frame', the last buffer
6960 is kept so that you can work with several indirect buffers at the same time.
6961 If `org-indirect-buffer-display' is `dedicated-frame', the \
6962 \\[universal-argument] prefix also
6963 requests that a new frame be made for the new buffer, so that the dedicated
6964 frame is not changed."
6965 (interactive "P")
6966 (let ((cbuf (current-buffer))
6967 (cwin (selected-window))
6968 (pos (point))
6969 beg end level heading ibuf)
6970 (save-excursion
6971 (org-back-to-heading t)
6972 (when (numberp arg)
6973 (setq level (org-outline-level))
6974 (if (< arg 0) (setq arg (+ level arg)))
6975 (while (> (setq level (org-outline-level)) arg)
6976 (org-up-heading-safe)))
6977 (setq beg (point)
6978 heading (org-get-heading))
6979 (org-end-of-subtree t t)
6980 (if (org-at-heading-p) (backward-char 1))
6981 (setq end (point)))
6982 (if (and (buffer-live-p org-last-indirect-buffer)
6983 (not (eq org-indirect-buffer-display 'new-frame))
6984 (not arg))
6985 (kill-buffer org-last-indirect-buffer))
6986 (setq ibuf (org-get-indirect-buffer cbuf)
6987 org-last-indirect-buffer ibuf)
6988 (cond
6989 ((or (eq org-indirect-buffer-display 'new-frame)
6990 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6991 (select-frame (make-frame))
6992 (delete-other-windows)
6993 (org-pop-to-buffer-same-window ibuf)
6994 (org-set-frame-title heading))
6995 ((eq org-indirect-buffer-display 'dedicated-frame)
6996 (raise-frame
6997 (select-frame (or (and org-indirect-dedicated-frame
6998 (frame-live-p org-indirect-dedicated-frame)
6999 org-indirect-dedicated-frame)
7000 (setq org-indirect-dedicated-frame (make-frame)))))
7001 (delete-other-windows)
7002 (org-pop-to-buffer-same-window ibuf)
7003 (org-set-frame-title (concat "Indirect: " heading)))
7004 ((eq org-indirect-buffer-display 'current-window)
7005 (org-pop-to-buffer-same-window ibuf))
7006 ((eq org-indirect-buffer-display 'other-window)
7007 (pop-to-buffer ibuf))
7008 (t (error "Invalid value")))
7009 (if (featurep 'xemacs)
7010 (save-excursion (org-mode) (turn-on-font-lock)))
7011 (narrow-to-region beg end)
7012 (show-all)
7013 (goto-char pos)
7014 (run-hook-with-args 'org-cycle-hook 'all)
7015 (and (window-live-p cwin) (select-window cwin))))
7017 (defun org-get-indirect-buffer (&optional buffer)
7018 (setq buffer (or buffer (current-buffer)))
7019 (let ((n 1) (base (buffer-name buffer)) bname)
7020 (while (buffer-live-p
7021 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7022 (setq n (1+ n)))
7023 (condition-case nil
7024 (make-indirect-buffer buffer bname 'clone)
7025 (error (make-indirect-buffer buffer bname)))))
7027 (defun org-set-frame-title (title)
7028 "Set the title of the current frame to the string TITLE."
7029 ;; FIXME: how to name a single frame in XEmacs???
7030 (unless (featurep 'xemacs)
7031 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7033 ;;;; Structure editing
7035 ;;; Inserting headlines
7037 (defun org-previous-line-empty-p ()
7038 (save-excursion
7039 (and (not (bobp))
7040 (or (beginning-of-line 0) t)
7041 (save-match-data
7042 (looking-at "[ \t]*$")))))
7044 (defun org-insert-heading (&optional force-heading invisible-ok)
7045 "Insert a new heading or item with same depth at point.
7046 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7047 If point is at the beginning of a headline, insert a sibling before the
7048 current headline. If point is not at the beginning, split the line,
7049 create the new headline with the text in the current line after point
7050 \(but see also the variable `org-M-RET-may-split-line').
7052 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7053 This is important for non-interactive uses of the command."
7054 (interactive "P")
7055 (if (or (= (buffer-size) 0)
7056 (and (not (save-excursion
7057 (and (ignore-errors (org-back-to-heading invisible-ok))
7058 (org-at-heading-p))))
7059 (or force-heading (not (org-in-item-p)))))
7060 (progn
7061 (insert "\n* ")
7062 (run-hooks 'org-insert-heading-hook))
7063 (when (or force-heading (not (org-insert-item)))
7064 (let* ((empty-line-p nil)
7065 (level nil)
7066 (on-heading (org-at-heading-p))
7067 (head (save-excursion
7068 (condition-case nil
7069 (progn
7070 (org-back-to-heading invisible-ok)
7071 (when (and (not on-heading)
7072 (featurep 'org-inlinetask)
7073 (integerp org-inlinetask-min-level)
7074 (>= (length (match-string 0))
7075 org-inlinetask-min-level))
7076 ;; Find a heading level before the inline task
7077 (while (and (setq level (org-up-heading-safe))
7078 (>= level org-inlinetask-min-level)))
7079 (if (org-at-heading-p)
7080 (org-back-to-heading invisible-ok)
7081 (error "This should not happen")))
7082 (setq empty-line-p (org-previous-line-empty-p))
7083 (match-string 0))
7084 (error "*"))))
7085 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7086 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7087 pos hide-previous previous-pos)
7088 (cond
7089 ((and (org-at-heading-p) (bolp)
7090 (or (bobp)
7091 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7092 ;; insert before the current line
7093 (open-line (if blank 2 1)))
7094 ((and (bolp)
7095 (not org-insert-heading-respect-content)
7096 (or (bobp)
7097 (save-excursion
7098 (backward-char 1) (not (outline-invisible-p)))))
7099 ;; insert right here
7100 nil)
7102 ;; somewhere in the line
7103 (save-excursion
7104 (setq previous-pos (point-at-bol))
7105 (end-of-line)
7106 (setq hide-previous (outline-invisible-p)))
7107 (and org-insert-heading-respect-content (org-show-subtree))
7108 (let ((split
7109 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7110 (save-excursion
7111 (let ((p (point)))
7112 (goto-char (point-at-bol))
7113 (and (looking-at org-complex-heading-regexp)
7114 (match-beginning 4)
7115 (> p (match-beginning 4)))))))
7116 tags pos)
7117 (cond
7118 (org-insert-heading-respect-content
7119 (org-end-of-subtree nil t)
7120 (when (featurep 'org-inlinetask)
7121 (while (and (not (eobp))
7122 (looking-at "\\(\\*+\\)[ \t]+")
7123 (>= (length (match-string 1))
7124 org-inlinetask-min-level))
7125 (org-end-of-subtree nil t)))
7126 (or (bolp) (newline))
7127 (or (org-previous-line-empty-p)
7128 (and blank (newline)))
7129 (open-line 1))
7130 ((org-at-heading-p)
7131 (when hide-previous
7132 (show-children)
7133 (org-show-entry))
7134 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7135 (setq tags (and (match-end 2) (match-string 2)))
7136 (and (match-end 1)
7137 (delete-region (match-beginning 1) (match-end 1)))
7138 (setq pos (point-at-bol))
7139 (or split (end-of-line 1))
7140 (delete-horizontal-space)
7141 (if (string-match "\\`\\*+\\'"
7142 (buffer-substring (point-at-bol) (point)))
7143 (insert " "))
7144 (newline (if blank 2 1))
7145 (when tags
7146 (save-excursion
7147 (goto-char pos)
7148 (end-of-line 1)
7149 (insert " " tags)
7150 (org-set-tags nil 'align))))
7152 (or split (end-of-line 1))
7153 (newline (if blank 2 1)))))))
7154 (insert head) (just-one-space)
7155 (setq pos (point))
7156 (end-of-line 1)
7157 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7158 (when (and org-insert-heading-respect-content hide-previous)
7159 (save-excursion
7160 (goto-char previous-pos)
7161 (hide-subtree)))
7162 (run-hooks 'org-insert-heading-hook)))))
7164 (defun org-get-heading (&optional no-tags no-todo)
7165 "Return the heading of the current entry, without the stars.
7166 When NO-TAGS is non-nil, don't include tags.
7167 When NO-TODO is non-nil, don't include TODO keywords."
7168 (save-excursion
7169 (org-back-to-heading t)
7170 (cond
7171 ((and no-tags no-todo)
7172 (looking-at org-complex-heading-regexp)
7173 (match-string 4))
7174 (no-tags
7175 (looking-at (concat org-outline-regexp
7176 "\\(.*?\\)"
7177 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7178 (match-string 1))
7179 (no-todo
7180 (looking-at org-todo-line-regexp)
7181 (match-string 3))
7182 (t (looking-at org-heading-regexp)
7183 (match-string 2)))))
7185 (defun org-heading-components ()
7186 "Return the components of the current heading.
7187 This is a list with the following elements:
7188 - the level as an integer
7189 - the reduced level, different if `org-odd-levels-only' is set.
7190 - the TODO keyword, or nil
7191 - the priority character, like ?A, or nil if no priority is given
7192 - the headline text itself, or the tags string if no headline text
7193 - the tags string, or nil."
7194 (save-excursion
7195 (org-back-to-heading t)
7196 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7197 (list (length (match-string 1))
7198 (org-reduced-level (length (match-string 1)))
7199 (org-match-string-no-properties 2)
7200 (and (match-end 3) (aref (match-string 3) 2))
7201 (org-match-string-no-properties 4)
7202 (org-match-string-no-properties 5)))))
7204 (defun org-get-entry ()
7205 "Get the entry text, after heading, entire subtree."
7206 (save-excursion
7207 (org-back-to-heading t)
7208 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7210 (defun org-insert-heading-after-current ()
7211 "Insert a new heading with same level as current, after current subtree."
7212 (interactive)
7213 (org-back-to-heading)
7214 (org-insert-heading)
7215 (org-move-subtree-down)
7216 (end-of-line 1))
7218 (defun org-insert-heading-respect-content ()
7219 (interactive)
7220 (let ((org-insert-heading-respect-content t))
7221 (org-insert-heading t)))
7223 (defun org-insert-todo-heading-respect-content (&optional force-state)
7224 (interactive "P")
7225 (let ((org-insert-heading-respect-content t))
7226 (org-insert-todo-heading force-state t)))
7228 (defun org-insert-todo-heading (arg &optional force-heading)
7229 "Insert a new heading with the same level and TODO state as current heading.
7230 If the heading has no TODO state, or if the state is DONE, use the first
7231 state (TODO by default). Also with prefix arg, force first state."
7232 (interactive "P")
7233 (when (or force-heading (not (org-insert-item 'checkbox)))
7234 (org-insert-heading force-heading)
7235 (save-excursion
7236 (org-back-to-heading)
7237 (outline-previous-heading)
7238 (looking-at org-todo-line-regexp))
7239 (let*
7240 ((new-mark-x
7241 (if (or arg
7242 (not (match-beginning 2))
7243 (member (match-string 2) org-done-keywords))
7244 (car org-todo-keywords-1)
7245 (match-string 2)))
7246 (new-mark
7248 (run-hook-with-args-until-success
7249 'org-todo-get-default-hook new-mark-x nil)
7250 new-mark-x)))
7251 (beginning-of-line 1)
7252 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7253 (if org-treat-insert-todo-heading-as-state-change
7254 (org-todo new-mark)
7255 (insert new-mark " "))))
7256 (when org-provide-todo-statistics
7257 (org-update-parent-todo-statistics))))
7259 (defun org-insert-subheading (arg)
7260 "Insert a new subheading and demote it.
7261 Works for outline headings and for plain lists alike."
7262 (interactive "P")
7263 (org-insert-heading arg)
7264 (cond
7265 ((org-at-heading-p) (org-do-demote))
7266 ((org-at-item-p) (org-indent-item))))
7268 (defun org-insert-todo-subheading (arg)
7269 "Insert a new subheading with TODO keyword or checkbox and demote it.
7270 Works for outline headings and for plain lists alike."
7271 (interactive "P")
7272 (org-insert-todo-heading arg)
7273 (cond
7274 ((org-at-heading-p) (org-do-demote))
7275 ((org-at-item-p) (org-indent-item))))
7277 ;;; Promotion and Demotion
7279 (defvar org-after-demote-entry-hook nil
7280 "Hook run after an entry has been demoted.
7281 The cursor will be at the beginning of the entry.
7282 When a subtree is being demoted, the hook will be called for each node.")
7284 (defvar org-after-promote-entry-hook nil
7285 "Hook run after an entry has been promoted.
7286 The cursor will be at the beginning of the entry.
7287 When a subtree is being promoted, the hook will be called for each node.")
7289 (defun org-promote-subtree ()
7290 "Promote the entire subtree.
7291 See also `org-promote'."
7292 (interactive)
7293 (save-excursion
7294 (org-with-limited-levels (org-map-tree 'org-promote)))
7295 (org-fix-position-after-promote))
7297 (defun org-demote-subtree ()
7298 "Demote the entire subtree. See `org-demote'.
7299 See also `org-promote'."
7300 (interactive)
7301 (save-excursion
7302 (org-with-limited-levels (org-map-tree 'org-demote)))
7303 (org-fix-position-after-promote))
7306 (defun org-do-promote ()
7307 "Promote the current heading higher up the tree.
7308 If the region is active in `transient-mark-mode', promote all headings
7309 in the region."
7310 (interactive)
7311 (save-excursion
7312 (if (org-region-active-p)
7313 (org-map-region 'org-promote (region-beginning) (region-end))
7314 (org-promote)))
7315 (org-fix-position-after-promote))
7317 (defun org-do-demote ()
7318 "Demote the current heading lower down the tree.
7319 If the region is active in `transient-mark-mode', demote all headings
7320 in the region."
7321 (interactive)
7322 (save-excursion
7323 (if (org-region-active-p)
7324 (org-map-region 'org-demote (region-beginning) (region-end))
7325 (org-demote)))
7326 (org-fix-position-after-promote))
7328 (defun org-fix-position-after-promote ()
7329 "Make sure that after pro/demotion cursor position is right."
7330 (let ((pos (point)))
7331 (when (save-excursion
7332 (beginning-of-line 1)
7333 (looking-at org-todo-line-regexp)
7334 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7335 (cond ((eobp) (insert " "))
7336 ((eolp) (insert " "))
7337 ((equal (char-after) ?\ ) (forward-char 1))))))
7339 (defun org-current-level ()
7340 "Return the level of the current entry, or nil if before the first headline.
7341 The level is the number of stars at the beginning of the headline."
7342 (save-excursion
7343 (org-with-limited-levels
7344 (if (ignore-errors (org-back-to-heading t))
7345 (funcall outline-level)))))
7347 (defun org-get-previous-line-level ()
7348 "Return the outline depth of the last headline before the current line.
7349 Returns 0 for the first headline in the buffer, and nil if before the
7350 first headline."
7351 (let ((current-level (org-current-level))
7352 (prev-level (when (> (line-number-at-pos) 1)
7353 (save-excursion
7354 (beginning-of-line 0)
7355 (org-current-level)))))
7356 (cond ((null current-level) nil) ; Before first headline
7357 ((null prev-level) 0) ; At first headline
7358 (prev-level))))
7360 (defun org-reduced-level (l)
7361 "Compute the effective level of a heading.
7362 This takes into account the setting of `org-odd-levels-only'."
7363 (cond
7364 ((zerop l) 0)
7365 (org-odd-levels-only (1+ (floor (/ l 2))))
7366 (t l)))
7368 (defun org-level-increment ()
7369 "Return the number of stars that will be added or removed at a
7370 time to headlines when structure editing, based on the value of
7371 `org-odd-levels-only'."
7372 (if org-odd-levels-only 2 1))
7374 (defun org-get-valid-level (level &optional change)
7375 "Rectify a level change under the influence of `org-odd-levels-only'
7376 LEVEL is a current level, CHANGE is by how much the level should be
7377 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7378 even level numbers will become the next higher odd number."
7379 (if org-odd-levels-only
7380 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7381 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7382 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7383 (max 1 (+ level (or change 0)))))
7385 (if (boundp 'define-obsolete-function-alias)
7386 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7387 (define-obsolete-function-alias 'org-get-legal-level
7388 'org-get-valid-level)
7389 (define-obsolete-function-alias 'org-get-legal-level
7390 'org-get-valid-level "23.1")))
7392 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7393 ;; ̀org-with-limited-levels'
7394 (defun org-promote ()
7395 "Promote the current heading higher up the tree.
7396 If the region is active in `transient-mark-mode', promote all headings
7397 in the region."
7398 (org-back-to-heading t)
7399 (let* ((level (save-match-data (funcall outline-level)))
7400 (after-change-functions (remove 'flyspell-after-change-function
7401 after-change-functions))
7402 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7403 (diff (abs (- level (length up-head) -1))))
7404 (cond ((and (= level 1) org-called-with-limited-levels
7405 org-allow-promoting-top-level-subtree)
7406 (replace-match "# " nil t))
7407 ((= level 1)
7408 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7409 (t (replace-match up-head nil t)))
7410 ;; Fixup tag positioning
7411 (unless (= level 1)
7412 (and org-auto-align-tags (org-set-tags nil t))
7413 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7414 (run-hooks 'org-after-promote-entry-hook)))
7416 (defun org-demote ()
7417 "Demote the current heading lower down the tree.
7418 If the region is active in `transient-mark-mode', demote all headings
7419 in the region."
7420 (org-back-to-heading t)
7421 (let* ((level (save-match-data (funcall outline-level)))
7422 (after-change-functions (remove 'flyspell-after-change-function
7423 after-change-functions))
7424 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7425 (diff (abs (- level (length down-head) -1))))
7426 (replace-match down-head nil t)
7427 ;; Fixup tag positioning
7428 (and org-auto-align-tags (org-set-tags nil t))
7429 (if org-adapt-indentation (org-fixup-indentation diff))
7430 (run-hooks 'org-after-demote-entry-hook)))
7432 (defun org-cycle-level ()
7433 "Cycle the level of an empty headline through possible states.
7434 This goes first to child, then to parent, level, then up the hierarchy.
7435 After top level, it switches back to sibling level."
7436 (interactive)
7437 (let ((org-adapt-indentation nil))
7438 (when (org-point-at-end-of-empty-headline)
7439 (setq this-command 'org-cycle-level) ; Only needed for caching
7440 (let ((cur-level (org-current-level))
7441 (prev-level (org-get-previous-line-level)))
7442 (cond
7443 ;; If first headline in file, promote to top-level.
7444 ((= prev-level 0)
7445 (loop repeat (/ (- cur-level 1) (org-level-increment))
7446 do (org-do-promote)))
7447 ;; If same level as prev, demote one.
7448 ((= prev-level cur-level)
7449 (org-do-demote))
7450 ;; If parent is top-level, promote to top level if not already.
7451 ((= prev-level 1)
7452 (loop repeat (/ (- cur-level 1) (org-level-increment))
7453 do (org-do-promote)))
7454 ;; If top-level, return to prev-level.
7455 ((= cur-level 1)
7456 (loop repeat (/ (- prev-level 1) (org-level-increment))
7457 do (org-do-demote)))
7458 ;; If less than prev-level, promote one.
7459 ((< cur-level prev-level)
7460 (org-do-promote))
7461 ;; If deeper than prev-level, promote until higher than
7462 ;; prev-level.
7463 ((> cur-level prev-level)
7464 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7465 do (org-do-promote))))
7466 t))))
7468 (defun org-map-tree (fun)
7469 "Call FUN for every heading underneath the current one."
7470 (org-back-to-heading)
7471 (let ((level (funcall outline-level)))
7472 (save-excursion
7473 (funcall fun)
7474 (while (and (progn
7475 (outline-next-heading)
7476 (> (funcall outline-level) level))
7477 (not (eobp)))
7478 (funcall fun)))))
7480 (defun org-map-region (fun beg end)
7481 "Call FUN for every heading between BEG and END."
7482 (let ((org-ignore-region t))
7483 (save-excursion
7484 (setq end (copy-marker end))
7485 (goto-char beg)
7486 (if (and (re-search-forward org-outline-regexp-bol nil t)
7487 (< (point) end))
7488 (funcall fun))
7489 (while (and (progn
7490 (outline-next-heading)
7491 (< (point) end))
7492 (not (eobp)))
7493 (funcall fun)))))
7495 (defvar org-property-end-re) ; silence byte-compiler
7496 (defun org-fixup-indentation (diff)
7497 "Change the indentation in the current entry by DIFF.
7498 However, if any line in the current entry has no indentation, or if it
7499 would end up with no indentation after the change, nothing at all is done."
7500 (save-excursion
7501 (let ((end (save-excursion (outline-next-heading)
7502 (point-marker)))
7503 (prohibit (if (> diff 0)
7504 "^\\S-"
7505 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7506 col)
7507 (unless (save-excursion (end-of-line 1)
7508 (re-search-forward prohibit end t))
7509 (while (and (< (point) end)
7510 (re-search-forward "^[ \t]+" end t))
7511 (goto-char (match-end 0))
7512 (setq col (current-column))
7513 (if (< diff 0) (replace-match ""))
7514 (org-indent-to-column (+ diff col))))
7515 (move-marker end nil))))
7517 (defun org-convert-to-odd-levels ()
7518 "Convert an org-mode file with all levels allowed to one with odd levels.
7519 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7520 level 5 etc."
7521 (interactive)
7522 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7523 (let ((outline-level 'org-outline-level)
7524 (org-odd-levels-only nil) n)
7525 (save-excursion
7526 (goto-char (point-min))
7527 (while (re-search-forward "^\\*\\*+ " nil t)
7528 (setq n (- (length (match-string 0)) 2))
7529 (while (>= (setq n (1- n)) 0)
7530 (org-demote))
7531 (end-of-line 1))))))
7533 (defun org-convert-to-oddeven-levels ()
7534 "Convert an org-mode file with only odd levels to one with odd/even levels.
7535 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7536 file contains a section with an even level, conversion would
7537 destroy the structure of the file. An error is signaled in this
7538 case."
7539 (interactive)
7540 (goto-char (point-min))
7541 ;; First check if there are no even levels
7542 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7543 (org-show-context t)
7544 (error "Not all levels are odd in this file. Conversion not possible"))
7545 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7546 (let ((outline-regexp org-outline-regexp)
7547 (outline-level 'org-outline-level)
7548 (org-odd-levels-only nil) n)
7549 (save-excursion
7550 (goto-char (point-min))
7551 (while (re-search-forward "^\\*\\*+ " nil t)
7552 (setq n (/ (1- (length (match-string 0))) 2))
7553 (while (>= (setq n (1- n)) 0)
7554 (org-promote))
7555 (end-of-line 1))))))
7557 (defun org-tr-level (n)
7558 "Make N odd if required."
7559 (if org-odd-levels-only (1+ (/ n 2)) n))
7561 ;;; Vertical tree motion, cutting and pasting of subtrees
7563 (defun org-move-subtree-up (&optional arg)
7564 "Move the current subtree up past ARG headlines of the same level."
7565 (interactive "p")
7566 (org-move-subtree-down (- (prefix-numeric-value arg))))
7568 (defun org-move-subtree-down (&optional arg)
7569 "Move the current subtree down past ARG headlines of the same level."
7570 (interactive "p")
7571 (setq arg (prefix-numeric-value arg))
7572 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7573 'org-get-last-sibling))
7574 (ins-point (make-marker))
7575 (cnt (abs arg))
7576 (col (current-column))
7577 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7578 ;; Select the tree
7579 (org-back-to-heading)
7580 (setq beg0 (point))
7581 (save-excursion
7582 (setq ne-beg (org-back-over-empty-lines))
7583 (setq beg (point)))
7584 (save-match-data
7585 (save-excursion (outline-end-of-heading)
7586 (setq folded (outline-invisible-p)))
7587 (outline-end-of-subtree))
7588 (outline-next-heading)
7589 (setq ne-end (org-back-over-empty-lines))
7590 (setq end (point))
7591 (goto-char beg0)
7592 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7593 ;; include less whitespace
7594 (save-excursion
7595 (goto-char beg)
7596 (forward-line (- ne-beg ne-end))
7597 (setq beg (point))))
7598 ;; Find insertion point, with error handling
7599 (while (> cnt 0)
7600 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7601 (progn (goto-char beg0)
7602 (error "Cannot move past superior level or buffer limit")))
7603 (setq cnt (1- cnt)))
7604 (if (> arg 0)
7605 ;; Moving forward - still need to move over subtree
7606 (progn (org-end-of-subtree t t)
7607 (save-excursion
7608 (org-back-over-empty-lines)
7609 (or (bolp) (newline)))))
7610 (setq ne-ins (org-back-over-empty-lines))
7611 (move-marker ins-point (point))
7612 (setq txt (buffer-substring beg end))
7613 (org-save-markers-in-region beg end)
7614 (delete-region beg end)
7615 (org-remove-empty-overlays-at beg)
7616 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7617 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7618 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7619 (let ((bbb (point)))
7620 (insert-before-markers txt)
7621 (org-reinstall-markers-in-region bbb)
7622 (move-marker ins-point bbb))
7623 (or (bolp) (insert "\n"))
7624 (setq ins-end (point))
7625 (goto-char ins-point)
7626 (org-skip-whitespace)
7627 (when (and (< arg 0)
7628 (org-first-sibling-p)
7629 (> ne-ins ne-beg))
7630 ;; Move whitespace back to beginning
7631 (save-excursion
7632 (goto-char ins-end)
7633 (let ((kill-whole-line t))
7634 (kill-line (- ne-ins ne-beg)) (point)))
7635 (insert (make-string (- ne-ins ne-beg) ?\n)))
7636 (move-marker ins-point nil)
7637 (if folded
7638 (hide-subtree)
7639 (org-show-entry)
7640 (show-children)
7641 (org-cycle-hide-drawers 'children))
7642 (org-clean-visibility-after-subtree-move)
7643 ;; move back to the initial column we were at
7644 (move-to-column col)))
7646 (defvar org-subtree-clip ""
7647 "Clipboard for cut and paste of subtrees.
7648 This is actually only a copy of the kill, because we use the normal kill
7649 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7651 (defvar org-subtree-clip-folded nil
7652 "Was the last copied subtree folded?
7653 This is used to fold the tree back after pasting.")
7655 (defun org-cut-subtree (&optional n)
7656 "Cut the current subtree into the clipboard.
7657 With prefix arg N, cut this many sequential subtrees.
7658 This is a short-hand for marking the subtree and then cutting it."
7659 (interactive "p")
7660 (org-copy-subtree n 'cut))
7662 (defun org-copy-subtree (&optional n cut force-store-markers)
7663 "Cut the current subtree into the clipboard.
7664 With prefix arg N, cut this many sequential subtrees.
7665 This is a short-hand for marking the subtree and then copying it.
7666 If CUT is non-nil, actually cut the subtree.
7667 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7668 of some markers in the region, even if CUT is non-nil. This is
7669 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7670 (interactive "p")
7671 (let (beg end folded (beg0 (point)))
7672 (if (org-called-interactively-p 'any)
7673 (org-back-to-heading nil) ; take what looks like a subtree
7674 (org-back-to-heading t)) ; take what is really there
7675 (org-back-over-empty-lines)
7676 (setq beg (point))
7677 (skip-chars-forward " \t\r\n")
7678 (save-match-data
7679 (save-excursion (outline-end-of-heading)
7680 (setq folded (outline-invisible-p)))
7681 (condition-case nil
7682 (org-forward-heading-same-level (1- n) t)
7683 (error nil))
7684 (org-end-of-subtree t t))
7685 (org-back-over-empty-lines)
7686 (setq end (point))
7687 (goto-char beg0)
7688 (when (> end beg)
7689 (setq org-subtree-clip-folded folded)
7690 (when (or cut force-store-markers)
7691 (org-save-markers-in-region beg end))
7692 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7693 (setq org-subtree-clip (current-kill 0))
7694 (message "%s: Subtree(s) with %d characters"
7695 (if cut "Cut" "Copied")
7696 (length org-subtree-clip)))))
7698 (defun org-paste-subtree (&optional level tree for-yank)
7699 "Paste the clipboard as a subtree, with modification of headline level.
7700 The entire subtree is promoted or demoted in order to match a new headline
7701 level.
7703 If the cursor is at the beginning of a headline, the same level as
7704 that headline is used to paste the tree
7706 If not, the new level is derived from the *visible* headings
7707 before and after the insertion point, and taken to be the inferior headline
7708 level of the two. So if the previous visible heading is level 3 and the
7709 next is level 4 (or vice versa), level 4 will be used for insertion.
7710 This makes sure that the subtree remains an independent subtree and does
7711 not swallow low level entries.
7713 You can also force a different level, either by using a numeric prefix
7714 argument, or by inserting the heading marker by hand. For example, if the
7715 cursor is after \"*****\", then the tree will be shifted to level 5.
7717 If optional TREE is given, use this text instead of the kill ring.
7719 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7720 move back over whitespace before inserting, and move point to the end of
7721 the inserted text when done."
7722 (interactive "P")
7723 (setq tree (or tree (and kill-ring (current-kill 0))))
7724 (unless (org-kill-is-subtree-p tree)
7725 (error "%s"
7726 (substitute-command-keys
7727 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7728 (org-with-limited-levels
7729 (let* ((visp (not (outline-invisible-p)))
7730 (txt tree)
7731 (^re_ "\\(\\*+\\)[ \t]*")
7732 (old-level (if (string-match org-outline-regexp-bol txt)
7733 (- (match-end 0) (match-beginning 0) 1)
7734 -1))
7735 (force-level (cond (level (prefix-numeric-value level))
7736 ((and (looking-at "[ \t]*$")
7737 (string-match
7738 "^\\*+$" (buffer-substring
7739 (point-at-bol) (point))))
7740 (- (match-end 1) (match-beginning 1)))
7741 ((and (bolp)
7742 (looking-at org-outline-regexp))
7743 (- (match-end 0) (point) 1))))
7744 (previous-level (save-excursion
7745 (condition-case nil
7746 (progn
7747 (outline-previous-visible-heading 1)
7748 (if (looking-at ^re_)
7749 (- (match-end 0) (match-beginning 0) 1)
7751 (error 1))))
7752 (next-level (save-excursion
7753 (condition-case nil
7754 (progn
7755 (or (looking-at org-outline-regexp)
7756 (outline-next-visible-heading 1))
7757 (if (looking-at ^re_)
7758 (- (match-end 0) (match-beginning 0) 1)
7760 (error 1))))
7761 (new-level (or force-level (max previous-level next-level)))
7762 (shift (if (or (= old-level -1)
7763 (= new-level -1)
7764 (= old-level new-level))
7766 (- new-level old-level)))
7767 (delta (if (> shift 0) -1 1))
7768 (func (if (> shift 0) 'org-demote 'org-promote))
7769 (org-odd-levels-only nil)
7770 beg end newend)
7771 ;; Remove the forced level indicator
7772 (if force-level
7773 (delete-region (point-at-bol) (point)))
7774 ;; Paste
7775 (beginning-of-line (if (bolp) 1 2))
7776 (unless for-yank (org-back-over-empty-lines))
7777 (setq beg (point))
7778 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7779 (insert-before-markers txt)
7780 (unless (string-match "\n\\'" txt) (insert "\n"))
7781 (setq newend (point))
7782 (org-reinstall-markers-in-region beg)
7783 (setq end (point))
7784 (goto-char beg)
7785 (skip-chars-forward " \t\n\r")
7786 (setq beg (point))
7787 (if (and (outline-invisible-p) visp)
7788 (save-excursion (outline-show-heading)))
7789 ;; Shift if necessary
7790 (unless (= shift 0)
7791 (save-restriction
7792 (narrow-to-region beg end)
7793 (while (not (= shift 0))
7794 (org-map-region func (point-min) (point-max))
7795 (setq shift (+ delta shift)))
7796 (goto-char (point-min))
7797 (setq newend (point-max))))
7798 (when (or (org-called-interactively-p 'interactive) for-yank)
7799 (message "Clipboard pasted as level %d subtree" new-level))
7800 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7801 kill-ring
7802 (eq org-subtree-clip (current-kill 0))
7803 org-subtree-clip-folded)
7804 ;; The tree was folded before it was killed/copied
7805 (hide-subtree))
7806 (and for-yank (goto-char newend)))))
7808 (defun org-kill-is-subtree-p (&optional txt)
7809 "Check if the current kill is an outline subtree, or a set of trees.
7810 Returns nil if kill does not start with a headline, or if the first
7811 headline level is not the largest headline level in the tree.
7812 So this will actually accept several entries of equal levels as well,
7813 which is OK for `org-paste-subtree'.
7814 If optional TXT is given, check this string instead of the current kill."
7815 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7816 (re (org-get-limited-outline-regexp))
7817 (^re (concat "^" re))
7818 (start-level (and kill
7819 (string-match
7820 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7821 kill)
7822 (- (match-end 2) (match-beginning 2) 1)))
7823 (start (1+ (or (match-beginning 2) -1))))
7824 (if (not start-level)
7825 (progn
7826 nil) ;; does not even start with a heading
7827 (catch 'exit
7828 (while (setq start (string-match ^re kill (1+ start)))
7829 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7830 (throw 'exit nil)))
7831 t))))
7833 (defvar org-markers-to-move nil
7834 "Markers that should be moved with a cut-and-paste operation.
7835 Those markers are stored together with their positions relative to
7836 the start of the region.")
7838 (defun org-save-markers-in-region (beg end)
7839 "Check markers in region.
7840 If these markers are between BEG and END, record their position relative
7841 to BEG, so that after moving the block of text, we can put the markers back
7842 into place.
7843 This function gets called just before an entry or tree gets cut from the
7844 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7845 called immediately, to move the markers with the entries."
7846 (setq org-markers-to-move nil)
7847 (when (featurep 'org-clock)
7848 (org-clock-save-markers-for-cut-and-paste beg end))
7849 (when (featurep 'org-agenda)
7850 (org-agenda-save-markers-for-cut-and-paste beg end)))
7852 (defun org-check-and-save-marker (marker beg end)
7853 "Check if MARKER is between BEG and END.
7854 If yes, remember the marker and the distance to BEG."
7855 (when (and (marker-buffer marker)
7856 (equal (marker-buffer marker) (current-buffer)))
7857 (if (and (>= marker beg) (< marker end))
7858 (push (cons marker (- marker beg)) org-markers-to-move))))
7860 (defun org-reinstall-markers-in-region (beg)
7861 "Move all remembered markers to their position relative to BEG."
7862 (mapc (lambda (x)
7863 (move-marker (car x) (+ beg (cdr x))))
7864 org-markers-to-move)
7865 (setq org-markers-to-move nil))
7867 (defun org-narrow-to-subtree ()
7868 "Narrow buffer to the current subtree."
7869 (interactive)
7870 (save-excursion
7871 (save-match-data
7872 (org-with-limited-levels
7873 (narrow-to-region
7874 (progn (org-back-to-heading t) (point))
7875 (progn (org-end-of-subtree t t)
7876 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7877 (point)))))))
7879 (defun org-narrow-to-block ()
7880 "Narrow buffer to the current block."
7881 (interactive)
7882 (let* ((case-fold-search t)
7883 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7884 "^[ \t]*#\\+end_.*")))
7885 (if blockp
7886 (narrow-to-region (car blockp) (cdr blockp))
7887 (error "Not in a block"))))
7889 (eval-when-compile
7890 (defvar org-property-drawer-re))
7892 (defvar org-property-start-re) ;; defined below
7893 (defun org-clone-subtree-with-time-shift (n &optional shift)
7894 "Clone the task (subtree) at point N times.
7895 The clones will be inserted as siblings.
7897 In interactive use, the user will be prompted for the number of
7898 clones to be produced, and for a time SHIFT, which may be a
7899 repeater as used in time stamps, for example `+3d'.
7901 When a valid repeater is given and the entry contains any time
7902 stamps, the clones will become a sequence in time, with time
7903 stamps in the subtree shifted for each clone produced. If SHIFT
7904 is nil or the empty string, time stamps will be left alone. The
7905 ID property of the original subtree is removed.
7907 If the original subtree did contain time stamps with a repeater,
7908 the following will happen:
7909 - the repeater will be removed in each clone
7910 - an additional clone will be produced, with the current, unshifted
7911 date(s) in the entry.
7912 - the original entry will be placed *after* all the clones, with
7913 repeater intact.
7914 - the start days in the repeater in the original entry will be shifted
7915 to past the last clone.
7916 In this way you can spell out a number of instances of a repeating task,
7917 and still retain the repeater to cover future instances of the task."
7918 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7919 (let (beg end template task idprop
7920 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7921 (drawer-re org-drawer-regexp))
7922 (if (not (and (integerp n) (> n 0)))
7923 (error "Invalid number of replications %s" n))
7924 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7925 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7926 shift)))
7927 (error "Invalid shift specification %s" shift))
7928 (when doshift
7929 (setq shift-n (string-to-number (match-string 1 shift))
7930 shift-what (cdr (assoc (match-string 2 shift)
7931 '(("d" . day) ("w" . week)
7932 ("m" . month) ("y" . year))))))
7933 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7934 (setq nmin 1 nmax n)
7935 (org-back-to-heading t)
7936 (setq beg (point))
7937 (setq idprop (org-entry-get nil "ID"))
7938 (org-end-of-subtree t t)
7939 (or (bolp) (insert "\n"))
7940 (setq end (point))
7941 (setq template (buffer-substring beg end))
7942 (when (and doshift
7943 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7944 (delete-region beg end)
7945 (setq end beg)
7946 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7947 (goto-char end)
7948 (loop for n from nmin to nmax do
7949 ;; prepare clone
7950 (with-temp-buffer
7951 (insert template)
7952 (org-mode)
7953 (goto-char (point-min))
7954 (org-show-subtree)
7955 (and idprop (if org-clone-delete-id
7956 (org-entry-delete nil "ID")
7957 (org-id-get-create t)))
7958 (unless (= n 0)
7959 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7960 (kill-whole-line))
7961 (goto-char (point-min))
7962 (while (re-search-forward drawer-re nil t)
7963 (mapc (lambda (d)
7964 (org-remove-empty-drawer-at d (point))) org-drawers)))
7965 (goto-char (point-min))
7966 (when doshift
7967 (while (re-search-forward org-ts-regexp-both nil t)
7968 (org-timestamp-change (* n shift-n) shift-what))
7969 (unless (= n n-no-remove)
7970 (goto-char (point-min))
7971 (while (re-search-forward org-ts-regexp nil t)
7972 (save-excursion
7973 (goto-char (match-beginning 0))
7974 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7975 (delete-region (match-beginning 1) (match-end 1)))))))
7976 (setq task (buffer-string)))
7977 (insert task))
7978 (goto-char beg)))
7980 ;;; Outline Sorting
7982 (defun org-sort (with-case)
7983 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7984 Optional argument WITH-CASE means sort case-sensitively."
7985 (interactive "P")
7986 (cond
7987 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7988 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7990 (org-call-with-arg 'org-sort-entries with-case))))
7992 (defun org-sort-remove-invisible (s)
7993 (remove-text-properties 0 (length s) org-rm-props s)
7994 (while (string-match org-bracket-link-regexp s)
7995 (setq s (replace-match (if (match-end 2)
7996 (match-string 3 s)
7997 (match-string 1 s)) t t s)))
8000 (defvar org-priority-regexp) ; defined later in the file
8002 (defvar org-after-sorting-entries-or-items-hook nil
8003 "Hook that is run after a bunch of entries or items have been sorted.
8004 When children are sorted, the cursor is in the parent line when this
8005 hook gets called. When a region or a plain list is sorted, the cursor
8006 will be in the first entry of the sorted region/list.")
8008 (defun org-sort-entries
8009 (&optional with-case sorting-type getkey-func compare-func property)
8010 "Sort entries on a certain level of an outline tree.
8011 If there is an active region, the entries in the region are sorted.
8012 Else, if the cursor is before the first entry, sort the top-level items.
8013 Else, the children of the entry at point are sorted.
8015 Sorting can be alphabetically, numerically, by date/time as given by
8016 a time stamp, by a property or by priority.
8018 The command prompts for the sorting type unless it has been given to the
8019 function through the SORTING-TYPE argument, which needs to be a character,
8020 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8021 precise meaning of each character:
8023 n Numerically, by converting the beginning of the entry/item to a number.
8024 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8025 t By date/time, either the first active time stamp in the entry, or, if
8026 none exist, by the first inactive one.
8027 s By the scheduled date/time.
8028 d By deadline date/time.
8029 c By creation time, which is assumed to be the first inactive time stamp
8030 at the beginning of a line.
8031 p By priority according to the cookie.
8032 r By the value of a property.
8034 Capital letters will reverse the sort order.
8036 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8037 called with point at the beginning of the record. It must return either
8038 a string or a number that should serve as the sorting key for that record.
8040 Comparing entries ignores case by default. However, with an optional argument
8041 WITH-CASE, the sorting considers case as well."
8042 (interactive "P")
8043 (let ((case-func (if with-case 'identity 'downcase))
8044 start beg end stars re re2
8045 txt what tmp)
8046 ;; Find beginning and end of region to sort
8047 (cond
8048 ((org-region-active-p)
8049 ;; we will sort the region
8050 (setq end (region-end)
8051 what "region")
8052 (goto-char (region-beginning))
8053 (if (not (org-at-heading-p)) (outline-next-heading))
8054 (setq start (point)))
8055 ((or (org-at-heading-p)
8056 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8057 ;; we will sort the children of the current headline
8058 (org-back-to-heading)
8059 (setq start (point)
8060 end (progn (org-end-of-subtree t t)
8061 (or (bolp) (insert "\n"))
8062 (org-back-over-empty-lines)
8063 (point))
8064 what "children")
8065 (goto-char start)
8066 (show-subtree)
8067 (outline-next-heading))
8069 ;; we will sort the top-level entries in this file
8070 (goto-char (point-min))
8071 (or (org-at-heading-p) (outline-next-heading))
8072 (setq start (point))
8073 (goto-char (point-max))
8074 (beginning-of-line 1)
8075 (when (looking-at ".*?\\S-")
8076 ;; File ends in a non-white line
8077 (end-of-line 1)
8078 (insert "\n"))
8079 (setq end (point-max))
8080 (setq what "top-level")
8081 (goto-char start)
8082 (show-all)))
8084 (setq beg (point))
8085 (if (>= beg end) (error "Nothing to sort"))
8087 (looking-at "\\(\\*+\\)")
8088 (setq stars (match-string 1)
8089 re (concat "^" (regexp-quote stars) " +")
8090 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8091 txt (buffer-substring beg end))
8092 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8093 (if (and (not (equal stars "*")) (string-match re2 txt))
8094 (error "Region to sort contains a level above the first entry"))
8096 (unless sorting-type
8097 (message
8098 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8099 [t]ime [s]cheduled [d]eadline [c]reated
8100 A/N/T/S/D/C/P/O/F means reversed:"
8101 what)
8102 (setq sorting-type (read-char-exclusive))
8104 (and (= (downcase sorting-type) ?f)
8105 (setq getkey-func
8106 (org-icompleting-read "Sort using function: "
8107 obarray 'fboundp t nil nil))
8108 (setq getkey-func (intern getkey-func)))
8110 (and (= (downcase sorting-type) ?r)
8111 (setq property
8112 (org-icompleting-read "Property: "
8113 (mapcar 'list (org-buffer-property-keys t))
8114 nil t))))
8116 (message "Sorting entries...")
8118 (save-restriction
8119 (narrow-to-region start end)
8120 (let ((dcst (downcase sorting-type))
8121 (case-fold-search nil)
8122 (now (current-time)))
8123 (sort-subr
8124 (/= dcst sorting-type)
8125 ;; This function moves to the beginning character of the "record" to
8126 ;; be sorted.
8127 (lambda nil
8128 (if (re-search-forward re nil t)
8129 (goto-char (match-beginning 0))
8130 (goto-char (point-max))))
8131 ;; This function moves to the last character of the "record" being
8132 ;; sorted.
8133 (lambda nil
8134 (save-match-data
8135 (condition-case nil
8136 (outline-forward-same-level 1)
8137 (error
8138 (goto-char (point-max))))))
8139 ;; This function returns the value that gets sorted against.
8140 (lambda nil
8141 (cond
8142 ((= dcst ?n)
8143 (if (looking-at org-complex-heading-regexp)
8144 (string-to-number (match-string 4))
8145 nil))
8146 ((= dcst ?a)
8147 (if (looking-at org-complex-heading-regexp)
8148 (funcall case-func (match-string 4))
8149 nil))
8150 ((= dcst ?t)
8151 (let ((end (save-excursion (outline-next-heading) (point))))
8152 (if (or (re-search-forward org-ts-regexp end t)
8153 (re-search-forward org-ts-regexp-both end t))
8154 (org-time-string-to-seconds (match-string 0))
8155 (org-float-time now))))
8156 ((= dcst ?c)
8157 (let ((end (save-excursion (outline-next-heading) (point))))
8158 (if (re-search-forward
8159 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8160 end t)
8161 (org-time-string-to-seconds (match-string 0))
8162 (org-float-time now))))
8163 ((= dcst ?s)
8164 (let ((end (save-excursion (outline-next-heading) (point))))
8165 (if (re-search-forward org-scheduled-time-regexp end t)
8166 (org-time-string-to-seconds (match-string 1))
8167 (org-float-time now))))
8168 ((= dcst ?d)
8169 (let ((end (save-excursion (outline-next-heading) (point))))
8170 (if (re-search-forward org-deadline-time-regexp end t)
8171 (org-time-string-to-seconds (match-string 1))
8172 (org-float-time now))))
8173 ((= dcst ?p)
8174 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8175 (string-to-char (match-string 2))
8176 org-default-priority))
8177 ((= dcst ?r)
8178 (or (org-entry-get nil property) ""))
8179 ((= dcst ?o)
8180 (if (looking-at org-complex-heading-regexp)
8181 (- 9999 (length (member (match-string 2)
8182 org-todo-keywords-1)))))
8183 ((= dcst ?f)
8184 (if getkey-func
8185 (progn
8186 (setq tmp (funcall getkey-func))
8187 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8188 tmp)
8189 (error "Invalid key function `%s'" getkey-func)))
8190 (t (error "Invalid sorting type `%c'" sorting-type))))
8192 (cond
8193 ((= dcst ?a) 'string<)
8194 ((= dcst ?f) compare-func)
8195 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8196 (run-hooks 'org-after-sorting-entries-or-items-hook)
8197 (message "Sorting entries...done")))
8199 (defun org-do-sort (table what &optional with-case sorting-type)
8200 "Sort TABLE of WHAT according to SORTING-TYPE.
8201 The user will be prompted for the SORTING-TYPE if the call to this
8202 function does not specify it. WHAT is only for the prompt, to indicate
8203 what is being sorted. The sorting key will be extracted from
8204 the car of the elements of the table.
8205 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8206 (unless sorting-type
8207 (message
8208 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8209 what)
8210 (setq sorting-type (read-char-exclusive)))
8211 (let ((dcst (downcase sorting-type))
8212 extractfun comparefun)
8213 ;; Define the appropriate functions
8214 (cond
8215 ((= dcst ?n)
8216 (setq extractfun 'string-to-number
8217 comparefun (if (= dcst sorting-type) '< '>)))
8218 ((= dcst ?a)
8219 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8220 (lambda(x) (downcase (org-sort-remove-invisible x))))
8221 comparefun (if (= dcst sorting-type)
8222 'string<
8223 (lambda (a b) (and (not (string< a b))
8224 (not (string= a b)))))))
8225 ((= dcst ?t)
8226 (setq extractfun
8227 (lambda (x)
8228 (if (or (string-match org-ts-regexp x)
8229 (string-match org-ts-regexp-both x))
8230 (org-float-time
8231 (org-time-string-to-time (match-string 0 x)))
8233 comparefun (if (= dcst sorting-type) '< '>)))
8234 (t (error "Invalid sorting type `%c'" sorting-type)))
8236 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8237 table)
8238 (lambda (a b) (funcall comparefun (car a) (car b))))))
8241 ;;; The orgstruct minor mode
8243 ;; Define a minor mode which can be used in other modes in order to
8244 ;; integrate the org-mode structure editing commands.
8246 ;; This is really a hack, because the org-mode structure commands use
8247 ;; keys which normally belong to the major mode. Here is how it
8248 ;; works: The minor mode defines all the keys necessary to operate the
8249 ;; structure commands, but wraps the commands into a function which
8250 ;; tests if the cursor is currently at a headline or a plain list
8251 ;; item. If that is the case, the structure command is used,
8252 ;; temporarily setting many Org-mode variables like regular
8253 ;; expressions for filling etc. However, when any of those keys is
8254 ;; used at a different location, function uses `key-binding' to look
8255 ;; up if the key has an associated command in another currently active
8256 ;; keymap (minor modes, major mode, global), and executes that
8257 ;; command. There might be problems if any of the keys is otherwise
8258 ;; used as a prefix key.
8260 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8261 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8262 ;; addresses this by checking explicitly for both bindings.
8264 (defvar orgstruct-mode-map (make-sparse-keymap)
8265 "Keymap for the minor `orgstruct-mode'.")
8267 (defvar org-local-vars nil
8268 "List of local variables, for use by `orgstruct-mode'.")
8270 ;;;###autoload
8271 (define-minor-mode orgstruct-mode
8272 "Toggle the minor mode `orgstruct-mode'.
8273 This mode is for using Org-mode structure commands in other
8274 modes. The following keys behave as if Org-mode were active, if
8275 the cursor is on a headline, or on a plain list item (both as
8276 defined by Org-mode).
8278 M-up Move entry/item up
8279 M-down Move entry/item down
8280 M-left Promote
8281 M-right Demote
8282 M-S-up Move entry/item up
8283 M-S-down Move entry/item down
8284 M-S-left Promote subtree
8285 M-S-right Demote subtree
8286 M-q Fill paragraph and items like in Org-mode
8287 C-c ^ Sort entries
8288 C-c - Cycle list bullet
8289 TAB Cycle item visibility
8290 M-RET Insert new heading/item
8291 S-M-RET Insert new TODO heading / Checkbox item
8292 C-c C-c Set tags / toggle checkbox"
8293 nil " OrgStruct" nil
8294 (org-load-modules-maybe)
8295 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8297 ;;;###autoload
8298 (defun turn-on-orgstruct ()
8299 "Unconditionally turn on `orgstruct-mode'."
8300 (orgstruct-mode 1))
8302 (defvar org-fb-vars nil)
8303 (make-variable-buffer-local 'org-fb-vars)
8304 (defun orgstruct++-mode (&optional arg)
8305 "Toggle `orgstruct-mode', the enhanced version of it.
8306 In addition to setting orgstruct-mode, this also exports all
8307 indentation and autofilling variables from org-mode into the
8308 buffer. It will also recognize item context in multiline items."
8309 (interactive "P")
8310 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8311 (if (< arg 1)
8312 (progn (orgstruct-mode -1)
8313 (mapc (lambda(v)
8314 (org-set-local (car v)
8315 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8316 org-fb-vars))
8317 (orgstruct-mode 1)
8318 (setq org-fb-vars nil)
8319 (let (var val)
8320 (mapc
8321 (lambda (x)
8322 (when (string-match
8323 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8324 (symbol-name (car x)))
8325 (setq var (car x) val (nth 1 x))
8326 (push (list var `(quote ,(eval var))) org-fb-vars)
8327 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8328 org-local-vars)
8329 (org-set-local 'orgstruct-is-++ t))))
8331 (defvar orgstruct-is-++ nil
8332 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8333 (make-variable-buffer-local 'orgstruct-is-++)
8335 ;;;###autoload
8336 (defun turn-on-orgstruct++ ()
8337 "Unconditionally turn on `orgstruct++-mode'."
8338 (orgstruct++-mode 1))
8340 (defun orgstruct-error ()
8341 "Error when there is no default binding for a structure key."
8342 (interactive)
8343 (error "This key has no function outside structure elements"))
8345 (defun orgstruct-setup ()
8346 "Setup orgstruct keymaps."
8347 (let ((nfunc 0)
8348 (bindings
8349 (list
8350 '([(meta up)] org-metaup)
8351 '([(meta down)] org-metadown)
8352 '([(meta left)] org-metaleft)
8353 '([(meta right)] org-metaright)
8354 '([(meta shift up)] org-shiftmetaup)
8355 '([(meta shift down)] org-shiftmetadown)
8356 '([(meta shift left)] org-shiftmetaleft)
8357 '([(meta shift right)] org-shiftmetaright)
8358 '([?\e (up)] org-metaup)
8359 '([?\e (down)] org-metadown)
8360 '([?\e (left)] org-metaleft)
8361 '([?\e (right)] org-metaright)
8362 '([?\e (shift up)] org-shiftmetaup)
8363 '([?\e (shift down)] org-shiftmetadown)
8364 '([?\e (shift left)] org-shiftmetaleft)
8365 '([?\e (shift right)] org-shiftmetaright)
8366 '([(shift up)] org-shiftup)
8367 '([(shift down)] org-shiftdown)
8368 '([(shift left)] org-shiftleft)
8369 '([(shift right)] org-shiftright)
8370 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8371 '("\M-q" fill-paragraph)
8372 '("\C-c^" org-sort)
8373 '("\C-c-" org-cycle-list-bullet)))
8374 elt key fun cmd)
8375 (while (setq elt (pop bindings))
8376 (setq nfunc (1+ nfunc))
8377 (setq key (org-key (car elt))
8378 fun (nth 1 elt)
8379 cmd (orgstruct-make-binding fun nfunc key))
8380 (org-defkey orgstruct-mode-map key cmd))
8382 ;; Prevent an error for users who forgot to make autoloads
8383 (require 'org-element)
8385 ;; Special treatment needed for TAB and RET
8386 (org-defkey orgstruct-mode-map [(tab)]
8387 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8388 (org-defkey orgstruct-mode-map "\C-i"
8389 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8391 (org-defkey orgstruct-mode-map "\M-\C-m"
8392 (orgstruct-make-binding 'org-insert-heading 105
8393 "\M-\C-m" [(meta return)]))
8394 (org-defkey orgstruct-mode-map [(meta return)]
8395 (orgstruct-make-binding 'org-insert-heading 106
8396 [(meta return)] "\M-\C-m"))
8398 (org-defkey orgstruct-mode-map [(shift meta return)]
8399 (orgstruct-make-binding 'org-insert-todo-heading 107
8400 [(meta return)] "\M-\C-m"))
8402 (org-defkey orgstruct-mode-map "\e\C-m"
8403 (orgstruct-make-binding 'org-insert-heading 108
8404 "\e\C-m" [?\e (return)]))
8405 (org-defkey orgstruct-mode-map [?\e (return)]
8406 (orgstruct-make-binding 'org-insert-heading 109
8407 [?\e (return)] "\e\C-m"))
8408 (org-defkey orgstruct-mode-map [?\e (shift return)]
8409 (orgstruct-make-binding 'org-insert-todo-heading 110
8410 [?\e (return)] "\e\C-m"))
8412 (unless org-local-vars
8413 (setq org-local-vars (org-get-local-variables)))
8417 (defun orgstruct-make-binding (fun n &rest keys)
8418 "Create a function for binding in the structure minor mode.
8419 FUN is the command to call inside a table. N is used to create a unique
8420 command name. KEYS are keys that should be checked in for a command
8421 to execute outside of tables."
8422 (eval
8423 (list 'defun
8424 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8425 '(arg)
8426 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8427 "Outside of structure, run the binding of `"
8428 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8429 "'.")
8430 '(interactive "p")
8431 (list 'if
8432 `(org-context-p 'headline 'item
8433 (and orgstruct-is-++
8434 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8435 'item-body))
8436 (list 'org-run-like-in-org-mode (list 'quote fun))
8437 (list 'let '(orgstruct-mode)
8438 (list 'call-interactively
8439 (append '(or)
8440 (mapcar (lambda (k)
8441 (list 'key-binding k))
8442 keys)
8443 '('orgstruct-error))))))))
8445 (defun org-contextualize-keys (alist contexts)
8446 "Return valid elements in ALIST depending on CONTEXTS.
8448 `org-agenda-custom-commands' or `org-capture-templates' are the
8449 values used for ALIST, and `org-agenda-custom-commands-contexts'
8450 or `org-capture-templates-contexts' are the associated contexts
8451 definitions."
8452 (let ((contexts
8453 ;; normalize contexts
8454 (mapcar
8455 (lambda(c) (cond ((listp (cadr c))
8456 (list (car c) (car c) (cadr c)))
8457 ((string= "" (cadr c))
8458 (list (car c) (car c) (caddr c)))
8459 (t c))) contexts))
8460 (a alist) c r s)
8461 ;; loop over all commands or templates
8462 (while (setq c (pop a))
8463 (let (vrules repl)
8464 (cond
8465 ((not (assoc (car c) contexts))
8466 (push c r))
8467 ((and (assoc (car c) contexts)
8468 (setq vrules (org-contextualize-validate-key
8469 (car c) contexts)))
8470 (mapc (lambda (vr)
8471 (when (not (equal (car vr) (cadr vr)))
8472 (setq repl vr))) vrules)
8473 (if (not repl) (push c r)
8474 (push (cadr repl) s)
8475 (push
8476 (cons (car c)
8477 (cdr (or (assoc (cadr repl) alist)
8478 (error "Undefined key `%s' as contextual replacement for `%s'"
8479 (cadr repl) (car c)))))
8480 r))))))
8481 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8482 (delq
8484 (delete-dups
8485 (mapcar (lambda (x)
8486 (let ((tpl (car x)))
8487 (when (not (delq
8489 (mapcar (lambda(y)
8490 (equal y tpl)) s))) x)))
8491 (reverse r))))))
8493 (defun org-contextualize-validate-key (key contexts)
8494 "Check CONTEXTS for agenda or capture KEY."
8495 (let (r rr res)
8496 (while (setq r (pop contexts))
8497 (mapc
8498 (lambda (rr)
8499 (when
8500 (and (equal key (car r))
8501 (if (functionp rr) (funcall rr)
8502 (or (and (eq (car rr) 'in-file)
8503 (buffer-file-name)
8504 (string-match (cdr rr) (buffer-file-name)))
8505 (and (eq (car rr) 'in-mode)
8506 (string-match (cdr rr) (symbol-name major-mode)))
8507 (when (and (eq (car rr) 'not-in-file)
8508 (buffer-file-name))
8509 (not (string-match (cdr rr) (buffer-file-name))))
8510 (when (eq (car rr) 'not-in-mode)
8511 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8512 (push r res)))
8513 (car (last r))))
8514 (delete-dups (delq nil res))))
8516 (defun org-context-p (&rest contexts)
8517 "Check if local context is any of CONTEXTS.
8518 Possible values in the list of contexts are `table', `headline', and `item'."
8519 (let ((pos (point)))
8520 (goto-char (point-at-bol))
8521 (prog1 (or (and (memq 'table contexts)
8522 (looking-at "[ \t]*|"))
8523 (and (memq 'headline contexts)
8524 (looking-at org-outline-regexp))
8525 (and (memq 'item contexts)
8526 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8527 (and (memq 'item-body contexts)
8528 (org-in-item-p)))
8529 (goto-char pos))))
8531 (defun org-get-local-variables ()
8532 "Return a list of all local variables in an Org mode buffer."
8533 (let (varlist)
8534 (with-current-buffer (get-buffer-create "*Org tmp*")
8535 (erase-buffer)
8536 (org-mode)
8537 (setq varlist (buffer-local-variables)))
8538 (kill-buffer "*Org tmp*")
8539 (delq nil
8540 (mapcar
8541 (lambda (x)
8542 (setq x
8543 (if (symbolp x)
8544 (list x)
8545 (list (car x) (list 'quote (cdr x)))))
8546 (if (string-match
8547 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8548 (symbol-name (car x)))
8549 x nil))
8550 varlist))))
8552 (defun org-clone-local-variables (from-buffer &optional regexp)
8553 "Clone local variables from FROM-BUFFER.
8554 Optional argument REGEXP selects variables to clone."
8555 (mapc
8556 (lambda (pair)
8557 (and (symbolp (car pair))
8558 (or (null regexp)
8559 (string-match regexp (symbol-name (car pair))))
8560 (set (make-local-variable (car pair))
8561 (cdr pair))))
8562 (buffer-local-variables from-buffer)))
8564 ;;;###autoload
8565 (defun org-run-like-in-org-mode (cmd)
8566 "Run a command, pretending that the current buffer is in Org-mode.
8567 This will temporarily bind local variables that are typically bound in
8568 Org-mode to the values they have in Org-mode, and then interactively
8569 call CMD."
8570 (org-load-modules-maybe)
8571 (unless org-local-vars
8572 (setq org-local-vars (org-get-local-variables)))
8573 (eval (list 'let org-local-vars
8574 (list 'call-interactively (list 'quote cmd)))))
8576 ;;;; Archiving
8578 (defun org-get-category (&optional pos force-refresh)
8579 "Get the category applying to position POS."
8580 (save-match-data
8581 (if force-refresh (org-refresh-category-properties))
8582 (let ((pos (or pos (point))))
8583 (or (get-text-property pos 'org-category)
8584 (progn (org-refresh-category-properties)
8585 (get-text-property pos 'org-category))))))
8587 (defun org-refresh-category-properties ()
8588 "Refresh category text properties in the buffer."
8589 (let ((case-fold-search t)
8590 (inhibit-read-only t)
8591 (def-cat (cond
8592 ((null org-category)
8593 (if buffer-file-name
8594 (file-name-sans-extension
8595 (file-name-nondirectory buffer-file-name))
8596 "???"))
8597 ((symbolp org-category) (symbol-name org-category))
8598 (t org-category)))
8599 beg end cat pos optionp)
8600 (org-unmodified
8601 (save-excursion
8602 (save-restriction
8603 (widen)
8604 (goto-char (point-min))
8605 (put-text-property (point) (point-max) 'org-category def-cat)
8606 (while (re-search-forward
8607 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8608 (setq pos (match-end 0)
8609 optionp (equal (char-after (match-beginning 0)) ?#)
8610 cat (org-trim (match-string 2)))
8611 (if optionp
8612 (setq beg (point-at-bol) end (point-max))
8613 (org-back-to-heading t)
8614 (setq beg (point) end (org-end-of-subtree t t)))
8615 (put-text-property beg end 'org-category cat)
8616 (put-text-property beg end 'org-category-position beg)
8617 (goto-char pos)))))))
8620 ;;;; Link Stuff
8622 ;;; Link abbreviations
8624 (defun org-link-expand-abbrev (link)
8625 "Apply replacements as defined in `org-link-abbrev-alist'."
8626 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8627 (let* ((key (match-string 1 link))
8628 (as (or (assoc key org-link-abbrev-alist-local)
8629 (assoc key org-link-abbrev-alist)))
8630 (tag (and (match-end 2) (match-string 3 link)))
8631 rpl)
8632 (if (not as)
8633 link
8634 (setq rpl (cdr as))
8635 (cond
8636 ((symbolp rpl) (funcall rpl tag))
8637 ((string-match "%(\\([^)]+\\))" rpl)
8638 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8639 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8640 ((string-match "%h" rpl)
8641 (replace-match (url-hexify-string (or tag "")) t t rpl))
8642 (t (concat rpl tag)))))
8643 link))
8645 ;;; Storing and inserting links
8647 (defvar org-insert-link-history nil
8648 "Minibuffer history for links inserted with `org-insert-link'.")
8650 (defvar org-stored-links nil
8651 "Contains the links stored with `org-store-link'.")
8653 (defvar org-store-link-plist nil
8654 "Plist with info about the most recently link created with `org-store-link'.")
8656 (defvar org-link-protocols nil
8657 "Link protocols added to Org-mode using `org-add-link-type'.")
8659 (defvar org-store-link-functions nil
8660 "List of functions that are called to create and store a link.
8661 Each function will be called in turn until one returns a non-nil
8662 value. Each function should check if it is responsible for creating
8663 this link (for example by looking at the major mode).
8664 If not, it must exit and return nil.
8665 If yes, it should return a non-nil value after a calling
8666 `org-store-link-props' with a list of properties and values.
8667 Special properties are:
8669 :type The link prefix, like \"http\". This must be given.
8670 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8671 This is obligatory as well.
8672 :description Optional default description for the second pair
8673 of brackets in an Org-mode link. The user can still change
8674 this when inserting this link into an Org-mode buffer.
8676 In addition to these, any additional properties can be specified
8677 and then used in capture templates.")
8679 (defun org-add-link-type (type &optional follow export)
8680 "Add TYPE to the list of `org-link-types'.
8681 Re-compute all regular expressions depending on `org-link-types'
8683 FOLLOW and EXPORT are two functions.
8685 FOLLOW should take the link path as the single argument and do whatever
8686 is necessary to follow the link, for example find a file or display
8687 a mail message.
8689 EXPORT should format the link path for export to one of the export formats.
8690 It should be a function accepting three arguments:
8692 path the path of the link, the text after the prefix (like \"http:\")
8693 desc the description of the link, if any, or a description added by
8694 org-export-normalize-links if there is none
8695 format the export format, a symbol like `html' or `latex' or `ascii'..
8697 The function may use the FORMAT information to return different values
8698 depending on the format. The return value will be put literally into
8699 the exported file. If the return value is nil, this means Org should
8700 do what it normally does with links which do not have EXPORT defined.
8702 Org-mode has a built-in default for exporting links. If you are happy with
8703 this default, there is no need to define an export function for the link
8704 type. For a simple example of an export function, see `org-bbdb.el'."
8705 (add-to-list 'org-link-types type t)
8706 (org-make-link-regexps)
8707 (if (assoc type org-link-protocols)
8708 (setcdr (assoc type org-link-protocols) (list follow export))
8709 (push (list type follow export) org-link-protocols)))
8711 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8712 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8714 ;;;###autoload
8715 (defun org-store-link (arg)
8716 "\\<org-mode-map>Store an org-link to the current location.
8717 This link is added to `org-stored-links' and can later be inserted
8718 into an org-buffer with \\[org-insert-link].
8720 For some link types, a prefix arg is interpreted:
8721 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8722 For file links, arg negates `org-context-in-file-links'."
8723 (interactive "P")
8724 (org-load-modules-maybe)
8725 (setq org-store-link-plist nil) ; reset
8726 (org-with-limited-levels
8727 (let (link cpltxt desc description search txt custom-id agenda-link)
8728 (cond
8730 ((run-hook-with-args-until-success 'org-store-link-functions)
8731 (setq link (plist-get org-store-link-plist :link)
8732 desc (or (plist-get org-store-link-plist :description) link)))
8734 ((org-src-edit-buffer-p)
8735 (let (label gc)
8736 (while (or (not label)
8737 (save-excursion
8738 (save-restriction
8739 (widen)
8740 (goto-char (point-min))
8741 (re-search-forward
8742 (regexp-quote (format org-coderef-label-format label))
8743 nil t))))
8744 (when label (message "Label exists already") (sit-for 2))
8745 (setq label (read-string "Code line label: " label)))
8746 (end-of-line 1)
8747 (setq link (format org-coderef-label-format label))
8748 (setq gc (- 79 (length link)))
8749 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8750 (insert link)
8751 (setq link (concat "(" label ")") desc nil)))
8753 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8754 ;; We are in the agenda, link to referenced location
8755 (let ((m (or (get-text-property (point) 'org-hd-marker)
8756 (get-text-property (point) 'org-marker))))
8757 (when m
8758 (org-with-point-at m
8759 (setq agenda-link
8760 (if (org-called-interactively-p 'any)
8761 (call-interactively 'org-store-link)
8762 (org-store-link nil)))))))
8764 ((eq major-mode 'calendar-mode)
8765 (let ((cd (calendar-cursor-to-date)))
8766 (setq link
8767 (format-time-string
8768 (car org-time-stamp-formats)
8769 (apply 'encode-time
8770 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8771 nil nil nil))))
8772 (org-store-link-props :type "calendar" :date cd)))
8774 ((eq major-mode 'help-mode)
8775 (setq link (concat "help:" (save-excursion
8776 (goto-char (point-min))
8777 (looking-at "^[^ ]+")
8778 (match-string 0))))
8779 (org-store-link-props :type "help"))
8781 ((eq major-mode 'w3-mode)
8782 (setq cpltxt (if (and (buffer-name)
8783 (not (string-match "Untitled" (buffer-name))))
8784 (buffer-name)
8785 (url-view-url t))
8786 link (url-view-url t))
8787 (org-store-link-props :type "w3" :url (url-view-url t)))
8789 ((eq major-mode 'w3m-mode)
8790 (setq cpltxt (or w3m-current-title w3m-current-url)
8791 link w3m-current-url)
8792 (org-store-link-props :type "w3m" :url (url-view-url t)))
8794 ((setq search (run-hook-with-args-until-success
8795 'org-create-file-search-functions))
8796 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8797 "::" search))
8798 (setq cpltxt (or description link)))
8800 ((eq major-mode 'image-mode)
8801 (setq cpltxt (concat "file:"
8802 (abbreviate-file-name buffer-file-name))
8803 link cpltxt)
8804 (org-store-link-props :type "image" :file buffer-file-name))
8806 ((eq major-mode 'dired-mode)
8807 ;; link to the file in the current line
8808 (let ((file (dired-get-filename nil t)))
8809 (setq file (if file
8810 (abbreviate-file-name
8811 (expand-file-name (dired-get-filename nil t)))
8812 ;; otherwise, no file so use current directory.
8813 default-directory))
8814 (setq cpltxt (concat "file:" file)
8815 link cpltxt)))
8817 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8818 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8819 (cond
8820 ((org-in-regexp "<<\\(.*?\\)>>")
8821 (setq cpltxt
8822 (concat "file:"
8823 (abbreviate-file-name
8824 (buffer-file-name (buffer-base-buffer)))
8825 "::" (match-string 1))
8826 link cpltxt))
8827 ((and (featurep 'org-id)
8828 (or (eq org-link-to-org-use-id t)
8829 (and (org-called-interactively-p 'any)
8830 (or (eq org-link-to-org-use-id 'create-if-interactive)
8831 (and (eq org-link-to-org-use-id
8832 'create-if-interactive-and-no-custom-id)
8833 (not custom-id))))
8834 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8835 ;; We can make a link using the ID.
8836 (setq link (condition-case nil
8837 (prog1 (org-id-store-link)
8838 (setq desc (plist-get org-store-link-plist :description)))
8839 (error
8840 ;; probably before first headline, link to file only
8841 (concat "file:"
8842 (abbreviate-file-name
8843 (buffer-file-name (buffer-base-buffer))))))))
8845 ;; Just link to current headline
8846 (setq cpltxt (concat "file:"
8847 (abbreviate-file-name
8848 (buffer-file-name (buffer-base-buffer)))))
8849 ;; Add a context search string
8850 (when (org-xor org-context-in-file-links arg)
8851 (setq txt (cond
8852 ((org-at-heading-p) nil)
8853 ((org-region-active-p)
8854 (buffer-substring (region-beginning) (region-end)))))
8855 (when (or (null txt) (string-match "\\S-" txt))
8856 (setq cpltxt
8857 (concat cpltxt "::"
8858 (condition-case nil
8859 (org-make-org-heading-search-string txt)
8860 (error "")))
8861 desc (or (nth 4 (ignore-errors
8862 (org-heading-components))) "NONE"))))
8863 (if (string-match "::\\'" cpltxt)
8864 (setq cpltxt (substring cpltxt 0 -2)))
8865 (setq link cpltxt))))
8867 ((buffer-file-name (buffer-base-buffer))
8868 ;; Just link to this file here.
8869 (setq cpltxt (concat "file:"
8870 (abbreviate-file-name
8871 (buffer-file-name (buffer-base-buffer)))))
8872 ;; Add a context string
8873 (when (org-xor org-context-in-file-links arg)
8874 (setq txt (if (org-region-active-p)
8875 (buffer-substring (region-beginning) (region-end))
8876 (buffer-substring (point-at-bol) (point-at-eol))))
8877 ;; Only use search option if there is some text.
8878 (when (string-match "\\S-" txt)
8879 (setq cpltxt
8880 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8881 desc "NONE")))
8882 (setq link cpltxt))
8884 ((org-called-interactively-p 'interactive)
8885 (error "Cannot link to a buffer which is not visiting a file"))
8887 (t (setq link nil)))
8889 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8890 (setq link (or link cpltxt)
8891 desc (or desc cpltxt))
8892 (if (equal desc "NONE") (setq desc nil))
8894 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8895 (progn
8896 (setq org-stored-links
8897 (cons (list link desc) org-stored-links))
8898 (message "Stored: %s" (or desc link))
8899 (when custom-id
8900 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8901 "::#" custom-id))
8902 (setq org-stored-links
8903 (cons (list link desc) org-stored-links))))
8904 (or agenda-link (and link (org-make-link-string link desc)))))))
8906 (defun org-store-link-props (&rest plist)
8907 "Store link properties, extract names and addresses."
8908 (let (x adr)
8909 (when (setq x (plist-get plist :from))
8910 (setq adr (mail-extract-address-components x))
8911 (setq plist (plist-put plist :fromname (car adr)))
8912 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8913 (when (setq x (plist-get plist :to))
8914 (setq adr (mail-extract-address-components x))
8915 (setq plist (plist-put plist :toname (car adr)))
8916 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8917 (let ((from (plist-get plist :from))
8918 (to (plist-get plist :to)))
8919 (when (and from to org-from-is-user-regexp)
8920 (setq plist
8921 (plist-put plist :fromto
8922 (if (string-match org-from-is-user-regexp from)
8923 (concat "to %t")
8924 (concat "from %f"))))))
8925 (setq org-store-link-plist plist))
8927 (defun org-add-link-props (&rest plist)
8928 "Add these properties to the link property list."
8929 (let (key value)
8930 (while plist
8931 (setq key (pop plist) value (pop plist))
8932 (setq org-store-link-plist
8933 (plist-put org-store-link-plist key value)))))
8935 (defun org-email-link-description (&optional fmt)
8936 "Return the description part of an email link.
8937 This takes information from `org-store-link-plist' and formats it
8938 according to FMT (default from `org-email-link-description-format')."
8939 (setq fmt (or fmt org-email-link-description-format))
8940 (let* ((p org-store-link-plist)
8941 (to (plist-get p :toaddress))
8942 (from (plist-get p :fromaddress))
8943 (table
8944 (list
8945 (cons "%c" (plist-get p :fromto))
8946 (cons "%F" (plist-get p :from))
8947 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8948 (cons "%T" (plist-get p :to))
8949 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8950 (cons "%s" (plist-get p :subject))
8951 (cons "%d" (plist-get p :date))
8952 (cons "%m" (plist-get p :message-id)))))
8953 (when (string-match "%c" fmt)
8954 ;; Check if the user wrote this message
8955 (if (and org-from-is-user-regexp from to
8956 (save-match-data (string-match org-from-is-user-regexp from)))
8957 (setq fmt (replace-match "to %t" t t fmt))
8958 (setq fmt (replace-match "from %f" t t fmt))))
8959 (org-replace-escapes fmt table)))
8961 (defun org-make-org-heading-search-string (&optional string heading)
8962 "Make search string for STRING or current headline."
8963 (interactive)
8964 (let ((s (or string (org-get-heading)))
8965 (lines org-context-in-file-links))
8966 (unless (and string (not heading))
8967 ;; We are using a headline, clean up garbage in there.
8968 (if (string-match org-todo-regexp s)
8969 (setq s (replace-match "" t t s)))
8970 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8971 (setq s (replace-match "" t t s)))
8972 (setq s (org-trim s))
8973 (if (string-match (concat "^\\(" org-quote-string "\\|"
8974 org-comment-string "\\)") s)
8975 (setq s (replace-match "" t t s)))
8976 (while (string-match org-ts-regexp s)
8977 (setq s (replace-match "" t t s))))
8978 (or string (setq s (concat "*" s))) ; Add * for headlines
8979 (when (and string (integerp lines) (> lines 0))
8980 (let ((slines (org-split-string s "\n")))
8981 (when (< lines (length slines))
8982 (setq s (mapconcat
8983 'identity
8984 (reverse (nthcdr (- (length slines) lines)
8985 (reverse slines))) "\n")))))
8986 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8988 (defun org-make-link-string (link &optional description)
8989 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8990 (unless (string-match "\\S-" link)
8991 (error "Empty link"))
8992 (when (and description
8993 (stringp description)
8994 (not (string-match "\\S-" description)))
8995 (setq description nil))
8996 (when (stringp description)
8997 ;; Remove brackets from the description, they are fatal.
8998 (while (string-match "\\[" description)
8999 (setq description (replace-match "{" t t description)))
9000 (while (string-match "\\]" description)
9001 (setq description (replace-match "}" t t description))))
9002 (when (equal link description)
9003 ;; No description needed, it is identical
9004 (setq description nil))
9005 (when (and (not description)
9006 (not (string-match (org-image-file-name-regexp) link))
9007 (not (equal link (org-link-escape link))))
9008 (setq description (org-extract-attributes link)))
9009 (setq link
9010 (cond ((string-match (org-image-file-name-regexp) link) link)
9011 ((string-match org-link-types-re link)
9012 (concat (match-string 1 link)
9013 (org-link-escape (substring link (match-end 1)))))
9014 (t (org-link-escape link))))
9015 (concat "[[" link "]"
9016 (if description (concat "[" description "]") "")
9017 "]"))
9019 (defconst org-link-escape-chars
9020 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9021 "List of characters that should be escaped in link.
9022 This is the list that is used for internal purposes.")
9024 (defconst org-link-escape-chars-browser
9025 '(?\ )
9026 "List of escapes for characters that are problematic in links.
9027 This is the list that is used before handing over to the browser.")
9029 (defun org-link-escape (text &optional table merge)
9030 "Return percent escaped representation of TEXT.
9031 TEXT is a string with the text to escape.
9032 Optional argument TABLE is a list with characters that should be
9033 escaped. When nil, `org-link-escape-chars' is used.
9034 If optional argument MERGE is set, merge TABLE into
9035 `org-link-escape-chars'."
9036 (cond
9037 ((and table merge)
9038 (mapc (lambda (defchr)
9039 (unless (member defchr table)
9040 (setq table (cons defchr table)))) org-link-escape-chars))
9041 ((null table)
9042 (setq table org-link-escape-chars)))
9043 (mapconcat
9044 (lambda (char)
9045 (if (or (member char table)
9046 (and (or (< char 32) (= char 37) (> char 126))
9047 org-url-hexify-p))
9048 (mapconcat (lambda (sequence-element)
9049 (format "%%%.2X" sequence-element))
9050 (or (encode-coding-char char 'utf-8)
9051 (error "Unable to percent escape character: %s"
9052 (char-to-string char))) "")
9053 (char-to-string char))) text ""))
9055 (defun org-link-unescape (str)
9056 "Unhex hexified Unicode strings as returned from the JavaScript function
9057 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9058 (unless (and (null str) (string= "" str))
9059 (let ((pos 0) (case-fold-search t) unhexed)
9060 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9061 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9062 (setq str (replace-match unhexed t t str))
9063 (setq pos (+ pos (length unhexed))))))
9064 str)
9066 (defun org-link-unescape-compound (hex)
9067 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9068 Note: this function also decodes single byte encodings like
9069 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9070 (save-match-data
9071 (let* ((bytes (cdr (split-string hex "%")))
9072 (ret "")
9073 (eat 0)
9074 (sum 0))
9075 (while bytes
9076 (let* ((val (string-to-number (pop bytes) 16))
9077 (shift-xor
9078 (if (= 0 eat)
9079 (cond
9080 ((>= val 252) (cons 6 252))
9081 ((>= val 248) (cons 5 248))
9082 ((>= val 240) (cons 4 240))
9083 ((>= val 224) (cons 3 224))
9084 ((>= val 192) (cons 2 192))
9085 (t (cons 0 0)))
9086 (cons 6 128))))
9087 (if (>= val 192) (setq eat (car shift-xor)))
9088 (setq val (logxor val (cdr shift-xor)))
9089 (setq sum (+ (lsh sum (car shift-xor)) val))
9090 (if (> eat 0) (setq eat (- eat 1)))
9091 (cond
9092 ((= 0 eat) ;multi byte
9093 (setq ret (concat ret (org-char-to-string sum)))
9094 (setq sum 0))
9095 ((not bytes) ; single byte(s)
9096 (setq ret (org-link-unescape-single-byte-sequence hex))))
9097 )) ;; end (while bytes
9098 ret )))
9100 (defun org-link-unescape-single-byte-sequence (hex)
9101 "Unhexify hex-encoded single byte character sequences."
9102 (mapconcat (lambda (byte)
9103 (char-to-string (string-to-number byte 16)))
9104 (cdr (split-string hex "%")) ""))
9106 (defun org-xor (a b)
9107 "Exclusive or."
9108 (if a (not b) b))
9110 (defun org-fixup-message-id-for-http (s)
9111 "Replace special characters in a message id, so it can be used in an http query."
9112 (when (string-match "%" s)
9113 (setq s (mapconcat (lambda (c)
9114 (if (eq c ?%)
9115 "%25"
9116 (char-to-string c)))
9117 s "")))
9118 (while (string-match "<" s)
9119 (setq s (replace-match "%3C" t t s)))
9120 (while (string-match ">" s)
9121 (setq s (replace-match "%3E" t t s)))
9122 (while (string-match "@" s)
9123 (setq s (replace-match "%40" t t s)))
9126 (defun org-link-prettify (link)
9127 "Return a human-readable representation of LINK.
9128 The car of LINK must be a raw link the cdr of LINK must be either
9129 a link description or nil."
9130 (let ((desc (or (cadr link) "<no description>")))
9131 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9132 "<" (car link) ">")))
9134 ;;;###autoload
9135 (defun org-insert-link-global ()
9136 "Insert a link like Org-mode does.
9137 This command can be called in any mode to insert a link in Org-mode syntax."
9138 (interactive)
9139 (org-load-modules-maybe)
9140 (org-run-like-in-org-mode 'org-insert-link))
9142 (defun org-insert-all-links (&optional keep)
9143 "Insert all links in `org-stored-links'."
9144 (interactive "P")
9145 (let ((links (copy-sequence org-stored-links)) l)
9146 (while (setq l (if keep (pop links) (pop org-stored-links)))
9147 (insert "- ")
9148 (org-insert-link nil (car l) (cadr l))
9149 (insert "\n"))))
9151 (defun org-link-fontify-links-to-this-file ()
9152 "Fontify links to the current file in `org-stored-links'."
9153 (let ((f (buffer-file-name)) a b)
9154 (setq a (mapcar (lambda(l)
9155 (let ((ll (car l)))
9156 (when (and (string-match "^file:\\(.+\\)::" ll)
9157 (equal f (expand-file-name (match-string 1 ll))))
9158 ll)))
9159 org-stored-links))
9160 (when (featurep 'org-id)
9161 (setq b (mapcar (lambda(l)
9162 (let ((ll (car l)))
9163 (when (and (string-match "^id:\\(.+\\)$" ll)
9164 (equal f (expand-file-name
9165 (or (org-id-find-id-file
9166 (match-string 1 ll)) ""))))
9167 ll)))
9168 org-stored-links)))
9169 (mapcar (lambda(l)
9170 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9171 (delq nil (append a b)))))
9173 (defvar org-link-links-in-this-file nil)
9174 (defun org-insert-link (&optional complete-file link-location default-description)
9175 "Insert a link. At the prompt, enter the link.
9177 Completion can be used to insert any of the link protocol prefixes like
9178 http or ftp in use.
9180 The history can be used to select a link previously stored with
9181 `org-store-link'. When the empty string is entered (i.e. if you just
9182 press RET at the prompt), the link defaults to the most recently
9183 stored link. As SPC triggers completion in the minibuffer, you need to
9184 use M-SPC or C-q SPC to force the insertion of a space character.
9186 You will also be prompted for a description, and if one is given, it will
9187 be displayed in the buffer instead of the link.
9189 If there is already a link at point, this command will allow you to edit link
9190 and description parts.
9192 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9193 be selected using completion. The path to the file will be relative to the
9194 current directory if the file is in the current directory or a subdirectory.
9195 Otherwise, the link will be the absolute path as completed in the minibuffer
9196 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9197 option `org-link-file-path-type'.
9199 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9200 the current directory or below.
9202 With three \\[universal-argument] prefixes, negate the meaning of
9203 `org-keep-stored-link-after-insertion'.
9205 If `org-make-link-description-function' is non-nil, this function will be
9206 called with the link target, and the result will be the default
9207 link description.
9209 If the LINK-LOCATION parameter is non-nil, this value will be
9210 used as the link location instead of reading one interactively.
9212 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9213 be used as the default description."
9214 (interactive "P")
9215 (let* ((wcf (current-window-configuration))
9216 (region (if (org-region-active-p)
9217 (buffer-substring (region-beginning) (region-end))))
9218 (remove (and region (list (region-beginning) (region-end))))
9219 (desc region)
9220 tmphist ; byte-compile incorrectly complains about this
9221 (link link-location)
9222 (abbrevs org-link-abbrev-alist-local)
9223 entry file all-prefixes auto-desc)
9224 (cond
9225 (link-location) ; specified by arg, just use it.
9226 ((org-in-regexp org-bracket-link-regexp 1)
9227 ;; We do have a link at point, and we are going to edit it.
9228 (setq remove (list (match-beginning 0) (match-end 0)))
9229 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9230 (setq link (read-string "Link: "
9231 (org-link-unescape
9232 (org-match-string-no-properties 1)))))
9233 ((or (org-in-regexp org-angle-link-re)
9234 (org-in-regexp org-plain-link-re))
9235 ;; Convert to bracket link
9236 (setq remove (list (match-beginning 0) (match-end 0))
9237 link (read-string "Link: "
9238 (org-remove-angle-brackets (match-string 0)))))
9239 ((member complete-file '((4) (16)))
9240 ;; Completing read for file names.
9241 (setq link (org-file-complete-link complete-file)))
9243 ;; Read link, with completion for stored links.
9244 (org-link-fontify-links-to-this-file)
9245 (org-switch-to-buffer-other-window "*Org Links*")
9246 (with-current-buffer "*Org Links*"
9247 (erase-buffer)
9248 (insert "Insert a link.
9249 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9250 (when org-stored-links
9251 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9252 (insert (mapconcat 'org-link-prettify
9253 (reverse org-stored-links) "\n")))
9254 (goto-char (point-min)))
9255 (let ((cw (selected-window)))
9256 (select-window (get-buffer-window "*Org Links*" 'visible))
9257 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9258 (unless (pos-visible-in-window-p (point-max))
9259 (org-fit-window-to-buffer))
9260 (and (window-live-p cw) (select-window cw)))
9261 ;; Fake a link history, containing the stored links.
9262 (setq tmphist (append (mapcar 'car org-stored-links)
9263 org-insert-link-history))
9264 (setq all-prefixes (append (mapcar 'car abbrevs)
9265 (mapcar 'car org-link-abbrev-alist)
9266 org-link-types))
9267 (unwind-protect
9268 (progn
9269 (setq link
9270 (let ((org-completion-use-ido nil)
9271 (org-completion-use-iswitchb nil))
9272 (org-completing-read
9273 "Link: "
9274 (append
9275 (mapcar (lambda (x) (list (concat x ":")))
9276 all-prefixes)
9277 (mapcar 'car org-stored-links)
9278 (mapcar 'cadr org-stored-links))
9279 nil nil nil
9280 'tmphist
9281 (caar org-stored-links))))
9282 (if (not (string-match "\\S-" link))
9283 (error "No link selected"))
9284 (mapc (lambda(l)
9285 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9286 org-stored-links)
9287 (if (or (member link all-prefixes)
9288 (and (equal ":" (substring link -1))
9289 (member (substring link 0 -1) all-prefixes)
9290 (setq link (substring link 0 -1))))
9291 (setq link (org-link-try-special-completion link))))
9292 (set-window-configuration wcf)
9293 (kill-buffer "*Org Links*"))
9294 (setq entry (assoc link org-stored-links))
9295 (or entry (push link org-insert-link-history))
9296 (setq desc (or desc (nth 1 entry)))))
9298 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9299 (not org-keep-stored-link-after-insertion))
9300 (setq org-stored-links (delq (assoc link org-stored-links)
9301 org-stored-links)))
9303 (if (string-match org-plain-link-re link)
9304 ;; URL-like link, normalize the use of angular brackets.
9305 (setq link (org-remove-angle-brackets link)))
9307 ;; Check if we are linking to the current file with a search option
9308 ;; If yes, simplify the link by using only the search option.
9309 (when (and buffer-file-name
9310 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9311 (let* ((path (match-string 1 link))
9312 (case-fold-search nil)
9313 (search (match-string 2 link)))
9314 (save-match-data
9315 (if (equal (file-truename buffer-file-name) (file-truename path))
9316 ;; We are linking to this same file, with a search option
9317 (setq link search)))))
9319 ;; Check if we can/should use a relative path. If yes, simplify the link
9320 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9321 (let* ((type (match-string 1 link))
9322 (path (match-string 2 link))
9323 (origpath path)
9324 (case-fold-search nil))
9325 (cond
9326 ((or (eq org-link-file-path-type 'absolute)
9327 (equal complete-file '(16)))
9328 (setq path (abbreviate-file-name (expand-file-name path))))
9329 ((eq org-link-file-path-type 'noabbrev)
9330 (setq path (expand-file-name path)))
9331 ((eq org-link-file-path-type 'relative)
9332 (setq path (file-relative-name path)))
9334 (save-match-data
9335 (if (string-match (concat "^" (regexp-quote
9336 (expand-file-name
9337 (file-name-as-directory
9338 default-directory))))
9339 (expand-file-name path))
9340 ;; We are linking a file with relative path name.
9341 (setq path (substring (expand-file-name path)
9342 (match-end 0)))
9343 (setq path (abbreviate-file-name (expand-file-name path)))))))
9344 (setq link (concat type path))
9345 (if (equal desc origpath)
9346 (setq desc path))))
9348 (if org-make-link-description-function
9349 (setq desc
9350 (or (condition-case nil
9351 (funcall org-make-link-description-function link desc)
9352 (error (progn (message "Can't get link description from `%s'"
9353 (symbol-name org-make-link-description-function))
9354 (sit-for 2) nil)))
9355 (read-string "Description: " default-description)))
9356 (if default-description (setq desc default-description)
9357 (setq desc (or (and auto-desc desc)
9358 (read-string "Description: " desc)))))
9360 (unless (string-match "\\S-" desc) (setq desc nil))
9361 (if remove (apply 'delete-region remove))
9362 (insert (org-make-link-string link desc))))
9364 (defun org-link-try-special-completion (type)
9365 "If there is completion support for link type TYPE, offer it."
9366 (let ((fun (intern (concat "org-" type "-complete-link"))))
9367 (if (functionp fun)
9368 (funcall fun)
9369 (read-string "Link (no completion support): " (concat type ":")))))
9371 (defun org-file-complete-link (&optional arg)
9372 "Create a file link using completion."
9373 (let (file link)
9374 (setq file (read-file-name "File: "))
9375 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9376 (pwd1 (file-name-as-directory (abbreviate-file-name
9377 (expand-file-name ".")))))
9378 (cond
9379 ((equal arg '(16))
9380 (setq link (concat
9381 "file:"
9382 (abbreviate-file-name (expand-file-name file)))))
9383 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9384 (setq link (concat "file:" (match-string 1 file))))
9385 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9386 (expand-file-name file))
9387 (setq link (concat
9388 "file:" (match-string 1 (expand-file-name file)))))
9389 (t (setq link (concat "file:" file)))))
9390 link))
9392 (defun org-completing-read (&rest args)
9393 "Completing-read with SPACE being a normal character."
9394 (let ((enable-recursive-minibuffers t)
9395 (minibuffer-local-completion-map
9396 (copy-keymap minibuffer-local-completion-map)))
9397 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9398 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9399 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9400 (apply 'org-icompleting-read args)))
9402 (defun org-completing-read-no-i (&rest args)
9403 (let (org-completion-use-ido org-completion-use-iswitchb)
9404 (apply 'org-completing-read args)))
9406 (defun org-iswitchb-completing-read (prompt choices &rest args)
9407 "Use iswitch as a completing-read replacement to choose from choices.
9408 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9409 from."
9410 (let* ((iswitchb-use-virtual-buffers nil)
9411 (iswitchb-make-buflist-hook
9412 (lambda ()
9413 (setq iswitchb-temp-buflist choices))))
9414 (iswitchb-read-buffer prompt)))
9416 (defun org-icompleting-read (&rest args)
9417 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9418 (org-without-partial-completion
9419 (if (and org-completion-use-ido
9420 (fboundp 'ido-completing-read)
9421 (boundp 'ido-mode) ido-mode
9422 (listp (second args)))
9423 (let ((ido-enter-matching-directory nil))
9424 (apply 'ido-completing-read (concat (car args))
9425 (if (consp (car (nth 1 args)))
9426 (mapcar 'car (nth 1 args))
9427 (nth 1 args))
9428 (cddr args)))
9429 (if (and org-completion-use-iswitchb
9430 (boundp 'iswitchb-mode) iswitchb-mode
9431 (listp (second args)))
9432 (apply 'org-iswitchb-completing-read (concat (car args))
9433 (if (consp (car (nth 1 args)))
9434 (mapcar 'car (nth 1 args))
9435 (nth 1 args))
9436 (cddr args))
9437 (apply 'completing-read args)))))
9439 (defun org-extract-attributes (s)
9440 "Extract the attributes cookie from a string and set as text property."
9441 (let (a attr (start 0) key value)
9442 (save-match-data
9443 (when (string-match "{{\\([^}]+\\)}}$" s)
9444 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9445 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9446 (setq key (match-string 1 a) value (match-string 2 a)
9447 start (match-end 0)
9448 attr (plist-put attr (intern key) value))))
9449 (org-add-props s nil 'org-attr attr))
9452 (defun org-extract-attributes-from-string (tag)
9453 (let (key value attr)
9454 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9455 (setq key (match-string 1 tag) value (match-string 2 tag)
9456 tag (replace-match "" t t tag)
9457 attr (plist-put attr (intern key) value)))
9458 (cons tag attr)))
9460 (defun org-attributes-to-string (plist)
9461 "Format a property list into an HTML attribute list."
9462 (let ((s "") key value)
9463 (while plist
9464 (setq key (pop plist) value (pop plist))
9465 (and value
9466 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9469 ;;; Opening/following a link
9471 (defvar org-link-search-failed nil)
9473 (defvar org-open-link-functions nil
9474 "Hook for functions finding a plain text link.
9475 These functions must take a single argument, the link content.
9476 They will be called for links that look like [[link text][description]]
9477 when LINK TEXT does not have a protocol like \"http:\" and does not look
9478 like a filename (e.g. \"./blue.png\").
9480 These functions will be called *before* Org attempts to resolve the
9481 link by doing text searches in the current buffer - so if you want a
9482 link \"[[target]]\" to still find \"<<target>>\", your function should
9483 handle this as a special case.
9485 When the function does handle the link, it must return a non-nil value.
9486 If it decides that it is not responsible for this link, it must return
9487 nil to indicate that that Org-mode can continue with other options
9488 like exact and fuzzy text search.")
9490 (defun org-next-link ()
9491 "Move forward to the next link.
9492 If the link is in hidden text, expose it."
9493 (interactive)
9494 (when (and org-link-search-failed (eq this-command last-command))
9495 (goto-char (point-min))
9496 (message "Link search wrapped back to beginning of buffer"))
9497 (setq org-link-search-failed nil)
9498 (let* ((pos (point))
9499 (ct (org-context))
9500 (a (assoc :link ct)))
9501 (if a (goto-char (nth 2 a)))
9502 (if (re-search-forward org-any-link-re nil t)
9503 (progn
9504 (goto-char (match-beginning 0))
9505 (if (outline-invisible-p) (org-show-context)))
9506 (goto-char pos)
9507 (setq org-link-search-failed t)
9508 (error "No further link found"))))
9510 (defun org-previous-link ()
9511 "Move backward to the previous link.
9512 If the link is in hidden text, expose it."
9513 (interactive)
9514 (when (and org-link-search-failed (eq this-command last-command))
9515 (goto-char (point-max))
9516 (message "Link search wrapped back to end of buffer"))
9517 (setq org-link-search-failed nil)
9518 (let* ((pos (point))
9519 (ct (org-context))
9520 (a (assoc :link ct)))
9521 (if a (goto-char (nth 1 a)))
9522 (if (re-search-backward org-any-link-re nil t)
9523 (progn
9524 (goto-char (match-beginning 0))
9525 (if (outline-invisible-p) (org-show-context)))
9526 (goto-char pos)
9527 (setq org-link-search-failed t)
9528 (error "No further link found"))))
9530 (defun org-translate-link (s)
9531 "Translate a link string if a translation function has been defined."
9532 (if (and org-link-translation-function
9533 (fboundp org-link-translation-function)
9534 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9535 (progn
9536 (setq s (funcall org-link-translation-function
9537 (match-string 1 s) (match-string 2 s)))
9538 (concat (car s) ":" (cdr s)))
9541 (defun org-translate-link-from-planner (type path)
9542 "Translate a link from Emacs Planner syntax so that Org can follow it.
9543 This is still an experimental function, your mileage may vary."
9544 (cond
9545 ((member type '("http" "https" "news" "ftp"))
9546 ;; standard Internet links are the same.
9547 nil)
9548 ((and (equal type "irc") (string-match "^//" path))
9549 ;; Planner has two / at the beginning of an irc link, we have 1.
9550 ;; We should have zero, actually....
9551 (setq path (substring path 1)))
9552 ((and (equal type "lisp") (string-match "^/" path))
9553 ;; Planner has a slash, we do not.
9554 (setq type "elisp" path (substring path 1)))
9555 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9556 ;; A typical message link. Planner has the id after the final slash,
9557 ;; we separate it with a hash mark
9558 (setq path (concat (match-string 1 path) "#"
9559 (org-remove-angle-brackets (match-string 2 path)))))
9561 (cons type path))
9563 (defun org-find-file-at-mouse (ev)
9564 "Open file link or URL at mouse."
9565 (interactive "e")
9566 (mouse-set-point ev)
9567 (org-open-at-point 'in-emacs))
9569 (defun org-open-at-mouse (ev)
9570 "Open file link or URL at mouse.
9571 See the docstring of `org-open-file' for details."
9572 (interactive "e")
9573 (mouse-set-point ev)
9574 (if (eq major-mode 'org-agenda-mode)
9575 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9576 (org-open-at-point))
9578 (defvar org-window-config-before-follow-link nil
9579 "The window configuration before following a link.
9580 This is saved in case the need arises to restore it.")
9582 (defvar org-open-link-marker (make-marker)
9583 "Marker pointing to the location where `org-open-at-point; was called.")
9585 ;;;###autoload
9586 (defun org-open-at-point-global ()
9587 "Follow a link like Org-mode does.
9588 This command can be called in any mode to follow a link that has
9589 Org-mode syntax."
9590 (interactive)
9591 (org-run-like-in-org-mode 'org-open-at-point))
9593 ;;;###autoload
9594 (defun org-open-link-from-string (s &optional arg reference-buffer)
9595 "Open a link in the string S, as if it was in Org-mode."
9596 (interactive "sLink: \nP")
9597 (let ((reference-buffer (or reference-buffer (current-buffer))))
9598 (with-temp-buffer
9599 (let ((org-inhibit-startup (not reference-buffer)))
9600 (org-mode)
9601 (insert s)
9602 (goto-char (point-min))
9603 (when reference-buffer
9604 (setq org-link-abbrev-alist-local
9605 (with-current-buffer reference-buffer
9606 org-link-abbrev-alist-local)))
9607 (org-open-at-point arg reference-buffer)))))
9609 (defvar org-open-at-point-functions nil
9610 "Hook that is run when following a link at point.
9612 Functions in this hook must return t if they identify and follow
9613 a link at point. If they don't find anything interesting at point,
9614 they must return nil.")
9616 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9617 (defun org-open-at-point (&optional arg reference-buffer)
9618 "Open link at or after point.
9619 If there is no link at point, this function will search forward up to
9620 the end of the current line.
9621 Normally, files will be opened by an appropriate application. If the
9622 optional prefix argument ARG is non-nil, Emacs will visit the file.
9623 With a double prefix argument, try to open outside of Emacs, in the
9624 application the system uses for this file type."
9625 (interactive "P")
9626 ;; if in a code block, then open the block's results
9627 (unless (call-interactively #'org-babel-open-src-block-result)
9628 (org-load-modules-maybe)
9629 (move-marker org-open-link-marker (point))
9630 (setq org-window-config-before-follow-link (current-window-configuration))
9631 (org-remove-occur-highlights nil nil t)
9632 (cond
9633 ((and (org-at-heading-p)
9634 (not (org-at-timestamp-p t))
9635 (not (org-in-regexp
9636 (concat org-plain-link-re "\\|"
9637 org-bracket-link-regexp "\\|"
9638 org-angle-link-re "\\|"
9639 "[ \t]:[^ \t\n]+:[ \t]*$")))
9640 (not (get-text-property (point) 'org-linked-text)))
9641 (or (org-offer-links-in-entry arg)
9642 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9643 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9644 ((and (org-at-timestamp-p t)
9645 (not (org-in-regexp org-bracket-link-regexp)))
9646 (org-follow-timestamp-link))
9647 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9648 (not (org-in-regexp org-bracket-link-regexp)))
9649 (org-footnote-action))
9651 (let (type path link line search (pos (point)))
9652 (catch 'match
9653 (save-excursion
9654 (skip-chars-forward "^]\n\r")
9655 (when (org-in-regexp org-bracket-link-regexp 1)
9656 (setq link (org-extract-attributes
9657 (org-link-unescape (org-match-string-no-properties 1))))
9658 (while (string-match " *\n *" link)
9659 (setq link (replace-match " " t t link)))
9660 (setq link (org-link-expand-abbrev link))
9661 (cond
9662 ((or (file-name-absolute-p link)
9663 (string-match "^\\.\\.?/" link))
9664 (setq type "file" path link))
9665 ((string-match org-link-re-with-space3 link)
9666 (setq type (match-string 1 link) path (match-string 2 link)))
9667 ((string-match "^help:+\\(.+\\)" link)
9668 (setq type "help" path (match-string 1 link)))
9669 (t (setq type "thisfile" path link)))
9670 (throw 'match t)))
9672 (when (get-text-property (point) 'org-linked-text)
9673 (setq type "thisfile"
9674 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9675 (1+ (point)) (point))
9676 path (buffer-substring
9677 (or (previous-single-property-change pos 'org-linked-text)
9678 (point-min))
9679 (or (next-single-property-change pos 'org-linked-text)
9680 (point-max))))
9681 (throw 'match t))
9683 (save-excursion
9684 (when (or (org-in-regexp org-angle-link-re)
9685 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9686 (save-match-data (not (looking-back "\\[\\[")))))
9687 (setq type (match-string 1)
9688 path (org-link-unescape (match-string 2)))
9689 (throw 'match t)))
9690 (save-excursion
9691 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9692 (setq type "tags"
9693 path (match-string 1))
9694 (while (string-match ":" path)
9695 (setq path (replace-match "+" t t path)))
9696 (throw 'match t)))
9697 (when (org-in-regexp "<\\([^><\n]+\\)>")
9698 (setq type "tree-match"
9699 path (match-string 1))
9700 (throw 'match t)))
9701 (unless path
9702 (error "No link found"))
9704 ;; switch back to reference buffer
9705 ;; needed when if called in a temporary buffer through
9706 ;; org-open-link-from-string
9707 (with-current-buffer (or reference-buffer (current-buffer))
9709 ;; Remove any trailing spaces in path
9710 (if (string-match " +\\'" path)
9711 (setq path (replace-match "" t t path)))
9712 (if (and org-link-translation-function
9713 (fboundp org-link-translation-function))
9714 ;; Check if we need to translate the link
9715 (let ((tmp (funcall org-link-translation-function type path)))
9716 (setq type (car tmp) path (cdr tmp))))
9718 (cond
9720 ((assoc type org-link-protocols)
9721 (funcall (nth 1 (assoc type org-link-protocols)) path))
9723 ((equal type "help")
9724 (let ((f-or-v (intern path)))
9725 (cond ((fboundp f-or-v)
9726 (describe-function f-or-v))
9727 ((boundp f-or-v)
9728 (describe-variable f-or-v))
9729 (t (error "Not a known function or variable")))))
9731 ((equal type "mailto")
9732 (let ((cmd (car org-link-mailto-program))
9733 (args (cdr org-link-mailto-program)) args1
9734 (address path) (subject "") a)
9735 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9736 (setq address (match-string 1 path)
9737 subject (org-link-escape (match-string 2 path))))
9738 (while args
9739 (cond
9740 ((not (stringp (car args))) (push (pop args) args1))
9741 (t (setq a (pop args))
9742 (if (string-match "%a" a)
9743 (setq a (replace-match address t t a)))
9744 (if (string-match "%s" a)
9745 (setq a (replace-match subject t t a)))
9746 (push a args1))))
9747 (apply cmd (nreverse args1))))
9749 ((member type '("http" "https" "ftp" "news"))
9750 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9751 (org-link-escape
9752 path org-link-escape-chars-browser)
9753 path))))
9755 ((string= type "doi")
9756 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9757 (org-link-escape
9758 path org-link-escape-chars-browser)
9759 path))))
9761 ((member type '("message"))
9762 (browse-url (concat type ":" path)))
9764 ((string= type "tags")
9765 (org-tags-view arg path))
9767 ((string= type "tree-match")
9768 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9770 ((string= type "file")
9771 (if (string-match "::\\([0-9]+\\)\\'" path)
9772 (setq line (string-to-number (match-string 1 path))
9773 path (substring path 0 (match-beginning 0)))
9774 (if (string-match "::\\(.+\\)\\'" path)
9775 (setq search (match-string 1 path)
9776 path (substring path 0 (match-beginning 0)))))
9777 (if (string-match "[*?{]" (file-name-nondirectory path))
9778 (dired path)
9779 (org-open-file path arg line search)))
9781 ((string= type "shell")
9782 (let ((buf (generate-new-buffer "*Org Shell Output"))
9783 (cmd path))
9784 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9785 (string-match org-confirm-shell-link-not-regexp cmd))
9786 (not org-confirm-shell-link-function)
9787 (funcall org-confirm-shell-link-function
9788 (format "Execute \"%s\" in shell? "
9789 (org-add-props cmd nil
9790 'face 'org-warning))))
9791 (progn
9792 (message "Executing %s" cmd)
9793 (shell-command cmd buf)
9794 (if (featurep 'midnight)
9795 (setq clean-buffer-list-kill-buffer-names
9796 (cons buf clean-buffer-list-kill-buffer-names))))
9797 (error "Abort"))))
9799 ((string= type "elisp")
9800 (let ((cmd path))
9801 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9802 (string-match org-confirm-elisp-link-not-regexp cmd))
9803 (not org-confirm-elisp-link-function)
9804 (funcall org-confirm-elisp-link-function
9805 (format "Execute \"%s\" as elisp? "
9806 (org-add-props cmd nil
9807 'face 'org-warning))))
9808 (message "%s => %s" cmd
9809 (if (equal (string-to-char cmd) ?\()
9810 (eval (read cmd))
9811 (call-interactively (read cmd))))
9812 (error "Abort"))))
9814 ((and (string= type "thisfile")
9815 (run-hook-with-args-until-success
9816 'org-open-link-functions path)))
9818 ((string= type "thisfile")
9819 (if arg
9820 (switch-to-buffer-other-window
9821 (org-get-buffer-for-internal-link (current-buffer)))
9822 (org-mark-ring-push))
9823 (let ((cmd `(org-link-search
9824 ,path
9825 ,(cond ((equal arg '(4)) ''occur)
9826 ((equal arg '(16)) ''org-occur))
9827 ,pos)))
9828 (condition-case nil (let ((org-link-search-inhibit-query t))
9829 (eval cmd))
9830 (error (progn (widen) (eval cmd))))))
9832 (t (browse-url-at-point)))))))
9833 (move-marker org-open-link-marker nil)
9834 (run-hook-with-args 'org-follow-link-hook)))
9836 (defun org-offer-links-in-entry (&optional nth zero)
9837 "Offer links in the current entry and follow the selected link.
9838 If there is only one link, follow it immediately as well.
9839 If NTH is an integer, immediately pick the NTH link found.
9840 If ZERO is a string, check also this string for a link, and if
9841 there is one, offer it as link number zero."
9842 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9843 "\\(" org-angle-link-re "\\)\\|"
9844 "\\(" org-plain-link-re "\\)"))
9845 (cnt ?0)
9846 (in-emacs (if (integerp nth) nil nth))
9847 have-zero end links link c)
9848 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9849 (push (match-string 0 zero) links)
9850 (setq cnt (1- cnt) have-zero t))
9851 (save-excursion
9852 (org-back-to-heading t)
9853 (setq end (save-excursion (outline-next-heading) (point)))
9854 (while (re-search-forward re end t)
9855 (push (match-string 0) links))
9856 (setq links (org-uniquify (reverse links))))
9858 (cond
9859 ((null links)
9860 (message "No links"))
9861 ((equal (length links) 1)
9862 (setq link (list (car links))))
9863 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9864 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9865 (t ; we have to select a link
9866 (save-excursion
9867 (save-window-excursion
9868 (delete-other-windows)
9869 (with-output-to-temp-buffer "*Select Link*"
9870 (mapc (lambda (l)
9871 (if (not (string-match org-bracket-link-regexp l))
9872 (princ (format "[%c] %s\n" (incf cnt)
9873 (org-remove-angle-brackets l)))
9874 (if (match-end 3)
9875 (princ (format "[%c] %s (%s)\n" (incf cnt)
9876 (match-string 3 l) (match-string 1 l)))
9877 (princ (format "[%c] %s\n" (incf cnt)
9878 (match-string 1 l))))))
9879 links))
9880 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9881 (message "Select link to open, RET to open all:")
9882 (setq c (read-char-exclusive))
9883 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9884 (when (equal c ?q) (error "Abort"))
9885 (if (equal c ?\C-m)
9886 (setq link links)
9887 (setq nth (- c ?0))
9888 (if have-zero (setq nth (1+ nth)))
9889 (unless (and (integerp nth) (>= (length links) nth))
9890 (error "Invalid link selection"))
9891 (setq link (list (nth (1- nth) links))))))
9892 (if link
9893 (let ((buf (current-buffer)))
9894 (dolist (l link)
9895 (org-open-link-from-string l in-emacs buf))
9897 nil)))
9899 ;; Add special file links that specify the way of opening
9901 (org-add-link-type "file+sys" 'org-open-file-with-system)
9902 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9903 (defun org-open-file-with-system (path)
9904 "Open file at PATH using the system way of opening it."
9905 (org-open-file path 'system))
9906 (defun org-open-file-with-emacs (path)
9907 "Open file at PATH in Emacs."
9908 (org-open-file path 'emacs))
9909 (defun org-remove-file-link-modifiers ()
9910 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9911 (goto-char (point-min))
9912 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9913 (org-if-unprotected
9914 (replace-match "file:" t t))))
9915 (eval-after-load "org-exp"
9916 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9917 'org-remove-file-link-modifiers))
9919 ;;;; Time estimates
9921 (defun org-get-effort (&optional pom)
9922 "Get the effort estimate for the current entry."
9923 (org-entry-get pom org-effort-property))
9925 ;;; File search
9927 (defvar org-create-file-search-functions nil
9928 "List of functions to construct the right search string for a file link.
9929 These functions are called in turn with point at the location to
9930 which the link should point.
9932 A function in the hook should first test if it would like to
9933 handle this file type, for example by checking the `major-mode'
9934 or the file extension. If it decides not to handle this file, it
9935 should just return nil to give other functions a chance. If it
9936 does handle the file, it must return the search string to be used
9937 when following the link. The search string will be part of the
9938 file link, given after a double colon, and `org-open-at-point'
9939 will automatically search for it. If special measures must be
9940 taken to make the search successful, another function should be
9941 added to the companion hook `org-execute-file-search-functions',
9942 which see.
9944 A function in this hook may also use `setq' to set the variable
9945 `description' to provide a suggestion for the descriptive text to
9946 be used for this link when it gets inserted into an Org-mode
9947 buffer with \\[org-insert-link].")
9949 (defvar org-execute-file-search-functions nil
9950 "List of functions to execute a file search triggered by a link.
9952 Functions added to this hook must accept a single argument, the
9953 search string that was part of the file link, the part after the
9954 double colon. The function must first check if it would like to
9955 handle this search, for example by checking the `major-mode' or
9956 the file extension. If it decides not to handle this search, it
9957 should just return nil to give other functions a chance. If it
9958 does handle the search, it must return a non-nil value to keep
9959 other functions from trying.
9961 Each function can access the current prefix argument through the
9962 variable `current-prefix-argument'. Note that a single prefix is
9963 used to force opening a link in Emacs, so it may be good to only
9964 use a numeric or double prefix to guide the search function.
9966 In case this is needed, a function in this hook can also restore
9967 the window configuration before `org-open-at-point' was called using:
9969 (set-window-configuration org-window-config-before-follow-link)")
9971 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9972 (defun org-link-search (s &optional type avoid-pos stealth)
9973 "Search for a link search option.
9974 If S is surrounded by forward slashes, it is interpreted as a
9975 regular expression. In org-mode files, this will create an `org-occur'
9976 sparse tree. In ordinary files, `occur' will be used to list matches.
9977 If the current buffer is in `dired-mode', grep will be used to search
9978 in all files. If AVOID-POS is given, ignore matches near that position.
9980 When optional argument STEALTH is non-nil, do not modify
9981 visibility around point, thus ignoring
9982 `org-show-hierarchy-above', `org-show-following-heading' and
9983 `org-show-siblings' variables."
9984 (let ((case-fold-search t)
9985 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9986 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9987 (append '(("") (" ") ("\t") ("\n"))
9988 org-emphasis-alist)
9989 "\\|") "\\)"))
9990 (pos (point))
9991 (pre nil) (post nil)
9992 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9993 (cond
9994 ;; First check if there are any special search functions
9995 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9996 ;; Now try the builtin stuff
9997 ((and (equal (string-to-char s0) ?#)
9998 (> (length s0) 1)
9999 (save-excursion
10000 (goto-char (point-min))
10001 (and
10002 (re-search-forward
10003 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10004 (setq type 'dedicated
10005 pos (match-beginning 0))))
10006 ;; There is an exact target for this
10007 (goto-char pos)
10008 (org-back-to-heading t)))
10009 ((save-excursion
10010 (goto-char (point-min))
10011 (and
10012 (re-search-forward
10013 (concat "<<" (regexp-quote s0) ">>") nil t)
10014 (setq type 'dedicated
10015 pos (match-beginning 0))))
10016 ;; There is an exact target for this
10017 (goto-char pos))
10018 ((save-excursion
10019 (goto-char (point-min))
10020 (and
10021 (re-search-forward
10022 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10023 (setq type 'dedicated pos (match-beginning 0))))
10024 ;; Found an invisible target.
10025 (goto-char pos))
10026 ((save-excursion
10027 (goto-char (point-min))
10028 (and
10029 (re-search-forward
10030 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10031 (setq type 'dedicated pos (match-beginning 0))))
10032 ;; Found an element with a matching #+name affiliated keyword.
10033 (goto-char pos))
10034 ((and (string-match "^(\\(.*\\))$" s0)
10035 (save-excursion
10036 (goto-char (point-min))
10037 (and
10038 (re-search-forward
10039 (concat "[^[]" (regexp-quote
10040 (format org-coderef-label-format
10041 (match-string 1 s0))))
10042 nil t)
10043 (setq type 'dedicated
10044 pos (1+ (match-beginning 0))))))
10045 ;; There is a coderef target for this
10046 (goto-char pos))
10047 ((string-match "^/\\(.*\\)/$" s)
10048 ;; A regular expression
10049 (cond
10050 ((derived-mode-p 'org-mode)
10051 (org-occur (match-string 1 s)))
10052 ;;((eq major-mode 'dired-mode)
10053 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10054 (t (org-do-occur (match-string 1 s)))))
10055 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10056 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10057 (goto-char (point-min))
10058 (cond
10059 ((let (case-fold-search)
10060 (re-search-forward (format org-complex-heading-regexp-format
10061 (regexp-quote s))
10062 nil t))
10063 ;; OK, found a match
10064 (setq type 'dedicated)
10065 (goto-char (match-beginning 0)))
10066 ((and (not org-link-search-inhibit-query)
10067 (eq org-link-search-must-match-exact-headline 'query-to-create)
10068 (y-or-n-p "No match - create this as a new heading? "))
10069 (goto-char (point-max))
10070 (or (bolp) (newline))
10071 (insert "* " s "\n")
10072 (beginning-of-line 0))
10074 (goto-char pos)
10075 (error "No match"))))
10077 ;; A normal search string
10078 (when (equal (string-to-char s) ?*)
10079 ;; Anchor on headlines, post may include tags.
10080 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10081 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10082 s (substring s 1)))
10083 (remove-text-properties
10084 0 (length s)
10085 '(face nil mouse-face nil keymap nil fontified nil) s)
10086 ;; Make a series of regular expressions to find a match
10087 (setq words (org-split-string s "[ \n\r\t]+")
10089 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10090 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10091 "\\)" markers)
10092 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10093 re2a (concat "[ \t\r\n]" re2a_)
10094 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10095 re4 (concat "[^a-zA-Z_]" re4_)
10097 re1 (concat pre re2 post)
10098 re3 (concat pre (if pre re4_ re4) post)
10099 re5 (concat pre ".*" re4)
10100 re2 (concat pre re2)
10101 re2a (concat pre (if pre re2a_ re2a))
10102 re4 (concat pre (if pre re4_ re4))
10103 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10104 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10105 re5 "\\)"
10107 (cond
10108 ((eq type 'org-occur) (org-occur reall))
10109 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10110 (t (goto-char (point-min))
10111 (setq type 'fuzzy)
10112 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10113 (org-search-not-self 1 re1 nil t)
10114 (org-search-not-self 1 re2 nil t)
10115 (org-search-not-self 1 re2a nil t)
10116 (org-search-not-self 1 re3 nil t)
10117 (org-search-not-self 1 re4 nil t)
10118 (org-search-not-self 1 re5 nil t)
10120 (goto-char (match-beginning 1))
10121 (goto-char pos)
10122 (error "No match"))))))
10123 (and (derived-mode-p 'org-mode)
10124 (not stealth)
10125 (org-show-context 'link-search))
10126 type))
10128 (defun org-search-not-self (group &rest args)
10129 "Execute `re-search-forward', but only accept matches that do not
10130 enclose the position of `org-open-link-marker'."
10131 (let ((m org-open-link-marker))
10132 (catch 'exit
10133 (while (apply 're-search-forward args)
10134 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10135 (goto-char (match-end group))
10136 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10137 (> (match-beginning 0) (marker-position m))
10138 (< (match-end 0) (marker-position m)))
10139 (save-match-data
10140 (or (not (org-in-regexp
10141 org-bracket-link-analytic-regexp 1))
10142 (not (match-end 4)) ; no description
10143 (and (<= (match-beginning 4) (point))
10144 (>= (match-end 4) (point))))))
10145 (throw 'exit (point))))))))
10147 (defun org-get-buffer-for-internal-link (buffer)
10148 "Return a buffer to be used for displaying the link target of internal links."
10149 (cond
10150 ((not org-display-internal-link-with-indirect-buffer)
10151 buffer)
10152 ((string-match "(Clone)$" (buffer-name buffer))
10153 (message "Buffer is already a clone, not making another one")
10154 ;; we also do not modify visibility in this case
10155 buffer)
10156 (t ; make a new indirect buffer for displaying the link
10157 (let* ((bn (buffer-name buffer))
10158 (ibn (concat bn "(Clone)"))
10159 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10160 (with-current-buffer ib (org-overview))
10161 ib))))
10163 (defun org-do-occur (regexp &optional cleanup)
10164 "Call the Emacs command `occur'.
10165 If CLEANUP is non-nil, remove the printout of the regular expression
10166 in the *Occur* buffer. This is useful if the regex is long and not useful
10167 to read."
10168 (occur regexp)
10169 (when cleanup
10170 (let ((cwin (selected-window)) win beg end)
10171 (when (setq win (get-buffer-window "*Occur*"))
10172 (select-window win))
10173 (goto-char (point-min))
10174 (when (re-search-forward "match[a-z]+" nil t)
10175 (setq beg (match-end 0))
10176 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10177 (setq end (1- (match-beginning 0)))))
10178 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10179 (goto-char (point-min))
10180 (select-window cwin))))
10182 ;;; The mark ring for links jumps
10184 (defvar org-mark-ring nil
10185 "Mark ring for positions before jumps in Org-mode.")
10186 (defvar org-mark-ring-last-goto nil
10187 "Last position in the mark ring used to go back.")
10188 ;; Fill and close the ring
10189 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10190 (loop for i from 1 to org-mark-ring-length do
10191 (push (make-marker) org-mark-ring))
10192 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10193 org-mark-ring)
10195 (defun org-mark-ring-push (&optional pos buffer)
10196 "Put the current position or POS into the mark ring and rotate it."
10197 (interactive)
10198 (setq pos (or pos (point)))
10199 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10200 (move-marker (car org-mark-ring)
10201 (or pos (point))
10202 (or buffer (current-buffer)))
10203 (message "%s"
10204 (substitute-command-keys
10205 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10207 (defun org-mark-ring-goto (&optional n)
10208 "Jump to the previous position in the mark ring.
10209 With prefix arg N, jump back that many stored positions. When
10210 called several times in succession, walk through the entire ring.
10211 Org-mode commands jumping to a different position in the current file,
10212 or to another Org-mode file, automatically push the old position
10213 onto the ring."
10214 (interactive "p")
10215 (let (p m)
10216 (if (eq last-command this-command)
10217 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10218 (setq p org-mark-ring))
10219 (setq org-mark-ring-last-goto p)
10220 (setq m (car p))
10221 (org-pop-to-buffer-same-window (marker-buffer m))
10222 (goto-char m)
10223 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10225 (defun org-remove-angle-brackets (s)
10226 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10227 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10229 (defun org-add-angle-brackets (s)
10230 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10231 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10233 (defun org-remove-double-quotes (s)
10234 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10235 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10238 ;;; Following specific links
10240 (defun org-follow-timestamp-link ()
10241 "Open an agenda view for the time-stamp date/range at point."
10242 (cond
10243 ((org-at-date-range-p t)
10244 (let ((org-agenda-start-on-weekday)
10245 (t1 (match-string 1))
10246 (t2 (match-string 2)) tt1 tt2)
10247 (setq tt1 (time-to-days (org-time-string-to-time t1))
10248 tt2 (time-to-days (org-time-string-to-time t2)))
10249 (let ((org-agenda-buffer-tmp-name
10250 (format "*Org Agenda(a:%s)"
10251 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10252 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10253 ((org-at-timestamp-p t)
10254 (let ((org-agenda-buffer-tmp-name
10255 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10256 (org-agenda-list nil (time-to-days (org-time-string-to-time
10257 (substring (match-string 1) 0 10)))
10258 1)))
10259 (t (error "This should not happen"))))
10262 ;;; Following file links
10263 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10264 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10265 (declare-function mailcap-mime-info
10266 "mailcap" (string &optional request no-decode))
10267 (defvar org-wait nil)
10268 (defun org-open-file (path &optional in-emacs line search)
10269 "Open the file at PATH.
10270 First, this expands any special file name abbreviations. Then the
10271 configuration variable `org-file-apps' is checked if it contains an
10272 entry for this file type, and if yes, the corresponding command is launched.
10274 If no application is found, Emacs simply visits the file.
10276 With optional prefix argument IN-EMACS, Emacs will visit the file.
10277 With a double \\[universal-argument] \\[universal-argument] \
10278 prefix arg, Org tries to avoid opening in Emacs
10279 and to use an external application to visit the file.
10281 Optional LINE specifies a line to go to, optional SEARCH a string
10282 to search for. If LINE or SEARCH is given, the file will be
10283 opened in Emacs, unless an entry from org-file-apps that makes
10284 use of groups in a regexp matches.
10286 If you want to change the way frames are used when following a
10287 link, please customize `org-link-frame-setup'.
10289 If the file does not exist, an error is thrown."
10290 (let* ((file (if (equal path "")
10291 buffer-file-name
10292 (substitute-in-file-name (expand-file-name path))))
10293 (file-apps (append org-file-apps (org-default-apps)))
10294 (apps (org-remove-if
10295 'org-file-apps-entry-match-against-dlink-p file-apps))
10296 (apps-dlink (org-remove-if-not
10297 'org-file-apps-entry-match-against-dlink-p file-apps))
10298 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10299 (dirp (if remp nil (file-directory-p file)))
10300 (file (if (and dirp org-open-directory-means-index-dot-org)
10301 (concat (file-name-as-directory file) "index.org")
10302 file))
10303 (a-m-a-p (assq 'auto-mode apps))
10304 (dfile (downcase file))
10305 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10306 (link (cond ((and (eq line nil)
10307 (eq search nil))
10308 file)
10309 (line
10310 (concat file "::" (number-to-string line)))
10311 (search
10312 (concat file "::" search))))
10313 (dlink (downcase link))
10314 (old-buffer (current-buffer))
10315 (old-pos (point))
10316 (old-mode major-mode)
10317 ext cmd link-match-data)
10318 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10319 (setq ext (match-string 1 dfile))
10320 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10321 (setq ext (match-string 1 dfile))))
10322 (cond
10323 ((member in-emacs '((16) system))
10324 (setq cmd (cdr (assoc 'system apps))))
10325 (in-emacs (setq cmd 'emacs))
10327 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10328 (and dirp (cdr (assoc 'directory apps)))
10329 ; first, try matching against apps-dlink
10330 ; if we get a match here, store the match data for later
10331 (let ((match (assoc-default dlink apps-dlink
10332 'string-match)))
10333 (if match
10334 (progn (setq link-match-data (match-data))
10335 match)
10336 (progn (setq in-emacs (or in-emacs line search))
10337 nil))) ; if we have no match in apps-dlink,
10338 ; always open the file in emacs if line or search
10339 ; is given (for backwards compatibility)
10340 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10341 'string-match)
10342 (cdr (assoc ext apps))
10343 (cdr (assoc t apps))))))
10344 (when (eq cmd 'system)
10345 (setq cmd (cdr (assoc 'system apps))))
10346 (when (eq cmd 'default)
10347 (setq cmd (cdr (assoc t apps))))
10348 (when (eq cmd 'mailcap)
10349 (require 'mailcap)
10350 (mailcap-parse-mailcaps)
10351 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10352 (command (mailcap-mime-info mime-type)))
10353 (if (stringp command)
10354 (setq cmd command)
10355 (setq cmd 'emacs))))
10356 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10357 (not (file-exists-p file))
10358 (not org-open-non-existing-files))
10359 (error "No such file: %s" file))
10360 (cond
10361 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10362 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10363 (while (string-match "['\"]%s['\"]" cmd)
10364 (setq cmd (replace-match "%s" t t cmd)))
10365 (while (string-match "%s" cmd)
10366 (setq cmd (replace-match
10367 (save-match-data
10368 (shell-quote-argument
10369 (convert-standard-filename file)))
10370 t t cmd)))
10372 ;; Replace "%1", "%2" etc. in command with group matches from regex
10373 (save-match-data
10374 (let ((match-index 1)
10375 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10376 (set-match-data link-match-data)
10377 (while (<= match-index number-of-groups)
10378 (let ((regex (concat "%" (number-to-string match-index)))
10379 (replace-with (match-string match-index dlink)))
10380 (while (string-match regex cmd)
10381 (setq cmd (replace-match replace-with t t cmd))))
10382 (setq match-index (+ match-index 1)))))
10384 (save-window-excursion
10385 (start-process-shell-command cmd nil cmd)
10386 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10388 ((or (stringp cmd)
10389 (eq cmd 'emacs))
10390 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10391 (widen)
10392 (if line (org-goto-line line)
10393 (if search (org-link-search search))))
10394 ((consp cmd)
10395 (let ((file (convert-standard-filename file)))
10396 (save-match-data
10397 (set-match-data link-match-data)
10398 (eval cmd))))
10399 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10400 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10401 (or (not (equal old-buffer (current-buffer)))
10402 (not (equal old-pos (point))))
10403 (org-mark-ring-push old-pos old-buffer))))
10405 (defun org-file-apps-entry-match-against-dlink-p (entry)
10406 "This function returns non-nil if `entry' uses a regular
10407 expression which should be matched against the whole link by
10408 org-open-file.
10410 It assumes that is the case when the entry uses a regular
10411 expression which has at least one grouping construct and the
10412 action is either a lisp form or a command string containing
10413 '%1', i.e. using at least one subexpression match as a
10414 parameter."
10415 (let ((selector (car entry))
10416 (action (cdr entry)))
10417 (if (stringp selector)
10418 (and (> (regexp-opt-depth selector) 0)
10419 (or (and (stringp action)
10420 (string-match "%[0-9]" action))
10421 (consp action)))
10422 nil)))
10424 (defun org-default-apps ()
10425 "Return the default applications for this operating system."
10426 (cond
10427 ((eq system-type 'darwin)
10428 org-file-apps-defaults-macosx)
10429 ((eq system-type 'windows-nt)
10430 org-file-apps-defaults-windowsnt)
10431 (t org-file-apps-defaults-gnu)))
10433 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10434 "Convert extensions to regular expressions in the cars of LIST.
10435 Also, weed out any non-string entries, because the return value is used
10436 only for regexp matching.
10437 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10438 point to the symbol `emacs', indicating that the file should
10439 be opened in Emacs."
10440 (append
10441 (delq nil
10442 (mapcar (lambda (x)
10443 (if (not (stringp (car x)))
10445 (if (string-match "\\W" (car x))
10447 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10448 list))
10449 (if add-auto-mode
10450 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10452 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10453 (defun org-file-remote-p (file)
10454 "Test whether FILE specifies a location on a remote system.
10455 Return non-nil if the location is indeed remote.
10457 For example, the filename \"/user@host:/foo\" specifies a location
10458 on the system \"/user@host:\"."
10459 (cond ((fboundp 'file-remote-p)
10460 (file-remote-p file))
10461 ((fboundp 'tramp-handle-file-remote-p)
10462 (tramp-handle-file-remote-p file))
10463 ((and (boundp 'ange-ftp-name-format)
10464 (string-match (car ange-ftp-name-format) file))
10465 t)))
10468 ;;;; Refiling
10470 (defun org-get-org-file ()
10471 "Read a filename, with default directory `org-directory'."
10472 (let ((default (or org-default-notes-file remember-data-file)))
10473 (read-file-name (format "File name [%s]: " default)
10474 (file-name-as-directory org-directory)
10475 default)))
10477 (defun org-notes-order-reversed-p ()
10478 "Check if the current file should receive notes in reversed order."
10479 (cond
10480 ((not org-reverse-note-order) nil)
10481 ((eq t org-reverse-note-order) t)
10482 ((not (listp org-reverse-note-order)) nil)
10483 (t (catch 'exit
10484 (let ((all org-reverse-note-order)
10485 entry)
10486 (while (setq entry (pop all))
10487 (if (string-match (car entry) buffer-file-name)
10488 (throw 'exit (cdr entry))))
10489 nil)))))
10491 (defvar org-refile-target-table nil
10492 "The list of refile targets, created by `org-refile'.")
10494 (defvar org-agenda-new-buffers nil
10495 "Buffers created to visit agenda files.")
10497 (defvar org-refile-cache nil
10498 "Cache for refile targets.")
10500 (defvar org-refile-markers nil
10501 "All the markers used for caching refile locations.")
10503 (defun org-refile-marker (pos)
10504 "Get a new refile marker, but only if caching is in use."
10505 (if (not org-refile-use-cache)
10507 (let ((m (make-marker)))
10508 (move-marker m pos)
10509 (push m org-refile-markers)
10510 m)))
10512 (defun org-refile-cache-clear ()
10513 "Clear the refile cache and disable all the markers."
10514 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10515 (setq org-refile-markers nil)
10516 (setq org-refile-cache nil)
10517 (message "Refile cache has been cleared"))
10519 (defun org-refile-cache-check-set (set)
10520 "Check if all the markers in the cache still have live buffers."
10521 (let (marker)
10522 (catch 'exit
10523 (while (and set (setq marker (nth 3 (pop set))))
10524 ;; if org-refile-use-outline-path is 'file, marker may be nil
10525 (when (and marker (null (marker-buffer marker)))
10526 (message "not found") (sit-for 3)
10527 (throw 'exit nil)))
10528 t)))
10530 (defun org-refile-cache-put (set &rest identifiers)
10531 "Push the refile targets SET into the cache, under IDENTIFIERS."
10532 (let* ((key (sha1 (prin1-to-string identifiers)))
10533 (entry (assoc key org-refile-cache)))
10534 (if entry
10535 (setcdr entry set)
10536 (push (cons key set) org-refile-cache))))
10538 (defun org-refile-cache-get (&rest identifiers)
10539 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10540 (cond
10541 ((not org-refile-cache) nil)
10542 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10544 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10545 org-refile-cache))))
10546 (and set (org-refile-cache-check-set set) set)))))
10548 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10549 "Produce a table with refile targets."
10550 (let ((case-fold-search nil)
10551 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10552 (entries (or org-refile-targets '((nil . (:level . 1)))))
10553 targets tgs txt re files f desc descre fast-path-p level pos0)
10554 (message "Getting targets...")
10555 (with-current-buffer (or default-buffer (current-buffer))
10556 (while (setq entry (pop entries))
10557 (setq files (car entry) desc (cdr entry))
10558 (setq fast-path-p nil)
10559 (cond
10560 ((null files) (setq files (list (current-buffer))))
10561 ((eq files 'org-agenda-files)
10562 (setq files (org-agenda-files 'unrestricted)))
10563 ((and (symbolp files) (fboundp files))
10564 (setq files (funcall files)))
10565 ((and (symbolp files) (boundp files))
10566 (setq files (symbol-value files))))
10567 (if (stringp files) (setq files (list files)))
10568 (cond
10569 ((eq (car desc) :tag)
10570 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10571 ((eq (car desc) :todo)
10572 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10573 ((eq (car desc) :regexp)
10574 (setq descre (cdr desc)))
10575 ((eq (car desc) :level)
10576 (setq descre (concat "^\\*\\{" (number-to-string
10577 (if org-odd-levels-only
10578 (1- (* 2 (cdr desc)))
10579 (cdr desc)))
10580 "\\}[ \t]")))
10581 ((eq (car desc) :maxlevel)
10582 (setq fast-path-p t)
10583 (setq descre (concat "^\\*\\{1," (number-to-string
10584 (if org-odd-levels-only
10585 (1- (* 2 (cdr desc)))
10586 (cdr desc)))
10587 "\\}[ \t]")))
10588 (t (error "Bad refiling target description %s" desc)))
10589 (while (setq f (pop files))
10590 (with-current-buffer
10591 (if (bufferp f) f (org-get-agenda-file-buffer f))
10593 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10594 (progn
10595 (if (bufferp f) (setq f (buffer-file-name
10596 (buffer-base-buffer f))))
10597 (setq f (and f (expand-file-name f)))
10598 (if (eq org-refile-use-outline-path 'file)
10599 (push (list (file-name-nondirectory f) f nil nil) tgs))
10600 (save-excursion
10601 (save-restriction
10602 (widen)
10603 (goto-char (point-min))
10604 (while (re-search-forward descre nil t)
10605 (goto-char (setq pos0 (point-at-bol)))
10606 (catch 'next
10607 (when org-refile-target-verify-function
10608 (save-match-data
10609 (or (funcall org-refile-target-verify-function)
10610 (throw 'next t))))
10611 (when (and (looking-at org-complex-heading-regexp)
10612 (not (member (match-string 4) excluded-entries))
10613 (match-string 4))
10614 (setq level (org-reduced-level
10615 (- (match-end 1) (match-beginning 1)))
10616 txt (org-link-display-format (match-string 4))
10617 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10618 re (format org-complex-heading-regexp-format
10619 (regexp-quote (match-string 4))))
10620 (when org-refile-use-outline-path
10621 (setq txt (mapconcat
10622 'org-protect-slash
10623 (append
10624 (if (eq org-refile-use-outline-path
10625 'file)
10626 (list (file-name-nondirectory
10627 (buffer-file-name
10628 (buffer-base-buffer))))
10629 (if (eq org-refile-use-outline-path
10630 'full-file-path)
10631 (list (buffer-file-name
10632 (buffer-base-buffer)))))
10633 (org-get-outline-path fast-path-p
10634 level txt)
10635 (list txt))
10636 "/")))
10637 (push (list txt f re (org-refile-marker (point)))
10638 tgs)))
10639 (when (= (point) pos0)
10640 ;; verification function has not moved point
10641 (goto-char (point-at-eol))))))))
10642 (when org-refile-use-cache
10643 (org-refile-cache-put tgs (buffer-file-name) descre))
10644 (setq targets (append tgs targets))
10645 ))))
10646 (message "Getting targets...done")
10647 (nreverse targets)))
10649 (defun org-protect-slash (s)
10650 (while (string-match "/" s)
10651 (setq s (replace-match "\\" t t s)))
10654 (defvar org-olpa (make-vector 20 nil))
10656 (defun org-get-outline-path (&optional fastp level heading)
10657 "Return the outline path to the current entry, as a list.
10659 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10660 routine which makes outline path derivations for an entire file,
10661 avoiding backtracing. Refile target collection makes use of that."
10662 (if fastp
10663 (progn
10664 (if (> level 19)
10665 (error "Outline path failure, more than 19 levels"))
10666 (loop for i from level upto 19 do
10667 (aset org-olpa i nil))
10668 (prog1
10669 (delq nil (append org-olpa nil))
10670 (aset org-olpa level heading)))
10671 (let (rtn case-fold-search)
10672 (save-excursion
10673 (save-restriction
10674 (widen)
10675 (while (org-up-heading-safe)
10676 (when (looking-at org-complex-heading-regexp)
10677 (push (org-match-string-no-properties 4) rtn)))
10678 rtn)))))
10680 (defun org-format-outline-path (path &optional width prefix)
10681 "Format the outline path PATH for display.
10682 Width is the maximum number of characters that is available.
10683 Prefix is a prefix to be included in the returned string,
10684 such as the file name."
10685 (setq width (or width 79))
10686 (if prefix (setq width (- width (length prefix))))
10687 (if (not path)
10688 (or prefix "")
10689 (let* ((nsteps (length path))
10690 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10691 (maxwidth (if (<= total-width width)
10692 10000 ;; everything fits
10693 ;; we need to shorten the level headings
10694 (/ (- width nsteps) nsteps)))
10695 (org-odd-levels-only nil)
10696 (n 0)
10697 (total (1+ (length prefix))))
10698 (setq maxwidth (max maxwidth 10))
10699 (concat prefix
10700 (mapconcat
10701 (lambda (h)
10702 (setq n (1+ n))
10703 (if (and (= n nsteps) (< maxwidth 10000))
10704 (setq maxwidth (- total-width total)))
10705 (if (< (length h) maxwidth)
10706 (progn (setq total (+ total (length h) 1)) h)
10707 (setq h (substring h 0 (- maxwidth 2))
10708 total (+ total maxwidth 1))
10709 (if (string-match "[ \t]+\\'" h)
10710 (setq h (substring h 0 (match-beginning 0))))
10711 (setq h (concat h "..")))
10712 (org-add-props h nil 'face
10713 (nth (% (1- n) org-n-level-faces)
10714 org-level-faces))
10716 path "/")))))
10718 (defun org-display-outline-path (&optional file current)
10719 "Display the current outline path in the echo area."
10720 (interactive "P")
10721 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10722 (case-fold-search nil)
10723 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10724 (if current (setq path (append path
10725 (save-excursion
10726 (org-back-to-heading t)
10727 (if (looking-at org-complex-heading-regexp)
10728 (list (match-string 4)))))))
10729 (message "%s"
10730 (org-format-outline-path
10731 path
10732 (1- (frame-width))
10733 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10735 (defvar org-refile-history nil
10736 "History for refiling operations.")
10738 (defvar org-after-refile-insert-hook nil
10739 "Hook run after `org-refile' has inserted its stuff at the new location.
10740 Note that this is still *before* the stuff will be removed from
10741 the *old* location.")
10743 (defvar org-capture-last-stored-marker)
10744 (defun org-refile (&optional goto default-buffer rfloc)
10745 "Move the entry or entries at point to another heading.
10746 The list of target headings is compiled using the information in
10747 `org-refile-targets', which see.
10749 At the target location, the entry is filed as a subitem of the target
10750 heading. Depending on `org-reverse-note-order', the new subitem will
10751 either be the first or the last subitem.
10753 If there is an active region, all entries in that region will be moved.
10754 However, the region must fulfill the requirement that the first heading
10755 is the first one sets the top-level of the moved text - at most siblings
10756 below it are allowed.
10758 With prefix arg GOTO, the command will only visit the target location
10759 and not actually move anything.
10761 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10762 go to the location where the last refiling operation has put the subtree.
10763 With a prefix argument of `2', refile to the running clock.
10765 RFLOC can be a refile location obtained in a different way.
10767 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10769 If you are using target caching (see `org-refile-use-cache'),
10770 you have to clear the target cache in order to find new targets.
10771 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10772 prefix argument (`C-u C-u C-u C-c C-w')."
10774 (interactive "P")
10775 (if (member goto '(0 (64)))
10776 (org-refile-cache-clear)
10777 (let* ((cbuf (current-buffer))
10778 (regionp (org-region-active-p))
10779 (region-start (and regionp (region-beginning)))
10780 (region-end (and regionp (region-end)))
10781 (region-length (and regionp (- region-end region-start)))
10782 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10783 pos it nbuf file re level reversed)
10784 (setq last-command nil)
10785 (when regionp
10786 (goto-char region-start)
10787 (or (bolp) (goto-char (point-at-bol)))
10788 (setq region-start (point))
10789 (unless (or (org-kill-is-subtree-p
10790 (buffer-substring region-start region-end))
10791 (prog1 org-refile-active-region-within-subtree
10792 (org-toggle-heading)))
10793 (error "The region is not a (sequence of) subtree(s)")))
10794 (if (equal goto '(16))
10795 (org-refile-goto-last-stored)
10796 (when (or
10797 (and (equal goto 2)
10798 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10799 (prog1
10800 (setq it (list (or org-clock-heading "running clock")
10801 (buffer-file-name
10802 (marker-buffer org-clock-hd-marker))
10804 (marker-position org-clock-hd-marker)))
10805 (setq goto nil)))
10806 (setq it (or rfloc
10807 (let (heading-text)
10808 (save-excursion
10809 (unless goto
10810 (org-back-to-heading t)
10811 (setq heading-text
10812 (nth 4 (org-heading-components))))
10813 (org-refile-get-location
10814 (cond (goto "Goto")
10815 (regionp "Refile region to")
10816 (t (concat "Refile subtree \""
10817 heading-text "\" to")))
10818 default-buffer
10819 (and (not (equal '(4) goto))
10820 org-refile-allow-creating-parent-nodes)
10821 goto))))))
10822 (setq file (nth 1 it)
10823 re (nth 2 it)
10824 pos (nth 3 it))
10825 (if (and (not goto)
10827 (equal (buffer-file-name) file)
10828 (if regionp
10829 (and (>= pos region-start)
10830 (<= pos region-end))
10831 (and (>= pos (point))
10832 (< pos (save-excursion
10833 (org-end-of-subtree t t))))))
10834 (error "Cannot refile to position inside the tree or region"))
10836 (setq nbuf (or (find-buffer-visiting file)
10837 (find-file-noselect file)))
10838 (if goto
10839 (progn
10840 (org-pop-to-buffer-same-window nbuf)
10841 (goto-char pos)
10842 (org-show-context 'org-goto))
10843 (if regionp
10844 (progn
10845 (org-kill-new (buffer-substring region-start region-end))
10846 (org-save-markers-in-region region-start region-end))
10847 (org-copy-subtree 1 nil t))
10848 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10849 (find-file-noselect file)))
10850 (setq reversed (org-notes-order-reversed-p))
10851 (save-excursion
10852 (save-restriction
10853 (widen)
10854 (if pos
10855 (progn
10856 (goto-char pos)
10857 (looking-at org-outline-regexp)
10858 (setq level (org-get-valid-level (funcall outline-level) 1))
10859 (goto-char
10860 (if reversed
10861 (or (outline-next-heading) (point-max))
10862 (or (save-excursion (org-get-next-sibling))
10863 (org-end-of-subtree t t)
10864 (point-max)))))
10865 (setq level 1)
10866 (if (not reversed)
10867 (goto-char (point-max))
10868 (goto-char (point-min))
10869 (or (outline-next-heading) (goto-char (point-max)))))
10870 (if (not (bolp)) (newline))
10871 (org-paste-subtree level)
10872 (when org-log-refile
10873 (org-add-log-setup 'refile nil nil 'findpos
10874 org-log-refile)
10875 (unless (eq org-log-refile 'note)
10876 (save-excursion (org-add-log-note))))
10877 (and org-auto-align-tags
10878 (let ((org-loop-over-headlines-in-active-region nil))
10879 (org-set-tags nil t)))
10880 (with-demoted-errors
10881 (bookmark-set "org-refile-last-stored"))
10882 ;; If we are refiling for capture, make sure that the
10883 ;; last-capture pointers point here
10884 (when (org-bound-and-true-p org-refile-for-capture)
10885 (with-demoted-errors
10886 (bookmark-set "org-capture-last-stored-marker"))
10887 (move-marker org-capture-last-stored-marker (point)))
10888 (if (fboundp 'deactivate-mark) (deactivate-mark))
10889 (run-hooks 'org-after-refile-insert-hook))))
10890 (if regionp
10891 (delete-region (point) (+ (point) region-length))
10892 (org-cut-subtree))
10893 (when (featurep 'org-inlinetask)
10894 (org-inlinetask-remove-END-maybe))
10895 (setq org-markers-to-move nil)
10896 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10898 (defun org-refile-goto-last-stored ()
10899 "Go to the location where the last refile was stored."
10900 (interactive)
10901 (bookmark-jump "org-refile-last-stored")
10902 (message "This is the location of the last refile"))
10904 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10905 no-exclude)
10906 "Prompt the user for a refile location, using PROMPT.
10907 PROMPT should not be suffixed with a colon and a space, because
10908 this function appends the default value from
10909 `org-refile-history' automatically, if that is not empty.
10910 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10911 this is used for the GOTO interface."
10912 (let ((org-refile-targets org-refile-targets)
10913 (org-refile-use-outline-path org-refile-use-outline-path)
10914 excluded-entries)
10915 (when (and (derived-mode-p 'org-mode)
10916 (not org-refile-use-cache)
10917 (not no-exclude))
10918 (org-map-tree
10919 (lambda()
10920 (setq excluded-entries
10921 (append excluded-entries (list (org-get-heading t t)))))))
10922 (setq org-refile-target-table
10923 (org-refile-get-targets default-buffer excluded-entries)))
10924 (unless org-refile-target-table
10925 (error "No refile targets"))
10926 (let* ((prompt (concat prompt
10927 (and (car org-refile-history)
10928 (concat " (default " (car org-refile-history) ")"))
10929 ": "))
10930 (cbuf (current-buffer))
10931 (partial-completion-mode nil)
10932 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10933 (cfunc (if (and org-refile-use-outline-path
10934 org-outline-path-complete-in-steps)
10935 'org-olpath-completing-read
10936 'org-icompleting-read))
10937 (extra (if org-refile-use-outline-path "/" ""))
10938 (filename (and cfn (expand-file-name cfn)))
10939 (tbl (mapcar
10940 (lambda (x)
10941 (if (and (not (member org-refile-use-outline-path
10942 '(file full-file-path)))
10943 (not (equal filename (nth 1 x))))
10944 (cons (concat (car x) extra " ("
10945 (file-name-nondirectory (nth 1 x)) ")")
10946 (cdr x))
10947 (cons (concat (car x) extra) (cdr x))))
10948 org-refile-target-table))
10949 (completion-ignore-case t)
10950 pa answ parent-target child parent old-hist)
10951 (setq old-hist org-refile-history)
10952 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10953 nil 'org-refile-history (car org-refile-history)))
10954 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10955 (org-refile-check-position pa)
10956 (if pa
10957 (progn
10958 (when (or (not org-refile-history)
10959 (not (eq old-hist org-refile-history))
10960 (not (equal (car pa) (car org-refile-history))))
10961 (setq org-refile-history
10962 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10963 org-refile-history
10964 (cdr org-refile-history))))
10965 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10966 (pop org-refile-history)))
10968 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10969 (progn
10970 (setq parent (match-string 1 answ)
10971 child (match-string 2 answ))
10972 (setq parent-target (or (assoc parent tbl)
10973 (assoc (concat parent "/") tbl)))
10974 (when (and parent-target
10975 (or (eq new-nodes t)
10976 (and (eq new-nodes 'confirm)
10977 (y-or-n-p (format "Create new node \"%s\"? "
10978 child)))))
10979 (org-refile-new-child parent-target child)))
10980 (error "Invalid target location")))))
10982 (declare-function org-string-nw-p "org-macs" (s))
10983 (defun org-refile-check-position (refile-pointer)
10984 "Check if the refile pointer matches the headline to which it points."
10985 (let* ((file (nth 1 refile-pointer))
10986 (re (nth 2 refile-pointer))
10987 (pos (nth 3 refile-pointer))
10988 buffer)
10989 (if (and (not (markerp pos)) (not file))
10990 (error "Please save the buffer to a file before refiling")
10991 (when (org-string-nw-p re)
10992 (setq buffer (if (markerp pos)
10993 (marker-buffer pos)
10994 (or (find-buffer-visiting file)
10995 (find-file-noselect file))))
10996 (with-current-buffer buffer
10997 (save-excursion
10998 (save-restriction
10999 (widen)
11000 (goto-char pos)
11001 (beginning-of-line 1)
11002 (unless (org-looking-at-p re)
11003 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11005 (defun org-refile-new-child (parent-target child)
11006 "Use refile target PARENT-TARGET to add new CHILD below it."
11007 (unless parent-target
11008 (error "Cannot find parent for new node"))
11009 (let ((file (nth 1 parent-target))
11010 (pos (nth 3 parent-target))
11011 level)
11012 (with-current-buffer (or (find-buffer-visiting file)
11013 (find-file-noselect file))
11014 (save-excursion
11015 (save-restriction
11016 (widen)
11017 (if pos
11018 (goto-char pos)
11019 (goto-char (point-max))
11020 (if (not (bolp)) (newline)))
11021 (when (looking-at org-outline-regexp)
11022 (setq level (funcall outline-level))
11023 (org-end-of-subtree t t))
11024 (org-back-over-empty-lines)
11025 (insert "\n" (make-string
11026 (if pos (org-get-valid-level level 1) 1) ?*)
11027 " " child "\n")
11028 (beginning-of-line 0)
11029 (list (concat (car parent-target) "/" child) file "" (point)))))))
11031 (defun org-olpath-completing-read (prompt collection &rest args)
11032 "Read an outline path like a file name."
11033 (let ((thetable collection)
11034 (org-completion-use-ido nil) ; does not work with ido.
11035 (org-completion-use-iswitchb nil)) ; or iswitchb
11036 (apply
11037 'org-icompleting-read prompt
11038 (lambda (string predicate &optional flag)
11039 (let (rtn r f (l (length string)))
11040 (cond
11041 ((eq flag nil)
11042 ;; try completion
11043 (try-completion string thetable))
11044 ((eq flag t)
11045 ;; all-completions
11046 (setq rtn (all-completions string thetable predicate))
11047 (mapcar
11048 (lambda (x)
11049 (setq r (substring x l))
11050 (if (string-match " ([^)]*)$" x)
11051 (setq f (match-string 0 x))
11052 (setq f ""))
11053 (if (string-match "/" r)
11054 (concat string (substring r 0 (match-end 0)) f)
11056 rtn))
11057 ((eq flag 'lambda)
11058 ;; exact match?
11059 (assoc string thetable)))))
11060 args)))
11062 ;;;; Dynamic blocks
11064 (defun org-find-dblock (name)
11065 "Find the first dynamic block with name NAME in the buffer.
11066 If not found, stay at current position and return nil."
11067 (let ((case-fold-search t) pos)
11068 (save-excursion
11069 (goto-char (point-min))
11070 (setq pos (and (re-search-forward
11071 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11072 (match-beginning 0))))
11073 (if pos (goto-char pos))
11074 pos))
11076 (defconst org-dblock-start-re
11077 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11078 "Matches the start line of a dynamic block, with parameters.")
11080 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11081 "Matches the end of a dynamic block.")
11083 (defun org-create-dblock (plist)
11084 "Create a dynamic block section, with parameters taken from PLIST.
11085 PLIST must contain a :name entry which is used as name of the block."
11086 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11087 (end-of-line 1)
11088 (newline))
11089 (let ((col (current-column))
11090 (name (plist-get plist :name)))
11091 (insert "#+BEGIN: " name)
11092 (while plist
11093 (if (eq (car plist) :name)
11094 (setq plist (cddr plist))
11095 (insert " " (prin1-to-string (pop plist)))))
11096 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11097 (beginning-of-line -2)))
11099 (defun org-prepare-dblock ()
11100 "Prepare dynamic block for refresh.
11101 This empties the block, puts the cursor at the insert position and returns
11102 the property list including an extra property :name with the block name."
11103 (unless (looking-at org-dblock-start-re)
11104 (error "Not at a dynamic block"))
11105 (let* ((begdel (1+ (match-end 0)))
11106 (name (org-no-properties (match-string 1)))
11107 (params (append (list :name name)
11108 (read (concat "(" (match-string 3) ")")))))
11109 (save-excursion
11110 (beginning-of-line 1)
11111 (skip-chars-forward " \t")
11112 (setq params (plist-put params :indentation-column (current-column))))
11113 (unless (re-search-forward org-dblock-end-re nil t)
11114 (error "Dynamic block not terminated"))
11115 (setq params
11116 (append params
11117 (list :content (buffer-substring
11118 begdel (match-beginning 0)))))
11119 (delete-region begdel (match-beginning 0))
11120 (goto-char begdel)
11121 (open-line 1)
11122 params))
11124 (defun org-map-dblocks (&optional command)
11125 "Apply COMMAND to all dynamic blocks in the current buffer.
11126 If COMMAND is not given, use `org-update-dblock'."
11127 (let ((cmd (or command 'org-update-dblock)))
11128 (save-excursion
11129 (goto-char (point-min))
11130 (while (re-search-forward org-dblock-start-re nil t)
11131 (goto-char (match-beginning 0))
11132 (save-excursion
11133 (condition-case nil
11134 (funcall cmd)
11135 (error (message "Error during update of dynamic block"))))
11136 (unless (re-search-forward org-dblock-end-re nil t)
11137 (error "Dynamic block not terminated"))))))
11139 (defun org-dblock-update (&optional arg)
11140 "User command for updating dynamic blocks.
11141 Update the dynamic block at point. With prefix ARG, update all dynamic
11142 blocks in the buffer."
11143 (interactive "P")
11144 (if arg
11145 (org-update-all-dblocks)
11146 (or (looking-at org-dblock-start-re)
11147 (org-beginning-of-dblock))
11148 (org-update-dblock)))
11150 (defun org-update-dblock ()
11151 "Update the dynamic block at point.
11152 This means to empty the block, parse for parameters and then call
11153 the correct writing function."
11154 (interactive)
11155 (save-window-excursion
11156 (let* ((pos (point))
11157 (line (org-current-line))
11158 (params (org-prepare-dblock))
11159 (name (plist-get params :name))
11160 (indent (plist-get params :indentation-column))
11161 (cmd (intern (concat "org-dblock-write:" name))))
11162 (message "Updating dynamic block `%s' at line %d..." name line)
11163 (funcall cmd params)
11164 (message "Updating dynamic block `%s' at line %d...done" name line)
11165 (goto-char pos)
11166 (when (and indent (> indent 0))
11167 (setq indent (make-string indent ?\ ))
11168 (save-excursion
11169 (org-beginning-of-dblock)
11170 (forward-line 1)
11171 (while (not (looking-at org-dblock-end-re))
11172 (insert indent)
11173 (beginning-of-line 2))
11174 (when (looking-at org-dblock-end-re)
11175 (and (looking-at "[ \t]+")
11176 (replace-match ""))
11177 (insert indent)))))))
11179 (defun org-beginning-of-dblock ()
11180 "Find the beginning of the dynamic block at point.
11181 Error if there is no such block at point."
11182 (let ((pos (point))
11183 beg)
11184 (end-of-line 1)
11185 (if (and (re-search-backward org-dblock-start-re nil t)
11186 (setq beg (match-beginning 0))
11187 (re-search-forward org-dblock-end-re nil t)
11188 (> (match-end 0) pos))
11189 (goto-char beg)
11190 (goto-char pos)
11191 (error "Not in a dynamic block"))))
11193 (defun org-update-all-dblocks ()
11194 "Update all dynamic blocks in the buffer.
11195 This function can be used in a hook."
11196 (interactive)
11197 (when (derived-mode-p 'org-mode)
11198 (org-map-dblocks 'org-update-dblock)))
11201 ;;;; Completion
11203 (defconst org-additional-option-like-keywords
11204 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11205 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11206 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11207 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11208 "BEGIN:" "END:"
11209 "ORGTBL" "TBLFM:" "TBLNAME:"
11210 "BEGIN_EXAMPLE" "END_EXAMPLE"
11211 "BEGIN_VERBATIM" "END_VERBATIM"
11212 "BEGIN_QUOTE" "END_QUOTE"
11213 "BEGIN_VERSE" "END_VERSE"
11214 "BEGIN_CENTER" "END_CENTER"
11215 "BEGIN_SRC" "END_SRC"
11216 "BEGIN_RESULT" "END_RESULT"
11217 "BEGIN_lstlisting" "END_lstlisting"
11218 "NAME:" "RESULTS:"
11219 "HEADER:" "HEADERS:"
11220 "COLUMNS:" "PROPERTY:"
11221 "CAPTION:" "LABEL:"
11222 "SETUPFILE:"
11223 "INCLUDE:" "INDEX:"
11224 "BIND:"
11225 "MACRO:"))
11227 (defconst org-options-keywords
11228 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11229 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11230 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11231 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11232 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11233 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11234 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11236 (defconst org-additional-option-like-keywords-for-flyspell
11237 (delete-dups
11238 (split-string
11239 (mapconcat (lambda(k)
11240 (replace-regexp-in-string
11241 "_\\|:" " "
11242 (concat k " " (downcase k) " " (upcase k))))
11243 (append org-options-keywords org-additional-option-like-keywords)
11244 " ")
11245 " +" t)))
11247 (defcustom org-structure-template-alist
11249 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11250 "<src lang=\"?\">\n\n</src>")
11251 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11252 "<example>\n?\n</example>")
11253 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11254 "<quote>\n?\n</quote>")
11255 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11256 "<verse>\n?\n</verse>")
11257 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11258 "<center>\n?\n</center>")
11259 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11260 "<literal style=\"latex\">\n?\n</literal>")
11261 ("L" "#+LaTeX: "
11262 "<literal style=\"latex\">?</literal>")
11263 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11264 "<literal style=\"html\">\n?\n</literal>")
11265 ("H" "#+HTML: "
11266 "<literal style=\"html\">?</literal>")
11267 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11268 ("A" "#+ASCII: ")
11269 ("i" "#+INDEX: ?"
11270 "#+INDEX: ?")
11271 ("I" "#+INCLUDE: %file ?"
11272 "<include file=%file markup=\"?\">")
11274 "Structure completion elements.
11275 This is a list of abbreviation keys and values. The value gets inserted
11276 if you type `<' followed by the key and then press the completion key,
11277 usually `M-TAB'. %file will be replaced by a file name after prompting
11278 for the file using completion. The cursor will be placed at the position
11279 of the `?` in the template.
11280 There are two templates for each key, the first uses the original Org syntax,
11281 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11282 the default when the /org-mtags.el/ module has been loaded. See also the
11283 variable `org-mtags-prefer-muse-templates'."
11284 :group 'org-completion
11285 :type '(repeat
11286 (string :tag "Key")
11287 (string :tag "Template")
11288 (string :tag "Muse Template")))
11290 (defun org-try-structure-completion ()
11291 "Try to complete a structure template before point.
11292 This looks for strings like \"<e\" on an otherwise empty line and
11293 expands them."
11294 (let ((l (buffer-substring (point-at-bol) (point)))
11296 (when (and (looking-at "[ \t]*$")
11297 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11298 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11299 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11300 (match-beginning 1)) a)
11301 t)))
11303 (defun org-complete-expand-structure-template (start cell)
11304 "Expand a structure template."
11305 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11306 (rpl (nth (if musep 2 1) cell))
11307 (ind ""))
11308 (delete-region start (point))
11309 (when (string-match "\\`#\\+" rpl)
11310 (cond
11311 ((bolp))
11312 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11313 (setq ind (buffer-substring (point-at-bol) (point))))
11314 (t (newline))))
11315 (setq start (point))
11316 (if (string-match "%file" rpl)
11317 (setq rpl (replace-match
11318 (concat
11319 "\""
11320 (save-match-data
11321 (abbreviate-file-name (read-file-name "Include file: ")))
11322 "\"")
11323 t t rpl)))
11324 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11325 (concat "\n" ind)))
11326 (insert rpl)
11327 (if (re-search-backward "\\?" start t) (delete-char 1))))
11329 ;;;; TODO, DEADLINE, Comments
11331 (defun org-toggle-comment ()
11332 "Change the COMMENT state of an entry."
11333 (interactive)
11334 (save-excursion
11335 (org-back-to-heading)
11336 (let (case-fold-search)
11337 (cond
11338 ((looking-at (format org-heading-keyword-regexp-format
11339 org-comment-string))
11340 (goto-char (match-end 1))
11341 (looking-at (concat " +" org-comment-string))
11342 (replace-match "" t t)
11343 (when (eolp) (insert " ")))
11344 ((looking-at org-outline-regexp)
11345 (goto-char (match-end 0))
11346 (insert org-comment-string " "))))))
11348 (defvar org-last-todo-state-is-todo nil
11349 "This is non-nil when the last TODO state change led to a TODO state.
11350 If the last change removed the TODO tag or switched to DONE, then
11351 this is nil.")
11353 (defvar org-setting-tags nil) ; dynamically skipped
11355 (defvar org-todo-setup-filter-hook nil
11356 "Hook for functions that pre-filter todo specs.
11357 Each function takes a todo spec and returns either nil or the spec
11358 transformed into canonical form." )
11360 (defvar org-todo-get-default-hook nil
11361 "Hook for functions that get a default item for todo.
11362 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11363 nil or a string to be used for the todo mark." )
11365 (defvar org-agenda-headline-snapshot-before-repeat)
11367 (defun org-current-effective-time ()
11368 "Return current time adjusted for `org-extend-today-until' variable."
11369 (let* ((ct (org-current-time))
11370 (dct (decode-time ct))
11371 (ct1
11372 (if (and org-use-effective-time
11373 (< (nth 2 dct) org-extend-today-until))
11374 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11375 ct)))
11376 ct1))
11378 (defun org-todo-yesterday (&optional arg)
11379 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11380 (interactive "P")
11381 (if (eq major-mode 'org-agenda-mode)
11382 (apply 'org-agenda-todo-yesterday arg)
11383 (let* ((hour (third (decode-time
11384 (org-current-time))))
11385 (org-extend-today-until (1+ hour)))
11386 (org-todo arg))))
11388 (defun org-todo (&optional arg)
11389 "Change the TODO state of an item.
11390 The state of an item is given by a keyword at the start of the heading,
11391 like
11392 *** TODO Write paper
11393 *** DONE Call mom
11395 The different keywords are specified in the variable `org-todo-keywords'.
11396 By default the available states are \"TODO\" and \"DONE\".
11397 So for this example: when the item starts with TODO, it is changed to DONE.
11398 When it starts with DONE, the DONE is removed. And when neither TODO nor
11399 DONE are present, add TODO at the beginning of the heading.
11401 With \\[universal-argument] prefix arg, use completion to determine the new \
11402 state.
11403 With numeric prefix arg, switch to that state.
11404 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11405 keywords (nextset).
11406 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11407 With a numeric prefix arg of 0, inhibit note taking for the change.
11409 For calling through lisp, arg is also interpreted in the following way:
11410 'none -> empty state
11411 \"\"(empty string) -> switch to empty state
11412 'done -> switch to DONE
11413 'nextset -> switch to the next set of keywords
11414 'previousset -> switch to the previous set of keywords
11415 \"WAITING\" -> switch to the specified keyword, but only if it
11416 really is a member of `org-todo-keywords'."
11417 (interactive "P")
11418 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11419 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11420 'region-start-level 'region))
11421 org-loop-over-headlines-in-active-region)
11422 (org-map-entries
11423 `(org-todo ,arg)
11424 org-loop-over-headlines-in-active-region
11425 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11426 (if (equal arg '(16)) (setq arg 'nextset))
11427 (let ((org-blocker-hook org-blocker-hook)
11428 (case-fold-search nil))
11429 (when (equal arg '(64))
11430 (setq arg nil org-blocker-hook nil))
11431 (when (and org-blocker-hook
11432 (or org-inhibit-blocking
11433 (org-entry-get nil "NOBLOCKING")))
11434 (setq org-blocker-hook nil))
11435 (save-excursion
11436 (catch 'exit
11437 (org-back-to-heading t)
11438 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11439 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11440 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11441 (let* ((match-data (match-data))
11442 (startpos (point-at-bol))
11443 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11444 (org-log-done org-log-done)
11445 (org-log-repeat org-log-repeat)
11446 (org-todo-log-states org-todo-log-states)
11447 (org-inhibit-logging
11448 (if (equal arg 0)
11449 (progn (setq arg nil) 'note) org-inhibit-logging))
11450 (this (match-string 1))
11451 (hl-pos (match-beginning 0))
11452 (head (org-get-todo-sequence-head this))
11453 (ass (assoc head org-todo-kwd-alist))
11454 (interpret (nth 1 ass))
11455 (done-word (nth 3 ass))
11456 (final-done-word (nth 4 ass))
11457 (org-last-state (or this ""))
11458 (completion-ignore-case t)
11459 (member (member this org-todo-keywords-1))
11460 (tail (cdr member))
11461 (org-state (cond
11462 ((and org-todo-key-trigger
11463 (or (and (equal arg '(4))
11464 (eq org-use-fast-todo-selection 'prefix))
11465 (and (not arg) org-use-fast-todo-selection
11466 (not (eq org-use-fast-todo-selection
11467 'prefix)))))
11468 ;; Use fast selection
11469 (org-fast-todo-selection))
11470 ((and (equal arg '(4))
11471 (or (not org-use-fast-todo-selection)
11472 (not org-todo-key-trigger)))
11473 ;; Read a state with completion
11474 (org-icompleting-read
11475 "State: " (mapcar (lambda(x) (list x))
11476 org-todo-keywords-1)
11477 nil t))
11478 ((eq arg 'right)
11479 (if this
11480 (if tail (car tail) nil)
11481 (car org-todo-keywords-1)))
11482 ((eq arg 'left)
11483 (if (equal member org-todo-keywords-1)
11485 (if this
11486 (nth (- (length org-todo-keywords-1)
11487 (length tail) 2)
11488 org-todo-keywords-1)
11489 (org-last org-todo-keywords-1))))
11490 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11491 (setq arg nil))) ; hack to fall back to cycling
11492 (arg
11493 ;; user or caller requests a specific state
11494 (cond
11495 ((equal arg "") nil)
11496 ((eq arg 'none) nil)
11497 ((eq arg 'done) (or done-word (car org-done-keywords)))
11498 ((eq arg 'nextset)
11499 (or (car (cdr (member head org-todo-heads)))
11500 (car org-todo-heads)))
11501 ((eq arg 'previousset)
11502 (let ((org-todo-heads (reverse org-todo-heads)))
11503 (or (car (cdr (member head org-todo-heads)))
11504 (car org-todo-heads))))
11505 ((car (member arg org-todo-keywords-1)))
11506 ((stringp arg)
11507 (error "State `%s' not valid in this file" arg))
11508 ((nth (1- (prefix-numeric-value arg))
11509 org-todo-keywords-1))))
11510 ((null member) (or head (car org-todo-keywords-1)))
11511 ((equal this final-done-word) nil) ;; -> make empty
11512 ((null tail) nil) ;; -> first entry
11513 ((memq interpret '(type priority))
11514 (if (eq this-command last-command)
11515 (car tail)
11516 (if (> (length tail) 0)
11517 (or done-word (car org-done-keywords))
11518 nil)))
11520 (car tail))))
11521 (org-state (or
11522 (run-hook-with-args-until-success
11523 'org-todo-get-default-hook org-state org-last-state)
11524 org-state))
11525 (next (if org-state (concat " " org-state " ") " "))
11526 (change-plist (list :type 'todo-state-change :from this :to org-state
11527 :position startpos))
11528 dolog now-done-p)
11529 (when org-blocker-hook
11530 (setq org-last-todo-state-is-todo
11531 (not (member this org-done-keywords)))
11532 (unless (save-excursion
11533 (save-match-data
11534 (org-with-wide-buffer
11535 (run-hook-with-args-until-failure
11536 'org-blocker-hook change-plist))))
11537 (if (org-called-interactively-p 'interactive)
11538 (error "TODO state change from %s to %s blocked" this org-state)
11539 ;; fail silently
11540 (message "TODO state change from %s to %s blocked" this org-state)
11541 (throw 'exit nil))))
11542 (store-match-data match-data)
11543 (replace-match next t t)
11544 (unless (pos-visible-in-window-p hl-pos)
11545 (message "TODO state changed to %s" (org-trim next)))
11546 (unless head
11547 (setq head (org-get-todo-sequence-head org-state)
11548 ass (assoc head org-todo-kwd-alist)
11549 interpret (nth 1 ass)
11550 done-word (nth 3 ass)
11551 final-done-word (nth 4 ass)))
11552 (when (memq arg '(nextset previousset))
11553 (message "Keyword-Set %d/%d: %s"
11554 (- (length org-todo-sets) -1
11555 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11556 (length org-todo-sets)
11557 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11558 (setq org-last-todo-state-is-todo
11559 (not (member org-state org-done-keywords)))
11560 (setq now-done-p (and (member org-state org-done-keywords)
11561 (not (member this org-done-keywords))))
11562 (and logging (org-local-logging logging))
11563 (when (and (or org-todo-log-states org-log-done)
11564 (not (eq org-inhibit-logging t))
11565 (not (memq arg '(nextset previousset))))
11566 ;; we need to look at recording a time and note
11567 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11568 (nth 2 (assoc this org-todo-log-states))))
11569 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11570 (setq dolog 'time))
11571 (when (and org-state
11572 (member org-state org-not-done-keywords)
11573 (not (member this org-not-done-keywords)))
11574 ;; This is now a todo state and was not one before
11575 ;; If there was a CLOSED time stamp, get rid of it.
11576 (org-add-planning-info nil nil 'closed))
11577 (when (and now-done-p org-log-done)
11578 ;; It is now done, and it was not done before
11579 (org-add-planning-info 'closed (org-current-effective-time))
11580 (if (and (not dolog) (eq 'note org-log-done))
11581 (org-add-log-setup 'done org-state this 'findpos 'note)))
11582 (when (and org-state dolog)
11583 ;; This is a non-nil state, and we need to log it
11584 (org-add-log-setup 'state org-state this 'findpos dolog)))
11585 ;; Fixup tag positioning
11586 (org-todo-trigger-tag-changes org-state)
11587 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11588 (when org-provide-todo-statistics
11589 (org-update-parent-todo-statistics))
11590 (run-hooks 'org-after-todo-state-change-hook)
11591 (if (and arg (not (member org-state org-done-keywords)))
11592 (setq head (org-get-todo-sequence-head org-state)))
11593 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11594 ;; Do we need to trigger a repeat?
11595 (when now-done-p
11596 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11597 ;; This is for the agenda, take a snapshot of the headline.
11598 (save-match-data
11599 (setq org-agenda-headline-snapshot-before-repeat
11600 (org-get-heading))))
11601 (org-auto-repeat-maybe org-state))
11602 ;; Fixup cursor location if close to the keyword
11603 (if (and (outline-on-heading-p)
11604 (not (bolp))
11605 (save-excursion (beginning-of-line 1)
11606 (looking-at org-todo-line-regexp))
11607 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11608 (progn
11609 (goto-char (or (match-end 2) (match-end 1)))
11610 (and (looking-at " ") (just-one-space))))
11611 (when org-trigger-hook
11612 (save-excursion
11613 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11615 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11616 "Block turning an entry into a TODO, using the hierarchy.
11617 This checks whether the current task should be blocked from state
11618 changes. Such blocking occurs when:
11620 1. The task has children which are not all in a completed state.
11622 2. A task has a parent with the property :ORDERED:, and there
11623 are siblings prior to the current task with incomplete
11624 status.
11626 3. The parent of the task is blocked because it has siblings that should
11627 be done first, or is child of a block grandparent TODO entry."
11629 (if (not org-enforce-todo-dependencies)
11630 t ; if locally turned off don't block
11631 (catch 'dont-block
11632 ;; If this is not a todo state change, or if this entry is already DONE,
11633 ;; do not block
11634 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11635 (member (plist-get change-plist :from)
11636 (cons 'done org-done-keywords))
11637 (member (plist-get change-plist :to)
11638 (cons 'todo org-not-done-keywords))
11639 (not (plist-get change-plist :to)))
11640 (throw 'dont-block t))
11641 ;; If this task has children, and any are undone, it's blocked
11642 (save-excursion
11643 (org-back-to-heading t)
11644 (let ((this-level (funcall outline-level)))
11645 (outline-next-heading)
11646 (let ((child-level (funcall outline-level)))
11647 (while (and (not (eobp))
11648 (> child-level this-level))
11649 ;; this todo has children, check whether they are all
11650 ;; completed
11651 (if (and (not (org-entry-is-done-p))
11652 (org-entry-is-todo-p))
11653 (throw 'dont-block nil))
11654 (outline-next-heading)
11655 (setq child-level (funcall outline-level))))))
11656 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11657 ;; any previous siblings are undone, it's blocked
11658 (save-excursion
11659 (org-back-to-heading t)
11660 (let* ((pos (point))
11661 (parent-pos (and (org-up-heading-safe) (point))))
11662 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11663 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11664 (forward-line 1)
11665 (re-search-forward org-not-done-heading-regexp pos t))
11666 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11667 ;; Search further up the hierarchy, to see if an ancestor is blocked
11668 (while t
11669 (goto-char parent-pos)
11670 (if (not (looking-at org-not-done-heading-regexp))
11671 (throw 'dont-block t)) ; do not block, parent is not a TODO
11672 (setq pos (point))
11673 (setq parent-pos (and (org-up-heading-safe) (point)))
11674 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11675 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11676 (forward-line 1)
11677 (re-search-forward org-not-done-heading-regexp pos t))
11678 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11680 (defcustom org-track-ordered-property-with-tag nil
11681 "Should the ORDERED property also be shown as a tag?
11682 The ORDERED property decides if an entry should require subtasks to be
11683 completed in sequence. Since a property is not very visible, setting
11684 this option means that toggling the ORDERED property with the command
11685 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11686 not relevant for the behavior, but it makes things more visible.
11688 Note that toggling the tag with tags commands will not change the property
11689 and therefore not influence behavior!
11691 This can be t, meaning the tag ORDERED should be used, It can also be a
11692 string to select a different tag for this task."
11693 :group 'org-todo
11694 :type '(choice
11695 (const :tag "No tracking" nil)
11696 (const :tag "Track with ORDERED tag" t)
11697 (string :tag "Use other tag")))
11699 (defun org-toggle-ordered-property ()
11700 "Toggle the ORDERED property of the current entry.
11701 For better visibility, you can track the value of this property with a tag.
11702 See variable `org-track-ordered-property-with-tag'."
11703 (interactive)
11704 (let* ((t1 org-track-ordered-property-with-tag)
11705 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11706 (save-excursion
11707 (org-back-to-heading)
11708 (if (org-entry-get nil "ORDERED")
11709 (progn
11710 (org-delete-property "ORDERED")
11711 (and tag (org-toggle-tag tag 'off))
11712 (message "Subtasks can be completed in arbitrary order"))
11713 (org-entry-put nil "ORDERED" "t")
11714 (and tag (org-toggle-tag tag 'on))
11715 (message "Subtasks must be completed in sequence")))))
11717 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11718 (defun org-block-todo-from-checkboxes (change-plist)
11719 "Block turning an entry into a TODO, using checkboxes.
11720 This checks whether the current task should be blocked from state
11721 changes because there are unchecked boxes in this entry."
11722 (if (not org-enforce-todo-checkbox-dependencies)
11723 t ; if locally turned off don't block
11724 (catch 'dont-block
11725 ;; If this is not a todo state change, or if this entry is already DONE,
11726 ;; do not block
11727 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11728 (member (plist-get change-plist :from)
11729 (cons 'done org-done-keywords))
11730 (member (plist-get change-plist :to)
11731 (cons 'todo org-not-done-keywords))
11732 (not (plist-get change-plist :to)))
11733 (throw 'dont-block t))
11734 ;; If this task has checkboxes that are not checked, it's blocked
11735 (save-excursion
11736 (org-back-to-heading t)
11737 (let ((beg (point)) end)
11738 (outline-next-heading)
11739 (setq end (point))
11740 (goto-char beg)
11741 (if (org-list-search-forward
11742 (concat (org-item-beginning-re)
11743 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11744 "\\[[- ]\\]")
11745 end t)
11746 (progn
11747 (if (boundp 'org-blocked-by-checkboxes)
11748 (setq org-blocked-by-checkboxes t))
11749 (throw 'dont-block nil)))))
11750 t))) ; do not block
11752 (defun org-entry-blocked-p ()
11753 "Is the current entry blocked?"
11754 (if (org-entry-get nil "NOBLOCKING")
11755 nil ;; Never block this entry
11756 (not
11757 (run-hook-with-args-until-failure
11758 'org-blocker-hook
11759 (list :type 'todo-state-change
11760 :position (point)
11761 :from 'todo
11762 :to 'done)))))
11764 (defun org-update-statistics-cookies (all)
11765 "Update the statistics cookie, either from TODO or from checkboxes.
11766 This should be called with the cursor in a line with a statistics cookie."
11767 (interactive "P")
11768 (if all
11769 (progn
11770 (org-update-checkbox-count 'all)
11771 (org-map-entries 'org-update-parent-todo-statistics))
11772 (if (not (org-at-heading-p))
11773 (org-update-checkbox-count)
11774 (let ((pos (move-marker (make-marker) (point)))
11775 end l1 l2)
11776 (ignore-errors (org-back-to-heading t))
11777 (if (not (org-at-heading-p))
11778 (org-update-checkbox-count)
11779 (setq l1 (org-outline-level))
11780 (setq end (save-excursion
11781 (outline-next-heading)
11782 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11783 (point)))
11784 (if (and (save-excursion
11785 (re-search-forward
11786 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11787 (not (save-excursion (re-search-forward
11788 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11789 (org-update-checkbox-count)
11790 (if (and l2 (> l2 l1))
11791 (progn
11792 (goto-char end)
11793 (org-update-parent-todo-statistics))
11794 (goto-char pos)
11795 (beginning-of-line 1)
11796 (while (re-search-forward
11797 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11798 (point-at-eol) t)
11799 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11800 (goto-char pos)
11801 (move-marker pos nil)))))
11803 (defvar org-entry-property-inherited-from) ;; defined below
11804 (defun org-update-parent-todo-statistics ()
11805 "Update any statistics cookie in the parent of the current headline.
11806 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11807 the entire subtree and this will travel up the hierarchy and update
11808 statistics everywhere."
11809 (let* ((prop (save-excursion (org-up-heading-safe)
11810 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11811 (recursive (or (not org-hierarchical-todo-statistics)
11812 (and prop (string-match "\\<recursive\\>" prop))))
11813 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11815 (first t)
11816 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11817 level ltoggle l1 new ndel
11818 (cnt-all 0) (cnt-done 0) is-percent kwd
11819 checkbox-beg ov ovs ove cookie-present)
11820 (catch 'exit
11821 (save-excursion
11822 (beginning-of-line 1)
11823 (setq ltoggle (funcall outline-level))
11824 ;; Three situations are to consider:
11826 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11827 ;; to the top-level ancestor on the headline;
11829 ;; 2. If parent has "recursive" property, repeat up to the
11830 ;; headline setting that property, taking inheritance into
11831 ;; account;
11833 ;; 3. Else, move up to direct parent and proceed only once.
11834 (while (and (setq level (org-up-heading-safe))
11835 (or recursive first)
11836 (>= (point) lim))
11837 (setq first nil cookie-present nil)
11838 (unless (and level
11839 (not (string-match
11840 "\\<checkbox\\>"
11841 (downcase (or (org-entry-get nil "COOKIE_DATA")
11842 "")))))
11843 (throw 'exit nil))
11844 (while (re-search-forward box-re (point-at-eol) t)
11845 (setq cnt-all 0 cnt-done 0 cookie-present t)
11846 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11847 (save-match-data
11848 (unless (outline-next-heading) (throw 'exit nil))
11849 (while (and (looking-at org-complex-heading-regexp)
11850 (> (setq l1 (length (match-string 1))) level))
11851 (setq kwd (and (or recursive (= l1 ltoggle))
11852 (match-string 2)))
11853 (if (or (eq org-provide-todo-statistics 'all-headlines)
11854 (and (listp org-provide-todo-statistics)
11855 (or (member kwd org-provide-todo-statistics)
11856 (member kwd org-done-keywords))))
11857 (setq cnt-all (1+ cnt-all))
11858 (if (eq org-provide-todo-statistics t)
11859 (and kwd (setq cnt-all (1+ cnt-all)))))
11860 (and (member kwd org-done-keywords)
11861 (setq cnt-done (1+ cnt-done)))
11862 (outline-next-heading)))
11863 (setq new
11864 (if is-percent
11865 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11866 (format "[%d/%d]" cnt-done cnt-all))
11867 ndel (- (match-end 0) checkbox-beg))
11868 ;; handle overlays when updating cookie from column view
11869 (when (setq ov (car (overlays-at checkbox-beg)))
11870 (setq ovs (overlay-start ov) ove (overlay-end ov))
11871 (delete-overlay ov))
11872 (goto-char checkbox-beg)
11873 (insert new)
11874 (delete-region (point) (+ (point) ndel))
11875 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11876 (when ov (move-overlay ov ovs ove)))
11877 (when cookie-present
11878 (run-hook-with-args 'org-after-todo-statistics-hook
11879 cnt-done (- cnt-all cnt-done))))))
11880 (run-hooks 'org-todo-statistics-hook)))
11882 (defvar org-after-todo-statistics-hook nil
11883 "Hook that is called after a TODO statistics cookie has been updated.
11884 Each function is called with two arguments: the number of not-done entries
11885 and the number of done entries.
11887 For example, the following function, when added to this hook, will switch
11888 an entry to DONE when all children are done, and back to TODO when new
11889 entries are set to a TODO status. Note that this hook is only called
11890 when there is a statistics cookie in the headline!
11892 (defun org-summary-todo (n-done n-not-done)
11893 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11894 (let (org-log-done org-log-states) ; turn off logging
11895 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11898 (defvar org-todo-statistics-hook nil
11899 "Hook that is run whenever Org thinks TODO statistics should be updated.
11900 This hook runs even if there is no statistics cookie present, in which case
11901 `org-after-todo-statistics-hook' would not run.")
11903 (defun org-todo-trigger-tag-changes (state)
11904 "Apply the changes defined in `org-todo-state-tags-triggers'."
11905 (let ((l org-todo-state-tags-triggers)
11906 changes)
11907 (when (or (not state) (equal state ""))
11908 (setq changes (append changes (cdr (assoc "" l)))))
11909 (when (and (stringp state) (> (length state) 0))
11910 (setq changes (append changes (cdr (assoc state l)))))
11911 (when (member state org-not-done-keywords)
11912 (setq changes (append changes (cdr (assoc 'todo l)))))
11913 (when (member state org-done-keywords)
11914 (setq changes (append changes (cdr (assoc 'done l)))))
11915 (dolist (c changes)
11916 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11918 (defun org-local-logging (value)
11919 "Get logging settings from a property VALUE."
11920 (let* (words w a)
11921 ;; directly set the variables, they are already local.
11922 (setq org-log-done nil
11923 org-log-repeat nil
11924 org-todo-log-states nil)
11925 (setq words (org-split-string value))
11926 (while (setq w (pop words))
11927 (cond
11928 ((setq a (assoc w org-startup-options))
11929 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11930 (set (nth 1 a) (nth 2 a))))
11931 ((setq a (org-extract-log-state-settings w))
11932 (and (member (car a) org-todo-keywords-1)
11933 (push a org-todo-log-states)))))))
11935 (defun org-get-todo-sequence-head (kwd)
11936 "Return the head of the TODO sequence to which KWD belongs.
11937 If KWD is not set, check if there is a text property remembering the
11938 right sequence."
11939 (let (p)
11940 (cond
11941 ((not kwd)
11942 (or (get-text-property (point-at-bol) 'org-todo-head)
11943 (progn
11944 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11945 nil (point-at-eol)))
11946 (get-text-property p 'org-todo-head))))
11947 ((not (member kwd org-todo-keywords-1))
11948 (car org-todo-keywords-1))
11949 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11951 (defun org-fast-todo-selection ()
11952 "Fast TODO keyword selection with single keys.
11953 Returns the new TODO keyword, or nil if no state change should occur."
11954 (let* ((fulltable org-todo-key-alist)
11955 (done-keywords org-done-keywords) ;; needed for the faces.
11956 (maxlen (apply 'max (mapcar
11957 (lambda (x)
11958 (if (stringp (car x)) (string-width (car x)) 0))
11959 fulltable)))
11960 (expert nil)
11961 (fwidth (+ maxlen 3 1 3))
11962 (ncol (/ (- (window-width) 4) fwidth))
11963 tg cnt e c tbl
11964 groups ingroup)
11965 (save-excursion
11966 (save-window-excursion
11967 (if expert
11968 (set-buffer (get-buffer-create " *Org todo*"))
11969 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11970 (erase-buffer)
11971 (org-set-local 'org-done-keywords done-keywords)
11972 (setq tbl fulltable cnt 0)
11973 (while (setq e (pop tbl))
11974 (cond
11975 ((equal e '(:startgroup))
11976 (push '() groups) (setq ingroup t)
11977 (when (not (= cnt 0))
11978 (setq cnt 0)
11979 (insert "\n"))
11980 (insert "{ "))
11981 ((equal e '(:endgroup))
11982 (setq ingroup nil cnt 0)
11983 (insert "}\n"))
11984 ((equal e '(:newline))
11985 (when (not (= cnt 0))
11986 (setq cnt 0)
11987 (insert "\n")
11988 (setq e (car tbl))
11989 (while (equal (car tbl) '(:newline))
11990 (insert "\n")
11991 (setq tbl (cdr tbl)))))
11993 (setq tg (car e) c (cdr e))
11994 (if ingroup (push tg (car groups)))
11995 (setq tg (org-add-props tg nil 'face
11996 (org-get-todo-face tg)))
11997 (if (and (= cnt 0) (not ingroup)) (insert " "))
11998 (insert "[" c "] " tg (make-string
11999 (- fwidth 4 (length tg)) ?\ ))
12000 (when (= (setq cnt (1+ cnt)) ncol)
12001 (insert "\n")
12002 (if ingroup (insert " "))
12003 (setq cnt 0)))))
12004 (insert "\n")
12005 (goto-char (point-min))
12006 (if (not expert) (org-fit-window-to-buffer))
12007 (message "[a-z..]:Set [SPC]:clear")
12008 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12009 (cond
12010 ((or (= c ?\C-g)
12011 (and (= c ?q) (not (rassoc c fulltable))))
12012 (setq quit-flag t))
12013 ((= c ?\ ) nil)
12014 ((setq e (rassoc c fulltable) tg (car e))
12016 (t (setq quit-flag t)))))))
12018 (defun org-entry-is-todo-p ()
12019 (member (org-get-todo-state) org-not-done-keywords))
12021 (defun org-entry-is-done-p ()
12022 (member (org-get-todo-state) org-done-keywords))
12024 (defun org-get-todo-state ()
12025 (save-excursion
12026 (org-back-to-heading t)
12027 (and (looking-at org-todo-line-regexp)
12028 (match-end 2)
12029 (match-string 2))))
12031 (defun org-at-date-range-p (&optional inactive-ok)
12032 "Is the cursor inside a date range?"
12033 (interactive)
12034 (save-excursion
12035 (catch 'exit
12036 (let ((pos (point)))
12037 (skip-chars-backward "^[<\r\n")
12038 (skip-chars-backward "<[")
12039 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12040 (>= (match-end 0) pos)
12041 (throw 'exit t))
12042 (skip-chars-backward "^<[\r\n")
12043 (skip-chars-backward "<[")
12044 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12045 (>= (match-end 0) pos)
12046 (throw 'exit t)))
12047 nil)))
12049 (defun org-get-repeat (&optional tagline)
12050 "Check if there is a deadline/schedule with repeater in this entry."
12051 (save-match-data
12052 (save-excursion
12053 (org-back-to-heading t)
12054 (and (re-search-forward (if tagline
12055 (concat tagline "\\s-*" org-repeat-re)
12056 org-repeat-re)
12057 (org-entry-end-position) t)
12058 (match-string-no-properties 1)))))
12060 (defvar org-last-changed-timestamp)
12061 (defvar org-last-inserted-timestamp)
12062 (defvar org-log-post-message)
12063 (defvar org-log-note-purpose)
12064 (defvar org-log-note-how)
12065 (defvar org-log-note-extra)
12066 (defun org-auto-repeat-maybe (done-word)
12067 "Check if the current headline contains a repeated deadline/schedule.
12068 If yes, set TODO state back to what it was and change the base date
12069 of repeating deadline/scheduled time stamps to new date.
12070 This function is run automatically after each state change to a DONE state."
12071 ;; last-state is dynamically scoped into this function
12072 (let* ((repeat (org-get-repeat))
12073 (aa (assoc org-last-state org-todo-kwd-alist))
12074 (interpret (nth 1 aa))
12075 (head (nth 2 aa))
12076 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12077 (msg "Entry repeats: ")
12078 (org-log-done nil)
12079 (org-todo-log-states nil)
12080 re type n what ts time to-state)
12081 (when repeat
12082 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12083 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12084 org-todo-repeat-to-state))
12085 (unless (and to-state (member to-state org-todo-keywords-1))
12086 (setq to-state (if (eq interpret 'type) org-last-state head)))
12087 (org-todo to-state)
12088 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12089 (org-entry-put nil "LAST_REPEAT" (format-time-string
12090 (org-time-stamp-format t t))))
12091 (when org-log-repeat
12092 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12093 (memq 'org-add-log-note post-command-hook))
12094 ;; OK, we are already setup for some record
12095 (if (eq org-log-repeat 'note)
12096 ;; make sure we take a note, not only a time stamp
12097 (setq org-log-note-how 'note))
12098 ;; Set up for taking a record
12099 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12100 org-last-state
12101 'findpos org-log-repeat)))
12102 (org-back-to-heading t)
12103 (org-add-planning-info nil nil 'closed)
12104 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12105 org-deadline-time-regexp "\\)\\|\\("
12106 org-ts-regexp "\\)"))
12107 (while (re-search-forward
12108 re (save-excursion (outline-next-heading) (point)) t)
12109 (setq type (if (match-end 1) org-scheduled-string
12110 (if (match-end 3) org-deadline-string "Plain:"))
12111 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12112 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12113 (setq n (string-to-number (match-string 2 ts))
12114 what (match-string 3 ts))
12115 (if (equal what "w") (setq n (* n 7) what "d"))
12116 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12117 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12118 ;; Preparation, see if we need to modify the start date for the change
12119 (when (match-end 1)
12120 (setq time (save-match-data (org-time-string-to-time ts)))
12121 (cond
12122 ((equal (match-string 1 ts) ".")
12123 ;; Shift starting date to today
12124 (org-timestamp-change
12125 (- (org-today) (time-to-days time))
12126 'day))
12127 ((equal (match-string 1 ts) "+")
12128 (let ((nshiftmax 10) (nshift 0))
12129 (while (or (= nshift 0)
12130 (<= (time-to-days time)
12131 (time-to-days (current-time))))
12132 (when (= (incf nshift) nshiftmax)
12133 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12134 (error "Abort")))
12135 (org-timestamp-change n (cdr (assoc what whata)))
12136 (org-at-timestamp-p t)
12137 (setq ts (match-string 1))
12138 (setq time (save-match-data (org-time-string-to-time ts)))))
12139 (org-timestamp-change (- n) (cdr (assoc what whata)))
12140 ;; rematch, so that we have everything in place for the real shift
12141 (org-at-timestamp-p t)
12142 (setq ts (match-string 1))
12143 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12144 (org-timestamp-change n (cdr (assoc what whata)))
12145 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12146 (setq org-log-post-message msg)
12147 (message "%s" msg))))
12149 (defun org-show-todo-tree (arg)
12150 "Make a compact tree which shows all headlines marked with TODO.
12151 The tree will show the lines where the regexp matches, and all higher
12152 headlines above the match.
12153 With a \\[universal-argument] prefix, prompt for a regexp to match.
12154 With a numeric prefix N, construct a sparse tree for the Nth element
12155 of `org-todo-keywords-1'."
12156 (interactive "P")
12157 (let ((case-fold-search nil)
12158 (kwd-re
12159 (cond ((null arg) org-not-done-regexp)
12160 ((equal arg '(4))
12161 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12162 (mapcar 'list org-todo-keywords-1))))
12163 (concat "\\("
12164 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12165 "\\)\\>")))
12166 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12167 (regexp-quote (nth (1- (prefix-numeric-value arg))
12168 org-todo-keywords-1)))
12169 (t (error "Invalid prefix argument: %s" arg)))))
12170 (message "%d TODO entries found"
12171 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12173 (defun org-deadline (&optional remove time)
12174 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12175 With argument REMOVE, remove any deadline from the item.
12176 With argument TIME, set the deadline at the corresponding date. TIME
12177 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12178 (interactive "P")
12179 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12180 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12181 'region-start-level 'region))
12182 org-loop-over-headlines-in-active-region)
12183 (org-map-entries
12184 `(org-deadline ',remove ,time)
12185 org-loop-over-headlines-in-active-region
12186 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12187 (let* ((old-date (org-entry-get nil "DEADLINE"))
12188 (repeater (and old-date
12189 (string-match
12190 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12191 old-date)
12192 (match-string 1 old-date))))
12193 (if remove
12194 (progn
12195 (when (and old-date org-log-redeadline)
12196 (org-add-log-setup 'deldeadline nil old-date 'findpos
12197 org-log-redeadline))
12198 (org-remove-timestamp-with-keyword org-deadline-string)
12199 (message "Item no longer has a deadline."))
12200 (org-add-planning-info 'deadline time 'closed)
12201 (when (and old-date org-log-redeadline
12202 (not (equal old-date
12203 (substring org-last-inserted-timestamp 1 -1))))
12204 (org-add-log-setup 'redeadline nil old-date 'findpos
12205 org-log-redeadline))
12206 (when repeater
12207 (save-excursion
12208 (org-back-to-heading t)
12209 (when (re-search-forward (concat org-deadline-string " "
12210 org-last-inserted-timestamp)
12211 (save-excursion
12212 (outline-next-heading) (point)) t)
12213 (goto-char (1- (match-end 0)))
12214 (insert " " repeater)
12215 (setq org-last-inserted-timestamp
12216 (concat (substring org-last-inserted-timestamp 0 -1)
12217 " " repeater
12218 (substring org-last-inserted-timestamp -1))))))
12219 (message "Deadline on %s" org-last-inserted-timestamp)))))
12221 (defun org-schedule (&optional remove time)
12222 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12223 With argument REMOVE, remove any scheduling date from the item.
12224 With argument TIME, scheduled at the corresponding date. TIME can
12225 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12226 (interactive "P")
12227 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12228 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12229 'region-start-level 'region))
12230 org-loop-over-headlines-in-active-region)
12231 (org-map-entries
12232 `(org-schedule ',remove ,time)
12233 org-loop-over-headlines-in-active-region
12234 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12235 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12236 (repeater (and old-date
12237 (string-match
12238 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12239 old-date)
12240 (match-string 1 old-date))))
12241 (if remove
12242 (progn
12243 (when (and old-date org-log-reschedule)
12244 (org-add-log-setup 'delschedule nil old-date 'findpos
12245 org-log-reschedule))
12246 (org-remove-timestamp-with-keyword org-scheduled-string)
12247 (message "Item is no longer scheduled."))
12248 (org-add-planning-info 'scheduled time 'closed)
12249 (when (and old-date org-log-reschedule
12250 (not (equal old-date
12251 (substring org-last-inserted-timestamp 1 -1))))
12252 (org-add-log-setup 'reschedule nil old-date 'findpos
12253 org-log-reschedule))
12254 (when repeater
12255 (save-excursion
12256 (org-back-to-heading t)
12257 (when (re-search-forward (concat org-scheduled-string " "
12258 org-last-inserted-timestamp)
12259 (save-excursion
12260 (outline-next-heading) (point)) t)
12261 (goto-char (1- (match-end 0)))
12262 (insert " " repeater)
12263 (setq org-last-inserted-timestamp
12264 (concat (substring org-last-inserted-timestamp 0 -1)
12265 " " repeater
12266 (substring org-last-inserted-timestamp -1))))))
12267 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12269 (defun org-get-scheduled-time (pom &optional inherit)
12270 "Get the scheduled time as a time tuple, of a format suitable
12271 for calling org-schedule with, or if there is no scheduling,
12272 returns nil."
12273 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12274 (when time
12275 (apply 'encode-time (org-parse-time-string time)))))
12277 (defun org-get-deadline-time (pom &optional inherit)
12278 "Get the deadline as a time tuple, of a format suitable for
12279 calling org-deadline with, or if there is no scheduling, returns
12280 nil."
12281 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12282 (when time
12283 (apply 'encode-time (org-parse-time-string time)))))
12285 (defun org-remove-timestamp-with-keyword (keyword)
12286 "Remove all time stamps with KEYWORD in the current entry."
12287 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12288 beg)
12289 (save-excursion
12290 (org-back-to-heading t)
12291 (setq beg (point))
12292 (outline-next-heading)
12293 (while (re-search-backward re beg t)
12294 (replace-match "")
12295 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12296 (equal (char-before) ?\ ))
12297 (backward-delete-char 1)
12298 (if (string-match "^[ \t]*$" (buffer-substring
12299 (point-at-bol) (point-at-eol)))
12300 (delete-region (point-at-bol)
12301 (min (point-max) (1+ (point-at-eol))))))))))
12303 (defun org-add-planning-info (what &optional time &rest remove)
12304 "Insert new timestamp with keyword in the line directly after the headline.
12305 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12306 If non is given, the user is prompted for a date.
12307 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12308 be removed."
12309 (interactive)
12310 (let (org-time-was-given org-end-time-was-given ts
12311 end default-time default-input)
12313 (catch 'exit
12314 (when (and (memq what '(scheduled deadline))
12315 (or (not time)
12316 (and (stringp time)
12317 (string-match "^[-+]+[0-9]" time))))
12318 ;; Try to get a default date/time from existing timestamp
12319 (save-excursion
12320 (org-back-to-heading t)
12321 (setq end (save-excursion (outline-next-heading) (point)))
12322 (when (re-search-forward (if (eq what 'scheduled)
12323 org-scheduled-time-regexp
12324 org-deadline-time-regexp)
12325 end t)
12326 (setq ts (match-string 1)
12327 default-time
12328 (apply 'encode-time (org-parse-time-string ts))
12329 default-input (and ts (org-get-compact-tod ts))))))
12330 (when what
12331 (setq time
12332 (if (stringp time)
12333 ;; This is a string (relative or absolute), set proper date
12334 (apply 'encode-time
12335 (org-read-date-analyze
12336 time default-time (decode-time default-time)))
12337 ;; If necessary, get the time from the user
12338 (or time (org-read-date nil 'to-time nil nil
12339 default-time default-input)))))
12341 (when (and org-insert-labeled-timestamps-at-point
12342 (member what '(scheduled deadline)))
12343 (insert
12344 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12345 (org-insert-time-stamp time org-time-was-given
12346 nil nil nil (list org-end-time-was-given))
12347 (setq what nil))
12348 (save-excursion
12349 (save-restriction
12350 (let (col list elt ts buffer-invisibility-spec)
12351 (org-back-to-heading t)
12352 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12353 (goto-char (match-end 1))
12354 (setq col (current-column))
12355 (goto-char (match-end 0))
12356 (if (eobp) (insert "\n") (forward-char 1))
12357 (when (and (not what)
12358 (not (looking-at
12359 (concat "[ \t]*"
12360 org-keyword-time-not-clock-regexp))))
12361 ;; Nothing to add, nothing to remove...... :-)
12362 (throw 'exit nil))
12363 (if (and (not (looking-at org-outline-regexp))
12364 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12365 "[^\r\n]*"))
12366 (not (equal (match-string 1) org-clock-string)))
12367 (narrow-to-region (match-beginning 0) (match-end 0))
12368 (insert-before-markers "\n")
12369 (backward-char 1)
12370 (narrow-to-region (point) (point))
12371 (and org-adapt-indentation (org-indent-to-column col)))
12372 ;; Check if we have to remove something.
12373 (setq list (cons what remove))
12374 (while list
12375 (setq elt (pop list))
12376 (when (or (and (eq elt 'scheduled)
12377 (re-search-forward org-scheduled-time-regexp nil t))
12378 (and (eq elt 'deadline)
12379 (re-search-forward org-deadline-time-regexp nil t))
12380 (and (eq elt 'closed)
12381 (re-search-forward org-closed-time-regexp nil t)))
12382 (replace-match "")
12383 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12384 (and (looking-at "[ \t]+") (replace-match ""))
12385 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12386 (when what
12387 (insert
12388 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12389 (cond ((eq what 'scheduled) org-scheduled-string)
12390 ((eq what 'deadline) org-deadline-string)
12391 ((eq what 'closed) org-closed-string))
12392 " ")
12393 (setq ts (org-insert-time-stamp
12394 time
12395 (or org-time-was-given
12396 (and (eq what 'closed) org-log-done-with-time))
12397 (eq what 'closed)
12398 nil nil (list org-end-time-was-given)))
12399 (insert
12400 (if (not (or (bolp) (eq (char-before) ?\ )
12401 (memq (char-after) '(32 10))
12402 (eobp))) " " ""))
12403 (end-of-line 1))
12404 (goto-char (point-min))
12405 (widen)
12406 (if (and (looking-at "[ \t]*\n")
12407 (equal (char-before) ?\n))
12408 (delete-region (1- (point)) (point-at-eol)))
12409 ts))))))
12411 (defvar org-log-note-marker (make-marker))
12412 (defvar org-log-note-purpose nil)
12413 (defvar org-log-note-state nil)
12414 (defvar org-log-note-previous-state nil)
12415 (defvar org-log-note-how nil)
12416 (defvar org-log-note-extra nil)
12417 (defvar org-log-note-window-configuration nil)
12418 (defvar org-log-note-return-to (make-marker))
12419 (defvar org-log-note-effective-time nil
12420 "Remembered current time so that dynamically scoped
12421 `org-extend-today-until' affects tha timestamps in state change
12422 log")
12424 (defvar org-log-post-message nil
12425 "Message to be displayed after a log note has been stored.
12426 The auto-repeater uses this.")
12428 (defun org-add-note ()
12429 "Add a note to the current entry.
12430 This is done in the same way as adding a state change note."
12431 (interactive)
12432 (org-add-log-setup 'note nil nil 'findpos nil))
12434 (defvar org-property-end-re)
12435 (defun org-add-log-setup (&optional purpose state prev-state
12436 findpos how extra)
12437 "Set up the post command hook to take a note.
12438 If this is about to TODO state change, the new state is expected in STATE.
12439 When FINDPOS is non-nil, find the correct position for the note in
12440 the current entry. If not, assume that it can be inserted at point.
12441 HOW is an indicator what kind of note should be created.
12442 EXTRA is additional text that will be inserted into the notes buffer."
12443 (let* ((org-log-into-drawer (org-log-into-drawer))
12444 (drawer (cond ((stringp org-log-into-drawer)
12445 org-log-into-drawer)
12446 (org-log-into-drawer "LOGBOOK"))))
12447 (save-restriction
12448 (save-excursion
12449 (when findpos
12450 (org-back-to-heading t)
12451 (narrow-to-region (point) (save-excursion
12452 (outline-next-heading) (point)))
12453 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12454 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12455 "[^\r\n]*\\)?"))
12456 (goto-char (match-end 0))
12457 (cond
12458 (drawer
12459 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12460 nil t)
12461 (progn
12462 (goto-char (match-end 0))
12463 (or org-log-states-order-reversed
12464 (and (re-search-forward org-property-end-re nil t)
12465 (goto-char (1- (match-beginning 0))))))
12466 (insert "\n:" drawer ":\n:END:")
12467 (beginning-of-line 0)
12468 (org-indent-line)
12469 (beginning-of-line 2)
12470 (org-indent-line)
12471 (end-of-line 0)))
12472 ((and org-log-state-notes-insert-after-drawers
12473 (save-excursion
12474 (forward-line) (looking-at org-drawer-regexp)))
12475 (forward-line)
12476 (while (looking-at org-drawer-regexp)
12477 (goto-char (match-end 0))
12478 (re-search-forward org-property-end-re (point-max) t)
12479 (forward-line))
12480 (forward-line -1)))
12481 (unless org-log-states-order-reversed
12482 (and (= (char-after) ?\n) (forward-char 1))
12483 (org-skip-over-state-notes)
12484 (skip-chars-backward " \t\n\r")))
12485 (move-marker org-log-note-marker (point))
12486 (setq org-log-note-purpose purpose
12487 org-log-note-state state
12488 org-log-note-previous-state prev-state
12489 org-log-note-how how
12490 org-log-note-extra extra
12491 org-log-note-effective-time (org-current-effective-time))
12492 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12494 (defun org-skip-over-state-notes ()
12495 "Skip past the list of State notes in an entry."
12496 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12497 (when (ignore-errors (goto-char (org-in-item-p)))
12498 (let* ((struct (org-list-struct))
12499 (prevs (org-list-prevs-alist struct)))
12500 (while (looking-at "[ \t]*- State")
12501 (goto-char (or (org-list-get-next-item (point) struct prevs)
12502 (org-list-get-item-end (point) struct)))))))
12504 (defun org-add-log-note (&optional purpose)
12505 "Pop up a window for taking a note, and add this note later at point."
12506 (remove-hook 'post-command-hook 'org-add-log-note)
12507 (setq org-log-note-window-configuration (current-window-configuration))
12508 (delete-other-windows)
12509 (move-marker org-log-note-return-to (point))
12510 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12511 (goto-char org-log-note-marker)
12512 (org-switch-to-buffer-other-window "*Org Note*")
12513 (erase-buffer)
12514 (if (memq org-log-note-how '(time state))
12515 (let (current-prefix-arg) (org-store-log-note))
12516 (let ((org-inhibit-startup t)) (org-mode))
12517 (insert (format "# Insert note for %s.
12518 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12519 (cond
12520 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12521 ((eq org-log-note-purpose 'done) "closed todo item")
12522 ((eq org-log-note-purpose 'state)
12523 (format "state change from \"%s\" to \"%s\""
12524 (or org-log-note-previous-state "")
12525 (or org-log-note-state "")))
12526 ((eq org-log-note-purpose 'reschedule)
12527 "rescheduling")
12528 ((eq org-log-note-purpose 'delschedule)
12529 "no longer scheduled")
12530 ((eq org-log-note-purpose 'redeadline)
12531 "changing deadline")
12532 ((eq org-log-note-purpose 'deldeadline)
12533 "removing deadline")
12534 ((eq org-log-note-purpose 'refile)
12535 "refiling")
12536 ((eq org-log-note-purpose 'note)
12537 "this entry")
12538 (t (error "This should not happen")))))
12539 (if org-log-note-extra (insert org-log-note-extra))
12540 (org-set-local 'org-finish-function 'org-store-log-note)
12541 (run-hooks 'org-log-buffer-setup-hook)))
12543 (defvar org-note-abort nil) ; dynamically scoped
12544 (defun org-store-log-note ()
12545 "Finish taking a log note, and insert it to where it belongs."
12546 (let ((txt (buffer-string))
12547 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12548 lines ind bul)
12549 (kill-buffer (current-buffer))
12550 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12551 (setq txt (replace-match "" t t txt)))
12552 (if (string-match "\\s-+\\'" txt)
12553 (setq txt (replace-match "" t t txt)))
12554 (setq lines (org-split-string txt "\n"))
12555 (when (and note (string-match "\\S-" note))
12556 (setq note
12557 (org-replace-escapes
12558 note
12559 (list (cons "%u" (user-login-name))
12560 (cons "%U" user-full-name)
12561 (cons "%t" (format-time-string
12562 (org-time-stamp-format 'long 'inactive)
12563 org-log-note-effective-time))
12564 (cons "%T" (format-time-string
12565 (org-time-stamp-format 'long nil)
12566 org-log-note-effective-time))
12567 (cons "%d" (format-time-string
12568 (org-time-stamp-format nil 'inactive)
12569 org-log-note-effective-time))
12570 (cons "%D" (format-time-string
12571 (org-time-stamp-format nil nil)
12572 org-log-note-effective-time))
12573 (cons "%s" (if org-log-note-state
12574 (concat "\"" org-log-note-state "\"")
12575 ""))
12576 (cons "%S" (if org-log-note-previous-state
12577 (concat "\"" org-log-note-previous-state "\"")
12578 "\"\"")))))
12579 (if lines (setq note (concat note " \\\\")))
12580 (push note lines))
12581 (when (or current-prefix-arg org-note-abort)
12582 (when org-log-into-drawer
12583 (org-remove-empty-drawer-at
12584 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12585 org-log-note-marker))
12586 (setq lines nil))
12587 (when lines
12588 (with-current-buffer (marker-buffer org-log-note-marker)
12589 (save-excursion
12590 (goto-char org-log-note-marker)
12591 (move-marker org-log-note-marker nil)
12592 (end-of-line 1)
12593 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12594 (setq ind (save-excursion
12595 (if (ignore-errors (goto-char (org-in-item-p)))
12596 (let ((struct (org-list-struct)))
12597 (org-list-get-ind
12598 (org-list-get-top-point struct) struct))
12599 (skip-chars-backward " \r\t\n")
12600 (cond
12601 ((and (org-at-heading-p)
12602 org-adapt-indentation)
12603 (1+ (org-current-level)))
12604 ((org-at-heading-p) 0)
12605 (t (org-get-indentation))))))
12606 (setq bul (org-list-bullet-string "-"))
12607 (org-indent-line-to ind)
12608 (insert bul (pop lines))
12609 (let ((ind-body (+ (length bul) ind)))
12610 (while lines
12611 (insert "\n")
12612 (org-indent-line-to ind-body)
12613 (insert (pop lines))))
12614 (message "Note stored")
12615 (org-back-to-heading t)
12616 (org-cycle-hide-drawers 'children)))))
12617 (set-window-configuration org-log-note-window-configuration)
12618 (with-current-buffer (marker-buffer org-log-note-return-to)
12619 (goto-char org-log-note-return-to))
12620 (move-marker org-log-note-return-to nil)
12621 (and org-log-post-message (message "%s" org-log-post-message)))
12623 (defun org-remove-empty-drawer-at (drawer pos)
12624 "Remove an empty drawer DRAWER at position POS.
12625 POS may also be a marker."
12626 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12627 (save-excursion
12628 (save-restriction
12629 (widen)
12630 (goto-char pos)
12631 (if (org-in-regexp
12632 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12633 (replace-match ""))))))
12635 (defvar org-ts-type nil)
12636 (defun org-sparse-tree (&optional arg type)
12637 "Create a sparse tree, prompt for the details.
12638 This command can create sparse trees. You first need to select the type
12639 of match used to create the tree:
12641 t Show all TODO entries.
12642 T Show entries with a specific TODO keyword.
12643 m Show entries selected by a tags/property match.
12644 p Enter a property name and its value (both with completion on existing
12645 names/values) and show entries with that property.
12646 r Show entries matching a regular expression (`/' can be used as well).
12647 b Show deadlines and scheduled items before a date.
12648 a Show deadlines and scheduled items after a date.
12649 d Show deadlines due within `org-deadline-warning-days'.
12650 D Show deadlines and scheduled items between a date range."
12651 (interactive "P")
12652 (let (ans kwd value ts-type)
12653 (setq type (or type org-sparse-tree-default-date-type))
12654 (setq org-ts-type type)
12655 (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"
12656 (cond ((eq type 'all) "all timestamps")
12657 ((eq type 'scheduled) "only scheduled")
12658 ((eq type 'deadline) "only deadline")
12659 ((eq type 'active) "only active timestamps")
12660 ((eq type 'inactive) "only inactive timestamps")
12661 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12662 (t "scheduled/deadline")))
12663 (setq ans (read-char-exclusive))
12664 (cond
12665 ((equal ans ?c)
12666 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12667 ((equal ans ?d)
12668 (call-interactively 'org-check-deadlines))
12669 ((equal ans ?b)
12670 (call-interactively 'org-check-before-date))
12671 ((equal ans ?a)
12672 (call-interactively 'org-check-after-date))
12673 ((equal ans ?D)
12674 (call-interactively 'org-check-dates-range))
12675 ((equal ans ?t)
12676 (call-interactively 'org-show-todo-tree))
12677 ((equal ans ?T)
12678 (org-show-todo-tree '(4)))
12679 ((member ans '(?T ?m))
12680 (call-interactively 'org-match-sparse-tree))
12681 ((member ans '(?p ?P))
12682 (setq kwd (org-icompleting-read "Property: "
12683 (mapcar 'list (org-buffer-property-keys))))
12684 (setq value (org-icompleting-read "Value: "
12685 (mapcar 'list (org-property-values kwd))))
12686 (unless (string-match "\\`{.*}\\'" value)
12687 (setq value (concat "\"" value "\"")))
12688 (org-match-sparse-tree arg (concat kwd "=" value)))
12689 ((member ans '(?r ?R ?/))
12690 (call-interactively 'org-occur))
12691 (t (error "No such sparse tree command \"%c\"" ans)))))
12693 (defvar org-occur-highlights nil
12694 "List of overlays used for occur matches.")
12695 (make-variable-buffer-local 'org-occur-highlights)
12696 (defvar org-occur-parameters nil
12697 "Parameters of the active org-occur calls.
12698 This is a list, each call to org-occur pushes as cons cell,
12699 containing the regular expression and the callback, onto the list.
12700 The list can contain several entries if `org-occur' has been called
12701 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12702 will only contain one set of parameters. When the highlights are
12703 removed (for example with `C-c C-c', or with the next edit (depending
12704 on `org-remove-highlights-with-change'), this variable is emptied
12705 as well.")
12706 (make-variable-buffer-local 'org-occur-parameters)
12708 (defun org-occur (regexp &optional keep-previous callback)
12709 "Make a compact tree which shows all matches of REGEXP.
12710 The tree will show the lines where the regexp matches, and all higher
12711 headlines above the match. It will also show the heading after the match,
12712 to make sure editing the matching entry is easy.
12713 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12714 call to `org-occur' will be kept, to allow stacking of calls to this
12715 command.
12716 If CALLBACK is non-nil, it is a function which is called to confirm
12717 that the match should indeed be shown."
12718 (interactive "sRegexp: \nP")
12719 (when (equal regexp "")
12720 (error "Regexp cannot be empty"))
12721 (unless keep-previous
12722 (org-remove-occur-highlights nil nil t))
12723 (push (cons regexp callback) org-occur-parameters)
12724 (let ((cnt 0))
12725 (save-excursion
12726 (goto-char (point-min))
12727 (if (or (not keep-previous) ; do not want to keep
12728 (not org-occur-highlights)) ; no previous matches
12729 ;; hide everything
12730 (org-overview))
12731 (while (re-search-forward regexp nil t)
12732 (when (or (not callback)
12733 (save-match-data (funcall callback)))
12734 (setq cnt (1+ cnt))
12735 (when org-highlight-sparse-tree-matches
12736 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12737 (org-show-context 'occur-tree))))
12738 (when org-remove-highlights-with-change
12739 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12740 nil 'local))
12741 (unless org-sparse-tree-open-archived-trees
12742 (org-hide-archived-subtrees (point-min) (point-max)))
12743 (run-hooks 'org-occur-hook)
12744 (if (org-called-interactively-p 'interactive)
12745 (message "%d match(es) for regexp %s" cnt regexp))
12746 cnt))
12748 (defun org-occur-next-match (&optional n reset)
12749 "Function for `next-error-function' to find sparse tree matches.
12750 N is the number of matches to move, when negative move backwards.
12751 RESET is entirely ignored - this function always goes back to the
12752 starting point when no match is found."
12753 (let* ((limit (if (< n 0) (point-min) (point-max)))
12754 (search-func (if (< n 0)
12755 'previous-single-char-property-change
12756 'next-single-char-property-change))
12757 (n (abs n))
12758 (pos (point))
12760 (catch 'exit
12761 (while (setq p1 (funcall search-func (point) 'org-type))
12762 (when (equal p1 limit)
12763 (goto-char pos)
12764 (error "No more matches"))
12765 (when (equal (get-char-property p1 'org-type) 'org-occur)
12766 (setq n (1- n))
12767 (when (= n 0)
12768 (goto-char p1)
12769 (throw 'exit (point))))
12770 (goto-char p1))
12771 (goto-char p1)
12772 (error "No more matches"))))
12774 (defun org-show-context (&optional key)
12775 "Make sure point and context are visible.
12776 How much context is shown depends upon the variables
12777 `org-show-hierarchy-above', `org-show-following-heading',
12778 `org-show-entry-below' and `org-show-siblings'."
12779 (let ((heading-p (org-at-heading-p t))
12780 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12781 (following-p (org-get-alist-option org-show-following-heading key))
12782 (entry-p (org-get-alist-option org-show-entry-below key))
12783 (siblings-p (org-get-alist-option org-show-siblings key)))
12784 (catch 'exit
12785 ;; Show heading or entry text
12786 (if (and heading-p (not entry-p))
12787 (org-flag-heading nil) ; only show the heading
12788 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12789 (org-show-hidden-entry))) ; show entire entry
12790 (when following-p
12791 ;; Show next sibling, or heading below text
12792 (save-excursion
12793 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12794 (org-flag-heading nil))))
12795 (when siblings-p (org-show-siblings))
12796 (when hierarchy-p
12797 ;; show all higher headings, possibly with siblings
12798 (save-excursion
12799 (while (and (condition-case nil
12800 (progn (org-up-heading-all 1) t)
12801 (error nil))
12802 (not (bobp)))
12803 (org-flag-heading nil)
12804 (when siblings-p (org-show-siblings))))))))
12806 (defvar org-reveal-start-hook nil
12807 "Hook run before revealing a location.")
12809 (defun org-reveal (&optional siblings)
12810 "Show current entry, hierarchy above it, and the following headline.
12811 This can be used to show a consistent set of context around locations
12812 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12813 not t for the search context.
12815 With optional argument SIBLINGS, on each level of the hierarchy all
12816 siblings are shown. This repairs the tree structure to what it would
12817 look like when opened with hierarchical calls to `org-cycle'.
12818 With double optional argument \\[universal-argument] \\[universal-argument], \
12819 go to the parent and show the
12820 entire tree."
12821 (interactive "P")
12822 (run-hooks 'org-reveal-start-hook)
12823 (let ((org-show-hierarchy-above t)
12824 (org-show-following-heading t)
12825 (org-show-siblings (if siblings t org-show-siblings)))
12826 (org-show-context nil))
12827 (when (equal siblings '(16))
12828 (save-excursion
12829 (when (org-up-heading-safe)
12830 (org-show-subtree)
12831 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12833 (defun org-highlight-new-match (beg end)
12834 "Highlight from BEG to END and mark the highlight is an occur headline."
12835 (let ((ov (make-overlay beg end)))
12836 (overlay-put ov 'face 'secondary-selection)
12837 (overlay-put ov 'org-type 'org-occur)
12838 (push ov org-occur-highlights)))
12840 (defun org-remove-occur-highlights (&optional beg end noremove)
12841 "Remove the occur highlights from the buffer.
12842 BEG and END are ignored. If NOREMOVE is nil, remove this function
12843 from the `before-change-functions' in the current buffer."
12844 (interactive)
12845 (unless org-inhibit-highlight-removal
12846 (mapc 'delete-overlay org-occur-highlights)
12847 (setq org-occur-highlights nil)
12848 (setq org-occur-parameters nil)
12849 (unless noremove
12850 (remove-hook 'before-change-functions
12851 'org-remove-occur-highlights 'local))))
12853 ;;;; Priorities
12855 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12856 "Regular expression matching the priority indicator.")
12858 (defvar org-remove-priority-next-time nil)
12860 (defun org-priority-up ()
12861 "Increase the priority of the current item."
12862 (interactive)
12863 (org-priority 'up))
12865 (defun org-priority-down ()
12866 "Decrease the priority of the current item."
12867 (interactive)
12868 (org-priority 'down))
12870 (defun org-priority (&optional action show)
12871 "Change the priority of an item.
12872 ACTION can be `set', `up', `down', or a character."
12873 (interactive "P")
12874 (if (equal action '(4))
12875 (org-show-priority)
12876 (unless org-enable-priority-commands
12877 (error "Priority commands are disabled"))
12878 (setq action (or action 'set))
12879 (let (current new news have remove)
12880 (save-excursion
12881 (org-back-to-heading t)
12882 (if (looking-at org-priority-regexp)
12883 (setq current (string-to-char (match-string 2))
12884 have t))
12885 (cond
12886 ((eq action 'remove)
12887 (setq remove t new ?\ ))
12888 ((or (eq action 'set)
12889 (if (featurep 'xemacs) (characterp action) (integerp action)))
12890 (if (not (eq action 'set))
12891 (setq new action)
12892 (message "Priority %c-%c, SPC to remove: "
12893 org-highest-priority org-lowest-priority)
12894 (save-match-data
12895 (setq new (read-char-exclusive))))
12896 (if (and (= (upcase org-highest-priority) org-highest-priority)
12897 (= (upcase org-lowest-priority) org-lowest-priority))
12898 (setq new (upcase new)))
12899 (cond ((equal new ?\ ) (setq remove t))
12900 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12901 (error "Priority must be between `%c' and `%c'"
12902 org-highest-priority org-lowest-priority))))
12903 ((eq action 'up)
12904 (setq new (if have
12905 (1- current) ; normal cycling
12906 ;; last priority was empty
12907 (if (eq last-command this-command)
12908 org-lowest-priority ; wrap around empty to lowest
12909 ;; default
12910 (if org-priority-start-cycle-with-default
12911 org-default-priority
12912 (1- org-default-priority))))))
12913 ((eq action 'down)
12914 (setq new (if have
12915 (1+ current) ; normal cycling
12916 ;; last priority was empty
12917 (if (eq last-command this-command)
12918 org-highest-priority ; wrap around empty to highest
12919 ;; default
12920 (if org-priority-start-cycle-with-default
12921 org-default-priority
12922 (1+ org-default-priority))))))
12923 (t (error "Invalid action")))
12924 (if (or (< (upcase new) org-highest-priority)
12925 (> (upcase new) org-lowest-priority))
12926 (if (and (memq action '(up down))
12927 (not have) (not (eq last-command this-command)))
12928 ;; `new' is from default priority
12929 (error
12930 "The default can not be set, see `org-default-priority' why")
12931 ;; normal cycling: `new' is beyond highest/lowest priority
12932 ;; and is wrapped around to the empty priority
12933 (setq remove t)))
12934 (setq news (format "%c" new))
12935 (if have
12936 (if remove
12937 (replace-match "" t t nil 1)
12938 (replace-match news t t nil 2))
12939 (if remove
12940 (error "No priority cookie found in line")
12941 (let ((case-fold-search nil))
12942 (looking-at org-todo-line-regexp))
12943 (if (match-end 2)
12944 (progn
12945 (goto-char (match-end 2))
12946 (insert " [#" news "]"))
12947 (goto-char (match-beginning 3))
12948 (insert "[#" news "] "))))
12949 (org-preserve-lc (org-set-tags nil 'align)))
12950 (if remove
12951 (message "Priority removed")
12952 (message "Priority of current item set to %s" news)))))
12954 (defun org-show-priority ()
12955 "Show the priority of the current item.
12956 This priority is composed of the main priority given with the [#A] cookies,
12957 and by additional input from the age of a schedules or deadline entry."
12958 (interactive)
12959 (let ((pri (if (eq major-mode 'org-agenda-mode)
12960 (org-get-at-bol 'priority)
12961 (save-excursion
12962 (save-match-data
12963 (beginning-of-line)
12964 (and (looking-at org-heading-regexp)
12965 (org-get-priority (match-string 0))))))))
12966 (message "Priority is %d" (if pri pri -1000))))
12968 (defun org-get-priority (s)
12969 "Find priority cookie and return priority."
12970 (if (functionp org-get-priority-function)
12971 (funcall org-get-priority-function)
12972 (save-match-data
12973 (if (not (string-match org-priority-regexp s))
12974 (* 1000 (- org-lowest-priority org-default-priority))
12975 (* 1000 (- org-lowest-priority
12976 (string-to-char (match-string 2 s))))))))
12978 ;;;; Tags
12980 (defvar org-agenda-archives-mode)
12981 (defvar org-map-continue-from nil
12982 "Position from where mapping should continue.
12983 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12985 (defvar org-scanner-tags nil
12986 "The current tag list while the tags scanner is running.")
12987 (defvar org-trust-scanner-tags nil
12988 "Should `org-get-tags-at' use the tags for the scanner.
12989 This is for internal dynamical scoping only.
12990 When this is non-nil, the function `org-get-tags-at' will return the value
12991 of `org-scanner-tags' instead of building the list by itself. This
12992 can lead to large speed-ups when the tags scanner is used in a file with
12993 many entries, and when the list of tags is retrieved, for example to
12994 obtain a list of properties. Building the tags list for each entry in such
12995 a file becomes an N^2 operation - but with this variable set, it scales
12996 as N.")
12998 (defun org-scan-tags (action matcher todo-only &optional start-level)
12999 "Scan headline tags with inheritance and produce output ACTION.
13001 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13002 or `agenda' to produce an entry list for an agenda view. It can also be
13003 a Lisp form or a function that should be called at each matched headline, in
13004 this case the return value is a list of all return values from these calls.
13006 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13007 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13008 only lines with a not-done TODO keyword are included in the output.
13009 This should be the same variable that was scoped into
13010 and set by `org-make-tags-matcher' when it constructed MATCHER.
13012 START-LEVEL can be a string with asterisks, reducing the scope to
13013 headlines matching this string."
13014 (require 'org-agenda)
13015 (let* ((re (concat "^"
13016 (if start-level
13017 ;; Get the correct level to match
13018 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13019 org-outline-regexp)
13020 " *\\(\\<\\("
13021 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13022 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13023 (props (list 'face 'default
13024 'done-face 'org-agenda-done
13025 'undone-face 'default
13026 'mouse-face 'highlight
13027 'org-not-done-regexp org-not-done-regexp
13028 'org-todo-regexp org-todo-regexp
13029 'org-complex-heading-regexp org-complex-heading-regexp
13030 'help-echo
13031 (format "mouse-2 or RET jump to org file %s"
13032 (abbreviate-file-name
13033 (or (buffer-file-name (buffer-base-buffer))
13034 (buffer-name (buffer-base-buffer)))))))
13035 (case-fold-search nil)
13036 (org-map-continue-from nil)
13037 lspos tags tags-list
13038 (tags-alist (list (cons 0 org-file-tags)))
13039 (llast 0) rtn rtn1 level category i txt
13040 todo marker entry priority)
13041 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13042 (setq action (list 'lambda nil action)))
13043 (save-excursion
13044 (goto-char (point-min))
13045 (when (eq action 'sparse-tree)
13046 (org-overview)
13047 (org-remove-occur-highlights))
13048 (while (re-search-forward re nil t)
13049 (setq org-map-continue-from nil)
13050 (catch :skip
13051 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13052 tags (if (match-end 4) (org-match-string-no-properties 4)))
13053 (goto-char (setq lspos (match-beginning 0)))
13054 (setq level (org-reduced-level (funcall outline-level))
13055 category (org-get-category))
13056 (setq i llast llast level)
13057 ;; remove tag lists from same and sublevels
13058 (while (>= i level)
13059 (when (setq entry (assoc i tags-alist))
13060 (setq tags-alist (delete entry tags-alist)))
13061 (setq i (1- i)))
13062 ;; add the next tags
13063 (when tags
13064 (setq tags (org-split-string tags ":")
13065 tags-alist
13066 (cons (cons level tags) tags-alist)))
13067 ;; compile tags for current headline
13068 (setq tags-list
13069 (if org-use-tag-inheritance
13070 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13071 tags)
13072 org-scanner-tags tags-list)
13073 (when org-use-tag-inheritance
13074 (setcdr (car tags-alist)
13075 (mapcar (lambda (x)
13076 (setq x (copy-sequence x))
13077 (org-add-prop-inherited x))
13078 (cdar tags-alist))))
13079 (when (and tags org-use-tag-inheritance
13080 (or (not (eq t org-use-tag-inheritance))
13081 org-tags-exclude-from-inheritance))
13082 ;; selective inheritance, remove uninherited ones
13083 (setcdr (car tags-alist)
13084 (org-remove-uninherited-tags (cdar tags-alist))))
13085 (when (and
13087 ;; eval matcher only when the todo condition is OK
13088 (and (or (not todo-only) (member todo org-not-done-keywords))
13089 (let ((case-fold-search t) (org-trust-scanner-tags t))
13090 (eval matcher)))
13092 ;; Call the skipper, but return t if it does not skip,
13093 ;; so that the `and' form continues evaluating
13094 (progn
13095 (unless (eq action 'sparse-tree) (org-agenda-skip))
13098 ;; Check if timestamps are deselecting this entry
13099 (or (not todo-only)
13100 (and (member todo org-not-done-keywords)
13101 (or (not org-agenda-tags-todo-honor-ignore-options)
13102 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13104 ;; Extra check for the archive tag
13105 ;; FIXME: Does the skipper already do this????
13107 (not (member org-archive-tag tags-list))
13108 ;; we have an archive tag, should we use this anyway?
13109 (or (not org-agenda-skip-archived-trees)
13110 (and (eq action 'agenda) org-agenda-archives-mode))))
13112 ;; select this headline
13114 (cond
13115 ((eq action 'sparse-tree)
13116 (and org-highlight-sparse-tree-matches
13117 (org-get-heading) (match-end 0)
13118 (org-highlight-new-match
13119 (match-beginning 1) (match-end 1)))
13120 (org-show-context 'tags-tree))
13121 ((eq action 'agenda)
13122 (setq txt (org-agenda-format-item
13124 (concat
13125 (if (eq org-tags-match-list-sublevels 'indented)
13126 (make-string (1- level) ?.) "")
13127 (org-get-heading))
13128 category
13129 tags-list)
13130 priority (org-get-priority txt))
13131 (goto-char lspos)
13132 (setq marker (org-agenda-new-marker))
13133 (org-add-props txt props
13134 'org-marker marker 'org-hd-marker marker 'org-category category
13135 'todo-state todo
13136 'priority priority 'type "tagsmatch")
13137 (push txt rtn))
13138 ((functionp action)
13139 (setq org-map-continue-from nil)
13140 (save-excursion
13141 (setq rtn1 (funcall action))
13142 (push rtn1 rtn)))
13143 (t (error "Invalid action")))
13145 ;; if we are to skip sublevels, jump to end of subtree
13146 (unless org-tags-match-list-sublevels
13147 (org-end-of-subtree t)
13148 (backward-char 1))))
13149 ;; Get the correct position from where to continue
13150 (if org-map-continue-from
13151 (goto-char org-map-continue-from)
13152 (and (= (point) lspos) (end-of-line 1)))))
13153 (when (and (eq action 'sparse-tree)
13154 (not org-sparse-tree-open-archived-trees))
13155 (org-hide-archived-subtrees (point-min) (point-max)))
13156 (nreverse rtn)))
13158 (defun org-remove-uninherited-tags (tags)
13159 "Remove all tags that are not inherited from the list TAGS."
13160 (cond
13161 ((eq org-use-tag-inheritance t)
13162 (if org-tags-exclude-from-inheritance
13163 (org-delete-all org-tags-exclude-from-inheritance tags)
13164 tags))
13165 ((not org-use-tag-inheritance) nil)
13166 ((stringp org-use-tag-inheritance)
13167 (delq nil (mapcar
13168 (lambda (x)
13169 (if (and (string-match org-use-tag-inheritance x)
13170 (not (member x org-tags-exclude-from-inheritance)))
13171 x nil))
13172 tags)))
13173 ((listp org-use-tag-inheritance)
13174 (delq nil (mapcar
13175 (lambda (x)
13176 (if (member x org-use-tag-inheritance) x nil))
13177 tags)))))
13179 (defun org-match-sparse-tree (&optional todo-only match)
13180 "Create a sparse tree according to tags string MATCH.
13181 MATCH can contain positive and negative selection of tags, like
13182 \"+WORK+URGENT-WITHBOSS\".
13183 If optional argument TODO-ONLY is non-nil, only select lines that are
13184 also TODO lines."
13185 (interactive "P")
13186 (org-agenda-prepare-buffers (list (current-buffer)))
13187 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13189 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13191 (defvar org-cached-props nil)
13192 (defun org-cached-entry-get (pom property)
13193 (if (or (eq t org-use-property-inheritance)
13194 (and (stringp org-use-property-inheritance)
13195 (string-match org-use-property-inheritance property))
13196 (and (listp org-use-property-inheritance)
13197 (member property org-use-property-inheritance)))
13198 ;; Caching is not possible, check it directly
13199 (org-entry-get pom property 'inherit)
13200 ;; Get all properties, so that we can do complicated checks easily
13201 (cdr (assoc property (or org-cached-props
13202 (setq org-cached-props
13203 (org-entry-properties pom)))))))
13205 (defun org-global-tags-completion-table (&optional files)
13206 "Return the list of all tags in all agenda buffer/files.
13207 Optional FILES argument is a list of files which can be used
13208 instead of the agenda files."
13209 (save-excursion
13210 (org-uniquify
13211 (delq nil
13212 (apply 'append
13213 (mapcar
13214 (lambda (file)
13215 (set-buffer (find-file-noselect file))
13216 (append (org-get-buffer-tags)
13217 (mapcar (lambda (x) (if (stringp (car-safe x))
13218 (list (car-safe x)) nil))
13219 org-tag-alist)))
13220 (if (and files (car files))
13221 files
13222 (org-agenda-files))))))))
13224 (defun org-make-tags-matcher (match)
13225 "Create the TAGS/TODO matcher form for the selection string MATCH.
13227 The variable `todo-only' is scoped dynamically into this function.
13228 It will be set to t if the matcher restricts matching to TODO entries,
13229 otherwise will not be touched.
13231 Returns a cons of the selection string MATCH and the constructed
13232 lisp form implementing the matcher. The matcher is to be evaluated
13233 at an Org entry, with point on the headline, and returns t if the
13234 entry matches the selection string MATCH. The returned lisp form
13235 references two variables with information about the entry, which
13236 must be bound around the form's evaluation: todo, the TODO keyword
13237 at the entry (or nil of none); and tags-list, the list of all tags
13238 at the entry including inherited ones. Additionally, the category
13239 of the entry (if any) must be specified as the text property
13240 'org-category on the headline.
13242 See also `org-scan-tags'.
13244 (declare (special todo-only))
13245 (unless (boundp 'todo-only)
13246 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13247 (unless match
13248 ;; Get a new match request, with completion
13249 (let ((org-last-tags-completion-table
13250 (org-global-tags-completion-table)))
13251 (setq match (org-completing-read-no-i
13252 "Match: " 'org-tags-completion-function nil nil nil
13253 'org-tags-history))))
13255 ;; Parse the string and create a lisp form
13256 (let ((match0 match)
13257 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13258 minus tag mm
13259 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13260 orterms term orlist re-p str-p level-p level-op time-p
13261 prop-p pn pv po gv rest)
13262 (if (string-match "/+" match)
13263 ;; match contains also a todo-matching request
13264 (progn
13265 (setq tagsmatch (substring match 0 (match-beginning 0))
13266 todomatch (substring match (match-end 0)))
13267 (if (string-match "^!" todomatch)
13268 (setq todo-only t todomatch (substring todomatch 1)))
13269 (if (string-match "^\\s-*$" todomatch)
13270 (setq todomatch nil)))
13271 ;; only matching tags
13272 (setq tagsmatch match todomatch nil))
13274 ;; Make the tags matcher
13275 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13276 (setq tagsmatcher t)
13277 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13278 (while (setq term (pop orterms))
13279 (while (and (equal (substring term -1) "\\") orterms)
13280 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13281 (while (string-match re term)
13282 (setq rest (substring term (match-end 0))
13283 minus (and (match-end 1)
13284 (equal (match-string 1 term) "-"))
13285 tag (save-match-data (replace-regexp-in-string
13286 "\\\\-" "-"
13287 (match-string 2 term)))
13288 re-p (equal (string-to-char tag) ?{)
13289 level-p (match-end 4)
13290 prop-p (match-end 5)
13291 mm (cond
13292 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13293 (level-p
13294 (setq level-op (org-op-to-function (match-string 3 term)))
13295 `(,level-op level ,(string-to-number
13296 (match-string 4 term))))
13297 (prop-p
13298 (setq pn (match-string 5 term)
13299 po (match-string 6 term)
13300 pv (match-string 7 term)
13301 re-p (equal (string-to-char pv) ?{)
13302 str-p (equal (string-to-char pv) ?\")
13303 time-p (save-match-data
13304 (string-match "^\"[[<].*[]>]\"$" pv))
13305 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13306 (if time-p (setq pv (org-matcher-time pv)))
13307 (setq po (org-op-to-function po (if time-p 'time str-p)))
13308 (cond
13309 ((equal pn "CATEGORY")
13310 (setq gv '(get-text-property (point) 'org-category)))
13311 ((equal pn "TODO")
13312 (setq gv 'todo))
13314 (setq gv `(org-cached-entry-get nil ,pn))))
13315 (if re-p
13316 (if (eq po 'org<>)
13317 `(not (string-match ,pv (or ,gv "")))
13318 `(string-match ,pv (or ,gv "")))
13319 (if str-p
13320 `(,po (or ,gv "") ,pv)
13321 `(,po (string-to-number (or ,gv ""))
13322 ,(string-to-number pv) ))))
13323 (t `(member ,tag tags-list)))
13324 mm (if minus (list 'not mm) mm)
13325 term rest)
13326 (push mm tagsmatcher))
13327 (push (if (> (length tagsmatcher) 1)
13328 (cons 'and tagsmatcher)
13329 (car tagsmatcher))
13330 orlist)
13331 (setq tagsmatcher nil))
13332 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13333 (setq tagsmatcher
13334 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13335 ;; Make the todo matcher
13336 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13337 (setq todomatcher t)
13338 (setq orterms (org-split-string todomatch "|") orlist nil)
13339 (while (setq term (pop orterms))
13340 (while (string-match re term)
13341 (setq minus (and (match-end 1)
13342 (equal (match-string 1 term) "-"))
13343 kwd (match-string 2 term)
13344 re-p (equal (string-to-char kwd) ?{)
13345 term (substring term (match-end 0))
13346 mm (if re-p
13347 `(string-match ,(substring kwd 1 -1) todo)
13348 (list 'equal 'todo kwd))
13349 mm (if minus (list 'not mm) mm))
13350 (push mm todomatcher))
13351 (push (if (> (length todomatcher) 1)
13352 (cons 'and todomatcher)
13353 (car todomatcher))
13354 orlist)
13355 (setq todomatcher nil))
13356 (setq todomatcher (if (> (length orlist) 1)
13357 (cons 'or orlist) (car orlist))))
13359 ;; Return the string and lisp forms of the matcher
13360 (setq matcher (if todomatcher
13361 (list 'and tagsmatcher todomatcher)
13362 tagsmatcher))
13363 (when todo-only
13364 (setq matcher (list 'and '(member todo org-not-done-keywords)
13365 matcher)))
13366 (cons match0 matcher)))
13368 (defun org-op-to-function (op &optional stringp)
13369 "Turn an operator into the appropriate function."
13370 (setq op
13371 (cond
13372 ((equal op "<" ) '(< string< org-time<))
13373 ((equal op ">" ) '(> org-string> org-time>))
13374 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13375 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13376 ((member op '("=" "==")) '(= string= org-time=))
13377 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13378 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13380 (defun org<> (a b) (not (= a b)))
13381 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13382 (defun org-string>= (a b) (not (string< a b)))
13383 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13384 (defun org-string<> (a b) (not (string= 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) (<= a b)))
13388 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13389 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13390 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13391 (defun org-2ft (s)
13392 "Convert S to a floating point time.
13393 If S is already a number, just return it. If it is a string, parse
13394 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13395 (cond
13396 ((numberp s) s)
13397 ((stringp s)
13398 (condition-case nil
13399 (float-time (apply 'encode-time (org-parse-time-string s)))
13400 (error 0.)))
13401 (t 0.)))
13403 (defun org-time-today ()
13404 "Time in seconds today at 0:00.
13405 Returns the float number of seconds since the beginning of the
13406 epoch to the beginning of today (00:00)."
13407 (float-time (apply 'encode-time
13408 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13410 (defun org-matcher-time (s)
13411 "Interpret a time comparison value."
13412 (save-match-data
13413 (cond
13414 ((string= s "<now>") (float-time))
13415 ((string= s "<today>") (org-time-today))
13416 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13417 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13418 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13419 (+ (org-time-today)
13420 (* (string-to-number (match-string 1 s))
13421 (cdr (assoc (match-string 2 s)
13422 '(("d" . 86400.0) ("w" . 604800.0)
13423 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13424 (t (org-2ft s)))))
13426 (defun org-match-any-p (re list)
13427 "Does re match any element of list?"
13428 (setq list (mapcar (lambda (x) (string-match re x)) list))
13429 (delq nil list))
13431 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13432 (defvar org-tags-overlay (make-overlay 1 1))
13433 (org-detach-overlay org-tags-overlay)
13435 (defun org-get-local-tags-at (&optional pos)
13436 "Get a list of tags defined in the current headline."
13437 (org-get-tags-at pos 'local))
13439 (defun org-get-local-tags ()
13440 "Get a list of tags defined in the current headline."
13441 (org-get-tags-at nil 'local))
13443 (defun org-get-tags-at (&optional pos local)
13444 "Get a list of all headline tags applicable at POS.
13445 POS defaults to point. If tags are inherited, the list contains
13446 the targets in the same sequence as the headlines appear, i.e.
13447 the tags of the current headline come last.
13448 When LOCAL is non-nil, only return tags from the current headline,
13449 ignore inherited ones."
13450 (interactive)
13451 (if (and org-trust-scanner-tags
13452 (or (not pos) (equal pos (point)))
13453 (not local))
13454 org-scanner-tags
13455 (let (tags ltags lastpos parent)
13456 (save-excursion
13457 (save-restriction
13458 (widen)
13459 (goto-char (or pos (point)))
13460 (save-match-data
13461 (catch 'done
13462 (condition-case nil
13463 (progn
13464 (org-back-to-heading t)
13465 (while (not (equal lastpos (point)))
13466 (setq lastpos (point))
13467 (when (looking-at
13468 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13469 (setq ltags (org-split-string
13470 (org-match-string-no-properties 1) ":"))
13471 (when parent
13472 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13473 (setq tags (append
13474 (if parent
13475 (org-remove-uninherited-tags ltags)
13476 ltags)
13477 tags)))
13478 (or org-use-tag-inheritance (throw 'done t))
13479 (if local (throw 'done t))
13480 (or (org-up-heading-safe) (error nil))
13481 (setq parent t)))
13482 (error nil)))))
13483 (if local
13484 tags
13485 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13487 (defun org-add-prop-inherited (s)
13488 (add-text-properties 0 (length s) '(inherited t) s)
13491 (defun org-toggle-tag (tag &optional onoff)
13492 "Toggle the tag TAG for the current line.
13493 If ONOFF is `on' or `off', don't toggle but set to this state."
13494 (let (res current)
13495 (save-excursion
13496 (org-back-to-heading t)
13497 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13498 (point-at-eol) t)
13499 (progn
13500 (setq current (match-string 1))
13501 (replace-match ""))
13502 (setq current ""))
13503 (setq current (nreverse (org-split-string current ":")))
13504 (cond
13505 ((eq onoff 'on)
13506 (setq res t)
13507 (or (member tag current) (push tag current)))
13508 ((eq onoff 'off)
13509 (or (not (member tag current)) (setq current (delete tag current))))
13510 (t (if (member tag current)
13511 (setq current (delete tag current))
13512 (setq res t)
13513 (push tag current))))
13514 (end-of-line 1)
13515 (if current
13516 (progn
13517 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13518 (org-set-tags nil t))
13519 (delete-horizontal-space))
13520 (run-hooks 'org-after-tags-change-hook))
13521 res))
13523 (defun org-align-tags-here (to-col)
13524 ;; Assumes that this is a headline
13525 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13526 (beginning-of-line 1)
13527 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13528 (< pos (match-beginning 2)))
13529 (progn
13530 (setq tags-l (- (match-end 2) (match-beginning 2)))
13531 (goto-char (match-beginning 1))
13532 (insert " ")
13533 (delete-region (point) (1+ (match-beginning 2)))
13534 (setq ncol (max (current-column)
13535 (1+ col)
13536 (if (> to-col 0)
13537 to-col
13538 (- (abs to-col) tags-l))))
13539 (setq p (point))
13540 (insert (make-string (- ncol (current-column)) ?\ ))
13541 (setq ncol (current-column))
13542 (when indent-tabs-mode (tabify p (point-at-eol)))
13543 (org-move-to-column (min ncol col) t))
13544 (goto-char pos))))
13546 (defun org-set-tags-command (&optional arg just-align)
13547 "Call the set-tags command for the current entry."
13548 (interactive "P")
13549 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13550 (org-set-tags arg just-align)
13551 (save-excursion
13552 (org-back-to-heading t)
13553 (org-set-tags arg just-align))))
13555 (defun org-set-tags-to (data)
13556 "Set the tags of the current entry to DATA, replacing the current tags.
13557 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13558 If DATA is nil or the empty string, any tags will be removed."
13559 (interactive "sTags: ")
13560 (setq data
13561 (cond
13562 ((eq data nil) "")
13563 ((equal data "") "")
13564 ((stringp data)
13565 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13566 ":"))
13567 ((listp data)
13568 (concat ":" (mapconcat 'identity data ":") ":"))))
13569 (when data
13570 (save-excursion
13571 (org-back-to-heading t)
13572 (when (looking-at org-complex-heading-regexp)
13573 (if (match-end 5)
13574 (progn
13575 (goto-char (match-beginning 5))
13576 (insert data)
13577 (delete-region (point) (point-at-eol))
13578 (org-set-tags nil 'align))
13579 (goto-char (point-at-eol))
13580 (insert " " data)
13581 (org-set-tags nil 'align)))
13582 (beginning-of-line 1)
13583 (if (looking-at ".*?\\([ \t]+\\)$")
13584 (delete-region (match-beginning 1) (match-end 1))))))
13586 (defun org-align-all-tags ()
13587 "Align the tags i all headings."
13588 (interactive)
13589 (save-excursion
13590 (or (ignore-errors (org-back-to-heading t))
13591 (outline-next-heading))
13592 (if (org-at-heading-p)
13593 (org-set-tags t)
13594 (message "No headings"))))
13596 (defvar org-indent-indentation-per-level)
13597 (defun org-set-tags (&optional arg just-align)
13598 "Set the tags for the current headline.
13599 With prefix ARG, realign all tags in headings in the current buffer."
13600 (interactive "P")
13601 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13602 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13603 'region-start-level 'region))
13604 org-loop-over-headlines-in-active-region)
13605 (org-map-entries
13606 ;; We don't use ARG and JUST-ALIGN here these args are not
13607 ;; useful when looping over headlines
13608 `(org-set-tags)
13609 org-loop-over-headlines-in-active-region
13610 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13611 (let* ((re org-outline-regexp-bol)
13612 (current (unless arg (org-get-tags-string)))
13613 (col (current-column))
13614 (org-setting-tags t)
13615 table current-tags inherited-tags ; computed below when needed
13616 tags p0 c0 c1 rpl di tc level)
13617 (if arg
13618 (save-excursion
13619 (goto-char (point-min))
13620 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13621 (while (re-search-forward re nil t)
13622 (org-set-tags nil t)
13623 (end-of-line 1)))
13624 (message "All tags realigned to column %d" org-tags-column))
13625 (if just-align
13626 (setq tags current)
13627 ;; Get a new set of tags from the user
13628 (save-excursion
13629 (setq table (append org-tag-persistent-alist
13630 (or org-tag-alist (org-get-buffer-tags))
13631 (and
13632 org-complete-tags-always-offer-all-agenda-tags
13633 (org-global-tags-completion-table
13634 (org-agenda-files))))
13635 org-last-tags-completion-table table
13636 current-tags (org-split-string current ":")
13637 inherited-tags (nreverse
13638 (nthcdr (length current-tags)
13639 (nreverse (org-get-tags-at))))
13640 tags
13641 (if (or (eq t org-use-fast-tag-selection)
13642 (and org-use-fast-tag-selection
13643 (delq nil (mapcar 'cdr table))))
13644 (org-fast-tag-selection
13645 current-tags inherited-tags table
13646 (if org-fast-tag-selection-include-todo
13647 org-todo-key-alist))
13648 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13649 (org-trim
13650 (org-icompleting-read "Tags: "
13651 'org-tags-completion-function
13652 nil nil current 'org-tags-history))))))
13653 (while (string-match "[-+&]+" tags)
13654 ;; No boolean logic, just a list
13655 (setq tags (replace-match ":" t t tags))))
13657 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13659 (if org-tags-sort-function
13660 (setq tags (mapconcat 'identity
13661 (sort (org-split-string
13662 tags (org-re "[^[:alnum:]_@#%]+"))
13663 org-tags-sort-function) ":")))
13665 (if (string-match "\\`[\t ]*\\'" tags)
13666 (setq tags "")
13667 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13668 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13670 ;; Insert new tags at the correct column
13671 (beginning-of-line 1)
13672 (setq level (or (and (looking-at org-outline-regexp)
13673 (- (match-end 0) (point) 1))
13675 (cond
13676 ((and (equal current "") (equal tags "")))
13677 ((re-search-forward
13678 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13679 (point-at-eol) t)
13680 (if (equal tags "")
13681 (setq rpl "")
13682 (goto-char (match-beginning 0))
13683 (setq c0 (current-column)
13684 ;; compute offset for the case of org-indent-mode active
13685 di (if org-indent-mode
13686 (* (1- org-indent-indentation-per-level) (1- level))
13688 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13689 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13690 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13691 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13692 (replace-match rpl t t)
13693 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13694 tags)
13695 (t (error "Tags alignment failed")))
13696 (org-move-to-column col)
13697 (unless just-align
13698 (run-hooks 'org-after-tags-change-hook))))))
13700 (defun org-change-tag-in-region (beg end tag off)
13701 "Add or remove TAG for each entry in the region.
13702 This works in the agenda, and also in an org-mode buffer."
13703 (interactive
13704 (list (region-beginning) (region-end)
13705 (let ((org-last-tags-completion-table
13706 (if (derived-mode-p 'org-mode)
13707 (org-get-buffer-tags)
13708 (org-global-tags-completion-table))))
13709 (org-icompleting-read
13710 "Tag: " 'org-tags-completion-function nil nil nil
13711 'org-tags-history))
13712 (progn
13713 (message "[s]et or [r]emove? ")
13714 (equal (read-char-exclusive) ?r))))
13715 (if (fboundp 'deactivate-mark) (deactivate-mark))
13716 (let ((agendap (equal major-mode 'org-agenda-mode))
13717 l1 l2 m buf pos newhead (cnt 0))
13718 (goto-char end)
13719 (setq l2 (1- (org-current-line)))
13720 (goto-char beg)
13721 (setq l1 (org-current-line))
13722 (loop for l from l1 to l2 do
13723 (org-goto-line l)
13724 (setq m (get-text-property (point) 'org-hd-marker))
13725 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13726 (and agendap m))
13727 (setq buf (if agendap (marker-buffer m) (current-buffer))
13728 pos (if agendap m (point)))
13729 (with-current-buffer buf
13730 (save-excursion
13731 (save-restriction
13732 (goto-char pos)
13733 (setq cnt (1+ cnt))
13734 (org-toggle-tag tag (if off 'off 'on))
13735 (setq newhead (org-get-heading)))))
13736 (and agendap (org-agenda-change-all-lines newhead m))))
13737 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13739 (defun org-tags-completion-function (string predicate &optional flag)
13740 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13741 (confirm (lambda (x) (stringp (car x)))))
13742 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13743 (setq s1 (match-string 1 string)
13744 s2 (match-string 2 string))
13745 (setq s1 "" s2 string))
13746 (cond
13747 ((eq flag nil)
13748 ;; try completion
13749 (setq rtn (try-completion s2 ctable confirm))
13750 (if (stringp rtn)
13751 (setq rtn
13752 (concat s1 s2 (substring rtn (length s2))
13753 (if (and org-add-colon-after-tag-completion
13754 (assoc rtn ctable))
13755 ":" ""))))
13756 rtn)
13757 ((eq flag t)
13758 ;; all-completions
13759 (all-completions s2 ctable confirm)
13761 ((eq flag 'lambda)
13762 ;; exact match?
13763 (assoc s2 ctable)))
13766 (defun org-fast-tag-insert (kwd tags face &optional end)
13767 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13768 (insert (format "%-12s" (concat kwd ":"))
13769 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13770 (or end "")))
13772 (defun org-fast-tag-show-exit (flag)
13773 (save-excursion
13774 (org-goto-line 3)
13775 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13776 (replace-match ""))
13777 (when flag
13778 (end-of-line 1)
13779 (org-move-to-column (- (window-width) 19) t)
13780 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13782 (defun org-set-current-tags-overlay (current prefix)
13783 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13784 (if (featurep 'xemacs)
13785 (org-overlay-display org-tags-overlay (concat prefix s)
13786 'secondary-selection)
13787 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13788 (org-overlay-display org-tags-overlay (concat prefix s)))))
13790 (defvar org-last-tag-selection-key nil)
13791 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13792 "Fast tag selection with single keys.
13793 CURRENT is the current list of tags in the headline, INHERITED is the
13794 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13795 possibly with grouping information. TODO-TABLE is a similar table with
13796 TODO keywords, should these have keys assigned to them.
13797 If the keys are nil, a-z are automatically assigned.
13798 Returns the new tags string, or nil to not change the current settings."
13799 (let* ((fulltable (append table todo-table))
13800 (maxlen (apply 'max (mapcar
13801 (lambda (x)
13802 (if (stringp (car x)) (string-width (car x)) 0))
13803 fulltable)))
13804 (buf (current-buffer))
13805 (expert (eq org-fast-tag-selection-single-key 'expert))
13806 (buffer-tags nil)
13807 (fwidth (+ maxlen 3 1 3))
13808 (ncol (/ (- (window-width) 4) fwidth))
13809 (i-face 'org-done)
13810 (c-face 'org-todo)
13811 tg cnt e c char c1 c2 ntable tbl rtn
13812 ov-start ov-end ov-prefix
13813 (exit-after-next org-fast-tag-selection-single-key)
13814 (done-keywords org-done-keywords)
13815 groups ingroup)
13816 (save-excursion
13817 (beginning-of-line 1)
13818 (if (looking-at
13819 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13820 (setq ov-start (match-beginning 1)
13821 ov-end (match-end 1)
13822 ov-prefix "")
13823 (setq ov-start (1- (point-at-eol))
13824 ov-end (1+ ov-start))
13825 (skip-chars-forward "^\n\r")
13826 (setq ov-prefix
13827 (concat
13828 (buffer-substring (1- (point)) (point))
13829 (if (> (current-column) org-tags-column)
13831 (make-string (- org-tags-column (current-column)) ?\ ))))))
13832 (move-overlay org-tags-overlay ov-start ov-end)
13833 (save-window-excursion
13834 (if expert
13835 (set-buffer (get-buffer-create " *Org tags*"))
13836 (delete-other-windows)
13837 (split-window-vertically)
13838 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13839 (erase-buffer)
13840 (org-set-local 'org-done-keywords done-keywords)
13841 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13842 (org-fast-tag-insert "Current" current c-face "\n\n")
13843 (org-fast-tag-show-exit exit-after-next)
13844 (org-set-current-tags-overlay current ov-prefix)
13845 (setq tbl fulltable char ?a cnt 0)
13846 (while (setq e (pop tbl))
13847 (cond
13848 ((equal (car e) :startgroup)
13849 (push '() groups) (setq ingroup t)
13850 (when (not (= cnt 0))
13851 (setq cnt 0)
13852 (insert "\n"))
13853 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13854 ((equal (car e) :endgroup)
13855 (setq ingroup nil cnt 0)
13856 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13857 ((equal e '(:newline))
13858 (when (not (= cnt 0))
13859 (setq cnt 0)
13860 (insert "\n")
13861 (setq e (car tbl))
13862 (while (equal (car tbl) '(:newline))
13863 (insert "\n")
13864 (setq tbl (cdr tbl)))))
13866 (setq tg (copy-sequence (car e)) c2 nil)
13867 (if (cdr e)
13868 (setq c (cdr e))
13869 ;; automatically assign a character.
13870 (setq c1 (string-to-char
13871 (downcase (substring
13872 tg (if (= (string-to-char tg) ?@) 1 0)))))
13873 (if (or (rassoc c1 ntable) (rassoc c1 table))
13874 (while (or (rassoc char ntable) (rassoc char table))
13875 (setq char (1+ char)))
13876 (setq c2 c1))
13877 (setq c (or c2 char)))
13878 (if ingroup (push tg (car groups)))
13879 (setq tg (org-add-props tg nil 'face
13880 (cond
13881 ((not (assoc tg table))
13882 (org-get-todo-face tg))
13883 ((member tg current) c-face)
13884 ((member tg inherited) i-face))))
13885 (if (and (= cnt 0) (not ingroup)) (insert " "))
13886 (insert "[" c "] " tg (make-string
13887 (- fwidth 4 (length tg)) ?\ ))
13888 (push (cons tg c) ntable)
13889 (when (= (setq cnt (1+ cnt)) ncol)
13890 (insert "\n")
13891 (if ingroup (insert " "))
13892 (setq cnt 0)))))
13893 (setq ntable (nreverse ntable))
13894 (insert "\n")
13895 (goto-char (point-min))
13896 (if (not expert) (org-fit-window-to-buffer))
13897 (setq rtn
13898 (catch 'exit
13899 (while t
13900 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13901 (if (not groups) "no " "")
13902 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13903 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13904 (setq org-last-tag-selection-key c)
13905 (cond
13906 ((= c ?\r) (throw 'exit t))
13907 ((= c ?!)
13908 (setq groups (not groups))
13909 (goto-char (point-min))
13910 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13911 ((= c ?\C-c)
13912 (if (not expert)
13913 (org-fast-tag-show-exit
13914 (setq exit-after-next (not exit-after-next)))
13915 (setq expert nil)
13916 (delete-other-windows)
13917 (set-window-buffer (split-window-vertically) " *Org tags*")
13918 (org-switch-to-buffer-other-window " *Org tags*")
13919 (org-fit-window-to-buffer)))
13920 ((or (= c ?\C-g)
13921 (and (= c ?q) (not (rassoc c ntable))))
13922 (org-detach-overlay org-tags-overlay)
13923 (setq quit-flag t))
13924 ((= c ?\ )
13925 (setq current nil)
13926 (if exit-after-next (setq exit-after-next 'now)))
13927 ((= c ?\t)
13928 (condition-case nil
13929 (setq tg (org-icompleting-read
13930 "Tag: "
13931 (or buffer-tags
13932 (with-current-buffer buf
13933 (org-get-buffer-tags)))))
13934 (quit (setq tg "")))
13935 (when (string-match "\\S-" tg)
13936 (add-to-list 'buffer-tags (list tg))
13937 (if (member tg current)
13938 (setq current (delete tg current))
13939 (push tg current)))
13940 (if exit-after-next (setq exit-after-next 'now)))
13941 ((setq e (rassoc c todo-table) tg (car e))
13942 (with-current-buffer buf
13943 (save-excursion (org-todo tg)))
13944 (if exit-after-next (setq exit-after-next 'now)))
13945 ((setq e (rassoc c ntable) tg (car e))
13946 (if (member tg current)
13947 (setq current (delete tg current))
13948 (loop for g in groups do
13949 (if (member tg g)
13950 (mapc (lambda (x)
13951 (setq current (delete x current)))
13952 g)))
13953 (push tg current))
13954 (if exit-after-next (setq exit-after-next 'now))))
13956 ;; Create a sorted list
13957 (setq current
13958 (sort current
13959 (lambda (a b)
13960 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13961 (if (eq exit-after-next 'now) (throw 'exit t))
13962 (goto-char (point-min))
13963 (beginning-of-line 2)
13964 (delete-region (point) (point-at-eol))
13965 (org-fast-tag-insert "Current" current c-face)
13966 (org-set-current-tags-overlay current ov-prefix)
13967 (while (re-search-forward
13968 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13969 (setq tg (match-string 1))
13970 (add-text-properties
13971 (match-beginning 1) (match-end 1)
13972 (list 'face
13973 (cond
13974 ((member tg current) c-face)
13975 ((member tg inherited) i-face)
13976 (t (get-text-property (match-beginning 1) 'face))))))
13977 (goto-char (point-min)))))
13978 (org-detach-overlay org-tags-overlay)
13979 (if rtn
13980 (mapconcat 'identity current ":")
13981 nil))))
13983 (defun org-get-tags-string ()
13984 "Get the TAGS string in the current headline."
13985 (unless (org-at-heading-p t)
13986 (error "Not on a heading"))
13987 (save-excursion
13988 (beginning-of-line 1)
13989 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13990 (org-match-string-no-properties 1)
13991 "")))
13993 (defun org-get-tags ()
13994 "Get the list of tags specified in the current headline."
13995 (org-split-string (org-get-tags-string) ":"))
13997 (defun org-get-buffer-tags ()
13998 "Get a table of all tags used in the buffer, for completion."
13999 (let (tags)
14000 (save-excursion
14001 (goto-char (point-min))
14002 (while (re-search-forward
14003 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14004 (when (equal (char-after (point-at-bol 0)) ?*)
14005 (mapc (lambda (x) (add-to-list 'tags x))
14006 (org-split-string (org-match-string-no-properties 1) ":")))))
14007 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14008 (mapcar 'list tags)))
14010 ;;;; The mapping API
14012 (defun org-map-entries (func &optional match scope &rest skip)
14013 "Call FUNC at each headline selected by MATCH in SCOPE.
14015 FUNC is a function or a lisp form. The function will be called without
14016 arguments, with the cursor positioned at the beginning of the headline.
14017 The return values of all calls to the function will be collected and
14018 returned as a list.
14020 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14021 does not need to preserve point. After evaluation, the cursor will be
14022 moved to the end of the line (presumably of the headline of the
14023 processed entry) and search continues from there. Under some
14024 circumstances, this may not produce the wanted results. For example,
14025 if you have removed (e.g. archived) the current (sub)tree it could
14026 mean that the next entry will be skipped entirely. In such cases, you
14027 can specify the position from where search should continue by making
14028 FUNC set the variable `org-map-continue-from' to the desired buffer
14029 position.
14031 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14032 Only headlines that are matched by this query will be considered during
14033 the iteration. When MATCH is nil or t, all headlines will be
14034 visited by the iteration.
14036 SCOPE determines the scope of this command. It can be any of:
14038 nil The current buffer, respecting the restriction if any
14039 tree The subtree started with the entry at point
14040 region The entries within the active region, if any
14041 region-start-level
14042 The entries within the active region, but only those at
14043 the same level than the first one.
14044 file The current buffer, without restriction
14045 file-with-archives
14046 The current buffer, and any archives associated with it
14047 agenda All agenda files
14048 agenda-with-archives
14049 All agenda files with any archive files associated with them
14050 \(file1 file2 ...)
14051 If this is a list, all files in the list will be scanned
14053 The remaining args are treated as settings for the skipping facilities of
14054 the scanner. The following items can be given here:
14056 archive skip trees with the archive tag.
14057 comment skip trees with the COMMENT keyword
14058 function or Emacs Lisp form:
14059 will be used as value for `org-agenda-skip-function', so whenever
14060 the function returns t, FUNC will not be called for that
14061 entry and search will continue from the point where the
14062 function leaves it.
14064 If your function needs to retrieve the tags including inherited tags
14065 at the *current* entry, you can use the value of the variable
14066 `org-scanner-tags' which will be much faster than getting the value
14067 with `org-get-tags-at'. If your function gets properties with
14068 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14069 to t around the call to `org-entry-properties' to get the same speedup.
14070 Note that if your function moves around to retrieve tags and properties at
14071 a *different* entry, you cannot use these techniques."
14072 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14073 (not (org-region-active-p)))
14074 (let* ((org-agenda-archives-mode nil) ; just to make sure
14075 (org-agenda-skip-archived-trees (memq 'archive skip))
14076 (org-agenda-skip-comment-trees (memq 'comment skip))
14077 (org-agenda-skip-function
14078 (car (org-delete-all '(comment archive) skip)))
14079 (org-tags-match-list-sublevels t)
14080 (start-level (eq scope 'region-start-level))
14081 matcher file res
14082 org-todo-keywords-for-agenda
14083 org-done-keywords-for-agenda
14084 org-todo-keyword-alist-for-agenda
14085 org-drawers-for-agenda
14086 org-tag-alist-for-agenda
14087 todo-only)
14089 (cond
14090 ((eq match t) (setq matcher t))
14091 ((eq match nil) (setq matcher t))
14092 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14094 (save-excursion
14095 (save-restriction
14096 (cond ((eq scope 'tree)
14097 (org-back-to-heading t)
14098 (org-narrow-to-subtree)
14099 (setq scope nil))
14100 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14101 (org-region-active-p))
14102 ;; If needed, set start-level to a string like "2"
14103 (when start-level
14104 (save-excursion
14105 (goto-char (region-beginning))
14106 (unless (org-at-heading-p) (outline-next-heading))
14107 (setq start-level (org-current-level))))
14108 (narrow-to-region (region-beginning)
14109 (save-excursion
14110 (goto-char (region-end))
14111 (unless (and (bolp) (org-at-heading-p))
14112 (outline-next-heading))
14113 (point)))
14114 (setq scope nil)))
14116 (if (not scope)
14117 (progn
14118 (org-agenda-prepare-buffers
14119 (list (buffer-file-name (current-buffer))))
14120 (setq res (org-scan-tags func matcher todo-only start-level)))
14121 ;; Get the right scope
14122 (cond
14123 ((and scope (listp scope) (symbolp (car scope)))
14124 (setq scope (eval scope)))
14125 ((eq scope 'agenda)
14126 (setq scope (org-agenda-files t)))
14127 ((eq scope 'agenda-with-archives)
14128 (setq scope (org-agenda-files t))
14129 (setq scope (org-add-archive-files scope)))
14130 ((eq scope 'file)
14131 (setq scope (list (buffer-file-name))))
14132 ((eq scope 'file-with-archives)
14133 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14134 (org-agenda-prepare-buffers scope)
14135 (while (setq file (pop scope))
14136 (with-current-buffer (org-find-base-buffer-visiting file)
14137 (save-excursion
14138 (save-restriction
14139 (widen)
14140 (goto-char (point-min))
14141 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14142 res)))
14144 ;;;; Properties
14146 ;;; Setting and retrieving properties
14148 (defconst org-special-properties
14149 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14150 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14151 "The special properties valid in Org-mode.
14153 These are properties that are not defined in the property drawer,
14154 but in some other way.")
14156 (defconst org-default-properties
14157 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14158 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14159 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14160 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14161 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14162 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14163 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14164 "Some properties that are used by Org-mode for various purposes.
14165 Being in this list makes sure that they are offered for completion.")
14167 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14168 "Regular expression matching the first line of a property drawer.")
14170 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14171 "Regular expression matching the last line of a property drawer.")
14173 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14174 "Regular expression matching the first line of a property drawer.")
14176 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14177 "Regular expression matching the first line of a property drawer.")
14179 (defconst org-property-drawer-re
14180 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14181 org-property-end-re "\\)\n?")
14182 "Matches an entire property drawer.")
14184 (defconst org-clock-drawer-re
14185 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14186 org-property-end-re "\\)\n?")
14187 "Matches an entire clock drawer.")
14189 (defsubst org-re-property (property)
14190 "Return a regexp matching a PROPERTY line.
14191 Match group 1 will be set to the value."
14192 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14194 (defsubst org-re-property-keyword (property)
14195 "Return a regexp matching a PROPERTY line, possibly with no
14196 value for the property."
14197 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14199 (defun org-property-action ()
14200 "Do an action on properties."
14201 (interactive)
14202 (let (c)
14203 (org-at-property-p)
14204 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14205 (setq c (read-char-exclusive))
14206 (cond
14207 ((equal c ?s)
14208 (call-interactively 'org-set-property))
14209 ((equal c ?d)
14210 (call-interactively 'org-delete-property))
14211 ((equal c ?D)
14212 (call-interactively 'org-delete-property-globally))
14213 ((equal c ?c)
14214 (call-interactively 'org-compute-property-at-point))
14215 (t (error "No such property action %c" c)))))
14217 (defun org-inc-effort ()
14218 "Increment the value of the effort property in the current entry."
14219 (interactive)
14220 (org-set-effort nil t))
14222 (defun org-set-effort (&optional value increment)
14223 "Set the effort property of the current entry.
14224 With numerical prefix arg, use the nth allowed value, 0 stands for the
14225 10th allowed value.
14227 When INCREMENT is non-nil, set the property to the next allowed value."
14228 (interactive "P")
14229 (if (equal value 0) (setq value 10))
14230 (let* ((completion-ignore-case t)
14231 (prop org-effort-property)
14232 (cur (org-entry-get nil prop))
14233 (allowed (org-property-get-allowed-values nil prop 'table))
14234 (existing (mapcar 'list (org-property-values prop)))
14236 (val (cond
14237 ((stringp value) value)
14238 ((and allowed (integerp value))
14239 (or (car (nth (1- value) allowed))
14240 (car (org-last allowed))))
14241 ((and allowed increment)
14242 (or (caadr (member (list cur) allowed))
14243 (error "Allowed effort values are not set")))
14244 (allowed
14245 (message "Select 1-9,0, [RET%s]: %s"
14246 (if cur (concat "=" cur) "")
14247 (mapconcat 'car allowed " "))
14248 (setq rpl (read-char-exclusive))
14249 (if (equal rpl ?\r)
14251 (setq rpl (- rpl ?0))
14252 (if (equal rpl 0) (setq rpl 10))
14253 (if (and (> rpl 0) (<= rpl (length allowed)))
14254 (car (nth (1- rpl) allowed))
14255 (org-completing-read "Effort: " allowed nil))))
14257 (let (org-completion-use-ido org-completion-use-iswitchb)
14258 (org-completing-read
14259 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14260 (concat "[" cur "]") "")
14261 ": ")
14262 existing nil nil "" nil cur))))))
14263 (unless (equal (org-entry-get nil prop) val)
14264 (org-entry-put nil prop val))
14265 (message "%s is now %s" prop val)))
14267 (defun org-at-property-p ()
14268 "Is cursor inside a property drawer?"
14269 (save-excursion
14270 (beginning-of-line 1)
14271 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14272 (save-match-data ;; Used by calling procedures
14273 (let ((p (point))
14274 (range (unless (org-before-first-heading-p)
14275 (org-get-property-block))))
14276 (and range (<= (car range) p) (< p (cdr range))))))))
14278 (defun org-get-property-block (&optional beg end force)
14279 "Return the (beg . end) range of the body of the property drawer.
14280 BEG and END are the beginning and end of the current subtree, or of
14281 the part before the first headline. If they are not given, they will
14282 be found. If the drawer does not exist and FORCE is non-nil, create
14283 the drawer."
14284 (catch 'exit
14285 (save-excursion
14286 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14287 (progn (org-back-to-heading t) (point))))
14288 (end (or end (and (not (outline-next-heading)) (point-max))
14289 (point))))
14290 (goto-char beg)
14291 (if (re-search-forward org-property-start-re end t)
14292 (setq beg (1+ (match-end 0)))
14293 (if force
14294 (save-excursion
14295 (org-insert-property-drawer)
14296 (setq end (progn (outline-next-heading) (point))))
14297 (throw 'exit nil))
14298 (goto-char beg)
14299 (if (re-search-forward org-property-start-re end t)
14300 (setq beg (1+ (match-end 0)))))
14301 (if (re-search-forward org-property-end-re end t)
14302 (setq end (match-beginning 0))
14303 (or force (throw 'exit nil))
14304 (goto-char beg)
14305 (setq end beg)
14306 (org-indent-line)
14307 (insert ":END:\n"))
14308 (cons beg end)))))
14310 (defun org-entry-properties (&optional pom which specific)
14311 "Get all properties of the entry at point-or-marker POM.
14312 This includes the TODO keyword, the tags, time strings for deadline,
14313 scheduled, and clocking, and any additional properties defined in the
14314 entry. The return value is an alist, keys may occur multiple times
14315 if the property key was used several times.
14316 POM may also be nil, in which case the current entry is used.
14317 If WHICH is nil or `all', get all properties. If WHICH is
14318 `special' or `standard', only get that subclass. If WHICH
14319 is a string only get exactly this property. SPECIFIC can be a string, the
14320 specific property we are interested in. Specifying it can speed
14321 things up because then unnecessary parsing is avoided."
14322 (setq which (or which 'all))
14323 (org-with-point-at pom
14324 (let ((clockstr (substring org-clock-string 0 -1))
14325 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14326 (case-fold-search nil)
14327 beg end range props sum-props key key1 value string clocksum clocksumt)
14328 (save-excursion
14329 (when (condition-case nil
14330 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14331 (error nil))
14332 (setq beg (point))
14333 (setq sum-props (get-text-property (point) 'org-summaries))
14334 (setq clocksum (get-text-property (point) :org-clock-minutes)
14335 clocksumt (get-text-property (point) :org-clock-minutes-today))
14336 (outline-next-heading)
14337 (setq end (point))
14338 (when (memq which '(all special))
14339 ;; Get the special properties, like TODO and tags
14340 (goto-char beg)
14341 (when (and (or (not specific) (string= specific "TODO"))
14342 (looking-at org-todo-line-regexp) (match-end 2))
14343 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14344 (when (and (or (not specific) (string= specific "PRIORITY"))
14345 (looking-at org-priority-regexp))
14346 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14347 (when (or (not specific) (string= specific "FILE"))
14348 (push (cons "FILE" buffer-file-name) props))
14349 (when (and (or (not specific) (string= specific "TAGS"))
14350 (setq value (org-get-tags-string))
14351 (string-match "\\S-" value))
14352 (push (cons "TAGS" value) props))
14353 (when (and (or (not specific) (string= specific "ALLTAGS"))
14354 (setq value (org-get-tags-at)))
14355 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14356 ":"))
14357 props))
14358 (when (or (not specific) (string= specific "BLOCKED"))
14359 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14360 (when (or (not specific)
14361 (member specific
14362 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14363 "TIMESTAMP" "TIMESTAMP_IA")))
14364 (catch 'match
14365 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14366 (setq key (if (match-end 1)
14367 (substring (org-match-string-no-properties 1)
14368 0 -1))
14369 string (if (equal key clockstr)
14370 (org-trim
14371 (buffer-substring-no-properties
14372 (match-beginning 3) (goto-char
14373 (point-at-eol))))
14374 (substring (org-match-string-no-properties 3)
14375 1 -1)))
14376 ;; Get the correct property name from the key. This is
14377 ;; necessary if the user has configured time keywords.
14378 (setq key1 (concat key ":"))
14379 (cond
14380 ((not key)
14381 (setq key
14382 (if (= (char-after (match-beginning 3)) ?\[)
14383 "TIMESTAMP_IA" "TIMESTAMP")))
14384 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14385 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14386 ((equal key1 org-closed-string) (setq key "CLOSED"))
14387 ((equal key1 org-clock-string) (setq key "CLOCK")))
14388 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14389 (progn
14390 (push (cons key string) props)
14391 ;; no need to search further if match is found
14392 (throw 'match t))
14393 (when (or (equal key "CLOCK") (not (assoc key props)))
14394 (push (cons key string) props)))))))
14396 (when (memq which '(all standard))
14397 ;; Get the standard properties, like :PROP: ...
14398 (setq range (org-get-property-block beg end))
14399 (when range
14400 (goto-char (car range))
14401 (while (re-search-forward
14402 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14403 (cdr range) t)
14404 (setq key (org-match-string-no-properties 1)
14405 value (org-trim (or (org-match-string-no-properties 2) "")))
14406 (unless (member key excluded)
14407 (push (cons key (or value "")) props)))))
14408 (if clocksum
14409 (push (cons "CLOCKSUM"
14410 (org-columns-number-to-string (/ (float clocksum) 60.)
14411 'add_times))
14412 props))
14413 (if clocksumt
14414 (push (cons "CLOCKSUM_T"
14415 (org-columns-number-to-string (/ (float clocksumt) 60.)
14416 'add_times))
14417 props))
14418 (unless (assoc "CATEGORY" props)
14419 (push (cons "CATEGORY" (org-get-category)) props))
14420 (append sum-props (nreverse props)))))))
14422 (defun org-entry-get (pom property &optional inherit literal-nil)
14423 "Get value of PROPERTY for entry or content at point-or-marker POM.
14424 If INHERIT is non-nil and the entry does not have the property,
14425 then also check higher levels of the hierarchy.
14426 If INHERIT is the symbol `selective', use inheritance only if the setting
14427 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14428 If the property is present but empty, the return value is the empty string.
14429 If the property is not present at all, nil is returned.
14431 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14432 do not interpret it as the list atom nil. This is used for inheritance
14433 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14434 (org-with-point-at pom
14435 (if (and inherit (if (eq inherit 'selective)
14436 (org-property-inherit-p property)
14438 (org-entry-get-with-inheritance property literal-nil)
14439 (if (member property org-special-properties)
14440 ;; We need a special property. Use `org-entry-properties' to
14441 ;; retrieve it, but specify the wanted property
14442 (cdr (assoc property (org-entry-properties nil 'special property)))
14443 (let* ((range (org-get-property-block))
14444 (props (list (or (assoc property org-file-properties)
14445 (assoc property org-global-properties)
14446 (assoc property org-global-properties-fixed))))
14447 (ap (lambda (key)
14448 (when (re-search-forward
14449 (org-re-property key) (cdr range) t)
14450 (setq props
14451 (org-update-property-plist
14453 (if (match-end 1)
14454 (org-match-string-no-properties 1) "")
14455 props)))))
14456 val)
14457 (when (and range (goto-char (car range)))
14458 (funcall ap property)
14459 (goto-char (car range))
14460 (while (funcall ap (concat property "+")))
14461 (setq val (cdr (assoc property props)))
14462 (when val (if literal-nil val (org-not-nil val)))))))))
14464 (defun org-property-or-variable-value (var &optional inherit)
14465 "Check if there is a property fixing the value of VAR.
14466 If yes, return this value. If not, return the current value of the variable."
14467 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14468 (if (and prop (stringp prop) (string-match "\\S-" prop))
14469 (read prop)
14470 (symbol-value var))))
14472 (defun org-entry-delete (pom property)
14473 "Delete the property PROPERTY from entry at point-or-marker POM."
14474 (org-with-point-at pom
14475 (if (member property org-special-properties)
14476 nil ; cannot delete these properties.
14477 (let ((range (org-get-property-block)))
14478 (if (and range
14479 (goto-char (car range))
14480 (re-search-forward
14481 (org-re-property property)
14482 (cdr range) t))
14483 (progn
14484 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14486 nil)))))
14488 ;; Multi-values properties are properties that contain multiple values
14489 ;; These values are assumed to be single words, separated by whitespace.
14490 (defun org-entry-add-to-multivalued-property (pom property value)
14491 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14492 (let* ((old (org-entry-get pom property))
14493 (values (and old (org-split-string old "[ \t]"))))
14494 (setq value (org-entry-protect-space value))
14495 (unless (member value values)
14496 (setq values (cons value values))
14497 (org-entry-put pom property
14498 (mapconcat 'identity values " ")))))
14500 (defun org-entry-remove-from-multivalued-property (pom property value)
14501 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14502 (let* ((old (org-entry-get pom property))
14503 (values (and old (org-split-string old "[ \t]"))))
14504 (setq value (org-entry-protect-space value))
14505 (when (member value values)
14506 (setq values (delete value values))
14507 (org-entry-put pom property
14508 (mapconcat 'identity values " ")))))
14510 (defun org-entry-member-in-multivalued-property (pom property value)
14511 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14512 (let* ((old (org-entry-get pom property))
14513 (values (and old (org-split-string old "[ \t]"))))
14514 (setq value (org-entry-protect-space value))
14515 (member value values)))
14517 (defun org-entry-get-multivalued-property (pom property)
14518 "Return a list of values in a multivalued property."
14519 (let* ((value (org-entry-get pom property))
14520 (values (and value (org-split-string value "[ \t]"))))
14521 (mapcar 'org-entry-restore-space values)))
14523 (defun org-entry-put-multivalued-property (pom property &rest values)
14524 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14525 VALUES should be a list of strings. Spaces will be protected."
14526 (org-entry-put pom property
14527 (mapconcat 'org-entry-protect-space values " "))
14528 (let* ((value (org-entry-get pom property))
14529 (values (and value (org-split-string value "[ \t]"))))
14530 (mapcar 'org-entry-restore-space values)))
14532 (defun org-entry-protect-space (s)
14533 "Protect spaces and newline in string S."
14534 (while (string-match " " s)
14535 (setq s (replace-match "%20" t t s)))
14536 (while (string-match "\n" s)
14537 (setq s (replace-match "%0A" t t s)))
14540 (defun org-entry-restore-space (s)
14541 "Restore spaces and newline in string S."
14542 (while (string-match "%20" s)
14543 (setq s (replace-match " " t t s)))
14544 (while (string-match "%0A" s)
14545 (setq s (replace-match "\n" t t s)))
14548 (defvar org-entry-property-inherited-from (make-marker)
14549 "Marker pointing to the entry from where a property was inherited.
14550 Each call to `org-entry-get-with-inheritance' will set this marker to the
14551 location of the entry where the inheritance search matched. If there was
14552 no match, the marker will point nowhere.
14553 Note that also `org-entry-get' calls this function, if the INHERIT flag
14554 is set.")
14556 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14557 "Get PROPERTY of entry or content at point, search higher levels if needed.
14558 The search will stop at the first ancestor which has the property defined.
14559 If the value found is \"nil\", return nil to show that the property
14560 should be considered as undefined (this is the meaning of nil here).
14561 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14562 (move-marker org-entry-property-inherited-from nil)
14563 (let (tmp)
14564 (save-excursion
14565 (save-restriction
14566 (widen)
14567 (catch 'ex
14568 (while t
14569 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14570 (or (ignore-errors (org-back-to-heading t))
14571 (goto-char (point-min)))
14572 (move-marker org-entry-property-inherited-from (point))
14573 (throw 'ex tmp))
14574 (or (ignore-errors (org-up-heading-safe))
14575 (throw 'ex nil))))))
14576 (setq tmp (or tmp
14577 (cdr (assoc property org-file-properties))
14578 (cdr (assoc property org-global-properties))
14579 (cdr (assoc property org-global-properties-fixed))))
14580 (if literal-nil tmp (org-not-nil tmp))))
14582 (defvar org-property-changed-functions nil
14583 "Hook called when the value of a property has changed.
14584 Each hook function should accept two arguments, the name of the property
14585 and the new value.")
14587 (defun org-entry-put (pom property value)
14588 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14589 (org-with-point-at pom
14590 (org-back-to-heading t)
14591 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14592 range)
14593 (cond
14594 ((equal property "TODO")
14595 (when (and (stringp value) (string-match "\\S-" value)
14596 (not (member value org-todo-keywords-1)))
14597 (error "\"%s\" is not a valid TODO state" value))
14598 (if (or (not value)
14599 (not (string-match "\\S-" value)))
14600 (setq value 'none))
14601 (org-todo value)
14602 (org-set-tags nil 'align))
14603 ((equal property "PRIORITY")
14604 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14605 (string-to-char value) ?\ ))
14606 (org-set-tags nil 'align))
14607 ((equal property "SCHEDULED")
14608 (if (re-search-forward org-scheduled-time-regexp end t)
14609 (cond
14610 ((eq value 'earlier) (org-timestamp-change -1 'day))
14611 ((eq value 'later) (org-timestamp-change 1 'day))
14612 (t (call-interactively 'org-schedule)))
14613 (call-interactively 'org-schedule)))
14614 ((equal property "DEADLINE")
14615 (if (re-search-forward org-deadline-time-regexp end t)
14616 (cond
14617 ((eq value 'earlier) (org-timestamp-change -1 'day))
14618 ((eq value 'later) (org-timestamp-change 1 'day))
14619 (t (call-interactively 'org-deadline)))
14620 (call-interactively 'org-deadline)))
14621 ((member property org-special-properties)
14622 (error "The %s property can not yet be set with `org-entry-put'"
14623 property))
14624 (t ; a non-special property
14625 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14626 (setq range (org-get-property-block beg end 'force))
14627 (goto-char (car range))
14628 (if (re-search-forward
14629 (org-re-property-keyword property) (cdr range) t)
14630 (progn
14631 (delete-region (match-beginning 0) (match-end 0))
14632 (goto-char (match-beginning 0)))
14633 (goto-char (cdr range))
14634 (insert "\n")
14635 (backward-char 1)
14636 (org-indent-line))
14637 (insert ":" property ":")
14638 (and value (insert " " value))
14639 (org-indent-line)))))
14640 (run-hook-with-args 'org-property-changed-functions property value)))
14642 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14643 "Get all property keys in the current buffer.
14644 With INCLUDE-SPECIALS, also list the special properties that reflect things
14645 like tags and TODO state.
14646 With INCLUDE-DEFAULTS, also include properties that has special meaning
14647 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14648 and others.
14649 With INCLUDE-COLUMNS, also include property names given in COLUMN
14650 formats in the current buffer."
14651 (let (rtn range cfmt s p)
14652 (save-excursion
14653 (save-restriction
14654 (widen)
14655 (goto-char (point-min))
14656 (while (re-search-forward org-property-start-re nil t)
14657 (setq range (org-get-property-block))
14658 (goto-char (car range))
14659 (while (re-search-forward
14660 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14661 (cdr range) t)
14662 (add-to-list 'rtn (org-match-string-no-properties 1)))
14663 (outline-next-heading))))
14665 (when include-specials
14666 (setq rtn (append org-special-properties rtn)))
14668 (when include-defaults
14669 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14670 (add-to-list 'rtn org-effort-property))
14672 (when include-columns
14673 (save-excursion
14674 (save-restriction
14675 (widen)
14676 (goto-char (point-min))
14677 (while (re-search-forward
14678 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14679 nil t)
14680 (setq cfmt (match-string 2) s 0)
14681 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14682 cfmt s)
14683 (setq s (match-end 0)
14684 p (match-string 1 cfmt))
14685 (unless (or (equal p "ITEM")
14686 (member p org-special-properties))
14687 (add-to-list 'rtn (match-string 1 cfmt))))))))
14689 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14691 (defun org-property-values (key)
14692 "Return a list of all values of property KEY in the current buffer."
14693 (save-excursion
14694 (save-restriction
14695 (widen)
14696 (goto-char (point-min))
14697 (let ((re (org-re-property key))
14698 values)
14699 (while (re-search-forward re nil t)
14700 (add-to-list 'values (org-trim (match-string 1))))
14701 (delete "" values)))))
14703 (defun org-insert-property-drawer ()
14704 "Insert a property drawer into the current entry."
14705 (org-back-to-heading t)
14706 (looking-at org-outline-regexp)
14707 (let ((indent (if org-adapt-indentation
14708 (- (match-end 0) (match-beginning 0))
14710 (beg (point))
14711 (re (concat "^[ \t]*" org-keyword-time-regexp))
14712 end hiddenp)
14713 (outline-next-heading)
14714 (setq end (point))
14715 (goto-char beg)
14716 (while (re-search-forward re end t))
14717 (setq hiddenp (outline-invisible-p))
14718 (end-of-line 1)
14719 (and (equal (char-after) ?\n) (forward-char 1))
14720 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14721 (if (member (match-string 1) '("CLOCK:" ":END:"))
14722 ;; just skip this line
14723 (beginning-of-line 2)
14724 ;; Drawer start, find the end
14725 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14726 (beginning-of-line 1)))
14727 (org-skip-over-state-notes)
14728 (skip-chars-backward " \t\n\r")
14729 (if (eq (char-before) ?*) (forward-char 1))
14730 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14731 (beginning-of-line 0)
14732 (org-indent-to-column indent)
14733 (beginning-of-line 2)
14734 (org-indent-to-column indent)
14735 (beginning-of-line 0)
14736 (if hiddenp
14737 (save-excursion
14738 (org-back-to-heading t)
14739 (hide-entry))
14740 (org-flag-drawer t))))
14742 (defun org-insert-drawer (&optional arg drawer)
14743 "Insert a drawer at point.
14745 Optional argument DRAWER, when non-nil, is a string representing
14746 drawer's name. Otherwise, the user is prompted for a name.
14748 If a region is active, insert the drawer around that region
14749 instead.
14751 Point is left between drawer's boundaries."
14752 (interactive "P")
14753 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14754 "LOGBOOK"))
14755 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14756 ;; internally by Org. They are meant to be inserted
14757 ;; automatically.
14758 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14759 ;; Remove system drawers from list. Note: For some reason,
14760 ;; `org-completing-read' ignores the predicate while
14761 ;; `completing-read' handles it fine.
14762 (drawer (if arg "PROPERTIES"
14763 (or drawer
14764 (completing-read
14765 "Drawer: " org-drawers
14766 (lambda (d) (not (member d system-drawers))))))))
14767 (cond
14768 ;; With C-u, fall back on `org-insert-property-drawer'
14769 (arg (org-insert-property-drawer))
14770 ;; With an active region, insert a drawer at point.
14771 ((not (org-region-active-p))
14772 (progn
14773 (unless (bolp) (insert "\n"))
14774 (insert (format ":%s:\n\n:END:\n" drawer))
14775 (forward-line -2)))
14776 ;; Otherwise, insert the drawer at point
14778 (let ((rbeg (region-beginning))
14779 (rend (copy-marker (region-end))))
14780 (unwind-protect
14781 (progn
14782 (goto-char rbeg)
14783 (beginning-of-line)
14784 (when (save-excursion
14785 (re-search-forward org-outline-regexp-bol rend t))
14786 (error "Drawers cannot contain headlines"))
14787 ;; Position point at the beginning of the first
14788 ;; non-blank line in region. Insert drawer's opening
14789 ;; there, then indent it.
14790 (org-skip-whitespace)
14791 (beginning-of-line)
14792 (insert ":" drawer ":\n")
14793 (forward-line -1)
14794 (indent-for-tab-command)
14795 ;; Move point to the beginning of the first blank line
14796 ;; after the last non-blank line in region. Insert
14797 ;; drawer's closing, then indent it.
14798 (goto-char rend)
14799 (skip-chars-backward " \r\t\n")
14800 (insert "\n:END:")
14801 (deactivate-mark t)
14802 (indent-for-tab-command)
14803 (unless (eolp) (insert "\n")))
14804 ;; Clear marker, whatever the outcome of insertion is.
14805 (set-marker rend nil)))))))
14807 (defvar org-property-set-functions-alist nil
14808 "Property set function alist.
14809 Each entry should have the following format:
14811 (PROPERTY . READ-FUNCTION)
14813 The read function will be called with the same argument as
14814 `org-completing-read'.")
14816 (defun org-set-property-function (property)
14817 "Get the function that should be used to set PROPERTY.
14818 This is computed according to `org-property-set-functions-alist'."
14819 (or (cdr (assoc property org-property-set-functions-alist))
14820 'org-completing-read))
14822 (defun org-read-property-value (property)
14823 "Read PROPERTY value from user."
14824 (let* ((completion-ignore-case t)
14825 (allowed (org-property-get-allowed-values nil property 'table))
14826 (cur (org-entry-get nil property))
14827 (prompt (concat property " value"
14828 (if (and cur (string-match "\\S-" cur))
14829 (concat " [" cur "]") "") ": "))
14830 (set-function (org-set-property-function property))
14831 (val (if allowed
14832 (funcall set-function prompt allowed nil
14833 (not (get-text-property 0 'org-unrestricted
14834 (caar allowed))))
14835 (let (org-completion-use-ido org-completion-use-iswitchb)
14836 (funcall set-function prompt
14837 (mapcar 'list (org-property-values property))
14838 nil nil "" nil cur)))))
14839 (if (equal val "")
14841 val)))
14843 (defvar org-last-set-property nil)
14844 (defun org-read-property-name ()
14845 "Read a property name."
14846 (let* ((completion-ignore-case t)
14847 (keys (org-buffer-property-keys nil t t))
14848 (default-prop (or (save-excursion
14849 (save-match-data
14850 (beginning-of-line)
14851 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14852 (null (string= (match-string 1) "END"))
14853 (match-string 1))))
14854 org-last-set-property))
14855 (property (org-icompleting-read
14856 (concat "Property"
14857 (if default-prop (concat " [" default-prop "]") "")
14858 ": ")
14859 (mapcar 'list keys)
14860 nil nil nil nil
14861 default-prop
14863 (if (member property keys)
14864 property
14865 (or (cdr (assoc (downcase property)
14866 (mapcar (lambda (x) (cons (downcase x) x))
14867 keys)))
14868 property))))
14870 (defun org-set-property (property value)
14871 "In the current entry, set PROPERTY to VALUE.
14872 When called interactively, this will prompt for a property name, offering
14873 completion on existing and default properties. And then it will prompt
14874 for a value, offering completion either on allowed values (via an inherited
14875 xxx_ALL property) or on existing values in other instances of this property
14876 in the current file."
14877 (interactive (list nil nil))
14878 (let* ((property (or property (org-read-property-name)))
14879 (value (or value (org-read-property-value property)))
14880 (fn (cdr (assoc property org-properties-postprocess-alist))))
14881 (setq org-last-set-property property)
14882 ;; Possibly postprocess the inserted value:
14883 (when fn (setq value (funcall fn value)))
14884 (unless (equal (org-entry-get nil property) value)
14885 (org-entry-put nil property value))))
14887 (defun org-delete-property (property)
14888 "In the current entry, delete PROPERTY."
14889 (interactive
14890 (let* ((completion-ignore-case t)
14891 (prop (org-icompleting-read "Property: "
14892 (org-entry-properties nil 'standard))))
14893 (list prop)))
14894 (message "Property %s %s" property
14895 (if (org-entry-delete nil property)
14896 "deleted"
14897 "was not present in the entry")))
14899 (defun org-delete-property-globally (property)
14900 "Remove PROPERTY globally, from all entries."
14901 (interactive
14902 (let* ((completion-ignore-case t)
14903 (prop (org-icompleting-read
14904 "Globally remove property: "
14905 (mapcar 'list (org-buffer-property-keys)))))
14906 (list prop)))
14907 (save-excursion
14908 (save-restriction
14909 (widen)
14910 (goto-char (point-min))
14911 (let ((cnt 0))
14912 (while (re-search-forward
14913 (org-re-property property)
14914 nil t)
14915 (setq cnt (1+ cnt))
14916 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14917 (message "Property \"%s\" removed from %d entries" property cnt)))))
14919 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14921 (defun org-compute-property-at-point ()
14922 "Compute the property at point.
14923 This looks for an enclosing column format, extracts the operator and
14924 then applies it to the property in the column format's scope."
14925 (interactive)
14926 (unless (org-at-property-p)
14927 (error "Not at a property"))
14928 (let ((prop (org-match-string-no-properties 2)))
14929 (org-columns-get-format-and-top-level)
14930 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14931 (error "No operator defined for property %s" prop))
14932 (org-columns-compute prop)))
14934 (defvar org-property-allowed-value-functions nil
14935 "Hook for functions supplying allowed values for a specific property.
14936 The functions must take a single argument, the name of the property, and
14937 return a flat list of allowed values. If \":ETC\" is one of
14938 the values, this means that these values are intended as defaults for
14939 completion, but that other values should be allowed too.
14940 The functions must return nil if they are not responsible for this
14941 property.")
14943 (defun org-property-get-allowed-values (pom property &optional table)
14944 "Get allowed values for the property PROPERTY.
14945 When TABLE is non-nil, return an alist that can directly be used for
14946 completion."
14947 (let (vals)
14948 (cond
14949 ((equal property "TODO")
14950 (setq vals (org-with-point-at pom
14951 (append org-todo-keywords-1 '("")))))
14952 ((equal property "PRIORITY")
14953 (let ((n org-lowest-priority))
14954 (while (>= n org-highest-priority)
14955 (push (char-to-string n) vals)
14956 (setq n (1- n)))))
14957 ((member property org-special-properties))
14958 ((setq vals (run-hook-with-args-until-success
14959 'org-property-allowed-value-functions property)))
14961 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14962 (when (and vals (string-match "\\S-" vals))
14963 (setq vals (car (read-from-string (concat "(" vals ")"))))
14964 (setq vals (mapcar (lambda (x)
14965 (cond ((stringp x) x)
14966 ((numberp x) (number-to-string x))
14967 ((symbolp x) (symbol-name x))
14968 (t "???")))
14969 vals)))))
14970 (when (member ":ETC" vals)
14971 (setq vals (remove ":ETC" vals))
14972 (org-add-props (car vals) '(org-unrestricted t)))
14973 (if table (mapcar 'list vals) vals)))
14975 (defun org-property-previous-allowed-value (&optional previous)
14976 "Switch to the next allowed value for this property."
14977 (interactive)
14978 (org-property-next-allowed-value t))
14980 (defun org-property-next-allowed-value (&optional previous)
14981 "Switch to the next allowed value for this property."
14982 (interactive)
14983 (unless (org-at-property-p)
14984 (error "Not at a property"))
14985 (let* ((key (match-string 2))
14986 (value (match-string 3))
14987 (allowed (or (org-property-get-allowed-values (point) key)
14988 (and (member value '("[ ]" "[-]" "[X]"))
14989 '("[ ]" "[X]"))))
14990 nval)
14991 (unless allowed
14992 (error "Allowed values for this property have not been defined"))
14993 (if previous (setq allowed (reverse allowed)))
14994 (if (member value allowed)
14995 (setq nval (car (cdr (member value allowed)))))
14996 (setq nval (or nval (car allowed)))
14997 (if (equal nval value)
14998 (error "Only one allowed value for this property"))
14999 (org-at-property-p)
15000 (replace-match (concat " :" key ": " nval) t t)
15001 (org-indent-line)
15002 (beginning-of-line 1)
15003 (skip-chars-forward " \t")
15004 (run-hook-with-args 'org-property-changed-functions key nval)))
15006 (defun org-find-olp (path &optional this-buffer)
15007 "Return a marker pointing to the entry at outline path OLP.
15008 If anything goes wrong, throw an error.
15009 You can wrap this call to catch the error like this:
15011 (condition-case msg
15012 (org-mobile-locate-entry (match-string 4))
15013 (error (nth 1 msg)))
15015 The return value will then be either a string with the error message,
15016 or a marker if everything is OK.
15018 If THIS-BUFFER is set, the outline path does not contain a file,
15019 only headings."
15020 (let* ((file (if this-buffer buffer-file-name (pop path)))
15021 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15022 (level 1)
15023 (lmin 1)
15024 (lmax 1)
15025 limit re end found pos heading cnt flevel)
15026 (unless buffer (error "File not found :%s" file))
15027 (with-current-buffer buffer
15028 (save-excursion
15029 (save-restriction
15030 (widen)
15031 (setq limit (point-max))
15032 (goto-char (point-min))
15033 (while (setq heading (pop path))
15034 (setq re (format org-complex-heading-regexp-format
15035 (regexp-quote heading)))
15036 (setq cnt 0 pos (point))
15037 (while (re-search-forward re end t)
15038 (setq level (- (match-end 1) (match-beginning 1)))
15039 (if (and (>= level lmin) (<= level lmax))
15040 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15041 (when (= cnt 0) (error "Heading not found on level %d: %s"
15042 lmax heading))
15043 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15044 lmax heading))
15045 (goto-char found)
15046 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15047 (setq end (save-excursion (org-end-of-subtree t t))))
15048 (when (org-at-heading-p)
15049 (move-marker (make-marker) (point))))))))
15051 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15052 "Find node HEADING in BUFFER.
15053 Return a marker to the heading if it was found, or nil if not.
15054 If POS-ONLY is set, return just the position instead of a marker.
15056 The heading text must match exact, but it may have a TODO keyword,
15057 a priority cookie and tags in the standard locations."
15058 (with-current-buffer (or buffer (current-buffer))
15059 (save-excursion
15060 (save-restriction
15061 (widen)
15062 (goto-char (point-min))
15063 (let (case-fold-search)
15064 (if (re-search-forward
15065 (format org-complex-heading-regexp-format
15066 (regexp-quote heading)) nil t)
15067 (if pos-only
15068 (match-beginning 0)
15069 (move-marker (make-marker) (match-beginning 0)))))))))
15071 (defun org-find-exact-heading-in-directory (heading &optional dir)
15072 "Find Org node headline HEADING in all .org files in directory DIR.
15073 When the target headline is found, return a marker to this location."
15074 (let ((files (directory-files (or dir default-directory)
15075 nil "\\`[^.#].*\\.org\\'"))
15076 file visiting m buffer)
15077 (catch 'found
15078 (while (setq file (pop files))
15079 (message "trying %s" file)
15080 (setq visiting (org-find-base-buffer-visiting file))
15081 (setq buffer (or visiting (find-file-noselect file)))
15082 (setq m (org-find-exact-headline-in-buffer
15083 heading buffer))
15084 (when (and (not m) (not visiting)) (kill-buffer buffer))
15085 (and m (throw 'found m))))))
15087 (defun org-find-entry-with-id (ident)
15088 "Locate the entry that contains the ID property with exact value IDENT.
15089 IDENT can be a string, a symbol or a number, this function will search for
15090 the string representation of it.
15091 Return the position where this entry starts, or nil if there is no such entry."
15092 (interactive "sID: ")
15093 (let ((id (cond
15094 ((stringp ident) ident)
15095 ((symbol-name ident) (symbol-name ident))
15096 ((numberp ident) (number-to-string ident))
15097 (t (error "IDENT %s must be a string, symbol or number" ident))))
15098 (case-fold-search nil))
15099 (save-excursion
15100 (save-restriction
15101 (widen)
15102 (goto-char (point-min))
15103 (when (re-search-forward
15104 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15105 nil t)
15106 (org-back-to-heading t)
15107 (point))))))
15109 ;;;; Timestamps
15111 (defvar org-last-changed-timestamp nil)
15112 (defvar org-last-inserted-timestamp nil
15113 "The last time stamp inserted with `org-insert-time-stamp'.")
15114 (defvar org-time-was-given) ; dynamically scoped parameter
15115 (defvar org-end-time-was-given) ; dynamically scoped parameter
15116 (defvar org-ts-what) ; dynamically scoped parameter
15118 (defun org-time-stamp (arg &optional inactive)
15119 "Prompt for a date/time and insert a time stamp.
15120 If the user specifies a time like HH:MM or if this command is
15121 called with at least one prefix argument, the time stamp contains
15122 the date and the time. Otherwise, only the date is be included.
15124 All parts of a date not specified by the user is filled in from
15125 the current date/time. So if you just press return without
15126 typing anything, the time stamp will represent the current
15127 date/time.
15129 If there is already a timestamp at the cursor, it will be
15130 modified.
15132 With two universal prefix arguments, insert an active timestamp
15133 with the current time without prompting the user."
15134 (interactive "P")
15135 (let* ((ts nil)
15136 (default-time
15137 ;; Default time is either today, or, when entering a range,
15138 ;; the range start.
15139 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15140 (save-excursion
15141 (re-search-backward
15142 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15143 (- (point) 20) t)))
15144 (apply 'encode-time (org-parse-time-string (match-string 1)))
15145 (current-time)))
15146 (default-input (and ts (org-get-compact-tod ts)))
15147 (repeater (save-excursion
15148 (save-match-data
15149 (beginning-of-line)
15150 (when (re-search-forward
15151 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15152 (save-excursion (progn (end-of-line) (point))) t)
15153 (match-string 0)))))
15154 org-time-was-given org-end-time-was-given time)
15155 (cond
15156 ((and (org-at-timestamp-p t)
15157 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15158 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15159 (insert "--")
15160 (setq time (let ((this-command this-command))
15161 (org-read-date arg 'totime nil nil
15162 default-time default-input inactive)))
15163 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15164 ((org-at-timestamp-p t)
15165 (setq time (let ((this-command this-command))
15166 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15167 (when (org-at-timestamp-p t) ; just to get the match data
15168 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15169 (replace-match "")
15170 (setq org-last-changed-timestamp
15171 (org-insert-time-stamp
15172 time (or org-time-was-given arg)
15173 inactive nil nil (list org-end-time-was-given)))
15174 (when repeater (goto-char (1- (point))) (insert " " repeater)
15175 (setq org-last-changed-timestamp
15176 (concat (substring org-last-inserted-timestamp 0 -1)
15177 " " repeater ">"))))
15178 (message "Timestamp updated"))
15179 ((equal arg '(16))
15180 (org-insert-time-stamp (current-time) t))
15182 (setq time (let ((this-command this-command))
15183 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15184 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15185 nil nil (list org-end-time-was-given))))))
15187 ;; FIXME: can we use this for something else, like computing time differences?
15188 (defun org-get-compact-tod (s)
15189 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15190 (let* ((t1 (match-string 1 s))
15191 (h1 (string-to-number (match-string 2 s)))
15192 (m1 (string-to-number (match-string 3 s)))
15193 (t2 (and (match-end 4) (match-string 5 s)))
15194 (h2 (and t2 (string-to-number (match-string 6 s))))
15195 (m2 (and t2 (string-to-number (match-string 7 s))))
15196 dh dm)
15197 (if (not t2)
15199 (setq dh (- h2 h1) dm (- m2 m1))
15200 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15201 (concat t1 "+" (number-to-string dh)
15202 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15204 (defun org-time-stamp-inactive (&optional arg)
15205 "Insert an inactive time stamp.
15206 An inactive time stamp is enclosed in square brackets instead of angle
15207 brackets. It is inactive in the sense that it does not trigger agenda entries,
15208 does not link to the calendar and cannot be changed with the S-cursor keys.
15209 So these are more for recording a certain time/date."
15210 (interactive "P")
15211 (org-time-stamp arg 'inactive))
15213 (defvar org-date-ovl (make-overlay 1 1))
15214 (overlay-put org-date-ovl 'face 'org-date-selected)
15215 (org-detach-overlay org-date-ovl)
15217 (defvar org-ans1) ; dynamically scoped parameter
15218 (defvar org-ans2) ; dynamically scoped parameter
15220 (defvar org-plain-time-of-day-regexp) ; defined below
15222 (defvar org-overriding-default-time nil) ; dynamically scoped
15223 (defvar org-read-date-overlay nil)
15224 (defvar org-dcst nil) ; dynamically scoped
15225 (defvar org-read-date-history nil)
15226 (defvar org-read-date-final-answer nil)
15227 (defvar org-read-date-analyze-futurep nil)
15228 (defvar org-read-date-analyze-forced-year nil)
15229 (defvar org-read-date-inactive)
15231 (defun org-read-date (&optional org-with-time to-time from-string prompt
15232 default-time default-input inactive)
15233 "Read a date, possibly a time, and make things smooth for the user.
15234 The prompt will suggest to enter an ISO date, but you can also enter anything
15235 which will at least partially be understood by `parse-time-string'.
15236 Unrecognized parts of the date will default to the current day, month, year,
15237 hour and minute. If this command is called to replace a timestamp at point,
15238 or to enter the second timestamp of a range, the default time is taken
15239 from the existing stamp. Furthermore, the command prefers the future,
15240 so if you are giving a date where the year is not given, and the day-month
15241 combination is already past in the current year, it will assume you
15242 mean next year. For details, see the manual. A few examples:
15244 3-2-5 --> 2003-02-05
15245 feb 15 --> currentyear-02-15
15246 2/15 --> currentyear-02-15
15247 sep 12 9 --> 2009-09-12
15248 12:45 --> today 12:45
15249 22 sept 0:34 --> currentyear-09-22 0:34
15250 12 --> currentyear-currentmonth-12
15251 Fri --> nearest Friday (today or later)
15252 etc.
15254 Furthermore you can specify a relative date by giving, as the *first* thing
15255 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15256 change in days weeks, months, years.
15257 With a single plus or minus, the date is relative to today. With a double
15258 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15259 +4d --> four days from today
15260 +4 --> same as above
15261 +2w --> two weeks from today
15262 ++5 --> five days from default date
15264 The function understands only English month and weekday abbreviations.
15266 While prompting, a calendar is popped up - you can also select the
15267 date with the mouse (button 1). The calendar shows a period of three
15268 months. To scroll it to other months, use the keys `>' and `<'.
15269 If you don't like the calendar, turn it off with
15270 \(setq org-read-date-popup-calendar nil)
15272 With optional argument TO-TIME, the date will immediately be converted
15273 to an internal time.
15274 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15275 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15276 still enter a time, and this function will inform the calling routine
15277 about this change. The calling routine may then choose to change the
15278 format used to insert the time stamp into the buffer to include the time.
15279 With optional argument FROM-STRING, read from this string instead from
15280 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15281 the time/date that is used for everything that is not specified by the
15282 user."
15283 (require 'parse-time)
15284 (let* ((org-time-stamp-rounding-minutes
15285 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15286 (org-dcst org-display-custom-times)
15287 (ct (org-current-time))
15288 (org-def (or org-overriding-default-time default-time ct))
15289 (org-defdecode (decode-time org-def))
15290 (dummy (progn
15291 (when (< (nth 2 org-defdecode) org-extend-today-until)
15292 (setcar (nthcdr 2 org-defdecode) -1)
15293 (setcar (nthcdr 1 org-defdecode) 59)
15294 (setq org-def (apply 'encode-time org-defdecode)
15295 org-defdecode (decode-time org-def)))))
15296 (calendar-frame-setup nil)
15297 (calendar-setup nil)
15298 (calendar-move-hook nil)
15299 (calendar-view-diary-initially-flag nil)
15300 (calendar-view-holidays-initially-flag nil)
15301 (timestr (format-time-string
15302 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15303 (prompt (concat (if prompt (concat prompt " ") "")
15304 (format "Date+time [%s]: " timestr)))
15305 ans (org-ans0 "") org-ans1 org-ans2 final)
15307 (cond
15308 (from-string (setq ans from-string))
15309 (org-read-date-popup-calendar
15310 (save-excursion
15311 (save-window-excursion
15312 (calendar)
15313 (org-eval-in-calendar '(setq cursor-type nil) t)
15314 (unwind-protect
15315 (progn
15316 (calendar-forward-day (- (time-to-days org-def)
15317 (calendar-absolute-from-gregorian
15318 (calendar-current-date))))
15319 (org-eval-in-calendar nil t)
15320 (let* ((old-map (current-local-map))
15321 (map (copy-keymap calendar-mode-map))
15322 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15323 (org-defkey map (kbd "RET") 'org-calendar-select)
15324 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15325 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15326 (org-defkey minibuffer-local-map [(meta shift left)]
15327 (lambda () (interactive)
15328 (org-eval-in-calendar '(calendar-backward-month 1))))
15329 (org-defkey minibuffer-local-map [(meta shift right)]
15330 (lambda () (interactive)
15331 (org-eval-in-calendar '(calendar-forward-month 1))))
15332 (org-defkey minibuffer-local-map [(meta shift up)]
15333 (lambda () (interactive)
15334 (org-eval-in-calendar '(calendar-backward-year 1))))
15335 (org-defkey minibuffer-local-map [(meta shift down)]
15336 (lambda () (interactive)
15337 (org-eval-in-calendar '(calendar-forward-year 1))))
15338 (org-defkey minibuffer-local-map [?\e (shift left)]
15339 (lambda () (interactive)
15340 (org-eval-in-calendar '(calendar-backward-month 1))))
15341 (org-defkey minibuffer-local-map [?\e (shift right)]
15342 (lambda () (interactive)
15343 (org-eval-in-calendar '(calendar-forward-month 1))))
15344 (org-defkey minibuffer-local-map [?\e (shift up)]
15345 (lambda () (interactive)
15346 (org-eval-in-calendar '(calendar-backward-year 1))))
15347 (org-defkey minibuffer-local-map [?\e (shift down)]
15348 (lambda () (interactive)
15349 (org-eval-in-calendar '(calendar-forward-year 1))))
15350 (org-defkey minibuffer-local-map [(shift up)]
15351 (lambda () (interactive)
15352 (org-eval-in-calendar '(calendar-backward-week 1))))
15353 (org-defkey minibuffer-local-map [(shift down)]
15354 (lambda () (interactive)
15355 (org-eval-in-calendar '(calendar-forward-week 1))))
15356 (org-defkey minibuffer-local-map [(shift left)]
15357 (lambda () (interactive)
15358 (org-eval-in-calendar '(calendar-backward-day 1))))
15359 (org-defkey minibuffer-local-map [(shift right)]
15360 (lambda () (interactive)
15361 (org-eval-in-calendar '(calendar-forward-day 1))))
15362 (org-defkey minibuffer-local-map ">"
15363 (lambda () (interactive)
15364 (org-eval-in-calendar '(scroll-calendar-left 1))))
15365 (org-defkey minibuffer-local-map "<"
15366 (lambda () (interactive)
15367 (org-eval-in-calendar '(scroll-calendar-right 1))))
15368 (org-defkey minibuffer-local-map "\C-v"
15369 (lambda () (interactive)
15370 (org-eval-in-calendar
15371 '(calendar-scroll-left-three-months 1))))
15372 (org-defkey minibuffer-local-map "\M-v"
15373 (lambda () (interactive)
15374 (org-eval-in-calendar
15375 '(calendar-scroll-right-three-months 1))))
15376 (run-hooks 'org-read-date-minibuffer-setup-hook)
15377 (unwind-protect
15378 (progn
15379 (use-local-map map)
15380 (setq org-read-date-inactive inactive)
15381 (add-hook 'post-command-hook 'org-read-date-display)
15382 (setq org-ans0 (read-string prompt default-input
15383 'org-read-date-history nil))
15384 ;; org-ans0: from prompt
15385 ;; org-ans1: from mouse click
15386 ;; org-ans2: from calendar motion
15387 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15388 (remove-hook 'post-command-hook 'org-read-date-display)
15389 (use-local-map old-map)
15390 (when org-read-date-overlay
15391 (delete-overlay org-read-date-overlay)
15392 (setq org-read-date-overlay nil)))))
15393 (bury-buffer "*Calendar*")))))
15395 (t ; Naked prompt only
15396 (unwind-protect
15397 (setq ans (read-string prompt default-input
15398 'org-read-date-history timestr))
15399 (when org-read-date-overlay
15400 (delete-overlay org-read-date-overlay)
15401 (setq org-read-date-overlay nil)))))
15403 (setq final (org-read-date-analyze ans org-def org-defdecode))
15405 (when org-read-date-analyze-forced-year
15406 (message "Year was forced into %s"
15407 (if org-read-date-force-compatible-dates
15408 "compatible range (1970-2037)"
15409 "range representable on this machine"))
15410 (ding))
15412 ;; One round trip to get rid of 34th of August and stuff like that....
15413 (setq final (decode-time (apply 'encode-time final)))
15415 (setq org-read-date-final-answer ans)
15417 (if to-time
15418 (apply 'encode-time final)
15419 (if (and (boundp 'org-time-was-given) org-time-was-given)
15420 (format "%04d-%02d-%02d %02d:%02d"
15421 (nth 5 final) (nth 4 final) (nth 3 final)
15422 (nth 2 final) (nth 1 final))
15423 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15425 (defvar org-def)
15426 (defvar org-defdecode)
15427 (defvar org-with-time)
15428 (defun org-read-date-display ()
15429 "Display the current date prompt interpretation in the minibuffer."
15430 (when org-read-date-display-live
15431 (when org-read-date-overlay
15432 (delete-overlay org-read-date-overlay))
15433 (when (minibufferp (current-buffer))
15434 (save-excursion
15435 (end-of-line 1)
15436 (while (not (equal (buffer-substring
15437 (max (point-min) (- (point) 4)) (point))
15438 " "))
15439 (insert " ")))
15440 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15441 " " (or org-ans1 org-ans2)))
15442 (org-end-time-was-given nil)
15443 (f (org-read-date-analyze ans org-def org-defdecode))
15444 (fmts (if org-dcst
15445 org-time-stamp-custom-formats
15446 org-time-stamp-formats))
15447 (fmt (if (or org-with-time
15448 (and (boundp 'org-time-was-given) org-time-was-given))
15449 (cdr fmts)
15450 (car fmts)))
15451 (txt (format-time-string fmt (apply 'encode-time f)))
15452 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15453 (txt (concat "=> " txt)))
15454 (when (and org-end-time-was-given
15455 (string-match org-plain-time-of-day-regexp txt))
15456 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15457 org-end-time-was-given
15458 (substring txt (match-end 0)))))
15459 (when org-read-date-analyze-futurep
15460 (setq txt (concat txt " (=>F)")))
15461 (setq org-read-date-overlay
15462 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15463 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15465 (defun org-read-date-analyze (ans org-def org-defdecode)
15466 "Analyze the combined answer of the date prompt."
15467 ;; FIXME: cleanup and comment
15468 (let ((nowdecode (decode-time (current-time)))
15469 delta deltan deltaw deltadef year month day
15470 hour minute second wday pm h2 m2 tl wday1
15471 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15472 (setq org-read-date-analyze-futurep nil
15473 org-read-date-analyze-forced-year nil)
15474 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15475 (setq ans "+0"))
15477 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15478 (setq ans (replace-match "" t t ans)
15479 deltan (car delta)
15480 deltaw (nth 1 delta)
15481 deltadef (nth 2 delta)))
15483 ;; Check if there is an iso week date in there. If yes, store the
15484 ;; info and postpone interpreting it until the rest of the parsing
15485 ;; is done.
15486 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15487 (setq iso-year (if (match-end 1)
15488 (org-small-year-to-year
15489 (string-to-number (match-string 1 ans))))
15490 iso-weekday (if (match-end 3)
15491 (string-to-number (match-string 3 ans)))
15492 iso-week (string-to-number (match-string 2 ans)))
15493 (setq ans (replace-match "" t t ans)))
15495 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15496 (when (string-match
15497 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15498 (setq year (if (match-end 2)
15499 (string-to-number (match-string 2 ans))
15500 (progn (setq kill-year t)
15501 (string-to-number (format-time-string "%Y"))))
15502 month (string-to-number (match-string 3 ans))
15503 day (string-to-number (match-string 4 ans)))
15504 (if (< year 100) (setq year (+ 2000 year)))
15505 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15506 t nil ans)))
15508 ;; Help matching dotted european dates
15509 (when (string-match
15510 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15511 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15512 (setq kill-year t)
15513 (string-to-number (format-time-string "%Y")))
15514 day (string-to-number (match-string 1 ans))
15515 month (string-to-number (match-string 2 ans))
15516 ans (replace-match (format "%04d-%02d-%02d" year month day)
15517 t nil ans)))
15519 ;; Help matching american dates, like 5/30 or 5/30/7
15520 (when (string-match
15521 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15522 (setq year (if (match-end 4)
15523 (string-to-number (match-string 4 ans))
15524 (progn (setq kill-year t)
15525 (string-to-number (format-time-string "%Y"))))
15526 month (string-to-number (match-string 1 ans))
15527 day (string-to-number (match-string 2 ans)))
15528 (if (< year 100) (setq year (+ 2000 year)))
15529 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15530 t nil ans)))
15531 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15532 ;; If there is a time with am/pm, and *no* time without it, we convert
15533 ;; so that matching will be successful.
15534 (loop for i from 1 to 2 do ; twice, for end time as well
15535 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15536 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15537 (setq hour (string-to-number (match-string 1 ans))
15538 minute (if (match-end 3)
15539 (string-to-number (match-string 3 ans))
15541 pm (equal ?p
15542 (string-to-char (downcase (match-string 4 ans)))))
15543 (if (and (= hour 12) (not pm))
15544 (setq hour 0)
15545 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15546 (setq ans (replace-match (format "%02d:%02d" hour minute)
15547 t t ans))))
15549 ;; Check if a time range is given as a duration
15550 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15551 (setq hour (string-to-number (match-string 1 ans))
15552 h2 (+ hour (string-to-number (match-string 3 ans)))
15553 minute (string-to-number (match-string 2 ans))
15554 m2 (+ minute (if (match-end 5) (string-to-number
15555 (match-string 5 ans))0)))
15556 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15557 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15558 t t ans)))
15560 ;; Check if there is a time range
15561 (when (boundp 'org-end-time-was-given)
15562 (setq org-time-was-given nil)
15563 (when (and (string-match org-plain-time-of-day-regexp ans)
15564 (match-end 8))
15565 (setq org-end-time-was-given (match-string 8 ans))
15566 (setq ans (concat (substring ans 0 (match-beginning 7))
15567 (substring ans (match-end 7))))))
15569 (setq tl (parse-time-string ans)
15570 day (or (nth 3 tl) (nth 3 org-defdecode))
15571 month (or (nth 4 tl)
15572 (if (and org-read-date-prefer-future
15573 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15574 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15575 (nth 4 org-defdecode)))
15576 year (or (and (not kill-year) (nth 5 tl))
15577 (if (and org-read-date-prefer-future
15578 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15579 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15580 (nth 5 org-defdecode)))
15581 hour (or (nth 2 tl) (nth 2 org-defdecode))
15582 minute (or (nth 1 tl) (nth 1 org-defdecode))
15583 second (or (nth 0 tl) 0)
15584 wday (nth 6 tl))
15586 (when (and (eq org-read-date-prefer-future 'time)
15587 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15588 (equal day (nth 3 nowdecode))
15589 (equal month (nth 4 nowdecode))
15590 (equal year (nth 5 nowdecode))
15591 (nth 2 tl)
15592 (or (< (nth 2 tl) (nth 2 nowdecode))
15593 (and (= (nth 2 tl) (nth 2 nowdecode))
15594 (nth 1 tl)
15595 (< (nth 1 tl) (nth 1 nowdecode)))))
15596 (setq day (1+ day)
15597 futurep t))
15599 ;; Special date definitions below
15600 (cond
15601 (iso-week
15602 ;; There was an iso week
15603 (require 'cal-iso)
15604 (setq futurep nil)
15605 (setq year (or iso-year year)
15606 day (or iso-weekday wday 1)
15607 wday nil ; to make sure that the trigger below does not match
15608 iso-date (calendar-gregorian-from-absolute
15609 (calendar-absolute-from-iso
15610 (list iso-week day year))))
15611 ; FIXME: Should we also push ISO weeks into the future?
15612 ; (when (and org-read-date-prefer-future
15613 ; (not iso-year)
15614 ; (< (calendar-absolute-from-gregorian iso-date)
15615 ; (time-to-days (current-time))))
15616 ; (setq year (1+ year)
15617 ; iso-date (calendar-gregorian-from-absolute
15618 ; (calendar-absolute-from-iso
15619 ; (list iso-week day year)))))
15620 (setq month (car iso-date)
15621 year (nth 2 iso-date)
15622 day (nth 1 iso-date)))
15623 (deltan
15624 (setq futurep nil)
15625 (unless deltadef
15626 (let ((now (decode-time (current-time))))
15627 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15628 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15629 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15630 ((equal deltaw "m") (setq month (+ month deltan)))
15631 ((equal deltaw "y") (setq year (+ year deltan)))))
15632 ((and wday (not (nth 3 tl)))
15633 ;; Weekday was given, but no day, so pick that day in the week
15634 ;; on or after the derived date.
15635 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15636 (unless (equal wday wday1)
15637 (setq day (+ day (% (- wday wday1 -7) 7))))))
15638 (if (and (boundp 'org-time-was-given)
15639 (nth 2 tl))
15640 (setq org-time-was-given t))
15641 (if (< year 100) (setq year (+ 2000 year)))
15642 ;; Check of the date is representable
15643 (if org-read-date-force-compatible-dates
15644 (progn
15645 (if (< year 1970)
15646 (setq year 1970 org-read-date-analyze-forced-year t))
15647 (if (> year 2037)
15648 (setq year 2037 org-read-date-analyze-forced-year t)))
15649 (condition-case nil
15650 (ignore (encode-time second minute hour day month year))
15651 (error
15652 (setq year (nth 5 org-defdecode))
15653 (setq org-read-date-analyze-forced-year t))))
15654 (setq org-read-date-analyze-futurep futurep)
15655 (list second minute hour day month year)))
15657 (defvar parse-time-weekdays)
15658 (defun org-read-date-get-relative (s today default)
15659 "Check string S for special relative date string.
15660 TODAY and DEFAULT are internal times, for today and for a default.
15661 Return shift list (N what def-flag)
15662 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15663 N is the number of WHATs to shift.
15664 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15665 the DEFAULT date rather than TODAY."
15666 (require 'parse-time)
15667 (when (and
15668 (string-match
15669 (concat
15670 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15671 "\\([0-9]+\\)?"
15672 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15673 "\\([ \t]\\|$\\)") s)
15674 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15675 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15676 (string-to-char (substring (match-string 1 s) -1))
15677 ?+))
15678 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15679 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15680 (what (if (match-end 3) (match-string 3 s) "d"))
15681 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15682 (date (if rel default today))
15683 (wday (nth 6 (decode-time date)))
15684 delta)
15685 (if wday1
15686 (progn
15687 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15688 (if (= dir ?-) (setq delta (- delta 7)))
15689 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15690 (list delta "d" rel))
15691 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15693 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15694 "Turn a user-specified date into the internal representation.
15695 The internal representation needed by the calendar is (month day year).
15696 This is a wrapper to handle the brain-dead convention in calendar that
15697 user function argument order change dependent on argument order."
15698 (if (boundp 'calendar-date-style)
15699 (cond
15700 ((eq calendar-date-style 'american)
15701 (list arg1 arg2 arg3))
15702 ((eq calendar-date-style 'european)
15703 (list arg2 arg1 arg3))
15704 ((eq calendar-date-style 'iso)
15705 (list arg2 arg3 arg1)))
15706 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15707 (if (org-bound-and-true-p european-calendar-style)
15708 (list arg2 arg1 arg3)
15709 (list arg1 arg2 arg3)))))
15711 (defun org-eval-in-calendar (form &optional keepdate)
15712 "Eval FORM in the calendar window and return to current window.
15713 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15714 otherwise stick to the current value of `org-ans2'."
15715 (let ((sf (selected-frame))
15716 (sw (selected-window)))
15717 (select-window (get-buffer-window "*Calendar*" t))
15718 (eval form)
15719 (when (and (not keepdate) (calendar-cursor-to-date))
15720 (let* ((date (calendar-cursor-to-date))
15721 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15722 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15723 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15724 (select-window sw)
15725 (org-select-frame-set-input-focus sf)))
15727 (defun org-calendar-select ()
15728 "Return to `org-read-date' with the date currently selected.
15729 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15730 (interactive)
15731 (when (calendar-cursor-to-date)
15732 (let* ((date (calendar-cursor-to-date))
15733 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15734 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15735 (if (active-minibuffer-window) (exit-minibuffer))))
15737 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15738 "Insert a date stamp for the date given by the internal TIME.
15739 WITH-HM means use the stamp format that includes the time of the day.
15740 INACTIVE means use square brackets instead of angular ones, so that the
15741 stamp will not contribute to the agenda.
15742 PRE and POST are optional strings to be inserted before and after the
15743 stamp.
15744 The command returns the inserted time stamp."
15745 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15746 stamp)
15747 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15748 (insert-before-markers (or pre ""))
15749 (when (listp extra)
15750 (setq extra (car extra))
15751 (if (and (stringp extra)
15752 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15753 (setq extra (format "-%02d:%02d"
15754 (string-to-number (match-string 1 extra))
15755 (string-to-number (match-string 2 extra))))
15756 (setq extra nil)))
15757 (when extra
15758 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15759 (insert-before-markers (setq stamp (format-time-string fmt time)))
15760 (insert-before-markers (or post ""))
15761 (setq org-last-inserted-timestamp stamp)))
15763 (defun org-toggle-time-stamp-overlays ()
15764 "Toggle the use of custom time stamp formats."
15765 (interactive)
15766 (setq org-display-custom-times (not org-display-custom-times))
15767 (unless org-display-custom-times
15768 (let ((p (point-min)) (bmp (buffer-modified-p)))
15769 (while (setq p (next-single-property-change p 'display))
15770 (if (and (get-text-property p 'display)
15771 (eq (get-text-property p 'face) 'org-date))
15772 (remove-text-properties
15773 p (setq p (next-single-property-change p 'display))
15774 '(display t))))
15775 (set-buffer-modified-p bmp)))
15776 (if (featurep 'xemacs)
15777 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15778 (org-restart-font-lock)
15779 (setq org-table-may-need-update t)
15780 (if org-display-custom-times
15781 (message "Time stamps are overlaid with custom format")
15782 (message "Time stamp overlays removed")))
15784 (defun org-display-custom-time (beg end)
15785 "Overlay modified time stamp format over timestamp between BEG and END."
15786 (let* ((ts (buffer-substring beg end))
15787 t1 w1 with-hm tf time str w2 (off 0))
15788 (save-match-data
15789 (setq t1 (org-parse-time-string ts t))
15790 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15791 (setq off (- (match-end 0) (match-beginning 0)))))
15792 (setq end (- end off))
15793 (setq w1 (- end beg)
15794 with-hm (and (nth 1 t1) (nth 2 t1))
15795 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15796 time (org-fix-decoded-time t1)
15797 str (org-add-props
15798 (format-time-string
15799 (substring tf 1 -1) (apply 'encode-time time))
15800 nil 'mouse-face 'highlight)
15801 w2 (length str))
15802 (if (not (= w2 w1))
15803 (add-text-properties (1+ beg) (+ 2 beg)
15804 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15805 (if (featurep 'xemacs)
15806 (progn
15807 (put-text-property beg end 'invisible t)
15808 (put-text-property beg end 'end-glyph (make-glyph str)))
15809 (put-text-property beg end 'display str))))
15811 (defun org-translate-time (string)
15812 "Translate all timestamps in STRING to custom format.
15813 But do this only if the variable `org-display-custom-times' is set."
15814 (when org-display-custom-times
15815 (save-match-data
15816 (let* ((start 0)
15817 (re org-ts-regexp-both)
15818 t1 with-hm inactive tf time str beg end)
15819 (while (setq start (string-match re string start))
15820 (setq beg (match-beginning 0)
15821 end (match-end 0)
15822 t1 (save-match-data
15823 (org-parse-time-string (substring string beg end) t))
15824 with-hm (and (nth 1 t1) (nth 2 t1))
15825 inactive (equal (substring string beg (1+ beg)) "[")
15826 tf (funcall (if with-hm 'cdr 'car)
15827 org-time-stamp-custom-formats)
15828 time (org-fix-decoded-time t1)
15829 str (format-time-string
15830 (concat
15831 (if inactive "[" "<") (substring tf 1 -1)
15832 (if inactive "]" ">"))
15833 (apply 'encode-time time))
15834 string (replace-match str t t string)
15835 start (+ start (length str)))))))
15836 string)
15838 (defun org-fix-decoded-time (time)
15839 "Set 0 instead of nil for the first 6 elements of time.
15840 Don't touch the rest."
15841 (let ((n 0))
15842 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15844 (defun org-days-to-time (timestamp-string)
15845 "Difference between TIMESTAMP-STRING and now in days."
15846 (- (time-to-days (org-time-string-to-time timestamp-string))
15847 (time-to-days (current-time))))
15849 (defun org-deadline-close (timestamp-string &optional ndays)
15850 "Is the time in TIMESTAMP-STRING close to the current date?"
15851 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15852 (and (< (org-days-to-time timestamp-string) ndays)
15853 (not (org-entry-is-done-p))))
15855 (defun org-get-wdays (ts)
15856 "Get the deadline lead time appropriate for timestring TS."
15857 (cond
15858 ((<= org-deadline-warning-days 0)
15859 ;; 0 or negative, enforce this value no matter what
15860 (- org-deadline-warning-days))
15861 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15862 ;; lead time is specified.
15863 (floor (* (string-to-number (match-string 1 ts))
15864 (cdr (assoc (match-string 2 ts)
15865 '(("d" . 1) ("w" . 7)
15866 ("m" . 30.4) ("y" . 365.25)))))))
15867 ;; go for the default.
15868 (t org-deadline-warning-days)))
15870 (defun org-calendar-select-mouse (ev)
15871 "Return to `org-read-date' with the date currently selected.
15872 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15873 (interactive "e")
15874 (mouse-set-point ev)
15875 (when (calendar-cursor-to-date)
15876 (let* ((date (calendar-cursor-to-date))
15877 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15878 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15879 (if (active-minibuffer-window) (exit-minibuffer))))
15881 (defun org-check-deadlines (ndays)
15882 "Check if there are any deadlines due or past due.
15883 A deadline is considered due if it happens within `org-deadline-warning-days'
15884 days from today's date. If the deadline appears in an entry marked DONE,
15885 it is not shown. The prefix arg NDAYS can be used to test that many
15886 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15887 (interactive "P")
15888 (let* ((org-warn-days
15889 (cond
15890 ((equal ndays '(4)) 100000)
15891 (ndays (prefix-numeric-value ndays))
15892 (t (abs org-deadline-warning-days))))
15893 (case-fold-search nil)
15894 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15895 (callback
15896 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15898 (message "%d deadlines past-due or due within %d days"
15899 (org-occur regexp nil callback)
15900 org-warn-days)))
15902 (defsubst org-re-timestamp (type)
15903 "Return a regexp for timestamp TYPE.
15904 Allowed values for TYPE are:
15906 all: all timestamps
15907 active: only active timestamps (<...>)
15908 inactive: only inactive timestamps ([...])
15909 scheduled: only scheduled timestamps
15910 deadline: only deadline timestamps
15912 When TYPE is nil, fall back on returning a regexp that matches
15913 both scheduled and deadline timestamps."
15914 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15915 ((eq type 'active) org-ts-regexp)
15916 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15917 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15918 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15919 ((eq type 'scheduled-or-deadline)
15920 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15922 (defun org-check-before-date (date)
15923 "Check if there are deadlines or scheduled entries before DATE."
15924 (interactive (list (org-read-date)))
15925 (let ((case-fold-search nil)
15926 (regexp (org-re-timestamp org-ts-type))
15927 (callback
15928 (lambda () (time-less-p
15929 (org-time-string-to-time (match-string 1))
15930 (org-time-string-to-time date)))))
15931 (message "%d entries before %s"
15932 (org-occur regexp nil callback) date)))
15934 (defun org-check-after-date (date)
15935 "Check if there are deadlines or scheduled entries after DATE."
15936 (interactive (list (org-read-date)))
15937 (let ((case-fold-search nil)
15938 (regexp (org-re-timestamp org-ts-type))
15939 (callback
15940 (lambda () (not
15941 (time-less-p
15942 (org-time-string-to-time (match-string 1))
15943 (org-time-string-to-time date))))))
15944 (message "%d entries after %s"
15945 (org-occur regexp nil callback) date)))
15947 (defun org-check-dates-range (start-date end-date)
15948 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15949 (interactive (list (org-read-date nil nil nil "Range starts")
15950 (org-read-date nil nil nil "Range end")))
15951 (let ((case-fold-search nil)
15952 (regexp (org-re-timestamp org-ts-type))
15953 (callback
15954 (lambda ()
15955 (let ((match (match-string 1)))
15956 (and
15957 (not (time-less-p
15958 (org-time-string-to-time match)
15959 (org-time-string-to-time start-date)))
15960 (time-less-p
15961 (org-time-string-to-time match)
15962 (org-time-string-to-time end-date)))))))
15963 (message "%d entries between %s and %s"
15964 (org-occur regexp nil callback) start-date end-date)))
15966 (defun org-evaluate-time-range (&optional to-buffer)
15967 "Evaluate a time range by computing the difference between start and end.
15968 Normally the result is just printed in the echo area, but with prefix arg
15969 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15970 If the time range is actually in a table, the result is inserted into the
15971 next column.
15972 For time difference computation, a year is assumed to be exactly 365
15973 days in order to avoid rounding problems."
15974 (interactive "P")
15976 (org-clock-update-time-maybe)
15977 (save-excursion
15978 (unless (org-at-date-range-p t)
15979 (goto-char (point-at-bol))
15980 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15981 (if (not (org-at-date-range-p t))
15982 (error "Not at a time-stamp range, and none found in current line")))
15983 (let* ((ts1 (match-string 1))
15984 (ts2 (match-string 2))
15985 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15986 (match-end (match-end 0))
15987 (time1 (org-time-string-to-time ts1))
15988 (time2 (org-time-string-to-time ts2))
15989 (t1 (org-float-time time1))
15990 (t2 (org-float-time time2))
15991 (diff (abs (- t2 t1)))
15992 (negative (< (- t2 t1) 0))
15993 ;; (ys (floor (* 365 24 60 60)))
15994 (ds (* 24 60 60))
15995 (hs (* 60 60))
15996 (fy "%dy %dd %02d:%02d")
15997 (fy1 "%dy %dd")
15998 (fd "%dd %02d:%02d")
15999 (fd1 "%dd")
16000 (fh "%02d:%02d")
16001 y d h m align)
16002 (if havetime
16003 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16005 d (floor (/ diff ds)) diff (mod diff ds)
16006 h (floor (/ diff hs)) diff (mod diff hs)
16007 m (floor (/ diff 60)))
16008 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16010 d (floor (+ (/ diff ds) 0.5))
16011 h 0 m 0))
16012 (if (not to-buffer)
16013 (message "%s" (org-make-tdiff-string y d h m))
16014 (if (org-at-table-p)
16015 (progn
16016 (goto-char match-end)
16017 (setq align t)
16018 (and (looking-at " *|") (goto-char (match-end 0))))
16019 (goto-char match-end))
16020 (if (looking-at
16021 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16022 (replace-match ""))
16023 (if negative (insert " -"))
16024 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16025 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16026 (insert " " (format fh h m))))
16027 (if align (org-table-align))
16028 (message "Time difference inserted")))))
16030 (defun org-make-tdiff-string (y d h m)
16031 (let ((fmt "")
16032 (l nil))
16033 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16034 l (push y l)))
16035 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16036 l (push d l)))
16037 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16038 l (push h l)))
16039 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16040 l (push m l)))
16041 (apply 'format fmt (nreverse l))))
16043 (defun org-time-string-to-time (s &optional buffer pos)
16044 "Convert a timestamp string into internal time."
16045 (condition-case errdata
16046 (apply 'encode-time (org-parse-time-string s))
16047 (error (error "Bad timestamp `%s'%s\nError was: %s"
16048 s (if (not (and buffer pos))
16050 (format " at %d in buffer `%s'" pos buffer))
16051 (cdr errdata)))))
16053 (defun org-time-string-to-seconds (s)
16054 "Convert a timestamp string to a number of seconds."
16055 (org-float-time (org-time-string-to-time s)))
16057 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16058 "Convert a time stamp to an absolute day number.
16059 If there is a specifier for a cyclic time stamp, get the closest date to
16060 DAYNR.
16061 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16062 The variable date is bound by the calendar when this is called."
16063 (cond
16064 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16065 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16066 daynr
16067 (+ daynr 1000)))
16068 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16069 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16070 (time-to-days (current-time))) (match-string 0 s)
16071 prefer show-all))
16072 (t (time-to-days
16073 (condition-case errdata
16074 (apply 'encode-time (org-parse-time-string s))
16075 (error (error "Bad timestamp `%s'%s\nError was: %s"
16076 s (if (not (and buffer pos))
16078 (format " at %d in buffer `%s'" pos buffer))
16079 (cdr errdata))))))))
16081 (defun org-days-to-iso-week (days)
16082 "Return the iso week number."
16083 (require 'cal-iso)
16084 (car (calendar-iso-from-absolute days)))
16086 (defun org-small-year-to-year (year)
16087 "Convert 2-digit years into 4-digit years.
16088 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16089 The year 2000 cannot be abbreviated. Any year larger than 99
16090 is returned unchanged."
16091 (if (< year 38)
16092 (setq year (+ 2000 year))
16093 (if (< year 100)
16094 (setq year (+ 1900 year))))
16095 year)
16097 (defun org-time-from-absolute (d)
16098 "Return the time corresponding to date D.
16099 D may be an absolute day number, or a calendar-type list (month day year)."
16100 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16101 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16103 (defun org-calendar-holiday ()
16104 "List of holidays, for Diary display in Org-mode."
16105 (require 'holidays)
16106 (let ((hl (funcall
16107 (if (fboundp 'calendar-check-holidays)
16108 'calendar-check-holidays 'check-calendar-holidays) date)))
16109 (if hl (mapconcat 'identity hl "; "))))
16111 (defun org-diary-sexp-entry (sexp entry date)
16112 "Process a SEXP diary ENTRY for DATE."
16113 (require 'diary-lib)
16114 (let ((result (if calendar-debug-sexp
16115 (let ((stack-trace-on-error t))
16116 (eval (car (read-from-string sexp))))
16117 (condition-case nil
16118 (eval (car (read-from-string sexp)))
16119 (error
16120 (beep)
16121 (message "Bad sexp at line %d in %s: %s"
16122 (org-current-line)
16123 (buffer-file-name) sexp)
16124 (sleep-for 2))))))
16125 (cond ((stringp result) (split-string result "; "))
16126 ((and (consp result)
16127 (not (consp (cdr result)))
16128 (stringp (cdr result))) (cdr result))
16129 ((and (consp result)
16130 (stringp (car result))) result)
16131 (result entry))))
16133 (defun org-diary-to-ical-string (frombuf)
16134 "Get iCalendar entries from diary entries in buffer FROMBUF.
16135 This uses the icalendar.el library."
16136 (let* ((tmpdir (if (featurep 'xemacs)
16137 (temp-directory)
16138 temporary-file-directory))
16139 (tmpfile (make-temp-name
16140 (expand-file-name "orgics" tmpdir)))
16141 buf rtn b e)
16142 (with-current-buffer frombuf
16143 (icalendar-export-region (point-min) (point-max) tmpfile)
16144 (setq buf (find-buffer-visiting tmpfile))
16145 (set-buffer buf)
16146 (goto-char (point-min))
16147 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16148 (setq b (match-beginning 0)))
16149 (goto-char (point-max))
16150 (if (re-search-backward "^END:VEVENT" nil t)
16151 (setq e (match-end 0)))
16152 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16153 (kill-buffer buf)
16154 (delete-file tmpfile)
16155 rtn))
16157 (defun org-closest-date (start current change prefer show-all)
16158 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16159 When PREFER is `past', return a date that is either CURRENT or past.
16160 When PREFER is `future', return a date that is either CURRENT or future.
16161 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16162 ;; Make the proper lists from the dates
16163 (catch 'exit
16164 (let ((a1 '(("h" . hour)
16165 ("d" . day)
16166 ("w" . week)
16167 ("m" . month)
16168 ("y" . year)))
16169 (shour (nth 2 (org-parse-time-string start)))
16170 dn dw sday cday n1 n2 n0
16171 d m y y1 y2 date1 date2 nmonths nm ny m2)
16173 (setq start (org-date-to-gregorian start)
16174 current (org-date-to-gregorian
16175 (if show-all
16176 current
16177 (time-to-days (current-time))))
16178 sday (calendar-absolute-from-gregorian start)
16179 cday (calendar-absolute-from-gregorian current))
16181 (if (<= cday sday) (throw 'exit sday))
16183 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16184 (setq dn (string-to-number (match-string 1 change))
16185 dw (cdr (assoc (match-string 2 change) a1)))
16186 (error "Invalid change specifier: %s" change))
16187 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16188 (cond
16189 ((eq dw 'hour)
16190 (let ((missing-hours
16191 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16192 dn)))
16193 (setq n1 (if (zerop missing-hours) cday
16194 (- cday (1+ (floor (/ missing-hours 24)))))
16195 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16196 ((eq dw 'day)
16197 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16198 n2 (+ n1 dn)))
16199 ((eq dw 'year)
16200 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16201 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16202 (setq date1 (list m d y1)
16203 n1 (calendar-absolute-from-gregorian date1)
16204 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16205 n2 (calendar-absolute-from-gregorian date2)))
16206 ((eq dw 'month)
16207 ;; approx number of month between the two dates
16208 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16209 ;; How often does dn fit in there?
16210 (setq d (nth 1 start) m (car start) y (nth 2 start)
16211 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16212 m (+ m nm)
16213 ny (floor (/ m 12))
16214 y (+ y ny)
16215 m (- m (* ny 12)))
16216 (while (> m 12) (setq m (- m 12) y (1+ y)))
16217 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16218 (setq m2 (+ m dn) y2 y)
16219 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16220 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16221 (while (<= n2 cday)
16222 (setq n1 n2 m m2 y y2)
16223 (setq m2 (+ m dn) y2 y)
16224 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16225 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16226 ;; Make sure n1 is the earlier date
16227 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16228 (if show-all
16229 (cond
16230 ((eq prefer 'past) (if (= cday n2) n2 n1))
16231 ((eq prefer 'future) (if (= cday n1) n1 n2))
16232 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16233 (cond
16234 ((eq prefer 'past) (if (= cday n2) n2 n1))
16235 ((eq prefer 'future) (if (= cday n1) n1 n2))
16236 (t (if (= cday n1) n1 n2)))))))
16238 (defun org-date-to-gregorian (date)
16239 "Turn any specification of DATE into a Gregorian date for the calendar."
16240 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16241 ((and (listp date) (= (length date) 3)) date)
16242 ((stringp date)
16243 (setq date (org-parse-time-string date))
16244 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16245 ((listp date)
16246 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16248 (defun org-parse-time-string (s &optional nodefault)
16249 "Parse the standard Org-mode time string.
16250 This should be a lot faster than the normal `parse-time-string'.
16251 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16252 hour and minute fields will be nil if not given."
16253 (if (string-match org-ts-regexp0 s)
16254 (list 0
16255 (if (or (match-beginning 8) (not nodefault))
16256 (string-to-number (or (match-string 8 s) "0")))
16257 (if (or (match-beginning 7) (not nodefault))
16258 (string-to-number (or (match-string 7 s) "0")))
16259 (string-to-number (match-string 4 s))
16260 (string-to-number (match-string 3 s))
16261 (string-to-number (match-string 2 s))
16262 nil nil nil)
16263 (error "Not a standard Org-mode time string: %s" s)))
16265 (defun org-timestamp-up (&optional arg)
16266 "Increase the date item at the cursor by one.
16267 If the cursor is on the year, change the year. If it is on the month,
16268 the day or the time, change that.
16269 With prefix ARG, change by that many units."
16270 (interactive "p")
16271 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16273 (defun org-timestamp-down (&optional arg)
16274 "Decrease the date item at the cursor by one.
16275 If the cursor is on the year, change the year. If it is on the month,
16276 the day or the time, change that.
16277 With prefix ARG, change by that many units."
16278 (interactive "p")
16279 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16281 (defun org-timestamp-up-day (&optional arg)
16282 "Increase the date in the time stamp by one day.
16283 With prefix ARG, change that many days."
16284 (interactive "p")
16285 (if (and (not (org-at-timestamp-p t))
16286 (org-at-heading-p))
16287 (org-todo 'up)
16288 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16290 (defun org-timestamp-down-day (&optional arg)
16291 "Decrease the date in the time stamp by one day.
16292 With prefix ARG, change that many days."
16293 (interactive "p")
16294 (if (and (not (org-at-timestamp-p t))
16295 (org-at-heading-p))
16296 (org-todo 'down)
16297 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16299 (defun org-at-timestamp-p (&optional inactive-ok)
16300 "Determine if the cursor is in or at a timestamp."
16301 (interactive)
16302 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16303 (pos (point))
16304 (ans (or (looking-at tsr)
16305 (save-excursion
16306 (skip-chars-backward "^[<\n\r\t")
16307 (if (> (point) (point-min)) (backward-char 1))
16308 (and (looking-at tsr)
16309 (> (- (match-end 0) pos) -1))))))
16310 (and ans
16311 (boundp 'org-ts-what)
16312 (setq org-ts-what
16313 (cond
16314 ((= pos (match-beginning 0)) 'bracket)
16315 ;; Point is considered to be "on the bracket" whether
16316 ;; it's really on it or right after it.
16317 ((= pos (1- (match-end 0))) 'bracket)
16318 ((= pos (match-end 0)) 'after)
16319 ((org-pos-in-match-range pos 2) 'year)
16320 ((org-pos-in-match-range pos 3) 'month)
16321 ((org-pos-in-match-range pos 7) 'hour)
16322 ((org-pos-in-match-range pos 8) 'minute)
16323 ((or (org-pos-in-match-range pos 4)
16324 (org-pos-in-match-range pos 5)) 'day)
16325 ((and (> pos (or (match-end 8) (match-end 5)))
16326 (< pos (match-end 0)))
16327 (- pos (or (match-end 8) (match-end 5))))
16328 (t 'day))))
16329 ans))
16331 (defun org-toggle-timestamp-type ()
16332 "Toggle the type (<active> or [inactive]) of a time stamp."
16333 (interactive)
16334 (when (org-at-timestamp-p t)
16335 (let ((beg (match-beginning 0)) (end (match-end 0))
16336 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16337 (save-excursion
16338 (goto-char beg)
16339 (while (re-search-forward "[][<>]" end t)
16340 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16341 t t)))
16342 (message "Timestamp is now %sactive"
16343 (if (equal (char-after beg) ?<) "" "in")))))
16345 (defvar org-clock-history) ; defined in org-clock.el
16346 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16347 (defun org-timestamp-change (n &optional what updown)
16348 "Change the date in the time stamp at point.
16349 The date will be changed by N times WHAT. WHAT can be `day', `month',
16350 `year', `minute', `second'. If WHAT is not given, the cursor position
16351 in the timestamp determines what will be changed."
16352 (let ((origin (point)) origin-cat
16353 with-hm inactive
16354 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16355 org-ts-what
16356 extra rem
16357 ts time time0 fixnext clrgx)
16358 (if (not (org-at-timestamp-p t))
16359 (error "Not at a timestamp"))
16360 (if (and (not what) (eq org-ts-what 'bracket))
16361 (org-toggle-timestamp-type)
16362 ;; Point isn't on brackets. Remember the part of the time-stamp
16363 ;; the point was in. Indeed, size of time-stamps may change,
16364 ;; but point must be kept in the same category nonetheless.
16365 (setq origin-cat org-ts-what)
16366 (if (and (not what) (not (eq org-ts-what 'day))
16367 org-display-custom-times
16368 (get-text-property (point) 'display)
16369 (not (get-text-property (1- (point)) 'display)))
16370 (setq org-ts-what 'day))
16371 (setq org-ts-what (or what org-ts-what)
16372 inactive (= (char-after (match-beginning 0)) ?\[)
16373 ts (match-string 0))
16374 (replace-match "")
16375 (if (string-match
16376 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16378 (setq extra (match-string 1 ts)))
16379 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16380 (setq with-hm t))
16381 (setq time0 (org-parse-time-string ts))
16382 (when (and updown
16383 (eq org-ts-what 'minute)
16384 (not current-prefix-arg))
16385 ;; This looks like s-up and s-down. Change by one rounding step.
16386 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16387 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16388 (setcar (cdr time0) (+ (nth 1 time0)
16389 (if (> n 0) (- rem) (- dm rem))))))
16390 (setq time
16391 (encode-time (or (car time0) 0)
16392 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16393 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16394 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16395 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16396 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16397 (nthcdr 6 time0)))
16398 (when (and (member org-ts-what '(hour minute))
16399 extra
16400 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16401 (setq extra (org-modify-ts-extra
16402 extra
16403 (if (eq org-ts-what 'hour) 2 5)
16404 n dm)))
16405 (when (integerp org-ts-what)
16406 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16407 (if (eq what 'calendar)
16408 (let ((cal-date (org-get-date-from-calendar)))
16409 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16410 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16411 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16412 (setcar time0 (or (car time0) 0))
16413 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16414 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16415 (setq time (apply 'encode-time time0))))
16416 ;; Insert the new time-stamp, and ensure point stays in the same
16417 ;; category as before (i.e. not after the last position in that
16418 ;; category).
16419 (let ((pos (point)))
16420 ;; Stay before inserted string. `save-excursion' is of no use.
16421 (setq org-last-changed-timestamp
16422 (org-insert-time-stamp time with-hm inactive nil nil extra))
16423 (goto-char pos))
16424 (save-match-data
16425 (looking-at org-ts-regexp3)
16426 (goto-char (cond
16427 ;; `day' category ends before `hour' if any, or at
16428 ;; the end of the day name.
16429 ((eq origin-cat 'day)
16430 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16431 ((eq origin-cat 'hour) (min (match-end 7) origin))
16432 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16433 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16434 ;; `year' and `month' have both fixed size: point
16435 ;; couldn't have moved into another part.
16436 (t origin))))
16437 ;; Update clock if on a CLOCK line.
16438 (org-clock-update-time-maybe)
16439 ;; Maybe adjust the closest clock in `org-clock-history'
16440 (when org-clock-adjust-closest
16441 (if (not (and (org-at-clock-log-p)
16442 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16443 org-clock-history))))))
16444 (message "No clock to adjust")
16445 (cond ((save-excursion ; fix previous clock?
16446 (re-search-backward org-ts-regexp0 nil t)
16447 (org-looking-back (concat org-clock-string " \\[")))
16448 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16449 ((save-excursion ; fix next clock?
16450 (re-search-backward org-ts-regexp0 nil t)
16451 (looking-at (concat org-ts-regexp0 "\\] =>")))
16452 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16453 (save-window-excursion
16454 ;; Find closest clock to point, adjust the previous/next one in history
16455 (let* ((p (save-excursion (org-back-to-heading t)))
16456 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16457 (clfixnth
16458 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16459 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16460 (if (not clfixpos)
16461 (message "No clock to adjust")
16462 (save-excursion
16463 (org-goto-marker-or-bmk clfixpos)
16464 (org-show-subtree)
16465 (when (re-search-forward clrgx nil t)
16466 (goto-char (match-beginning 1))
16467 (let (org-clock-adjust-closest)
16468 (org-timestamp-change n org-ts-what updown))
16469 (message "Clock adjusted in %s for heading: %s"
16470 (file-name-nondirectory (buffer-file-name))
16471 (org-get-heading t t)))))))))
16472 ;; Try to recenter the calendar window, if any.
16473 (if (and org-calendar-follow-timestamp-change
16474 (get-buffer-window "*Calendar*" t)
16475 (memq org-ts-what '(day month year)))
16476 (org-recenter-calendar (time-to-days time))))))
16478 (defun org-modify-ts-extra (s pos n dm)
16479 "Change the different parts of the lead-time and repeat fields in timestamp."
16480 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16481 ng h m new rem)
16482 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16483 (cond
16484 ((or (org-pos-in-match-range pos 2)
16485 (org-pos-in-match-range pos 3))
16486 (setq m (string-to-number (match-string 3 s))
16487 h (string-to-number (match-string 2 s)))
16488 (if (org-pos-in-match-range pos 2)
16489 (setq h (+ h n))
16490 (setq n (* dm (org-no-warnings (signum n))))
16491 (when (not (= 0 (setq rem (% m dm))))
16492 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16493 (setq m (+ m n)))
16494 (if (< m 0) (setq m (+ m 60) h (1- h)))
16495 (if (> m 59) (setq m (- m 60) h (1+ h)))
16496 (setq h (min 24 (max 0 h)))
16497 (setq ng 1 new (format "-%02d:%02d" h m)))
16498 ((org-pos-in-match-range pos 6)
16499 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16500 ((org-pos-in-match-range pos 5)
16501 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16503 ((org-pos-in-match-range pos 9)
16504 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16505 ((org-pos-in-match-range pos 8)
16506 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16508 (when ng
16509 (setq s (concat
16510 (substring s 0 (match-beginning ng))
16512 (substring s (match-end ng))))))
16515 (defun org-recenter-calendar (date)
16516 "If the calendar is visible, recenter it to DATE."
16517 (let ((cwin (get-buffer-window "*Calendar*" t)))
16518 (when cwin
16519 (let ((calendar-move-hook nil))
16520 (with-selected-window cwin
16521 (calendar-goto-date (if (listp date) date
16522 (calendar-gregorian-from-absolute date))))))))
16524 (defun org-goto-calendar (&optional arg)
16525 "Go to the Emacs calendar at the current date.
16526 If there is a time stamp in the current line, go to that date.
16527 A prefix ARG can be used to force the current date."
16528 (interactive "P")
16529 (let ((tsr org-ts-regexp) diff
16530 (calendar-move-hook nil)
16531 (calendar-view-holidays-initially-flag nil)
16532 (calendar-view-diary-initially-flag nil))
16533 (if (or (org-at-timestamp-p)
16534 (save-excursion
16535 (beginning-of-line 1)
16536 (looking-at (concat ".*" tsr))))
16537 (let ((d1 (time-to-days (current-time)))
16538 (d2 (time-to-days
16539 (org-time-string-to-time (match-string 1)))))
16540 (setq diff (- d2 d1))))
16541 (calendar)
16542 (calendar-goto-today)
16543 (if (and diff (not arg)) (calendar-forward-day diff))))
16545 (defun org-get-date-from-calendar ()
16546 "Return a list (month day year) of date at point in calendar."
16547 (with-current-buffer "*Calendar*"
16548 (save-match-data
16549 (calendar-cursor-to-date))))
16551 (defun org-date-from-calendar ()
16552 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16553 If there is already a time stamp at the cursor position, update it."
16554 (interactive)
16555 (if (org-at-timestamp-p t)
16556 (org-timestamp-change 0 'calendar)
16557 (let ((cal-date (org-get-date-from-calendar)))
16558 (org-insert-time-stamp
16559 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16561 (defun org-minutes-to-hh:mm-string (m)
16562 "Compute H:MM from a number of minutes."
16563 (let ((h (/ m 60)))
16564 (setq m (- m (* 60 h)))
16565 (format org-time-clocksum-format h m)))
16567 (defun org-hh:mm-string-to-minutes (s)
16568 "Convert a string H:MM to a number of minutes.
16569 If the string is just a number, interpret it as minutes.
16570 In fact, the first hh:mm or number in the string will be taken,
16571 there can be extra stuff in the string.
16572 If no number is found, the return value is 0."
16573 (cond
16574 ((integerp s) s)
16575 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16576 (+ (* (string-to-number (match-string 1 s)) 60)
16577 (string-to-number (match-string 2 s))))
16578 ((string-match "\\([0-9]+\\)" s)
16579 (string-to-number (match-string 1 s)))
16580 (t 0)))
16582 (defcustom org-effort-durations
16583 `(("h" . 60)
16584 ("d" . ,(* 60 8))
16585 ("w" . ,(* 60 8 5))
16586 ("m" . ,(* 60 8 5 4))
16587 ("y" . ,(* 60 8 5 40)))
16588 "Conversion factor to minutes for an effort modifier.
16590 Each entry has the form (MODIFIER . MINUTES).
16592 In an effort string, a number followed by MODIFIER is multiplied
16593 by the specified number of MINUTES to obtain an effort in
16594 minutes.
16596 For example, if the value of this variable is ((\"hours\" . 60)), then an
16597 effort string \"2hours\" is equivalent to 120 minutes."
16598 :group 'org-agenda
16599 :version "24.1"
16600 :type '(alist :key-type (string :tag "Modifier")
16601 :value-type (number :tag "Minutes")))
16603 (defun org-duration-string-to-minutes (s &optional output-to-string)
16604 "Convert a duration string S to minutes.
16606 A bare number is interpreted as minutes, modifiers can be set by
16607 customizing `org-effort-durations' (which see).
16609 Entries containing a colon are interpreted as H:MM by
16610 `org-hh:mm-string-to-minutes'."
16611 (let ((result 0)
16612 (re (concat "\\([0-9.]+\\) *\\("
16613 (regexp-opt (mapcar 'car org-effort-durations))
16614 "\\)")))
16615 (while (string-match re s)
16616 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16617 (string-to-number (match-string 1 s))))
16618 (setq s (replace-match "" nil t s)))
16619 (setq result (floor result))
16620 (incf result (org-hh:mm-string-to-minutes s))
16621 (if output-to-string (number-to-string result) result)))
16623 ;;;; Files
16625 (defun org-save-all-org-buffers ()
16626 "Save all Org-mode buffers without user confirmation."
16627 (interactive)
16628 (message "Saving all Org-mode buffers...")
16629 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16630 (when (featurep 'org-id) (org-id-locations-save))
16631 (message "Saving all Org-mode buffers... done"))
16633 (defun org-revert-all-org-buffers ()
16634 "Revert all Org-mode buffers.
16635 Prompt for confirmation when there are unsaved changes.
16636 Be sure you know what you are doing before letting this function
16637 overwrite your changes.
16639 This function is useful in a setup where one tracks org files
16640 with a version control system, to revert on one machine after pulling
16641 changes from another. I believe the procedure must be like this:
16643 1. M-x org-save-all-org-buffers
16644 2. Pull changes from the other machine, resolve conflicts
16645 3. M-x org-revert-all-org-buffers"
16646 (interactive)
16647 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16648 (error "Abort"))
16649 (save-excursion
16650 (save-window-excursion
16651 (mapc
16652 (lambda (b)
16653 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16654 (with-current-buffer b buffer-file-name))
16655 (org-pop-to-buffer-same-window b)
16656 (revert-buffer t 'no-confirm)))
16657 (buffer-list))
16658 (when (and (featurep 'org-id) org-id-track-globally)
16659 (org-id-locations-load)))))
16661 ;;;; Agenda files
16663 ;;;###autoload
16664 (defun org-switchb (&optional arg)
16665 "Switch between Org buffers.
16666 With one prefix argument, restrict available buffers to files.
16667 With two prefix arguments, restrict available buffers to agenda files.
16669 Defaults to `iswitchb' for buffer name completion.
16670 Set `org-completion-use-ido' to make it use ido instead."
16671 (interactive "P")
16672 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16673 ((equal arg '(16)) (org-buffer-list 'agenda))
16674 (t (org-buffer-list))))
16675 (org-completion-use-iswitchb org-completion-use-iswitchb)
16676 (org-completion-use-ido org-completion-use-ido))
16677 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16678 (setq org-completion-use-iswitchb t))
16679 (org-pop-to-buffer-same-window
16680 (org-icompleting-read "Org buffer: "
16681 (mapcar 'list (mapcar 'buffer-name blist))
16682 nil t))))
16684 ;;; Define some older names previously used for this functionality
16685 ;;;###autoload
16686 (defalias 'org-ido-switchb 'org-switchb)
16687 ;;;###autoload
16688 (defalias 'org-iswitchb 'org-switchb)
16690 (defun org-buffer-list (&optional predicate exclude-tmp)
16691 "Return a list of Org buffers.
16692 PREDICATE can be `export', `files' or `agenda'.
16694 export restrict the list to Export buffers.
16695 files restrict the list to buffers visiting Org files.
16696 agenda restrict the list to buffers visiting agenda files.
16698 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16699 (let* ((bfn nil)
16700 (agenda-files (and (eq predicate 'agenda)
16701 (mapcar 'file-truename (org-agenda-files t))))
16702 (filter
16703 (cond
16704 ((eq predicate 'files)
16705 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16706 ((eq predicate 'export)
16707 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16708 ((eq predicate 'agenda)
16709 (lambda (b)
16710 (with-current-buffer b
16711 (and (derived-mode-p 'org-mode)
16712 (setq bfn (buffer-file-name b))
16713 (member (file-truename bfn) agenda-files)))))
16714 (t (lambda (b) (with-current-buffer b
16715 (or (derived-mode-p 'org-mode)
16716 (string-match "\*Org .*Export"
16717 (buffer-name b)))))))))
16718 (delq nil
16719 (mapcar
16720 (lambda(b)
16721 (if (and (funcall filter b)
16722 (or (not exclude-tmp)
16723 (not (string-match "tmp" (buffer-name b)))))
16725 nil))
16726 (buffer-list)))))
16728 (defun org-agenda-files (&optional unrestricted archives)
16729 "Get the list of agenda files.
16730 Optional UNRESTRICTED means return the full list even if a restriction
16731 is currently in place.
16732 When ARCHIVES is t, include all archive files that are really being
16733 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16734 `org-agenda-archives-mode' is t."
16735 (let ((files
16736 (cond
16737 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16738 ((stringp org-agenda-files) (org-read-agenda-file-list))
16739 ((listp org-agenda-files) org-agenda-files)
16740 (t (error "Invalid value of `org-agenda-files'")))))
16741 (setq files (apply 'append
16742 (mapcar (lambda (f)
16743 (if (file-directory-p f)
16744 (directory-files
16745 f t org-agenda-file-regexp)
16746 (list f)))
16747 files)))
16748 (when org-agenda-skip-unavailable-files
16749 (setq files (delq nil
16750 (mapcar (function
16751 (lambda (file)
16752 (and (file-readable-p file) file)))
16753 files))))
16754 (when (or (eq archives t)
16755 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16756 (setq files (org-add-archive-files files)))
16757 files))
16759 (defun org-agenda-file-p (&optional file)
16760 "Return non-nil, if FILE is an agenda file.
16761 If FILE is omitted, use the file associated with the current
16762 buffer."
16763 (member (or file (buffer-file-name))
16764 (org-agenda-files t)))
16766 (defun org-edit-agenda-file-list ()
16767 "Edit the list of agenda files.
16768 Depending on setup, this either uses customize to edit the variable
16769 `org-agenda-files', or it visits the file that is holding the list. In the
16770 latter case, the buffer is set up in a way that saving it automatically kills
16771 the buffer and restores the previous window configuration."
16772 (interactive)
16773 (if (stringp org-agenda-files)
16774 (let ((cw (current-window-configuration)))
16775 (find-file org-agenda-files)
16776 (org-set-local 'org-window-configuration cw)
16777 (org-add-hook 'after-save-hook
16778 (lambda ()
16779 (set-window-configuration
16780 (prog1 org-window-configuration
16781 (kill-buffer (current-buffer))))
16782 (org-install-agenda-files-menu)
16783 (message "New agenda file list installed"))
16784 nil 'local)
16785 (message "%s" (substitute-command-keys
16786 "Edit list and finish with \\[save-buffer]")))
16787 (customize-variable 'org-agenda-files)))
16789 (defun org-store-new-agenda-file-list (list)
16790 "Set new value for the agenda file list and save it correctly."
16791 (if (stringp org-agenda-files)
16792 (let ((fe (org-read-agenda-file-list t)) b u)
16793 (while (setq b (find-buffer-visiting org-agenda-files))
16794 (kill-buffer b))
16795 (with-temp-file org-agenda-files
16796 (insert
16797 (mapconcat
16798 (lambda (f) ;; Keep un-expanded entries.
16799 (if (setq u (assoc f fe))
16800 (cdr u)
16802 list "\n")
16803 "\n")))
16804 (let ((org-mode-hook nil) (org-inhibit-startup t)
16805 (org-insert-mode-line-in-empty-file nil))
16806 (setq org-agenda-files list)
16807 (customize-save-variable 'org-agenda-files org-agenda-files))))
16809 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16810 "Read the list of agenda files from a file.
16811 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16812 filenames, used by `org-store-new-agenda-file-list' to write back
16813 un-expanded file names."
16814 (when (file-directory-p org-agenda-files)
16815 (error "`org-agenda-files' cannot be a single directory"))
16816 (when (stringp org-agenda-files)
16817 (with-temp-buffer
16818 (insert-file-contents org-agenda-files)
16819 (mapcar
16820 (lambda (f)
16821 (let ((e (expand-file-name (substitute-in-file-name f)
16822 org-directory)))
16823 (if pair-with-expansion
16824 (cons e f)
16825 e)))
16826 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16828 ;;;###autoload
16829 (defun org-cycle-agenda-files ()
16830 "Cycle through the files in `org-agenda-files'.
16831 If the current buffer visits an agenda file, find the next one in the list.
16832 If the current buffer does not, find the first agenda file."
16833 (interactive)
16834 (let* ((fs (org-agenda-files t))
16835 (files (append fs (list (car fs))))
16836 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16837 file)
16838 (unless files (error "No agenda files"))
16839 (catch 'exit
16840 (while (setq file (pop files))
16841 (if (equal (file-truename file) tcf)
16842 (when (car files)
16843 (find-file (car files))
16844 (throw 'exit t))))
16845 (find-file (car fs)))
16846 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16848 (defun org-agenda-file-to-front (&optional to-end)
16849 "Move/add the current file to the top of the agenda file list.
16850 If the file is not present in the list, it is added to the front. If it is
16851 present, it is moved there. With optional argument TO-END, add/move to the
16852 end of the list."
16853 (interactive "P")
16854 (let ((org-agenda-skip-unavailable-files nil)
16855 (file-alist (mapcar (lambda (x)
16856 (cons (file-truename x) x))
16857 (org-agenda-files t)))
16858 (ctf (file-truename
16859 (or buffer-file-name
16860 (error "Please save the current buffer to a file"))))
16861 x had)
16862 (setq x (assoc ctf file-alist) had x)
16864 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16865 (if to-end
16866 (setq file-alist (append (delq x file-alist) (list x)))
16867 (setq file-alist (cons x (delq x file-alist))))
16868 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16869 (org-install-agenda-files-menu)
16870 (message "File %s to %s of agenda file list"
16871 (if had "moved" "added") (if to-end "end" "front"))))
16873 (defun org-remove-file (&optional file)
16874 "Remove current file from the list of files in variable `org-agenda-files'.
16875 These are the files which are being checked for agenda entries.
16876 Optional argument FILE means use this file instead of the current."
16877 (interactive)
16878 (let* ((org-agenda-skip-unavailable-files nil)
16879 (file (or file buffer-file-name
16880 (error "Current buffer does not visit a file")))
16881 (true-file (file-truename file))
16882 (afile (abbreviate-file-name file))
16883 (files (delq nil (mapcar
16884 (lambda (x)
16885 (if (equal true-file
16886 (file-truename x))
16887 nil x))
16888 (org-agenda-files t)))))
16889 (if (not (= (length files) (length (org-agenda-files t))))
16890 (progn
16891 (org-store-new-agenda-file-list files)
16892 (org-install-agenda-files-menu)
16893 (message "Removed file: %s" afile))
16894 (message "File was not in list: %s (not removed)" afile))))
16896 (defun org-file-menu-entry (file)
16897 (vector file (list 'find-file file) t))
16899 (defun org-check-agenda-file (file)
16900 "Make sure FILE exists. If not, ask user what to do."
16901 (when (not (file-exists-p file))
16902 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16903 (abbreviate-file-name file))
16904 (let ((r (downcase (read-char-exclusive))))
16905 (cond
16906 ((equal r ?r)
16907 (org-remove-file file)
16908 (throw 'nextfile t))
16909 (t (error "Abort"))))))
16911 (defun org-get-agenda-file-buffer (file)
16912 "Get a buffer visiting FILE. If the buffer needs to be created, add
16913 it to the list of buffers which might be released later."
16914 (let ((buf (org-find-base-buffer-visiting file)))
16915 (if buf
16916 buf ; just return it
16917 ;; Make a new buffer and remember it
16918 (setq buf (find-file-noselect file))
16919 (if buf (push buf org-agenda-new-buffers))
16920 buf)))
16922 (defun org-release-buffers (blist)
16923 "Release all buffers in list, asking the user for confirmation when needed.
16924 When a buffer is unmodified, it is just killed. When modified, it is saved
16925 \(if the user agrees) and then killed."
16926 (let (buf file)
16927 (while (setq buf (pop blist))
16928 (setq file (buffer-file-name buf))
16929 (when (and (buffer-modified-p buf)
16930 file
16931 (y-or-n-p (format "Save file %s? " file)))
16932 (with-current-buffer buf (save-buffer)))
16933 (kill-buffer buf))))
16935 (defun org-agenda-prepare-buffers (files)
16936 "Create buffers for all agenda files, protect archived trees and comments."
16937 (interactive)
16938 (let ((pa '(:org-archived t))
16939 (pc '(:org-comment t))
16940 (pall '(:org-archived t :org-comment t))
16941 (inhibit-read-only t)
16942 (rea (concat ":" org-archive-tag ":"))
16943 bmp file re)
16944 (save-excursion
16945 (save-restriction
16946 (while (setq file (pop files))
16947 (catch 'nextfile
16948 (if (bufferp file)
16949 (set-buffer file)
16950 (org-check-agenda-file file)
16951 (set-buffer (org-get-agenda-file-buffer file)))
16952 (widen)
16953 (setq bmp (buffer-modified-p))
16954 (org-refresh-category-properties)
16955 (setq org-todo-keywords-for-agenda
16956 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16957 (setq org-done-keywords-for-agenda
16958 (append org-done-keywords-for-agenda org-done-keywords))
16959 (setq org-todo-keyword-alist-for-agenda
16960 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16961 (setq org-drawers-for-agenda
16962 (append org-drawers-for-agenda org-drawers))
16963 (setq org-tag-alist-for-agenda
16964 (append org-tag-alist-for-agenda org-tag-alist))
16966 (save-excursion
16967 (remove-text-properties (point-min) (point-max) pall)
16968 (when org-agenda-skip-archived-trees
16969 (goto-char (point-min))
16970 (while (re-search-forward rea nil t)
16971 (if (org-at-heading-p t)
16972 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16973 (goto-char (point-min))
16974 (setq re (format org-heading-keyword-regexp-format
16975 org-comment-string))
16976 (while (re-search-forward re nil t)
16977 (add-text-properties
16978 (match-beginning 0) (org-end-of-subtree t) pc)))
16979 (set-buffer-modified-p bmp)))))
16980 (setq org-todo-keywords-for-agenda
16981 (org-uniquify org-todo-keywords-for-agenda))
16982 (setq org-todo-keyword-alist-for-agenda
16983 (org-uniquify org-todo-keyword-alist-for-agenda)
16984 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16986 ;;;; Embedded LaTeX
16988 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16989 "Keymap for the minor `org-cdlatex-mode'.")
16991 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16992 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16993 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16994 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16995 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16997 (defvar org-cdlatex-texmathp-advice-is-done nil
16998 "Flag remembering if we have applied the advice to texmathp already.")
17000 (define-minor-mode org-cdlatex-mode
17001 "Toggle the minor `org-cdlatex-mode'.
17002 This mode supports entering LaTeX environment and math in LaTeX fragments
17003 in Org-mode.
17004 \\{org-cdlatex-mode-map}"
17005 nil " OCDL" nil
17006 (when org-cdlatex-mode
17007 (require 'cdlatex)
17008 (run-hooks 'cdlatex-mode-hook)
17009 (cdlatex-compute-tables))
17010 (unless org-cdlatex-texmathp-advice-is-done
17011 (setq org-cdlatex-texmathp-advice-is-done t)
17012 (defadvice texmathp (around org-math-always-on activate)
17013 "Always return t in org-mode buffers.
17014 This is because we want to insert math symbols without dollars even outside
17015 the LaTeX math segments. If Orgmode thinks that point is actually inside
17016 an embedded LaTeX fragment, let texmathp do its job.
17017 \\[org-cdlatex-mode-map]"
17018 (interactive)
17019 (let (p)
17020 (cond
17021 ((not (derived-mode-p 'org-mode)) ad-do-it)
17022 ((eq this-command 'cdlatex-math-symbol)
17023 (setq ad-return-value t
17024 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17026 (let ((p (org-inside-LaTeX-fragment-p)))
17027 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17028 (setq ad-return-value t
17029 texmathp-why '("Org-mode embedded math" . 0))
17030 (if p ad-do-it)))))))))
17032 (defun turn-on-org-cdlatex ()
17033 "Unconditionally turn on `org-cdlatex-mode'."
17034 (org-cdlatex-mode 1))
17036 (defun org-inside-LaTeX-fragment-p ()
17037 "Test if point is inside a LaTeX fragment.
17038 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17039 sequence appearing also before point.
17040 Even though the matchers for math are configurable, this function assumes
17041 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17042 delimiters are skipped when they have been removed by customization.
17043 The return value is nil, or a cons cell with the delimiter and the
17044 position of this delimiter.
17046 This function does a reasonably good job, but can locally be fooled by
17047 for example currency specifications. For example it will assume being in
17048 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17049 fragments that are properly closed, but during editing, we have to live
17050 with the uncertainty caused by missing closing delimiters. This function
17051 looks only before point, not after."
17052 (catch 'exit
17053 (let ((pos (point))
17054 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17055 (lim (progn
17056 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17057 (point)))
17058 dd-on str (start 0) m re)
17059 (goto-char pos)
17060 (when dodollar
17061 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17062 re (nth 1 (assoc "$" org-latex-regexps)))
17063 (while (string-match re str start)
17064 (cond
17065 ((= (match-end 0) (length str))
17066 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17067 ((= (match-end 0) (- (length str) 5))
17068 (throw 'exit nil))
17069 (t (setq start (match-end 0))))))
17070 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17071 (goto-char pos)
17072 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17073 (and (match-beginning 2) (throw 'exit nil))
17074 ;; count $$
17075 (while (re-search-backward "\\$\\$" lim t)
17076 (setq dd-on (not dd-on)))
17077 (goto-char pos)
17078 (if dd-on (cons "$$" m))))))
17080 (defun org-inside-latex-macro-p ()
17081 "Is point inside a LaTeX macro or its arguments?"
17082 (save-match-data
17083 (org-in-regexp
17084 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17086 (defun org-try-cdlatex-tab ()
17087 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17088 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17089 - inside a LaTeX fragment, or
17090 - after the first word in a line, where an abbreviation expansion could
17091 insert a LaTeX environment."
17092 (when org-cdlatex-mode
17093 (cond
17094 ;; Before any word on the line: No expansion possible.
17095 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17096 ;; Just after first word on the line: Expand it. Make sure it
17097 ;; cannot happen on headlines, though.
17098 ((save-excursion
17099 (skip-chars-backward "a-zA-Z0-9*")
17100 (skip-chars-backward " \t")
17101 (and (bolp) (not (org-at-heading-p))))
17102 (cdlatex-tab) t)
17103 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17105 (defun org-cdlatex-underscore-caret (&optional arg)
17106 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17107 Revert to the normal definition outside of these fragments."
17108 (interactive "P")
17109 (if (org-inside-LaTeX-fragment-p)
17110 (call-interactively 'cdlatex-sub-superscript)
17111 (let (org-cdlatex-mode)
17112 (call-interactively (key-binding (vector last-input-event))))))
17114 (defun org-cdlatex-math-modify (&optional arg)
17115 "Execute `cdlatex-math-modify' in LaTeX fragments.
17116 Revert to the normal definition outside of these fragments."
17117 (interactive "P")
17118 (if (org-inside-LaTeX-fragment-p)
17119 (call-interactively 'cdlatex-math-modify)
17120 (let (org-cdlatex-mode)
17121 (call-interactively (key-binding (vector last-input-event))))))
17123 (defvar org-latex-fragment-image-overlays nil
17124 "List of overlays carrying the images of latex fragments.")
17125 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17127 (defun org-remove-latex-fragment-image-overlays ()
17128 "Remove all overlays with LaTeX fragment images in current buffer."
17129 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17130 (setq org-latex-fragment-image-overlays nil))
17132 (defun org-preview-latex-fragment (&optional subtree)
17133 "Preview the LaTeX fragment at point, or all locally or globally.
17134 If the cursor is in a LaTeX fragment, create the image and overlay
17135 it over the source code. If there is no fragment at point, display
17136 all fragments in the current text, from one headline to the next. With
17137 prefix SUBTREE, display all fragments in the current subtree. With a
17138 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17139 the cursor is before the first headline,
17140 display all fragments in the buffer.
17141 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17142 (interactive "P")
17143 (unless buffer-file-name
17144 (error "Can't preview LaTeX fragment in a non-file buffer"))
17145 (org-remove-latex-fragment-image-overlays)
17146 (save-excursion
17147 (save-restriction
17148 (let (beg end at msg)
17149 (cond
17150 ((or (equal subtree '(16))
17151 (not (save-excursion
17152 (re-search-backward org-outline-regexp-bol nil t))))
17153 (setq beg (point-min) end (point-max)
17154 msg "Creating images for buffer...%s"))
17155 ((equal subtree '(4))
17156 (org-back-to-heading)
17157 (setq beg (point) end (org-end-of-subtree t)
17158 msg "Creating images for subtree...%s"))
17160 (if (setq at (org-inside-LaTeX-fragment-p))
17161 (goto-char (max (point-min) (- (cdr at) 2)))
17162 (org-back-to-heading))
17163 (setq beg (point) end (progn (outline-next-heading) (point))
17164 msg (if at "Creating image...%s"
17165 "Creating images for entry...%s"))))
17166 (message msg "")
17167 (narrow-to-region beg end)
17168 (goto-char beg)
17169 (org-format-latex
17170 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17171 (file-name-nondirectory
17172 buffer-file-name)))
17173 default-directory 'overlays msg at 'forbuffer
17174 org-latex-create-formula-image-program)
17175 (message msg "done. Use `C-c C-c' to remove images.")))))
17177 (defvar org-latex-regexps
17178 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17179 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17180 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17181 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17182 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17183 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17184 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17185 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17186 "Regular expressions for matching embedded LaTeX.")
17188 (defvar org-export-have-math nil) ;; dynamic scoping
17189 (defun org-format-latex (prefix &optional dir overlays msg at
17190 forbuffer processing-type)
17191 "Replace LaTeX fragments with links to an image, and produce images.
17192 Some of the options can be changed using the variable
17193 `org-format-latex-options'."
17194 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17195 (let* ((prefixnodir (file-name-nondirectory prefix))
17196 (absprefix (expand-file-name prefix dir))
17197 (todir (file-name-directory absprefix))
17198 (opt org-format-latex-options)
17199 (matchers (plist-get opt :matchers))
17200 (re-list org-latex-regexps)
17201 (org-format-latex-header-extra
17202 (plist-get (org-infile-export-plist) :latex-header-extra))
17203 (cnt 0) txt hash link beg end re e checkdir
17204 executables-checked string
17205 m n block-type block linkfile movefile ov)
17206 ;; Check the different regular expressions
17207 (while (setq e (pop re-list))
17208 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17209 block (if block-type "\n\n" ""))
17210 (when (member m matchers)
17211 (goto-char (point-min))
17212 (while (re-search-forward re nil t)
17213 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17214 (not (get-text-property (match-beginning n)
17215 'org-protected))
17216 (or (not overlays)
17217 (not (eq (get-char-property (match-beginning n)
17218 'org-overlay-type)
17219 'org-latex-overlay))))
17220 (setq org-export-have-math t)
17221 (cond
17222 ((eq processing-type 'verbatim)
17223 ;; Leave the text verbatim, just protect it
17224 (add-text-properties (match-beginning n) (match-end n)
17225 '(org-protected t)))
17226 ((eq processing-type 'mathjax)
17227 ;; Prepare for MathJax processing
17228 (setq string (match-string n))
17229 (if (member m '("$" "$1"))
17230 (save-excursion
17231 (delete-region (match-beginning n) (match-end n))
17232 (goto-char (match-beginning n))
17233 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17234 "\\)")
17235 '(org-protected t))))
17236 (add-text-properties (match-beginning n) (match-end n)
17237 '(org-protected t))))
17238 ((or (eq processing-type 'dvipng)
17239 (eq processing-type 'imagemagick))
17240 ;; Process to an image
17241 (setq txt (match-string n)
17242 beg (match-beginning n) end (match-end n)
17243 cnt (1+ cnt))
17244 (let (print-length print-level) ; make sure full list is printed
17245 (setq hash (sha1 (prin1-to-string
17246 (list org-format-latex-header
17247 org-format-latex-header-extra
17248 org-export-latex-default-packages-alist
17249 org-export-latex-packages-alist
17250 org-format-latex-options
17251 forbuffer txt)))
17252 linkfile (format "%s_%s.png" prefix hash)
17253 movefile (format "%s_%s.png" absprefix hash)))
17254 (setq link (concat block "[[file:" linkfile "]]" block))
17255 (if msg (message msg cnt))
17256 (goto-char beg)
17257 (unless checkdir ; make sure the directory exists
17258 (setq checkdir t)
17259 (or (file-directory-p todir) (make-directory todir t)))
17260 (cond
17261 ((eq processing-type 'dvipng)
17262 (unless executables-checked
17263 (org-check-external-command
17264 "latex" "needed to convert LaTeX fragments to images")
17265 (org-check-external-command
17266 "dvipng" "needed to convert LaTeX fragments to images")
17267 (setq executables-checked t))
17268 (unless (file-exists-p movefile)
17269 (org-create-formula-image-with-dvipng
17270 txt movefile opt forbuffer)))
17271 ((eq processing-type 'imagemagick)
17272 (unless executables-checked
17273 (org-check-external-command
17274 "convert" "you need to install imagemagick")
17275 (setq executables-checked t))
17276 (unless (file-exists-p movefile)
17277 (org-create-formula-image-with-imagemagick
17278 txt movefile opt forbuffer))))
17279 (if overlays
17280 (progn
17281 (mapc (lambda (o)
17282 (if (eq (overlay-get o 'org-overlay-type)
17283 'org-latex-overlay)
17284 (delete-overlay o)))
17285 (overlays-in beg end))
17286 (setq ov (make-overlay beg end))
17287 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17288 (if (featurep 'xemacs)
17289 (progn
17290 (overlay-put ov 'invisible t)
17291 (overlay-put
17292 ov 'end-glyph
17293 (make-glyph (vector 'png :file movefile))))
17294 (overlay-put
17295 ov 'display
17296 (list 'image :type 'png :file movefile :ascent 'center)))
17297 (push ov org-latex-fragment-image-overlays)
17298 (goto-char end))
17299 (delete-region beg end)
17300 (insert (org-add-props link
17301 (list 'org-latex-src
17302 (replace-regexp-in-string
17303 "\"" "" txt)
17304 'org-latex-src-embed-type
17305 (if block-type 'paragraph 'character))))))
17306 ((eq processing-type 'mathml)
17307 ;; Process to MathML
17308 (unless executables-checked
17309 (unless (save-match-data (org-format-latex-mathml-available-p))
17310 (error "LaTeX to MathML converter not configured"))
17311 (setq executables-checked t))
17312 (setq txt (match-string n)
17313 beg (match-beginning n) end (match-end n)
17314 cnt (1+ cnt))
17315 (if msg (message msg cnt))
17316 (goto-char beg)
17317 (delete-region beg end)
17318 (insert (org-format-latex-as-mathml
17319 txt block-type prefix dir)))
17321 (error "Unknown conversion type %s for latex fragments"
17322 processing-type)))))))))
17324 (defun org-create-math-formula (latex-frag &optional mathml-file)
17325 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17326 Use `org-latex-to-mathml-convert-command'. If the conversion is
17327 sucessful, return the portion between \"<math...> </math>\"
17328 elements otherwise return nil. When MATHML-FILE is specified,
17329 write the results in to that file. When invoked as an
17330 interactive command, prompt for LATEX-FRAG, with initial value
17331 set to the current active region and echo the results for user
17332 inspection."
17333 (interactive (list (let ((frag (when (org-region-active-p)
17334 (buffer-substring-no-properties
17335 (region-beginning) (region-end)))))
17336 (read-string "LaTeX Fragment: " frag nil frag))))
17337 (unless latex-frag (error "Invalid latex-frag"))
17338 (let* ((tmp-in-file (file-relative-name
17339 (make-temp-name (expand-file-name "ltxmathml-in"))))
17340 (ignore (write-region latex-frag nil tmp-in-file))
17341 (tmp-out-file (file-relative-name
17342 (make-temp-name (expand-file-name "ltxmathml-out"))))
17343 (cmd (format-spec
17344 org-latex-to-mathml-convert-command
17345 `((?j . ,(shell-quote-argument
17346 (expand-file-name org-latex-to-mathml-jar-file)))
17347 (?I . ,(shell-quote-argument tmp-in-file))
17348 (?o . ,(shell-quote-argument tmp-out-file)))))
17349 mathml shell-command-output)
17350 (when (org-called-interactively-p 'any)
17351 (unless (org-format-latex-mathml-available-p)
17352 (error "LaTeX to MathML converter not configured")))
17353 (message "Running %s" cmd)
17354 (setq shell-command-output (shell-command-to-string cmd))
17355 (setq mathml
17356 (when (file-readable-p tmp-out-file)
17357 (with-current-buffer (find-file-noselect tmp-out-file t)
17358 (goto-char (point-min))
17359 (when (re-search-forward
17360 (concat
17361 (regexp-quote
17362 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17363 "\\(.\\|\n\\)*"
17364 (regexp-quote "</math>")) nil t)
17365 (prog1 (match-string 0) (kill-buffer))))))
17366 (cond
17367 (mathml
17368 (setq mathml
17369 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17370 (when mathml-file
17371 (write-region mathml nil mathml-file))
17372 (when (org-called-interactively-p 'any)
17373 (message mathml)))
17374 ((message "LaTeX to MathML conversion failed")
17375 (message shell-command-output)))
17376 (delete-file tmp-in-file)
17377 (when (file-exists-p tmp-out-file)
17378 (delete-file tmp-out-file))
17379 mathml))
17381 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17382 prefix &optional dir)
17383 "Use `org-create-math-formula' but check local cache first."
17384 (let* ((absprefix (expand-file-name prefix dir))
17385 (print-length nil) (print-level nil)
17386 (formula-id (concat
17387 "formula-"
17388 (sha1
17389 (prin1-to-string
17390 (list latex-frag
17391 org-latex-to-mathml-convert-command)))))
17392 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17393 (formula-cache-dir (file-name-directory formula-cache)))
17395 (unless (file-directory-p formula-cache-dir)
17396 (make-directory formula-cache-dir t))
17398 (unless (file-exists-p formula-cache)
17399 (org-create-math-formula latex-frag formula-cache))
17401 (if (file-exists-p formula-cache)
17402 ;; Successful conversion. Return the link to MathML file.
17403 (org-add-props
17404 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17405 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17406 'org-latex-src-embed-type (if latex-frag-type
17407 'paragraph 'character)))
17408 ;; Failed conversion. Return the LaTeX fragment verbatim
17409 (add-text-properties
17410 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17411 latex-frag)))
17413 ;; This function borrows from Ganesh Swami's latex2png.el
17414 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17415 "This calls dvipng."
17416 (require 'org-latex)
17417 (let* ((tmpdir (if (featurep 'xemacs)
17418 (temp-directory)
17419 temporary-file-directory))
17420 (texfilebase (make-temp-name
17421 (expand-file-name "orgtex" tmpdir)))
17422 (texfile (concat texfilebase ".tex"))
17423 (dvifile (concat texfilebase ".dvi"))
17424 (pngfile (concat texfilebase ".png"))
17425 (fnh (if (featurep 'xemacs)
17426 (font-height (face-font 'default))
17427 (face-attribute 'default :height nil)))
17428 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17429 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17430 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17431 "Black"))
17432 (bg (or (plist-get options (if buffer :background :html-background))
17433 "Transparent")))
17434 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17435 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17436 (with-temp-file texfile
17437 (insert (org-splice-latex-header
17438 org-format-latex-header
17439 org-export-latex-default-packages-alist
17440 org-export-latex-packages-alist t
17441 org-format-latex-header-extra))
17442 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17443 (require 'org-latex)
17444 (org-export-latex-fix-inputenc))
17445 (let ((dir default-directory))
17446 (condition-case nil
17447 (progn
17448 (cd tmpdir)
17449 (call-process "latex" nil nil nil texfile))
17450 (error nil))
17451 (cd dir))
17452 (if (not (file-exists-p dvifile))
17453 (progn (message "Failed to create dvi file from %s" texfile) nil)
17454 (condition-case nil
17455 (if (featurep 'xemacs)
17456 (call-process "dvipng" nil nil nil
17457 "-fg" fg "-bg" bg
17458 "-T" "tight"
17459 "-o" pngfile
17460 dvifile)
17461 (call-process "dvipng" nil nil nil
17462 "-fg" fg "-bg" bg
17463 "-D" dpi
17464 ;;"-x" scale "-y" scale
17465 "-T" "tight"
17466 "-o" pngfile
17467 dvifile))
17468 (error nil))
17469 (if (not (file-exists-p pngfile))
17470 (if org-format-latex-signal-error
17471 (error "Failed to create png file from %s" texfile)
17472 (message "Failed to create png file from %s" texfile)
17473 nil)
17474 ;; Use the requested file name and clean up
17475 (copy-file pngfile tofile 'replace)
17476 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17477 (if (file-exists-p (concat texfilebase e))
17478 (delete-file (concat texfilebase e))))
17479 pngfile))))
17481 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17482 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17483 "This calls convert, which is included into imagemagick."
17484 (require 'org-latex)
17485 (let* ((tmpdir (if (featurep 'xemacs)
17486 (temp-directory)
17487 temporary-file-directory))
17488 (texfilebase (make-temp-name
17489 (expand-file-name "orgtex" tmpdir)))
17490 (texfile (concat texfilebase ".tex"))
17491 (pdffile (concat texfilebase ".pdf"))
17492 (pngfile (concat texfilebase ".png"))
17493 (fnh (if (featurep 'xemacs)
17494 (font-height (face-font 'default))
17495 (face-attribute 'default :height nil)))
17496 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17497 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17498 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17499 "black"))
17500 (bg (or (plist-get options (if buffer :background :html-background))
17501 "white")))
17502 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17503 (setq fg (org-latex-color-format fg)))
17504 (if (eq bg 'default) (setq bg (org-latex-color :background))
17505 (setq bg (org-latex-color-format
17506 (if (string= bg "Transparent")(setq bg "white")))))
17507 (with-temp-file texfile
17508 (insert (org-splice-latex-header
17509 org-format-latex-header
17510 org-export-latex-default-packages-alist
17511 org-export-latex-packages-alist t
17512 org-format-latex-header-extra))
17513 (insert "\n\\begin{document}\n"
17514 "\\definecolor{fg}{rgb}{" fg "}\n"
17515 "\\definecolor{bg}{rgb}{" bg "}\n"
17516 "\n\\pagecolor{bg}\n"
17517 "\n{\\color{fg}\n"
17518 string
17519 "\n}\n"
17520 "\n\\end{document}\n" )
17521 (require 'org-latex)
17522 (org-export-latex-fix-inputenc))
17523 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17524 (condition-case nil
17525 (progn
17526 (cd tmpdir)
17527 (setq cmds org-latex-to-pdf-process)
17528 (while cmds
17529 (setq latex-frags-cmds (pop cmds))
17530 (if (listp latex-frags-cmds)
17531 (setq cmds nil)
17532 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17533 (while latex-frags-cmds
17534 (setq cmd (pop latex-frags-cmds))
17535 (while (string-match "%b" cmd)
17536 (setq cmd (replace-match
17537 (save-match-data
17538 (shell-quote-argument texfile))
17539 t t cmd)))
17540 (while (string-match "%f" cmd)
17541 (setq cmd (replace-match
17542 (save-match-data
17543 (shell-quote-argument (file-name-nondirectory texfile)))
17544 t t cmd)))
17545 (while (string-match "%o" cmd)
17546 (setq cmd (replace-match
17547 (save-match-data
17548 (shell-quote-argument (file-name-directory texfile)))
17549 t t cmd)))
17550 (setq cmd (split-string cmd))
17551 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17552 (error nil))
17553 (cd dir))
17554 (if (not (file-exists-p pdffile))
17555 (progn (message "Failed to create pdf file from %s" texfile) nil)
17556 (condition-case nil
17557 (if (featurep 'xemacs)
17558 (call-process "convert" nil nil nil
17559 "-density" "96"
17560 "-trim"
17561 "-antialias"
17562 pdffile
17563 "-quality" "100"
17564 ;; "-sharpen" "0x1.0"
17565 pngfile)
17566 (call-process "convert" nil nil nil
17567 "-density" dpi
17568 "-trim"
17569 "-antialias"
17570 pdffile
17571 "-quality" "100"
17572 ; "-sharpen" "0x1.0"
17573 pngfile))
17574 (error nil))
17575 (if (not (file-exists-p pngfile))
17576 (if org-format-latex-signal-error
17577 (error "Failed to create png file from %s" texfile)
17578 (message "Failed to create png file from %s" texfile)
17579 nil)
17580 ;; Use the requested file name and clean up
17581 (copy-file pngfile tofile 'replace)
17582 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17583 (if (file-exists-p (concat texfilebase e))
17584 (delete-file (concat texfilebase e))))
17585 pngfile))))
17587 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17588 "Fill a LaTeX header template TPL.
17589 In the template, the following place holders will be recognized:
17591 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17592 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17593 [PACKAGES] \\usepackage statements for PKG
17594 [NO-PACKAGES] do not include PKG
17595 [EXTRA] the string EXTRA
17596 [NO-EXTRA] do not include EXTRA
17598 For backward compatibility, if both the positive and the negative place
17599 holder is missing, the positive one (without the \"NO-\") will be
17600 assumed to be present at the end of the template.
17601 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17602 EXTRA is a string.
17603 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17604 (let (rpl (end ""))
17605 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17606 (setq rpl (if (or (match-end 1) (not def-pkg))
17607 "" (org-latex-packages-to-string def-pkg snippets-p t))
17608 tpl (replace-match rpl t t tpl))
17609 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17611 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17612 (setq rpl (if (or (match-end 1) (not pkg))
17613 "" (org-latex-packages-to-string pkg snippets-p t))
17614 tpl (replace-match rpl t t tpl))
17615 (if pkg (setq end
17616 (concat end "\n"
17617 (org-latex-packages-to-string pkg snippets-p)))))
17619 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17620 (setq rpl (if (or (match-end 1) (not extra))
17621 "" (concat extra "\n"))
17622 tpl (replace-match rpl t t tpl))
17623 (if (and extra (string-match "\\S-" extra))
17624 (setq end (concat end "\n" extra))))
17626 (if (string-match "\\S-" end)
17627 (concat tpl "\n" end)
17628 tpl)))
17630 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17631 "Turn an alist of packages into a string with the \\usepackage macros."
17632 (setq pkg (mapconcat (lambda(p)
17633 (cond
17634 ((stringp p) p)
17635 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17636 (format "%% Package %s omitted" (cadr p)))
17637 ((equal "" (car p))
17638 (format "\\usepackage{%s}" (cadr p)))
17640 (format "\\usepackage[%s]{%s}"
17641 (car p) (cadr p)))))
17643 "\n"))
17644 (if newline (concat pkg "\n") pkg))
17646 (defun org-dvipng-color (attr)
17647 "Return a RGB color specification for dvipng."
17648 (apply 'format "rgb %s %s %s"
17649 (mapcar 'org-normalize-color
17650 (if (featurep 'xemacs)
17651 (color-rgb-components
17652 (face-property 'default
17653 (cond ((eq attr :foreground) 'foreground)
17654 ((eq attr :background) 'background))))
17655 (color-values (face-attribute 'default attr nil))))))
17657 (defun org-latex-color (attr)
17658 "Return a RGB color for the LaTeX color package."
17659 (apply 'format "%s,%s,%s"
17660 (mapcar 'org-normalize-color
17661 (if (featurep 'xemacs)
17662 (color-rgb-components
17663 (face-property 'default
17664 (cond ((eq attr :foreground) 'foreground)
17665 ((eq attr :background) 'background))))
17666 (color-values (face-attribute 'default attr nil))))))
17668 (defun org-latex-color-format (color-name)
17669 "Convert COLOR-NAME to a RGB color value."
17670 (apply 'format "%s,%s,%s"
17671 (mapcar 'org-normalize-color
17672 (color-values color-name))))
17674 (defun org-normalize-color (value)
17675 "Return string to be used as color value for an RGB component."
17676 (format "%g" (/ value 65535.0)))
17678 ;; Image display
17681 (defvar org-inline-image-overlays nil)
17682 (make-variable-buffer-local 'org-inline-image-overlays)
17684 (defun org-toggle-inline-images (&optional include-linked)
17685 "Toggle the display of inline images.
17686 INCLUDE-LINKED is passed to `org-display-inline-images'."
17687 (interactive "P")
17688 (if org-inline-image-overlays
17689 (progn
17690 (org-remove-inline-images)
17691 (message "Inline image display turned off"))
17692 (org-display-inline-images include-linked)
17693 (if org-inline-image-overlays
17694 (message "%d images displayed inline"
17695 (length org-inline-image-overlays))
17696 (message "No images to display inline"))))
17698 (defun org-redisplay-inline-images ()
17699 "Refresh the display of inline images."
17700 (interactive)
17701 (if (not org-inline-image-overlays)
17702 (org-toggle-inline-images)
17703 (org-toggle-inline-images)
17704 (org-toggle-inline-images)))
17706 (defun org-display-inline-images (&optional include-linked refresh beg end)
17707 "Display inline images.
17708 Normally only links without a description part are inlined, because this
17709 is how it will work for export. When INCLUDE-LINKED is set, also links
17710 with a description part will be inlined. This can be nice for a quick
17711 look at those images, but it does not reflect what exported files will look
17712 like.
17713 When REFRESH is set, refresh existing images between BEG and END.
17714 This will create new image displays only if necessary.
17715 BEG and END default to the buffer boundaries."
17716 (interactive "P")
17717 (unless refresh
17718 (org-remove-inline-images)
17719 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17720 (save-excursion
17721 (save-restriction
17722 (widen)
17723 (setq beg (or beg (point-min)) end (or end (point-max)))
17724 (goto-char beg)
17725 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17726 (substring (org-image-file-name-regexp) 0 -2)
17727 "\\)\\]" (if include-linked "" "\\]")))
17728 old file ov img)
17729 (while (re-search-forward re end t)
17730 (setq old (get-char-property-and-overlay (match-beginning 1)
17731 'org-image-overlay))
17732 (setq file (expand-file-name
17733 (concat (or (match-string 3) "") (match-string 4))))
17734 (when (file-exists-p file)
17735 (if (and (car-safe old) refresh)
17736 (image-refresh (overlay-get (cdr old) 'display))
17737 (setq img (save-match-data (create-image file)))
17738 (when img
17739 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17740 (overlay-put ov 'display img)
17741 (overlay-put ov 'face 'default)
17742 (overlay-put ov 'org-image-overlay t)
17743 (overlay-put ov 'modification-hooks
17744 (list 'org-display-inline-remove-overlay))
17745 (push ov org-inline-image-overlays)))))))))
17747 (define-obsolete-function-alias
17748 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17750 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17751 "Remove inline-display overlay if a corresponding region is modified."
17752 (let ((inhibit-modification-hooks t))
17753 (when (and ov after)
17754 (delete ov org-inline-image-overlays)
17755 (delete-overlay ov))))
17757 (defun org-remove-inline-images ()
17758 "Remove inline display of images."
17759 (interactive)
17760 (mapc 'delete-overlay org-inline-image-overlays)
17761 (setq org-inline-image-overlays nil))
17763 ;;;; Key bindings
17765 ;; Outline functions from `outline-mode-prefix-map'
17766 ;; that can be remapped in Org:
17767 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17768 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17769 (define-key org-mode-map [remap outline-forward-same-level]
17770 'org-forward-heading-same-level)
17771 (define-key org-mode-map [remap outline-backward-same-level]
17772 'org-backward-heading-same-level)
17773 (define-key org-mode-map [remap show-branches]
17774 'org-kill-note-or-show-branches)
17775 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17776 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17777 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17779 ;; Outline functions from `outline-mode-prefix-map' that can not
17780 ;; be remapped in Org:
17782 ;; - the column "key binding" shows whether the Outline function is still
17783 ;; available in Org mode on the same key that it has been bound to in
17784 ;; Outline mode:
17785 ;; - "overridden": key used for a different functionality in Org mode
17786 ;; - else: key still bound to the same Outline function in Org mode
17788 ;; | Outline function | key binding | Org replacement |
17789 ;; |------------------------------------+-------------+-----------------------|
17790 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17791 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17792 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17793 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17794 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17795 ;; | `show-entry' | overridden | no replacement |
17796 ;; | `show-children' | `C-c C-i' | visibility cycling |
17797 ;; | `show-branches' | `C-c C-k' | still same function |
17798 ;; | `show-subtree' | overridden | visibility cycling |
17799 ;; | `show-all' | overridden | no replacement |
17800 ;; | `hide-subtree' | overridden | visibility cycling |
17801 ;; | `hide-body' | overridden | no replacement |
17802 ;; | `hide-entry' | overridden | visibility cycling |
17803 ;; | `hide-leaves' | overridden | no replacement |
17804 ;; | `hide-sublevels' | overridden | no replacement |
17805 ;; | `hide-other' | overridden | no replacement |
17807 ;; Make `C-c C-x' a prefix key
17808 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17810 ;; TAB key with modifiers
17811 (org-defkey org-mode-map "\C-i" 'org-cycle)
17812 (org-defkey org-mode-map [(tab)] 'org-cycle)
17813 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17814 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17815 ;; The following line is necessary under Suse GNU/Linux
17816 (unless (featurep 'xemacs)
17817 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17818 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17819 (define-key org-mode-map [backtab] 'org-shifttab)
17821 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17822 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17823 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17825 ;; Cursor keys with modifiers
17826 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17827 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17828 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17829 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17831 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17832 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17833 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17834 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17836 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17837 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17838 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17839 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17841 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17842 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17843 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17844 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17846 ;; Babel keys
17847 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17848 (mapc (lambda (pair)
17849 (define-key org-babel-map (car pair) (cdr pair)))
17850 org-babel-key-bindings)
17852 ;;; Extra keys for tty access.
17853 ;; We only set them when really needed because otherwise the
17854 ;; menus don't show the simple keys
17856 (when (or org-use-extra-keys
17857 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17858 (not window-system))
17859 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17860 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17861 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17862 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17863 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17864 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17865 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17866 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17867 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17868 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17869 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17870 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17871 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17872 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17873 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17874 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17875 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17876 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17877 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17878 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17879 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17880 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17881 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17882 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17883 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17884 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17885 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17886 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17888 ;; All the other keys
17890 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17891 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17892 (if (boundp 'narrow-map)
17893 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17894 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17895 (if (boundp 'narrow-map)
17896 (org-defkey narrow-map "b" 'org-narrow-to-block)
17897 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17898 (if (boundp 'narrow-map)
17899 (org-defkey narrow-map "e" 'org-narrow-to-element)
17900 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17901 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17902 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17903 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17904 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17905 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17906 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17907 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17908 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17909 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17910 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17911 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17912 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17913 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17914 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17915 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17916 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17917 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17918 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17919 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17920 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17921 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17922 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17923 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17924 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17925 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17926 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17927 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17928 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17929 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17930 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17931 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17932 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17933 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17934 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17935 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17936 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17937 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17938 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17939 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17940 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17941 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17942 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17943 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17944 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17945 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17946 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17947 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17948 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17949 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17950 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17951 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17952 (org-defkey org-mode-map "\C-c^" 'org-sort)
17953 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17954 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17955 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17956 (org-defkey org-mode-map "\C-m" 'org-return)
17957 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17958 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17959 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17960 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17961 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17962 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17963 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17964 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17965 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17966 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17967 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17968 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17969 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17970 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17971 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17972 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17973 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17974 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17975 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17976 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17977 (org-defkey org-mode-map "\M-h" 'org-mark-element)
17978 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17979 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17981 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17982 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17983 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17985 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17986 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17987 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
17988 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
17989 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17990 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17991 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
17992 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17993 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17994 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17995 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17996 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17997 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
17998 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17999 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18000 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18001 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18002 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18003 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18004 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18005 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18006 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18008 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18009 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18010 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18011 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18012 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18014 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18016 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18018 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18019 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18021 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18024 (when (featurep 'xemacs)
18025 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18028 (defconst org-speed-commands-default
18030 ("Outline Navigation")
18031 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18032 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18033 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18034 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18035 ("u" . (org-speed-move-safe 'outline-up-heading))
18036 ("j" . org-goto)
18037 ("g" . (org-refile t))
18038 ("Outline Visibility")
18039 ("c" . org-cycle)
18040 ("C" . org-shifttab)
18041 (" " . org-display-outline-path)
18042 (":" . org-columns)
18043 ("Outline Structure Editing")
18044 ("U" . org-shiftmetaup)
18045 ("D" . org-shiftmetadown)
18046 ("r" . org-metaright)
18047 ("l" . org-metaleft)
18048 ("R" . org-shiftmetaright)
18049 ("L" . org-shiftmetaleft)
18050 ("i" . (progn (forward-char 1) (call-interactively
18051 'org-insert-heading-respect-content)))
18052 ("^" . org-sort)
18053 ("w" . org-refile)
18054 ("a" . org-archive-subtree-default-with-confirmation)
18055 ("." . org-mark-subtree)
18056 ("#" . org-toggle-comment)
18057 ("Clock Commands")
18058 ("I" . org-clock-in)
18059 ("O" . org-clock-out)
18060 ("Meta Data Editing")
18061 ("t" . org-todo)
18062 ("," . (org-priority))
18063 ("0" . (org-priority ?\ ))
18064 ("1" . (org-priority ?A))
18065 ("2" . (org-priority ?B))
18066 ("3" . (org-priority ?C))
18067 (";" . org-set-tags-command)
18068 ("e" . org-set-effort)
18069 ("E" . org-inc-effort)
18070 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18071 (org-entry-put (point) "APPT_WARNTIME" m)))
18072 ("Agenda Views etc")
18073 ("v" . org-agenda)
18074 ("/" . org-sparse-tree)
18075 ("Misc")
18076 ("o" . org-open-at-point)
18077 ("?" . org-speed-command-help)
18078 ("<" . (org-agenda-set-restriction-lock 'subtree))
18079 (">" . (org-agenda-remove-restriction-lock))
18081 "The default speed commands.")
18083 (defun org-print-speed-command (e)
18084 (if (> (length (car e)) 1)
18085 (progn
18086 (princ "\n")
18087 (princ (car e))
18088 (princ "\n")
18089 (princ (make-string (length (car e)) ?-))
18090 (princ "\n"))
18091 (princ (car e))
18092 (princ " ")
18093 (if (symbolp (cdr e))
18094 (princ (symbol-name (cdr e)))
18095 (prin1 (cdr e)))
18096 (princ "\n")))
18098 (defun org-speed-command-help ()
18099 "Show the available speed commands."
18100 (interactive)
18101 (if (not org-use-speed-commands)
18102 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18103 (with-output-to-temp-buffer "*Help*"
18104 (princ "User-defined Speed commands\n===========================\n")
18105 (mapc 'org-print-speed-command org-speed-commands-user)
18106 (princ "\n")
18107 (princ "Built-in Speed commands\n=======================\n")
18108 (mapc 'org-print-speed-command org-speed-commands-default))
18109 (with-current-buffer "*Help*"
18110 (setq truncate-lines t))))
18112 (defun org-speed-move-safe (cmd)
18113 "Execute CMD, but make sure that the cursor always ends up in a headline.
18114 If not, return to the original position and throw an error."
18115 (interactive)
18116 (let ((pos (point)))
18117 (call-interactively cmd)
18118 (unless (and (bolp) (org-at-heading-p))
18119 (goto-char pos)
18120 (error "Boundary reached while executing %s" cmd))))
18122 (defvar org-self-insert-command-undo-counter 0)
18124 (defvar org-table-auto-blank-field) ; defined in org-table.el
18125 (defvar org-speed-command nil)
18127 (define-obsolete-function-alias
18128 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18130 (defun org-speed-command-activate (keys)
18131 "Hook for activating single-letter speed commands.
18132 `org-speed-commands-default' specifies a minimal command set.
18133 Use `org-speed-commands-user' for further customization."
18134 (when (or (and (bolp) (looking-at org-outline-regexp))
18135 (and (functionp org-use-speed-commands)
18136 (funcall org-use-speed-commands)))
18137 (cdr (assoc keys (append org-speed-commands-user
18138 org-speed-commands-default)))))
18140 (define-obsolete-function-alias
18141 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18143 (defun org-babel-speed-command-activate (keys)
18144 "Hook for activating single-letter code block commands."
18145 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18146 (cdr (assoc keys org-babel-key-bindings))))
18148 (defcustom org-speed-command-hook
18149 '(org-speed-command-default-hook org-babel-speed-command-hook)
18150 "Hook for activating speed commands at strategic locations.
18151 Hook functions are called in sequence until a valid handler is
18152 found.
18154 Each hook takes a single argument, a user-pressed command key
18155 which is also a `self-insert-command' from the global map.
18157 Within the hook, examine the cursor position and the command key
18158 and return nil or a valid handler as appropriate. Handler could
18159 be one of an interactive command, a function, or a form.
18161 Set `org-use-speed-commands' to non-nil value to enable this
18162 hook. The default setting is `org-speed-command-activate'."
18163 :group 'org-structure
18164 :version "24.1"
18165 :type 'hook)
18167 (defun org-self-insert-command (N)
18168 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18169 If the cursor is in a table looking at whitespace, the whitespace is
18170 overwritten, and the table is not marked as requiring realignment."
18171 (interactive "p")
18172 (org-check-before-invisible-edit 'insert)
18173 (cond
18174 ((and org-use-speed-commands
18175 (setq org-speed-command
18176 (run-hook-with-args-until-success
18177 'org-speed-command-hook (this-command-keys))))
18178 (cond
18179 ((commandp org-speed-command)
18180 (setq this-command org-speed-command)
18181 (call-interactively org-speed-command))
18182 ((functionp org-speed-command)
18183 (funcall org-speed-command))
18184 ((and org-speed-command (listp org-speed-command))
18185 (eval org-speed-command))
18186 (t (let (org-use-speed-commands)
18187 (call-interactively 'org-self-insert-command)))))
18188 ((and
18189 (org-table-p)
18190 (progn
18191 ;; check if we blank the field, and if that triggers align
18192 (and (featurep 'org-table) org-table-auto-blank-field
18193 (member last-command
18194 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18195 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18196 ;; got extra space, this field does not determine column width
18197 (let (org-table-may-need-update) (org-table-blank-field))
18198 ;; no extra space, this field may determine column width
18199 (org-table-blank-field)))
18201 (eq N 1)
18202 (looking-at "[^|\n]* |"))
18203 (let (org-table-may-need-update)
18204 (goto-char (1- (match-end 0)))
18205 (backward-delete-char 1)
18206 (goto-char (match-beginning 0))
18207 (self-insert-command N)))
18209 (setq org-table-may-need-update t)
18210 (self-insert-command N)
18211 (org-fix-tags-on-the-fly)
18212 (if org-self-insert-cluster-for-undo
18213 (if (not (eq last-command 'org-self-insert-command))
18214 (setq org-self-insert-command-undo-counter 1)
18215 (if (>= org-self-insert-command-undo-counter 20)
18216 (setq org-self-insert-command-undo-counter 1)
18217 (and (> org-self-insert-command-undo-counter 0)
18218 buffer-undo-list (listp buffer-undo-list)
18219 (not (cadr buffer-undo-list)) ; remove nil entry
18220 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18221 (setq org-self-insert-command-undo-counter
18222 (1+ org-self-insert-command-undo-counter))))))))
18224 (defun org-check-before-invisible-edit (kind)
18225 "Check is editing if kind KIND would be dangerous with invisible text around.
18226 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18227 ;; First, try to get out of here as quickly as possible, to reduce overhead
18228 (if (and org-catch-invisible-edits
18229 (or (not (boundp 'visible-mode)) (not visible-mode))
18230 (or (get-char-property (point) 'invisible)
18231 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18232 ;; OK, we need to take a closer look
18233 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18234 (invisible-before-point (if (bobp) nil (get-char-property
18235 (1- (point)) 'invisible)))
18236 (border-and-ok-direction
18238 ;; Check if we are acting predictably before invisible text
18239 (and invisible-at-point (not invisible-before-point)
18240 (memq kind '(insert delete-backward)))
18241 ;; Check if we are acting predictably after invisible text
18242 ;; This works not well, and I have turned it off. It seems
18243 ;; better to always show and stop after invisible text.
18244 ;; (and (not invisible-at-point) invisible-before-point
18245 ;; (memq kind '(insert delete)))
18247 (when (or (memq invisible-at-point '(outline org-hide-block t))
18248 (memq invisible-before-point '(outline org-hide-block t)))
18249 (if (eq org-catch-invisible-edits 'error)
18250 (error "Editing in invisible areas is prohibited - make visible first"))
18251 (if (and org-custom-properties-overlays
18252 (y-or-n-p "Display invisible properties in this buffer? "))
18253 (org-toggle-custom-properties-visibility)
18254 ;; Make the area visible
18255 (save-excursion
18256 (if invisible-before-point
18257 (goto-char (previous-single-char-property-change
18258 (point) 'invisible)))
18259 (org-cycle))
18260 (cond
18261 ((eq org-catch-invisible-edits 'show)
18262 ;; That's it, we do the edit after showing
18263 (message
18264 "Unfolding invisible region around point before editing")
18265 (sit-for 1))
18266 ((and (eq org-catch-invisible-edits 'smart)
18267 border-and-ok-direction)
18268 (message "Unfolding invisible region around point before editing"))
18270 ;; Don't do the edit, make the user repeat it in full visibility
18271 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18273 (defun org-fix-tags-on-the-fly ()
18274 (when (and (equal (char-after (point-at-bol)) ?*)
18275 (org-at-heading-p))
18276 (org-align-tags-here org-tags-column)))
18278 (defun org-delete-backward-char (N)
18279 "Like `delete-backward-char', insert whitespace at field end in tables.
18280 When deleting backwards, in tables this function will insert whitespace in
18281 front of the next \"|\" separator, to keep the table aligned. The table will
18282 still be marked for re-alignment if the field did fill the entire column,
18283 because, in this case the deletion might narrow the column."
18284 (interactive "p")
18285 (org-check-before-invisible-edit 'delete-backward)
18286 (if (and (org-table-p)
18287 (eq N 1)
18288 (string-match "|" (buffer-substring (point-at-bol) (point)))
18289 (looking-at ".*?|"))
18290 (let ((pos (point))
18291 (noalign (looking-at "[^|\n\r]* |"))
18292 (c org-table-may-need-update))
18293 (backward-delete-char N)
18294 (if (not overwrite-mode)
18295 (progn
18296 (skip-chars-forward "^|")
18297 (insert " ")
18298 (goto-char (1- pos))))
18299 ;; noalign: if there were two spaces at the end, this field
18300 ;; does not determine the width of the column.
18301 (if noalign (setq org-table-may-need-update c)))
18302 (backward-delete-char N)
18303 (org-fix-tags-on-the-fly)))
18305 (defun org-delete-char (N)
18306 "Like `delete-char', but insert whitespace at field end in tables.
18307 When deleting characters, in tables this function will insert whitespace in
18308 front of the next \"|\" separator, to keep the table aligned. The table will
18309 still be marked for re-alignment if the field did fill the entire column,
18310 because, in this case the deletion might narrow the column."
18311 (interactive "p")
18312 (org-check-before-invisible-edit 'delete)
18313 (if (and (org-table-p)
18314 (not (bolp))
18315 (not (= (char-after) ?|))
18316 (eq N 1))
18317 (if (looking-at ".*?|")
18318 (let ((pos (point))
18319 (noalign (looking-at "[^|\n\r]* |"))
18320 (c org-table-may-need-update))
18321 (replace-match (concat
18322 (substring (match-string 0) 1 -1)
18323 " |"))
18324 (goto-char pos)
18325 ;; noalign: if there were two spaces at the end, this field
18326 ;; does not determine the width of the column.
18327 (if noalign (setq org-table-may-need-update c)))
18328 (delete-char N))
18329 (delete-char N)
18330 (org-fix-tags-on-the-fly)))
18332 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18333 (put 'org-self-insert-command 'delete-selection t)
18334 (put 'orgtbl-self-insert-command 'delete-selection t)
18335 (put 'org-delete-char 'delete-selection 'supersede)
18336 (put 'org-delete-backward-char 'delete-selection 'supersede)
18337 (put 'org-yank 'delete-selection 'yank)
18339 ;; Make `flyspell-mode' delay after some commands
18340 (put 'org-self-insert-command 'flyspell-delayed t)
18341 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18342 (put 'org-delete-char 'flyspell-delayed t)
18343 (put 'org-delete-backward-char 'flyspell-delayed t)
18345 ;; Make pabbrev-mode expand after org-mode commands
18346 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18347 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18349 ;; How to do this: Measure non-white length of current string
18350 ;; If equal to column width, we should realign.
18352 (defun org-remap (map &rest commands)
18353 "In MAP, remap the functions given in COMMANDS.
18354 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18355 (let (new old)
18356 (while commands
18357 (setq old (pop commands) new (pop commands))
18358 (if (fboundp 'command-remapping)
18359 (org-defkey map (vector 'remap old) new)
18360 (substitute-key-definition old new map global-map)))))
18362 (when (eq org-enable-table-editor 'optimized)
18363 ;; If the user wants maximum table support, we need to hijack
18364 ;; some standard editing functions
18365 (org-remap org-mode-map
18366 'self-insert-command 'org-self-insert-command
18367 'delete-char 'org-delete-char
18368 'delete-backward-char 'org-delete-backward-char)
18369 (org-defkey org-mode-map "|" 'org-force-self-insert))
18371 (defvar org-ctrl-c-ctrl-c-hook nil
18372 "Hook for functions attaching themselves to `C-c C-c'.
18374 This can be used to add additional functionality to the C-c C-c
18375 key which executes context-dependent commands. This hook is run
18376 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18377 run after the last test.
18379 Each function will be called with no arguments. The function
18380 must check if the context is appropriate for it to act. If yes,
18381 it should do its thing and then return a non-nil value. If the
18382 context is wrong, just do nothing and return nil.")
18384 (defvar org-ctrl-c-ctrl-c-final-hook nil
18385 "Hook for functions attaching themselves to `C-c C-c'.
18387 This can be used to add additional functionality to the C-c C-c
18388 key which executes context-dependent commands. This hook is run
18389 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18390 before the first test.
18392 Each function will be called with no arguments. The function
18393 must check if the context is appropriate for it to act. If yes,
18394 it should do its thing and then return a non-nil value. If the
18395 context is wrong, just do nothing and return nil.")
18397 (defvar org-tab-first-hook nil
18398 "Hook for functions to attach themselves to TAB.
18399 See `org-ctrl-c-ctrl-c-hook' for more information.
18400 This hook runs as the first action when TAB is pressed, even before
18401 `org-cycle' messes around with the `outline-regexp' to cater for
18402 inline tasks and plain list item folding.
18403 If any function in this hook returns t, any other actions that
18404 would have been caused by TAB (such as table field motion or visibility
18405 cycling) will not occur.")
18407 (defvar org-tab-after-check-for-table-hook nil
18408 "Hook for functions to attach themselves to TAB.
18409 See `org-ctrl-c-ctrl-c-hook' for more information.
18410 This hook runs after it has been established that the cursor is not in a
18411 table, but before checking if the cursor is in a headline or if global cycling
18412 should be done.
18413 If any function in this hook returns t, not other actions like visibility
18414 cycling will be done.")
18416 (defvar org-tab-after-check-for-cycling-hook nil
18417 "Hook for functions to attach themselves to TAB.
18418 See `org-ctrl-c-ctrl-c-hook' for more information.
18419 This hook runs after it has been established that not table field motion and
18420 not visibility should be done because of current context. This is probably
18421 the place where a package like yasnippets can hook in.")
18423 (defvar org-tab-before-tab-emulation-hook nil
18424 "Hook for functions to attach themselves to TAB.
18425 See `org-ctrl-c-ctrl-c-hook' for more information.
18426 This hook runs after every other options for TAB have been exhausted, but
18427 before indentation and \t insertion takes place.")
18429 (defvar org-metaleft-hook nil
18430 "Hook for functions attaching themselves to `M-left'.
18431 See `org-ctrl-c-ctrl-c-hook' for more information.")
18432 (defvar org-metaright-hook nil
18433 "Hook for functions attaching themselves to `M-right'.
18434 See `org-ctrl-c-ctrl-c-hook' for more information.")
18435 (defvar org-metaup-hook nil
18436 "Hook for functions attaching themselves to `M-up'.
18437 See `org-ctrl-c-ctrl-c-hook' for more information.")
18438 (defvar org-metadown-hook nil
18439 "Hook for functions attaching themselves to `M-down'.
18440 See `org-ctrl-c-ctrl-c-hook' for more information.")
18441 (defvar org-shiftmetaleft-hook nil
18442 "Hook for functions attaching themselves to `M-S-left'.
18443 See `org-ctrl-c-ctrl-c-hook' for more information.")
18444 (defvar org-shiftmetaright-hook nil
18445 "Hook for functions attaching themselves to `M-S-right'.
18446 See `org-ctrl-c-ctrl-c-hook' for more information.")
18447 (defvar org-shiftmetaup-hook nil
18448 "Hook for functions attaching themselves to `M-S-up'.
18449 See `org-ctrl-c-ctrl-c-hook' for more information.")
18450 (defvar org-shiftmetadown-hook nil
18451 "Hook for functions attaching themselves to `M-S-down'.
18452 See `org-ctrl-c-ctrl-c-hook' for more information.")
18453 (defvar org-metareturn-hook nil
18454 "Hook for functions attaching themselves to `M-RET'.
18455 See `org-ctrl-c-ctrl-c-hook' for more information.")
18456 (defvar org-shiftup-hook nil
18457 "Hook for functions attaching themselves to `S-up'.
18458 See `org-ctrl-c-ctrl-c-hook' for more information.")
18459 (defvar org-shiftup-final-hook nil
18460 "Hook for functions attaching themselves to `S-up'.
18461 This one runs after all other options except shift-select have been excluded.
18462 See `org-ctrl-c-ctrl-c-hook' for more information.")
18463 (defvar org-shiftdown-hook nil
18464 "Hook for functions attaching themselves to `S-down'.
18465 See `org-ctrl-c-ctrl-c-hook' for more information.")
18466 (defvar org-shiftdown-final-hook nil
18467 "Hook for functions attaching themselves to `S-down'.
18468 This one runs after all other options except shift-select have been excluded.
18469 See `org-ctrl-c-ctrl-c-hook' for more information.")
18470 (defvar org-shiftleft-hook nil
18471 "Hook for functions attaching themselves to `S-left'.
18472 See `org-ctrl-c-ctrl-c-hook' for more information.")
18473 (defvar org-shiftleft-final-hook nil
18474 "Hook for functions attaching themselves to `S-left'.
18475 This one runs after all other options except shift-select have been excluded.
18476 See `org-ctrl-c-ctrl-c-hook' for more information.")
18477 (defvar org-shiftright-hook nil
18478 "Hook for functions attaching themselves to `S-right'.
18479 See `org-ctrl-c-ctrl-c-hook' for more information.")
18480 (defvar org-shiftright-final-hook nil
18481 "Hook for functions attaching themselves to `S-right'.
18482 This one runs after all other options except shift-select have been excluded.
18483 See `org-ctrl-c-ctrl-c-hook' for more information.")
18485 (defun org-modifier-cursor-error ()
18486 "Throw an error, a modified cursor command was applied in wrong context."
18487 (error "This command is active in special context like tables, headlines or items"))
18489 (defun org-shiftselect-error ()
18490 "Throw an error because Shift-Cursor command was applied in wrong context."
18491 (if (and (boundp 'shift-select-mode) shift-select-mode)
18492 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18493 (error "This command works only in special context like headlines or timestamps")))
18495 (defun org-call-for-shift-select (cmd)
18496 (let ((this-command-keys-shift-translated t))
18497 (call-interactively cmd)))
18499 (defun org-shifttab (&optional arg)
18500 "Global visibility cycling or move to previous table field.
18501 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18502 on context.
18503 See the individual commands for more information."
18504 (interactive "P")
18505 (cond
18506 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18507 ((integerp arg)
18508 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18509 (message "Content view to level: %d" arg)
18510 (org-content (prefix-numeric-value arg2))
18511 (setq org-cycle-global-status 'overview)))
18512 (t (call-interactively 'org-global-cycle))))
18514 (defun org-shiftmetaleft ()
18515 "Promote subtree or delete table column.
18516 Calls `org-promote-subtree', `org-outdent-item-tree', or
18517 `org-table-delete-column', depending on context. See the
18518 individual commands for more information."
18519 (interactive)
18520 (cond
18521 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18522 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18523 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18524 ((if (not (org-region-active-p)) (org-at-item-p)
18525 (save-excursion (goto-char (region-beginning))
18526 (org-at-item-p)))
18527 (call-interactively 'org-outdent-item-tree))
18528 (t (org-modifier-cursor-error))))
18530 (defun org-shiftmetaright ()
18531 "Demote subtree or insert table column.
18532 Calls `org-demote-subtree', `org-indent-item-tree', or
18533 `org-table-insert-column', depending on context. See the
18534 individual commands for more information."
18535 (interactive)
18536 (cond
18537 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18538 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18539 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18540 ((if (not (org-region-active-p)) (org-at-item-p)
18541 (save-excursion (goto-char (region-beginning))
18542 (org-at-item-p)))
18543 (call-interactively 'org-indent-item-tree))
18544 (t (org-modifier-cursor-error))))
18546 (defun org-shiftmetaup (&optional arg)
18547 "Move subtree up or kill table row.
18548 Calls `org-move-subtree-up' or `org-table-kill-row' or
18549 `org-move-item-up' or `org-timestamp-up', depending on context.
18550 See the individual commands for more information."
18551 (interactive "P")
18552 (cond
18553 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18554 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18555 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18556 ((org-at-item-p) (call-interactively 'org-move-item-up))
18557 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18558 (call-interactively 'org-timestamp-up)))
18559 (t (org-modifier-cursor-error))))
18561 (defun org-shiftmetadown (&optional arg)
18562 "Move subtree down or insert table row.
18563 Calls `org-move-subtree-down' or `org-table-insert-row' or
18564 `org-move-item-down' or `org-timestamp-up', depending on context.
18565 See the individual commands for more information."
18566 (interactive "P")
18567 (cond
18568 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18569 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18570 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18571 ((org-at-item-p) (call-interactively 'org-move-item-down))
18572 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18573 (call-interactively 'org-timestamp-down)))
18574 (t (org-modifier-cursor-error))))
18576 (defsubst org-hidden-tree-error ()
18577 (error
18578 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18580 (defun org-metaleft (&optional arg)
18581 "Promote heading or move table column to left.
18582 Calls `org-do-promote' or `org-table-move-column', depending on context.
18583 With no specific context, calls the Emacs default `backward-word'.
18584 See the individual commands for more information."
18585 (interactive "P")
18586 (cond
18587 ((run-hook-with-args-until-success 'org-metaleft-hook))
18588 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18589 ((org-with-limited-levels
18590 (or (org-at-heading-p)
18591 (and (org-region-active-p)
18592 (save-excursion
18593 (goto-char (region-beginning))
18594 (org-at-heading-p)))))
18595 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18596 (call-interactively 'org-do-promote))
18597 ;; At an inline task.
18598 ((org-at-heading-p)
18599 (call-interactively 'org-inlinetask-promote))
18600 ((or (org-at-item-p)
18601 (and (org-region-active-p)
18602 (save-excursion
18603 (goto-char (region-beginning))
18604 (org-at-item-p))))
18605 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18606 (call-interactively 'org-outdent-item))
18607 (t (call-interactively 'backward-word))))
18609 (defun org-metaright (&optional arg)
18610 "Demote a subtree, a list item or move table column to right.
18611 In front of a drawer or a block keyword, indent it correctly.
18612 With no specific context, calls the Emacs default `forward-word'.
18613 See the individual commands for more information."
18614 (interactive "P")
18615 (cond
18616 ((run-hook-with-args-until-success 'org-metaright-hook))
18617 ((org-at-table-p) (call-interactively 'org-table-move-column))
18618 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18619 ((org-at-block-p) (call-interactively 'org-indent-block))
18620 ((org-with-limited-levels
18621 (or (org-at-heading-p)
18622 (and (org-region-active-p)
18623 (save-excursion
18624 (goto-char (region-beginning))
18625 (org-at-heading-p)))))
18626 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18627 (call-interactively 'org-do-demote))
18628 ;; At an inline task.
18629 ((org-at-heading-p)
18630 (call-interactively 'org-inlinetask-demote))
18631 ((or (org-at-item-p)
18632 (and (org-region-active-p)
18633 (save-excursion
18634 (goto-char (region-beginning))
18635 (org-at-item-p))))
18636 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18637 (call-interactively 'org-indent-item))
18638 (t (call-interactively 'forward-word))))
18640 (defun org-check-for-hidden (what)
18641 "Check if there are hidden headlines/items in the current visual line.
18642 WHAT can be either `headlines' or `items'. If the current line is
18643 an outline or item heading and it has a folded subtree below it,
18644 this function returns t, nil otherwise."
18645 (let ((re (cond
18646 ((eq what 'headlines) org-outline-regexp-bol)
18647 ((eq what 'items) (org-item-beginning-re))
18648 (t (error "This should not happen"))))
18649 beg end)
18650 (save-excursion
18651 (catch 'exit
18652 (unless (org-region-active-p)
18653 (setq beg (point-at-bol))
18654 (beginning-of-line 2)
18655 (while (and (not (eobp)) ;; this is like `next-line'
18656 (get-char-property (1- (point)) 'invisible))
18657 (beginning-of-line 2))
18658 (setq end (point))
18659 (goto-char beg)
18660 (goto-char (point-at-eol))
18661 (setq end (max end (point)))
18662 (while (re-search-forward re end t)
18663 (if (get-char-property (match-beginning 0) 'invisible)
18664 (throw 'exit t))))
18665 nil))))
18667 (autoload 'org-element-at-point "org-element")
18668 (autoload 'org-element-type "org-element")
18670 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18671 (declare-function org-element-type "org-element" (element))
18672 (declare-function org-element-contents "org-element" (element))
18673 (declare-function org-element-property "org-element" (property element))
18674 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18675 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18676 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18677 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18678 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18680 (defun org-metaup (&optional arg)
18681 "Move subtree up or move table row up.
18682 Calls `org-move-subtree-up' or `org-table-move-row' or
18683 `org-move-item-up', depending on context. See the individual commands
18684 for more information."
18685 (interactive "P")
18686 (cond
18687 ((run-hook-with-args-until-success 'org-metaup-hook))
18688 ((org-region-active-p)
18689 (let* ((a (min (region-beginning) (region-end)))
18690 (b (1- (max (region-beginning) (region-end))))
18691 (c (save-excursion (goto-char a)
18692 (move-beginning-of-line 0)))
18693 (d (save-excursion (goto-char a)
18694 (move-end-of-line 0) (point))))
18695 (transpose-regions a b c d)
18696 (goto-char c)))
18697 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18698 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18699 ((org-at-item-p) (call-interactively 'org-move-item-up))
18700 (t (org-drag-element-backward))))
18702 (defun org-metadown (&optional arg)
18703 "Move subtree down or move table row down.
18704 Calls `org-move-subtree-down' or `org-table-move-row' or
18705 `org-move-item-down', depending on context. See the individual
18706 commands for more information."
18707 (interactive "P")
18708 (cond
18709 ((run-hook-with-args-until-success 'org-metadown-hook))
18710 ((org-region-active-p)
18711 (let* ((a (min (region-beginning) (region-end)))
18712 (b (max (region-beginning) (region-end)))
18713 (c (save-excursion (goto-char b)
18714 (move-beginning-of-line 1)))
18715 (d (save-excursion (goto-char b)
18716 (move-end-of-line 1) (1+ (point)))))
18717 (transpose-regions a b c d)
18718 (goto-char d)))
18719 ((org-at-table-p) (call-interactively 'org-table-move-row))
18720 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18721 ((org-at-item-p) (call-interactively 'org-move-item-down))
18722 (t (org-drag-element-forward))))
18724 (defun org-shiftup (&optional arg)
18725 "Increase item in timestamp or increase priority of current headline.
18726 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18727 depending on context. See the individual commands for more information."
18728 (interactive "P")
18729 (cond
18730 ((run-hook-with-args-until-success 'org-shiftup-hook))
18731 ((and org-support-shift-select (org-region-active-p))
18732 (org-call-for-shift-select 'previous-line))
18733 ((org-at-timestamp-p t)
18734 (call-interactively (if org-edit-timestamp-down-means-later
18735 'org-timestamp-down 'org-timestamp-up)))
18736 ((and (not (eq org-support-shift-select 'always))
18737 org-enable-priority-commands
18738 (org-at-heading-p))
18739 (call-interactively 'org-priority-up))
18740 ((and (not org-support-shift-select) (org-at-item-p))
18741 (call-interactively 'org-previous-item))
18742 ((org-clocktable-try-shift 'up arg))
18743 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18744 (org-support-shift-select
18745 (org-call-for-shift-select 'previous-line))
18746 (t (org-shiftselect-error))))
18748 (defun org-shiftdown (&optional arg)
18749 "Decrease item in timestamp or decrease priority of current headline.
18750 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18751 depending on context. See the individual commands for more information."
18752 (interactive "P")
18753 (cond
18754 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18755 ((and org-support-shift-select (org-region-active-p))
18756 (org-call-for-shift-select 'next-line))
18757 ((org-at-timestamp-p t)
18758 (call-interactively (if org-edit-timestamp-down-means-later
18759 'org-timestamp-up 'org-timestamp-down)))
18760 ((and (not (eq org-support-shift-select 'always))
18761 org-enable-priority-commands
18762 (org-at-heading-p))
18763 (call-interactively 'org-priority-down))
18764 ((and (not org-support-shift-select) (org-at-item-p))
18765 (call-interactively 'org-next-item))
18766 ((org-clocktable-try-shift 'down arg))
18767 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18768 (org-support-shift-select
18769 (org-call-for-shift-select 'next-line))
18770 (t (org-shiftselect-error))))
18772 (defun org-shiftright (&optional arg)
18773 "Cycle the thing at point or in the current line, depending on context.
18774 Depending on context, this does one of the following:
18776 - switch a timestamp at point one day into the future
18777 - on a headline, switch to the next TODO keyword.
18778 - on an item, switch entire list to the next bullet type
18779 - on a property line, switch to the next allowed value
18780 - on a clocktable definition line, move time block into the future"
18781 (interactive "P")
18782 (cond
18783 ((run-hook-with-args-until-success 'org-shiftright-hook))
18784 ((and org-support-shift-select (org-region-active-p))
18785 (org-call-for-shift-select 'forward-char))
18786 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18787 ((and (not (eq org-support-shift-select 'always))
18788 (org-at-heading-p))
18789 (let ((org-inhibit-logging
18790 (not org-treat-S-cursor-todo-selection-as-state-change))
18791 (org-inhibit-blocking
18792 (not org-treat-S-cursor-todo-selection-as-state-change)))
18793 (org-call-with-arg 'org-todo 'right)))
18794 ((or (and org-support-shift-select
18795 (not (eq org-support-shift-select 'always))
18796 (org-at-item-bullet-p))
18797 (and (not org-support-shift-select) (org-at-item-p)))
18798 (org-call-with-arg 'org-cycle-list-bullet nil))
18799 ((and (not (eq org-support-shift-select 'always))
18800 (org-at-property-p))
18801 (call-interactively 'org-property-next-allowed-value))
18802 ((org-clocktable-try-shift 'right arg))
18803 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18804 (org-support-shift-select
18805 (org-call-for-shift-select 'forward-char))
18806 (t (org-shiftselect-error))))
18808 (defun org-shiftleft (&optional arg)
18809 "Cycle the thing at point or in the current line, depending on context.
18810 Depending on context, this does one of the following:
18812 - switch a timestamp at point one day into the past
18813 - on a headline, switch to the previous TODO keyword.
18814 - on an item, switch entire list to the previous bullet type
18815 - on a property line, switch to the previous allowed value
18816 - on a clocktable definition line, move time block into the past"
18817 (interactive "P")
18818 (cond
18819 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18820 ((and org-support-shift-select (org-region-active-p))
18821 (org-call-for-shift-select 'backward-char))
18822 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18823 ((and (not (eq org-support-shift-select 'always))
18824 (org-at-heading-p))
18825 (let ((org-inhibit-logging
18826 (not org-treat-S-cursor-todo-selection-as-state-change))
18827 (org-inhibit-blocking
18828 (not org-treat-S-cursor-todo-selection-as-state-change)))
18829 (org-call-with-arg 'org-todo 'left)))
18830 ((or (and org-support-shift-select
18831 (not (eq org-support-shift-select 'always))
18832 (org-at-item-bullet-p))
18833 (and (not org-support-shift-select) (org-at-item-p)))
18834 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18835 ((and (not (eq org-support-shift-select 'always))
18836 (org-at-property-p))
18837 (call-interactively 'org-property-previous-allowed-value))
18838 ((org-clocktable-try-shift 'left arg))
18839 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18840 (org-support-shift-select
18841 (org-call-for-shift-select 'backward-char))
18842 (t (org-shiftselect-error))))
18844 (defun org-shiftcontrolright ()
18845 "Switch to next TODO set."
18846 (interactive)
18847 (cond
18848 ((and org-support-shift-select (org-region-active-p))
18849 (org-call-for-shift-select 'forward-word))
18850 ((and (not (eq org-support-shift-select 'always))
18851 (org-at-heading-p))
18852 (org-call-with-arg 'org-todo 'nextset))
18853 (org-support-shift-select
18854 (org-call-for-shift-select 'forward-word))
18855 (t (org-shiftselect-error))))
18857 (defun org-shiftcontrolleft ()
18858 "Switch to previous TODO set."
18859 (interactive)
18860 (cond
18861 ((and org-support-shift-select (org-region-active-p))
18862 (org-call-for-shift-select 'backward-word))
18863 ((and (not (eq org-support-shift-select 'always))
18864 (org-at-heading-p))
18865 (org-call-with-arg 'org-todo 'previousset))
18866 (org-support-shift-select
18867 (org-call-for-shift-select 'backward-word))
18868 (t (org-shiftselect-error))))
18870 (defun org-shiftcontrolup ()
18871 "Change timestamps synchronously up in CLOCK log lines."
18872 (interactive)
18873 (cond ((and (not org-support-shift-select)
18874 (org-at-clock-log-p)
18875 (org-at-timestamp-p t))
18876 (org-clock-timestamps-up))
18877 (t (org-shiftselect-error))))
18879 (defun org-shiftcontroldown ()
18880 "Change timestamps synchronously down in CLOCK log lines."
18881 (interactive)
18882 (cond ((and (not org-support-shift-select)
18883 (org-at-clock-log-p)
18884 (org-at-timestamp-p t))
18885 (org-clock-timestamps-down))
18886 (t (org-shiftselect-error))))
18888 (defun org-ctrl-c-ret ()
18889 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18890 (interactive)
18891 (cond
18892 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18893 (t (call-interactively 'org-insert-heading))))
18895 (defun org-find-visible ()
18896 (let ((s (point)))
18897 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18898 (get-char-property s 'invisible)))
18900 (defun org-find-invisible ()
18901 (let ((s (point)))
18902 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18903 (not (get-char-property s 'invisible))))
18906 (defun org-copy-visible (beg end)
18907 "Copy the visible parts of the region."
18908 (interactive "r")
18909 (let (snippets s)
18910 (save-excursion
18911 (save-restriction
18912 (narrow-to-region beg end)
18913 (setq s (goto-char (point-min)))
18914 (while (not (= (point) (point-max)))
18915 (goto-char (org-find-invisible))
18916 (push (buffer-substring s (point)) snippets)
18917 (setq s (goto-char (org-find-visible))))))
18918 (kill-new (apply 'concat (nreverse snippets)))))
18920 (defun org-copy-special ()
18921 "Copy region in table or copy current subtree.
18922 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18923 See the individual commands for more information."
18924 (interactive)
18925 (call-interactively
18926 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18928 (defun org-cut-special ()
18929 "Cut region in table or cut current subtree.
18930 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18931 See the individual commands for more information."
18932 (interactive)
18933 (call-interactively
18934 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18936 (defun org-paste-special (arg)
18937 "Paste rectangular region into table, or past subtree relative to level.
18938 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18939 See the individual commands for more information."
18940 (interactive "P")
18941 (if (org-at-table-p)
18942 (org-table-paste-rectangle)
18943 (org-paste-subtree arg)))
18945 (defun org-edit-special (&optional arg)
18946 "Call a special editor for the stuff at point.
18947 When at a table, call the formula editor with `org-table-edit-formulas'.
18948 When at the first line of an src example, call `org-edit-src-code'.
18949 When in an #+include line, visit the include file. Otherwise call
18950 `ffap' to visit the file at point."
18951 (interactive)
18952 ;; possibly prep session before editing source
18953 (when arg
18954 (let* ((info (org-babel-get-src-block-info))
18955 (lang (nth 0 info))
18956 (params (nth 2 info))
18957 (session (cdr (assoc :session params))))
18958 (when (and info session) ;; we are in a source-code block with a session
18959 (funcall
18960 (intern (concat "org-babel-prep-session:" lang)) session params))))
18961 (cond ;; proceed with `org-edit-special'
18962 ((save-excursion
18963 (beginning-of-line 1)
18964 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18965 (find-file (org-trim (match-string 1))))
18966 ((org-edit-src-code))
18967 ((org-edit-fixed-width-region))
18968 ((org-at-table.el-p)
18969 (org-edit-src-code))
18970 ((or (org-at-table-p)
18971 (save-excursion
18972 (beginning-of-line 1)
18973 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18974 (call-interactively 'org-table-edit-formulas))
18975 (t (call-interactively 'ffap))))
18977 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18978 (defun org-ctrl-c-ctrl-c (&optional arg)
18979 "Set tags in headline, or update according to changed information at point.
18981 This command does many different things, depending on context:
18983 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18984 this is what we do.
18986 - If the cursor is on a statistics cookie, update it.
18988 - If the cursor is in a headline, prompt for tags and insert them
18989 into the current line, aligned to `org-tags-column'. When called
18990 with prefix arg, realign all tags in the current buffer.
18992 - If the cursor is in one of the special #+KEYWORD lines, this
18993 triggers scanning the buffer for these lines and updating the
18994 information.
18996 - If the cursor is inside a table, realign the table. This command
18997 works even if the automatic table editor has been turned off.
18999 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19000 the entire table.
19002 - If the cursor is at a footnote reference or definition, jump to
19003 the corresponding definition or references, respectively.
19005 - If the cursor is a the beginning of a dynamic block, update it.
19007 - If the current buffer is a capture buffer, close note and file it.
19009 - If the cursor is on a <<<target>>>, update radio targets and
19010 corresponding links in this buffer.
19012 - If the cursor is on a numbered item in a plain list, renumber the
19013 ordered list.
19015 - If the cursor is on a checkbox, toggle it.
19017 - If the cursor is on a code block, evaluate it. The variable
19018 `org-confirm-babel-evaluate' can be used to control prompting
19019 before code block evaluation, by default every code block
19020 evaluation requires confirmation. Code block evaluation can be
19021 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19022 (interactive "P")
19023 (let ((org-enable-table-editor t))
19024 (cond
19025 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19026 org-occur-highlights
19027 org-latex-fragment-image-overlays)
19028 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19029 (org-remove-occur-highlights)
19030 (org-remove-latex-fragment-image-overlays)
19031 (message "Temporary highlights/overlays removed from current buffer"))
19032 ((and (local-variable-p 'org-finish-function (current-buffer))
19033 (fboundp org-finish-function))
19034 (funcall org-finish-function))
19035 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19036 ((org-in-regexp org-ts-regexp-both)
19037 (org-timestamp-change 0 'day))
19038 ((or (looking-at org-property-start-re)
19039 (org-at-property-p))
19040 (call-interactively 'org-property-action))
19041 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19042 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19043 (or (org-at-heading-p) (org-at-item-p)))
19044 (call-interactively 'org-update-statistics-cookies))
19045 ((org-at-heading-p) (call-interactively 'org-set-tags))
19046 ((org-at-table.el-p)
19047 (message "Use C-c ' to edit table.el tables"))
19048 ((org-at-table-p)
19049 (org-table-maybe-eval-formula)
19050 (if arg
19051 (call-interactively 'org-table-recalculate)
19052 (org-table-maybe-recalculate-line))
19053 (call-interactively 'org-table-align)
19054 (orgtbl-send-table 'maybe))
19055 ((or (org-footnote-at-reference-p)
19056 (org-footnote-at-definition-p))
19057 (call-interactively 'org-footnote-action))
19058 ((org-at-item-checkbox-p)
19059 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19060 ;; list only if at top item.
19061 (let* ((cbox (match-string 1))
19062 (struct (org-list-struct))
19063 (old-struct (copy-tree struct))
19064 (parents (org-list-parents-alist struct))
19065 (orderedp (org-entry-get nil "ORDERED"))
19066 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19067 block-item)
19068 ;; Use a light version of `org-toggle-checkbox' to avoid
19069 ;; computing list structure twice.
19070 (let ((new-box (cond
19071 ((equal arg '(16)) "[-]")
19072 ((equal arg '(4)) nil)
19073 ((equal "[X]" cbox) "[ ]")
19074 (t "[X]"))))
19075 (if (and firstp arg)
19076 ;; If at first item of sub-list, remove check-box from
19077 ;; every item at the same level.
19078 (mapc
19079 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19080 (org-list-get-all-items
19081 (point-at-bol) struct (org-list-prevs-alist struct)))
19082 (org-list-set-checkbox (point-at-bol) struct new-box)))
19083 ;; Replicate `org-list-write-struct', while grabbing a return
19084 ;; value from `org-list-struct-fix-box'.
19085 (org-list-struct-fix-ind struct parents 2)
19086 (org-list-struct-fix-item-end struct)
19087 (let ((prevs (org-list-prevs-alist struct)))
19088 (org-list-struct-fix-bul struct prevs)
19089 (org-list-struct-fix-ind struct parents)
19090 (setq block-item
19091 (org-list-struct-fix-box struct parents prevs orderedp)))
19092 (org-list-struct-apply-struct struct old-struct)
19093 (org-update-checkbox-count-maybe)
19094 (when block-item
19095 (message
19096 "Checkboxes were removed due to unchecked box at line %d"
19097 (org-current-line block-item)))
19098 (when firstp (org-list-send-list 'maybe))))
19099 ((org-at-item-p)
19100 ;; Cursor at an item: repair list. Do checkbox related actions
19101 ;; only if function was called with an argument. Send list only
19102 ;; if at top item.
19103 (let* ((struct (org-list-struct))
19104 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19105 old-struct)
19106 (when arg
19107 (setq old-struct (copy-tree struct))
19108 (if firstp
19109 ;; If at first item of sub-list, add check-box to every
19110 ;; item at the same level.
19111 (mapc
19112 (lambda (pos)
19113 (unless (org-list-get-checkbox pos struct)
19114 (org-list-set-checkbox pos struct "[ ]")))
19115 (org-list-get-all-items
19116 (point-at-bol) struct (org-list-prevs-alist struct)))
19117 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19118 (org-list-write-struct
19119 struct (org-list-parents-alist struct) old-struct)
19120 (when arg (org-update-checkbox-count-maybe))
19121 (when firstp (org-list-send-list 'maybe))))
19122 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19123 ;; Dynamic block
19124 (beginning-of-line 1)
19125 (save-excursion (org-update-dblock)))
19126 ((save-excursion
19127 (let ((case-fold-search t))
19128 (beginning-of-line 1)
19129 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19130 (cond
19131 ((or (equal (match-string 1) "TBLFM")
19132 (equal (match-string 1) "tblfm"))
19133 ;; Recalculate the table before this line
19134 (save-excursion
19135 (beginning-of-line 1)
19136 (skip-chars-backward " \r\n\t")
19137 (if (org-at-table-p)
19138 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19140 (let ((org-inhibit-startup-visibility-stuff t)
19141 (org-startup-align-all-tables nil))
19142 (when (boundp 'org-table-coordinate-overlays)
19143 (mapc 'delete-overlay org-table-coordinate-overlays)
19144 (setq org-table-coordinate-overlays nil))
19145 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19146 (message "Local setup has been refreshed"))))
19147 ((org-clock-update-time-maybe))
19149 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19150 (error "C-c C-c can do nothing useful at this location"))))))
19152 (defun org-mode-restart ()
19153 "Restart Org-mode, to scan again for special lines.
19154 Also updates the keyword regular expressions."
19155 (interactive)
19156 (org-mode)
19157 (message "Org-mode restarted"))
19159 (defun org-kill-note-or-show-branches ()
19160 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19161 (interactive)
19162 (if (not org-finish-function)
19163 (progn
19164 (hide-subtree)
19165 (call-interactively 'show-branches))
19166 (let ((org-note-abort t))
19167 (funcall org-finish-function))))
19169 (defun org-return (&optional indent)
19170 "Goto next table row or insert a newline.
19171 Calls `org-table-next-row' or `newline', depending on context.
19172 See the individual commands for more information."
19173 (interactive)
19174 (let (org-ts-what)
19175 (cond
19176 ((or (bobp) (org-in-src-block-p))
19177 (if indent (newline-and-indent) (newline)))
19178 ((org-at-table-p)
19179 (org-table-justify-field-maybe)
19180 (call-interactively 'org-table-next-row))
19181 ;; when `newline-and-indent' is called within a list, make sure
19182 ;; text moved stays inside the item.
19183 ((and (org-in-item-p) indent)
19184 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19185 (progn
19186 (save-match-data (newline))
19187 (org-indent-line-to (length (match-string 0))))
19188 (let ((ind (org-get-indentation)))
19189 (newline)
19190 (if (org-looking-back org-list-end-re)
19191 (org-indent-line)
19192 (org-indent-line-to ind)))))
19193 ((and org-return-follows-link
19194 (org-at-timestamp-p t)
19195 (not (eq org-ts-what 'after)))
19196 (org-follow-timestamp-link))
19197 ((and org-return-follows-link
19198 (let ((tprop (get-text-property (point) 'face)))
19199 (or (eq tprop 'org-link)
19200 (and (listp tprop) (memq 'org-link tprop)))))
19201 (call-interactively 'org-open-at-point))
19202 ((and (org-at-heading-p)
19203 (looking-at
19204 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19205 (org-show-entry)
19206 (end-of-line 1)
19207 (newline))
19208 (t (if indent (newline-and-indent) (newline))))))
19210 (defun org-return-indent ()
19211 "Goto next table row or insert a newline and indent.
19212 Calls `org-table-next-row' or `newline-and-indent', depending on
19213 context. See the individual commands for more information."
19214 (interactive)
19215 (org-return t))
19217 (defun org-ctrl-c-star ()
19218 "Compute table, or change heading status of lines.
19219 Calls `org-table-recalculate' or `org-toggle-heading',
19220 depending on context."
19221 (interactive)
19222 (cond
19223 ((org-at-table-p)
19224 (call-interactively 'org-table-recalculate))
19226 ;; Convert all lines in region to list items
19227 (call-interactively 'org-toggle-heading))))
19229 (defun org-ctrl-c-minus ()
19230 "Insert separator line in table or modify bullet status of line.
19231 Also turns a plain line or a region of lines into list items.
19232 Calls `org-table-insert-hline', `org-toggle-item', or
19233 `org-cycle-list-bullet', depending on context."
19234 (interactive)
19235 (cond
19236 ((org-at-table-p)
19237 (call-interactively 'org-table-insert-hline))
19238 ((org-region-active-p)
19239 (call-interactively 'org-toggle-item))
19240 ((org-in-item-p)
19241 (call-interactively 'org-cycle-list-bullet))
19243 (call-interactively 'org-toggle-item))))
19245 (defun org-toggle-item (arg)
19246 "Convert headings or normal lines to items, items to normal lines.
19247 If there is no active region, only the current line is considered.
19249 If the first non blank line in the region is an headline, convert
19250 all headlines to items, shifting text accordingly.
19252 If it is an item, convert all items to normal lines.
19254 If it is normal text, change region into an item. With a prefix
19255 argument ARG, change each line in region into an item."
19256 (interactive "P")
19257 (let ((shift-text
19258 (function
19259 ;; Shift text in current section to IND, from point to END.
19260 ;; The function leaves point to END line.
19261 (lambda (ind end)
19262 (let ((min-i 1000) (end (copy-marker end)))
19263 ;; First determine the minimum indentation (MIN-I) of
19264 ;; the text.
19265 (save-excursion
19266 (catch 'exit
19267 (while (< (point) end)
19268 (let ((i (org-get-indentation)))
19269 (cond
19270 ;; Skip blank lines and inline tasks.
19271 ((looking-at "^[ \t]*$"))
19272 ((looking-at org-outline-regexp-bol))
19273 ;; We can't find less than 0 indentation.
19274 ((zerop i) (throw 'exit (setq min-i 0)))
19275 ((< i min-i) (setq min-i i))))
19276 (forward-line))))
19277 ;; Then indent each line so that a line indented to
19278 ;; MIN-I becomes indented to IND. Ignore blank lines
19279 ;; and inline tasks in the process.
19280 (let ((delta (- ind min-i)))
19281 (while (< (point) end)
19282 (unless (or (looking-at "^[ \t]*$")
19283 (looking-at org-outline-regexp-bol))
19284 (org-indent-line-to (+ (org-get-indentation) delta)))
19285 (forward-line)))))))
19286 (skip-blanks
19287 (function
19288 ;; Return beginning of first non-blank line, starting from
19289 ;; line at POS.
19290 (lambda (pos)
19291 (save-excursion
19292 (goto-char pos)
19293 (skip-chars-forward " \r\t\n")
19294 (point-at-bol)))))
19295 beg end)
19296 ;; Determine boundaries of changes.
19297 (if (org-region-active-p)
19298 (setq beg (funcall skip-blanks (region-beginning))
19299 end (copy-marker (region-end)))
19300 (setq beg (funcall skip-blanks (point-at-bol))
19301 end (copy-marker (point-at-eol))))
19302 ;; Depending on the starting line, choose an action on the text
19303 ;; between BEG and END.
19304 (org-with-limited-levels
19305 (save-excursion
19306 (goto-char beg)
19307 (cond
19308 ;; Case 1. Start at an item: de-itemize. Note that it only
19309 ;; happens when a region is active: `org-ctrl-c-minus'
19310 ;; would call `org-cycle-list-bullet' otherwise.
19311 ((org-at-item-p)
19312 (while (< (point) end)
19313 (when (org-at-item-p)
19314 (skip-chars-forward " \t")
19315 (delete-region (point) (match-end 0)))
19316 (forward-line)))
19317 ;; Case 2. Start at an heading: convert to items.
19318 ((org-at-heading-p)
19319 (let* ((bul (org-list-bullet-string "-"))
19320 (bul-len (length bul))
19321 ;; Indentation of the first heading. It should be
19322 ;; relative to the indentation of its parent, if any.
19323 (start-ind (save-excursion
19324 (cond
19325 ((not org-adapt-indentation) 0)
19326 ((not (outline-previous-heading)) 0)
19327 (t (length (match-string 0))))))
19328 ;; Level of first heading. Further headings will be
19329 ;; compared to it to determine hierarchy in the list.
19330 (ref-level (org-reduced-level (org-outline-level))))
19331 (while (< (point) end)
19332 (let* ((level (org-reduced-level (org-outline-level)))
19333 (delta (max 0 (- level ref-level))))
19334 ;; If current headline is less indented than the first
19335 ;; one, set it as reference, in order to preserve
19336 ;; subtrees.
19337 (when (< level ref-level) (setq ref-level level))
19338 (replace-match bul t t)
19339 (org-indent-line-to (+ start-ind (* delta bul-len)))
19340 ;; Ensure all text down to END (or SECTION-END) belongs
19341 ;; to the newly created item.
19342 (let ((section-end (save-excursion
19343 (or (outline-next-heading) (point)))))
19344 (forward-line)
19345 (funcall shift-text
19346 (+ start-ind (* (1+ delta) bul-len))
19347 (min end section-end)))))))
19348 ;; Case 3. Normal line with ARG: turn each non-item line into
19349 ;; an item.
19350 (arg
19351 (while (< (point) end)
19352 (unless (or (org-at-heading-p) (org-at-item-p))
19353 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19354 (replace-match
19355 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19356 (forward-line)))
19357 ;; Case 4. Normal line without ARG: make the first line of
19358 ;; region an item, and shift indentation of others
19359 ;; lines to set them as item's body.
19360 (t (let* ((bul (org-list-bullet-string "-"))
19361 (bul-len (length bul))
19362 (ref-ind (org-get-indentation)))
19363 (skip-chars-forward " \t")
19364 (insert bul)
19365 (forward-line)
19366 (while (< (point) end)
19367 ;; Ensure that lines less indented than first one
19368 ;; still get included in item body.
19369 (funcall shift-text
19370 (+ ref-ind bul-len)
19371 (min end (save-excursion (or (outline-next-heading)
19372 (point)))))
19373 (forward-line)))))))))
19375 (defun org-toggle-heading (&optional nstars)
19376 "Convert headings to normal text, or items or text to headings.
19377 If there is no active region, only the current line is considered.
19379 With a \\[universal-argument] prefix, convert the whole list at
19380 point into heading.
19382 In a region:
19384 - If the first non blank line is an headline, remove the stars
19385 from all headlines in the region.
19387 - If it is a normal line turn each and every normal line (i.e. not an
19388 heading or an item) in the region into a heading.
19390 - If it is a plain list item, turn all plain list items into headings.
19392 When converting a line into a heading, the number of stars is chosen
19393 such that the lines become children of the current entry. However,
19394 when a prefix argument is given, its value determines the number of
19395 stars to add."
19396 (interactive "P")
19397 (let ((skip-blanks
19398 (function
19399 ;; Return beginning of first non-blank line, starting from
19400 ;; line at POS.
19401 (lambda (pos)
19402 (save-excursion
19403 (goto-char pos)
19404 (while (org-at-comment-p) (forward-line))
19405 (skip-chars-forward " \r\t\n")
19406 (point-at-bol)))))
19407 beg end toggled)
19408 ;; Determine boundaries of changes. If a universal prefix has
19409 ;; been given, put the list in a region. If region ends at a bol,
19410 ;; do not consider the last line to be in the region.
19412 (when (and current-prefix-arg (org-at-item-p))
19413 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19414 (org-mark-element))
19416 (if (org-region-active-p)
19417 (setq beg (funcall skip-blanks (region-beginning))
19418 end (copy-marker (save-excursion
19419 (goto-char (region-end))
19420 (if (bolp) (point) (point-at-eol)))))
19421 (setq beg (funcall skip-blanks (point-at-bol))
19422 end (copy-marker (point-at-eol))))
19423 ;; Ensure inline tasks don't count as headings.
19424 (org-with-limited-levels
19425 (save-excursion
19426 (goto-char beg)
19427 (cond
19428 ;; Case 1. Started at an heading: de-star headings.
19429 ((org-at-heading-p)
19430 (while (< (point) end)
19431 (when (org-at-heading-p t)
19432 (looking-at org-outline-regexp) (replace-match "")
19433 (setq toggled t))
19434 (forward-line)))
19435 ;; Case 2. Started at an item: change items into headlines.
19436 ;; One star will be added by `org-list-to-subtree'.
19437 ((org-at-item-p)
19438 (let* ((stars (make-string
19439 (if nstars
19440 ;; subtract the star that will be added again by
19441 ;; `org-list-to-subtree'
19442 (1- (prefix-numeric-value current-prefix-arg))
19443 (or (org-current-level) 0))
19444 ?*))
19445 (add-stars
19446 (cond (nstars "") ; stars from prefix only
19447 ((equal stars "") "") ; before first heading
19448 (org-odd-levels-only "*") ; inside heading, odd
19449 (t "")))) ; inside heading, oddeven
19450 (while (< (point) end)
19451 (when (org-at-item-p)
19452 ;; Pay attention to cases when region ends before list.
19453 (let* ((struct (org-list-struct))
19454 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19455 (save-restriction
19456 (narrow-to-region (point) list-end)
19457 (insert
19458 (org-list-to-subtree
19459 (org-list-parse-list t)
19460 '(:istart (concat stars add-stars (funcall get-stars depth))
19461 :icount (concat stars add-stars (funcall get-stars depth)))))))
19462 (setq toggled t))
19463 (forward-line))))
19464 ;; Case 3. Started at normal text: make every line an heading,
19465 ;; skipping headlines and items.
19466 (t (let* ((stars (make-string
19467 (if nstars
19468 (prefix-numeric-value current-prefix-arg)
19469 (or (org-current-level) 0))
19470 ?*))
19471 (add-stars
19472 (cond (nstars "") ; stars from prefix only
19473 ((equal stars "") "*") ; before first heading
19474 (org-odd-levels-only "**") ; inside heading, odd
19475 (t "*"))) ; inside heading, oddeven
19476 (rpl (concat stars add-stars " ")))
19477 (while (< (point) end)
19478 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19479 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19480 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19481 (forward-line)))))))
19482 (unless toggled (message "Cannot toggle heading from here"))))
19484 (defun org-meta-return (&optional arg)
19485 "Insert a new heading or wrap a region in a table.
19486 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19487 See the individual commands for more information."
19488 (interactive "P")
19489 (cond
19490 ((run-hook-with-args-until-success 'org-metareturn-hook))
19491 ((or (org-at-drawer-p) (org-at-property-p))
19492 (newline-and-indent))
19493 ((org-at-table-p)
19494 (call-interactively 'org-table-wrap-region))
19495 (t (call-interactively 'org-insert-heading))))
19497 ;;; Menu entries
19499 (defsubst org-in-subtree-not-table-p ()
19500 "Are we in a subtree and not in a table?"
19501 (and (not (org-before-first-heading-p))
19502 (not (org-at-table-p))))
19504 ;; Define the Org-mode menus
19505 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19506 '("Tbl"
19507 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19508 ["Next Field" org-cycle (org-at-table-p)]
19509 ["Previous Field" org-shifttab (org-at-table-p)]
19510 ["Next Row" org-return (org-at-table-p)]
19511 "--"
19512 ["Blank Field" org-table-blank-field (org-at-table-p)]
19513 ["Edit Field" org-table-edit-field (org-at-table-p)]
19514 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19515 "--"
19516 ("Column"
19517 ["Move Column Left" org-metaleft (org-at-table-p)]
19518 ["Move Column Right" org-metaright (org-at-table-p)]
19519 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19520 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19521 ("Row"
19522 ["Move Row Up" org-metaup (org-at-table-p)]
19523 ["Move Row Down" org-metadown (org-at-table-p)]
19524 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19525 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19526 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19527 "--"
19528 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19529 ("Rectangle"
19530 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19531 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19532 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19533 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19534 "--"
19535 ("Calculate"
19536 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19537 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19538 ["Edit Formulas" org-edit-special (org-at-table-p)]
19539 "--"
19540 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19541 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19542 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19543 "--"
19544 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19545 "--"
19546 ["Sum Column/Rectangle" org-table-sum
19547 (or (org-at-table-p) (org-region-active-p))]
19548 ["Which Column?" org-table-current-column (org-at-table-p)])
19549 ["Debug Formulas"
19550 org-table-toggle-formula-debugger
19551 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19552 ["Show Col/Row Numbers"
19553 org-table-toggle-coordinate-overlays
19554 :style toggle
19555 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19556 "--"
19557 ["Create" org-table-create (and (not (org-at-table-p))
19558 org-enable-table-editor)]
19559 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19560 ["Import from File" org-table-import (not (org-at-table-p))]
19561 ["Export to File" org-table-export (org-at-table-p)]
19562 "--"
19563 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19565 (easy-menu-define org-org-menu org-mode-map "Org menu"
19566 '("Org"
19567 ("Show/Hide"
19568 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19569 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19570 ["Sparse Tree..." org-sparse-tree t]
19571 ["Reveal Context" org-reveal t]
19572 ["Show All" show-all t]
19573 "--"
19574 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19575 "--"
19576 ["New Heading" org-insert-heading t]
19577 ("Navigate Headings"
19578 ["Up" outline-up-heading t]
19579 ["Next" outline-next-visible-heading t]
19580 ["Previous" outline-previous-visible-heading t]
19581 ["Next Same Level" outline-forward-same-level t]
19582 ["Previous Same Level" outline-backward-same-level t]
19583 "--"
19584 ["Jump" org-goto t])
19585 ("Edit Structure"
19586 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19587 "--"
19588 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19589 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19590 "--"
19591 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19592 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19593 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19594 "--"
19595 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19596 "--"
19597 ["Copy visible text" org-copy-visible t]
19598 "--"
19599 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19600 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19601 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19602 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19603 "--"
19604 ["Sort Region/Children" org-sort t]
19605 "--"
19606 ["Convert to odd levels" org-convert-to-odd-levels t]
19607 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19608 ("Editing"
19609 ["Emphasis..." org-emphasize t]
19610 ["Edit Source Example" org-edit-special t]
19611 "--"
19612 ["Footnote new/jump" org-footnote-action t]
19613 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19614 ("Archive"
19615 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19616 "--"
19617 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19618 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19619 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19621 "--"
19622 ("Hyperlinks"
19623 ["Store Link (Global)" org-store-link t]
19624 ["Find existing link to here" org-occur-link-in-agenda-files t]
19625 ["Insert Link" org-insert-link t]
19626 ["Follow Link" org-open-at-point t]
19627 "--"
19628 ["Next link" org-next-link t]
19629 ["Previous link" org-previous-link t]
19630 "--"
19631 ["Descriptive Links"
19632 org-toggle-link-display
19633 :style radio
19634 :selected org-descriptive-links
19636 ["Literal Links"
19637 org-toggle-link-display
19638 :style radio
19639 :selected (not org-descriptive-links)])
19640 "--"
19641 ("TODO Lists"
19642 ["TODO/DONE/-" org-todo t]
19643 ("Select keyword"
19644 ["Next keyword" org-shiftright (org-at-heading-p)]
19645 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19646 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19647 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19648 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19649 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19650 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19651 "--"
19652 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19653 :selected org-enforce-todo-dependencies :style toggle :active t]
19654 "Settings for tree at point"
19655 ["Do Children sequentially" org-toggle-ordered-property :style radio
19656 :selected (org-entry-get nil "ORDERED")
19657 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19658 ["Do Children parallel" org-toggle-ordered-property :style radio
19659 :selected (not (org-entry-get nil "ORDERED"))
19660 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19661 "--"
19662 ["Set Priority" org-priority t]
19663 ["Priority Up" org-shiftup t]
19664 ["Priority Down" org-shiftdown t]
19665 "--"
19666 ["Get news from all feeds" org-feed-update-all t]
19667 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19668 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19669 ("TAGS and Properties"
19670 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19671 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19672 "--"
19673 ["Set property" org-set-property (not (org-before-first-heading-p))]
19674 ["Column view of properties" org-columns t]
19675 ["Insert Column View DBlock" org-insert-columns-dblock t])
19676 ("Dates and Scheduling"
19677 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19678 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19679 ("Change Date"
19680 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19681 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19682 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19683 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19684 ["Compute Time Range" org-evaluate-time-range t]
19685 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19686 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19687 "--"
19688 ["Custom time format" org-toggle-time-stamp-overlays
19689 :style radio :selected org-display-custom-times]
19690 "--"
19691 ["Goto Calendar" org-goto-calendar t]
19692 ["Date from Calendar" org-date-from-calendar t]
19693 "--"
19694 ["Start/Restart Timer" org-timer-start t]
19695 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19696 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19697 ["Insert Timer String" org-timer t]
19698 ["Insert Timer Item" org-timer-item t])
19699 ("Logging work"
19700 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19701 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19702 ["Clock out" org-clock-out t]
19703 ["Clock cancel" org-clock-cancel t]
19704 "--"
19705 ["Mark as default task" org-clock-mark-default-task t]
19706 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19707 ["Goto running clock" org-clock-goto t]
19708 "--"
19709 ["Display times" org-clock-display t]
19710 ["Create clock table" org-clock-report t]
19711 "--"
19712 ["Record DONE time"
19713 (progn (setq org-log-done (not org-log-done))
19714 (message "Switching to %s will %s record a timestamp"
19715 (car org-done-keywords)
19716 (if org-log-done "automatically" "not")))
19717 :style toggle :selected org-log-done])
19718 "--"
19719 ["Agenda Command..." org-agenda t]
19720 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19721 ("File List for Agenda")
19722 ("Special views current file"
19723 ["TODO Tree" org-show-todo-tree t]
19724 ["Check Deadlines" org-check-deadlines t]
19725 ["Timeline" org-timeline t]
19726 ["Tags/Property tree" org-match-sparse-tree t])
19727 "--"
19728 ["Export/Publish..." org-export t]
19729 ("LaTeX"
19730 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19731 :selected org-cdlatex-mode]
19732 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19733 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19734 ["Modify math symbol" org-cdlatex-math-modify
19735 (org-inside-LaTeX-fragment-p)]
19736 ["Insert citation" org-reftex-citation t]
19737 "--"
19738 ["Template for BEAMER" (progn (require 'org-beamer)
19739 (org-insert-beamer-options-template)) t])
19740 "--"
19741 ("MobileOrg"
19742 ["Push Files and Views" org-mobile-push t]
19743 ["Get Captured and Flagged" org-mobile-pull t]
19744 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19745 "--"
19746 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19747 "--"
19748 ("Documentation"
19749 ["Show Version" org-version t]
19750 ["Info Documentation" org-info t])
19751 ("Customize"
19752 ["Browse Org Group" org-customize t]
19753 "--"
19754 ["Expand This Menu" org-create-customize-menu
19755 (fboundp 'customize-menu-create)])
19756 ["Send bug report" org-submit-bug-report t]
19757 "--"
19758 ("Refresh/Reload"
19759 ["Refresh setup current buffer" org-mode-restart t]
19760 ["Reload Org (after update)" org-reload t]
19761 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19764 (defun org-info (&optional node)
19765 "Read documentation for Org-mode in the info system.
19766 With optional NODE, go directly to that node."
19767 (interactive)
19768 (info (format "(org)%s" (or node ""))))
19770 ;;;###autoload
19771 (defun org-submit-bug-report ()
19772 "Submit a bug report on Org-mode via mail.
19774 Don't hesitate to report any problems or inaccurate documentation.
19776 If you don't have setup sending mail from (X)Emacs, please copy the
19777 output buffer into your mail program, as it gives us important
19778 information about your Org-mode version and configuration."
19779 (interactive)
19780 (require 'reporter)
19781 (org-load-modules-maybe)
19782 (org-require-autoloaded-modules)
19783 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19784 (reporter-submit-bug-report
19785 "emacs-orgmode@gnu.org"
19786 (org-version nil 'full)
19787 (let (list)
19788 (save-window-excursion
19789 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19790 (delete-other-windows)
19791 (erase-buffer)
19792 (insert "You are about to submit a bug report to the Org-mode mailing list.
19794 We would like to add your full Org-mode and Outline configuration to the
19795 bug report. This greatly simplifies the work of the maintainer and
19796 other experts on the mailing list.
19798 HOWEVER, some variables you have customized may contain private
19799 information. The names of customers, colleagues, or friends, might
19800 appear in the form of file names, tags, todo states, or search strings.
19801 If you answer yes to the prompt, you might want to check and remove
19802 such private information before sending the email.")
19803 (add-text-properties (point-min) (point-max) '(face org-warning))
19804 (when (yes-or-no-p "Include your Org-mode configuration ")
19805 (mapatoms
19806 (lambda (v)
19807 (and (boundp v)
19808 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19809 (or (and (symbol-value v)
19810 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19811 (and
19812 (get v 'custom-type) (get v 'standard-value)
19813 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19814 (push v list)))))
19815 (kill-buffer (get-buffer "*Warn about privacy*"))
19816 list))
19817 nil nil
19818 "Remember to cover the basics, that is, what you expected to happen and
19819 what in fact did happen. You don't know how to make a good report? See
19821 http://orgmode.org/manual/Feedback.html#Feedback
19823 Your bug report will be posted to the Org-mode mailing list.
19824 ------------------------------------------------------------------------")
19825 (save-excursion
19826 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19827 (replace-match "\\1Bug: \\3 [\\2]")))))
19830 (defun org-install-agenda-files-menu ()
19831 (let ((bl (buffer-list)))
19832 (save-excursion
19833 (while bl
19834 (set-buffer (pop bl))
19835 (if (derived-mode-p 'org-mode) (setq bl nil)))
19836 (when (derived-mode-p 'org-mode)
19837 (easy-menu-change
19838 '("Org") "File List for Agenda"
19839 (append
19840 (list
19841 ["Edit File List" (org-edit-agenda-file-list) t]
19842 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19843 ["Remove Current File from List" org-remove-file t]
19844 ["Cycle through agenda files" org-cycle-agenda-files t]
19845 ["Occur in all agenda files" org-occur-in-agenda-files t]
19846 "--")
19847 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19849 ;;;; Documentation
19851 (defun org-require-autoloaded-modules ()
19852 (interactive)
19853 (mapc 'require
19854 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19855 org-docbook org-exp org-html org-icalendar
19856 org-id org-latex
19857 org-publish org-remember org-table
19858 org-timer org-xoxo)))
19860 ;;;###autoload
19861 (defun org-reload (&optional uncompiled)
19862 "Reload all org lisp files.
19863 With prefix arg UNCOMPILED, load the uncompiled versions."
19864 (interactive "P")
19865 (require 'find-func)
19866 (let* ((file-re "^org\\(-.*\\)?\\.el")
19867 (dir-org (file-name-directory (org-find-library-dir "org")))
19868 (dir-org-contrib (ignore-errors
19869 (file-name-directory
19870 (org-find-library-dir "org-contribdir"))))
19871 (babel-files
19872 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19873 (append (list nil "comint" "eval" "exp" "keys"
19874 "lob" "ref" "table" "tangle")
19875 (delq nil
19876 (mapcar
19877 (lambda (lang)
19878 (when (cdr lang) (symbol-name (car lang))))
19879 org-babel-load-languages)))))
19880 (files
19881 (append babel-files
19882 (and dir-org-contrib
19883 (directory-files dir-org-contrib t file-re))
19884 (directory-files dir-org t file-re)))
19885 (remove-re (concat (if (featurep 'xemacs)
19886 "org-colview" "org-colview-xemacs")
19887 "\\'")))
19888 (setq files (mapcar 'file-name-sans-extension files))
19889 (setq files (mapcar
19890 (lambda (x) (if (string-match remove-re x) nil x))
19891 files))
19892 (setq files (delq nil files))
19893 (mapc
19894 (lambda (f)
19895 (when (featurep (intern (file-name-nondirectory f)))
19896 (if (and (not uncompiled)
19897 (file-exists-p (concat f ".elc")))
19898 (load (concat f ".elc") nil nil 'nosuffix)
19899 (load (concat f ".el") nil nil 'nosuffix))))
19900 files)
19901 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19902 (org-version nil 'full 'message))
19904 ;;;###autoload
19905 (defun org-customize ()
19906 "Call the customize function with org as argument."
19907 (interactive)
19908 (org-load-modules-maybe)
19909 (org-require-autoloaded-modules)
19910 (customize-browse 'org))
19912 (defun org-create-customize-menu ()
19913 "Create a full customization menu for Org-mode, insert it into the menu."
19914 (interactive)
19915 (org-load-modules-maybe)
19916 (org-require-autoloaded-modules)
19917 (if (fboundp 'customize-menu-create)
19918 (progn
19919 (easy-menu-change
19920 '("Org") "Customize"
19921 `(["Browse Org group" org-customize t]
19922 "--"
19923 ,(customize-menu-create 'org)
19924 ["Set" Custom-set t]
19925 ["Save" Custom-save t]
19926 ["Reset to Current" Custom-reset-current t]
19927 ["Reset to Saved" Custom-reset-saved t]
19928 ["Reset to Standard Settings" Custom-reset-standard t]))
19929 (message "\"Org\"-menu now contains full customization menu"))
19930 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19932 ;;;; Miscellaneous stuff
19934 ;;; Generally useful functions
19936 (defun org-get-at-bol (property)
19937 "Get text property PROPERTY at beginning of line."
19938 (get-text-property (point-at-bol) property))
19940 (defun org-find-text-property-in-string (prop s)
19941 "Return the first non-nil value of property PROP in string S."
19942 (or (get-text-property 0 prop s)
19943 (get-text-property (or (next-single-property-change 0 prop s) 0)
19944 prop s)))
19946 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19947 "Display the given MESSAGE as a warning."
19948 (if (fboundp 'display-warning)
19949 (display-warning 'org message
19950 (if (featurep 'xemacs) 'warning :warning))
19951 (let ((buf (get-buffer-create "*Org warnings*")))
19952 (with-current-buffer buf
19953 (goto-char (point-max))
19954 (insert "Warning (Org): " message)
19955 (unless (bolp)
19956 (newline)))
19957 (display-buffer buf)
19958 (sit-for 0))))
19960 (defun org-eval (form)
19961 "Eval FORM and return result."
19962 (condition-case error
19963 (eval form)
19964 (error (format "%%![Error: %s]" error))))
19966 (defun org-in-clocktable-p ()
19967 "Check if the cursor is in a clocktable."
19968 (let ((pos (point)) start)
19969 (save-excursion
19970 (end-of-line 1)
19971 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19972 (setq start (match-beginning 0))
19973 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19974 (>= (match-end 0) pos)
19975 start))))
19977 (defun org-in-commented-line ()
19978 "Is point in a line starting with `#'?"
19979 (equal (char-after (point-at-bol)) ?#))
19981 (defun org-in-indented-comment-line ()
19982 "Is point in a line starting with `#' after some white space?"
19983 (save-excursion
19984 (save-match-data
19985 (goto-char (point-at-bol))
19986 (looking-at "[ \t]*#"))))
19988 (defun org-in-verbatim-emphasis ()
19989 (save-match-data
19990 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19992 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19993 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19994 (if (and marker (marker-buffer marker)
19995 (buffer-live-p (marker-buffer marker)))
19996 (progn
19997 (org-pop-to-buffer-same-window (marker-buffer marker))
19998 (if (or (> marker (point-max)) (< marker (point-min)))
19999 (widen))
20000 (goto-char marker)
20001 (org-show-context 'org-goto))
20002 (if bookmark
20003 (bookmark-jump bookmark)
20004 (error "Cannot find location"))))
20006 (defun org-quote-csv-field (s)
20007 "Quote field for inclusion in CSV material."
20008 (if (string-match "[\",]" s)
20009 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20012 (defun org-force-self-insert (N)
20013 "Needed to enforce self-insert under remapping."
20014 (interactive "p")
20015 (self-insert-command N))
20017 (defun org-string-width (s)
20018 "Compute width of string, ignoring invisible characters.
20019 This ignores character with invisibility property `org-link', and also
20020 characters with property `org-cwidth', because these will become invisible
20021 upon the next fontification round."
20022 (let (b l)
20023 (when (or (eq t buffer-invisibility-spec)
20024 (assq 'org-link buffer-invisibility-spec))
20025 (while (setq b (text-property-any 0 (length s)
20026 'invisible 'org-link s))
20027 (setq s (concat (substring s 0 b)
20028 (substring s (or (next-single-property-change
20029 b 'invisible s) (length s)))))))
20030 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20031 (setq s (concat (substring s 0 b)
20032 (substring s (or (next-single-property-change
20033 b 'org-cwidth s) (length s))))))
20034 (setq l (string-width s) b -1)
20035 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20036 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20039 (defun org-shorten-string (s maxlength)
20040 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20041 If the string is shorter or has length MAXLENGTH, just return the
20042 original string. If it is longer, the functions finds a space in the
20043 string, breaks this string off at that locations and adds three dots
20044 as ellipsis. Including the ellipsis, the string will not be longer
20045 than MAXLENGTH. If finding a good breaking point in the string does
20046 not work, the string is just chopped off in the middle of a word
20047 if necessary."
20048 (if (<= (length s) maxlength)
20050 (let* ((n (max (- maxlength 4) 1))
20051 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20052 (if (string-match re s)
20053 (concat (match-string 1 s) "...")
20054 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20056 (defun org-get-indentation (&optional line)
20057 "Get the indentation of the current line, interpreting tabs.
20058 When LINE is given, assume it represents a line and compute its indentation."
20059 (if line
20060 (if (string-match "^ *" (org-remove-tabs line))
20061 (match-end 0))
20062 (save-excursion
20063 (beginning-of-line 1)
20064 (skip-chars-forward " \t")
20065 (current-column))))
20067 (defun org-get-string-indentation (s)
20068 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20069 (let ((n -1) (i 0) (w tab-width) c)
20070 (catch 'exit
20071 (while (< (setq n (1+ n)) (length s))
20072 (setq c (aref s n))
20073 (cond ((= c ?\ ) (setq i (1+ i)))
20074 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20075 (t (throw 'exit t)))))
20078 (defun org-remove-tabs (s &optional width)
20079 "Replace tabulators in S with spaces.
20080 Assumes that s is a single line, starting in column 0."
20081 (setq width (or width tab-width))
20082 (while (string-match "\t" s)
20083 (setq s (replace-match
20084 (make-string
20085 (- (* width (/ (+ (match-beginning 0) width) width))
20086 (match-beginning 0)) ?\ )
20087 t t s)))
20090 (defun org-fix-indentation (line ind)
20091 "Fix indentation in LINE.
20092 IND is a cons cell with target and minimum indentation.
20093 If the current indentation in LINE is smaller than the minimum,
20094 leave it alone. If it is larger than ind, set it to the target."
20095 (let* ((l (org-remove-tabs line))
20096 (i (org-get-indentation l))
20097 (i1 (car ind)) (i2 (cdr ind)))
20098 (if (>= i i2) (setq l (substring line i2)))
20099 (if (> i1 0)
20100 (concat (make-string i1 ?\ ) l)
20101 l)))
20103 (defun org-remove-indentation (code &optional n)
20104 "Remove the maximum common indentation from the lines in CODE.
20105 N may optionally be the number of spaces to remove."
20106 (with-temp-buffer
20107 (insert code)
20108 (org-do-remove-indentation n)
20109 (buffer-string)))
20111 (defun org-do-remove-indentation (&optional n)
20112 "Remove the maximum common indentation from the buffer."
20113 (untabify (point-min) (point-max))
20114 (let ((min 10000) re)
20115 (if n
20116 (setq min n)
20117 (goto-char (point-min))
20118 (while (re-search-forward "^ *[^ \n]" nil t)
20119 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20120 (unless (or (= min 0) (= min 10000))
20121 (setq re (format "^ \\{%d\\}" min))
20122 (goto-char (point-min))
20123 (while (re-search-forward re nil t)
20124 (replace-match "")
20125 (end-of-line 1))
20126 min)))
20128 (defun org-fill-template (template alist)
20129 "Find each %key of ALIST in TEMPLATE and replace it."
20130 (let ((case-fold-search nil)
20131 entry key value)
20132 (setq alist (sort (copy-sequence alist)
20133 (lambda (a b) (< (length (car a)) (length (car b))))))
20134 (while (setq entry (pop alist))
20135 (setq template
20136 (replace-regexp-in-string
20137 (concat "%" (regexp-quote (car entry)))
20138 (or (cdr entry) "") template t t)))
20139 template))
20141 (defun org-base-buffer (buffer)
20142 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20143 (if (not buffer)
20144 buffer
20145 (or (buffer-base-buffer buffer)
20146 buffer)))
20148 (defun org-trim (s)
20149 "Remove whitespace at beginning and end of string."
20150 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20151 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20154 (defun org-wrap (string &optional width lines)
20155 "Wrap string to either a number of lines, or a width in characters.
20156 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20157 that costs. If there is a word longer than WIDTH, the text is actually
20158 wrapped to the length of that word.
20159 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20160 many lines, whatever width that takes.
20161 The return value is a list of lines, without newlines at the end."
20162 (let* ((words (org-split-string string "[ \t\n]+"))
20163 (maxword (apply 'max (mapcar 'org-string-width words)))
20164 w ll)
20165 (cond (width
20166 (org-do-wrap words (max maxword width)))
20167 (lines
20168 (setq w maxword)
20169 (setq ll (org-do-wrap words maxword))
20170 (if (<= (length ll) lines)
20172 (setq ll words)
20173 (while (> (length ll) lines)
20174 (setq w (1+ w))
20175 (setq ll (org-do-wrap words w)))
20176 ll))
20177 (t (error "Cannot wrap this")))))
20179 (defun org-do-wrap (words width)
20180 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20181 (let (lines line)
20182 (while words
20183 (setq line (pop words))
20184 (while (and words (< (+ (length line) (length (car words))) width))
20185 (setq line (concat line " " (pop words))))
20186 (setq lines (push line lines)))
20187 (nreverse lines)))
20189 (defun org-split-string (string &optional separators)
20190 "Splits STRING into substrings at SEPARATORS.
20191 No empty strings are returned if there are matches at the beginning
20192 and end of string."
20193 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20194 (start 0)
20195 notfirst
20196 (list nil))
20197 (while (and (string-match rexp string
20198 (if (and notfirst
20199 (= start (match-beginning 0))
20200 (< start (length string)))
20201 (1+ start) start))
20202 (< (match-beginning 0) (length string)))
20203 (setq notfirst t)
20204 (or (eq (match-beginning 0) 0)
20205 (and (eq (match-beginning 0) (match-end 0))
20206 (eq (match-beginning 0) start))
20207 (setq list
20208 (cons (substring string start (match-beginning 0))
20209 list)))
20210 (setq start (match-end 0)))
20211 (or (eq start (length string))
20212 (setq list
20213 (cons (substring string start)
20214 list)))
20215 (nreverse list)))
20217 (defun org-quote-vert (s)
20218 "Replace \"|\" with \"\\vert\"."
20219 (while (string-match "|" s)
20220 (setq s (replace-match "\\vert" t t s)))
20223 (defun org-uuidgen-p (s)
20224 "Is S an ID created by UUIDGEN?"
20225 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20227 (defun org-in-src-block-p nil
20228 "Whether point is in a code source block."
20229 (let (ov)
20230 (when (setq ov (overlays-at (point)))
20231 (memq 'org-block-background
20232 (overlay-properties
20233 (car ov))))))
20235 (defun org-context ()
20236 "Return a list of contexts of the current cursor position.
20237 If several contexts apply, all are returned.
20238 Each context entry is a list with a symbol naming the context, and
20239 two positions indicating start and end of the context. Possible
20240 contexts are:
20242 :headline anywhere in a headline
20243 :headline-stars on the leading stars in a headline
20244 :todo-keyword on a TODO keyword (including DONE) in a headline
20245 :tags on the TAGS in a headline
20246 :priority on the priority cookie in a headline
20247 :item on the first line of a plain list item
20248 :item-bullet on the bullet/number of a plain list item
20249 :checkbox on the checkbox in a plain list item
20250 :table in an org-mode table
20251 :table-special on a special filed in a table
20252 :table-table in a table.el table
20253 :clocktable in a clocktable
20254 :src-block in a source block
20255 :link on a hyperlink
20256 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20257 :target on a <<target>>
20258 :radio-target on a <<<radio-target>>>
20259 :latex-fragment on a LaTeX fragment
20260 :latex-preview on a LaTeX fragment with overlaid preview image
20262 This function expects the position to be visible because it uses font-lock
20263 faces as a help to recognize the following contexts: :table-special, :link,
20264 and :keyword."
20265 (let* ((f (get-text-property (point) 'face))
20266 (faces (if (listp f) f (list f)))
20267 (case-fold-search t)
20268 (p (point)) clist o)
20269 ;; First the large context
20270 (cond
20271 ((org-at-heading-p t)
20272 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20273 (when (progn
20274 (beginning-of-line 1)
20275 (looking-at org-todo-line-tags-regexp))
20276 (push (org-point-in-group p 1 :headline-stars) clist)
20277 (push (org-point-in-group p 2 :todo-keyword) clist)
20278 (push (org-point-in-group p 4 :tags) clist))
20279 (goto-char p)
20280 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20281 (if (looking-at "\\[#[A-Z0-9]\\]")
20282 (push (org-point-in-group p 0 :priority) clist)))
20284 ((org-at-item-p)
20285 (push (org-point-in-group p 2 :item-bullet) clist)
20286 (push (list :item (point-at-bol)
20287 (save-excursion (org-end-of-item) (point)))
20288 clist)
20289 (and (org-at-item-checkbox-p)
20290 (push (org-point-in-group p 0 :checkbox) clist)))
20292 ((org-at-table-p)
20293 (push (list :table (org-table-begin) (org-table-end)) clist)
20294 (if (memq 'org-formula faces)
20295 (push (list :table-special
20296 (previous-single-property-change p 'face)
20297 (next-single-property-change p 'face)) clist)))
20298 ((org-at-table-p 'any)
20299 (push (list :table-table) clist)))
20300 (goto-char p)
20302 (let ((case-fold-search t))
20303 ;; New the "medium" contexts: clocktables, source blocks
20304 (cond ((org-in-clocktable-p)
20305 (push (list :clocktable
20306 (and (or (looking-at "#\\+BEGIN: clocktable")
20307 (search-backward "#+BEGIN: clocktable" nil t))
20308 (match-beginning 0))
20309 (and (re-search-forward "#\\+END:?" nil t)
20310 (match-end 0))) clist))
20311 ((org-in-src-block-p)
20312 (push (list :src-block
20313 (and (or (looking-at "#\\+BEGIN_SRC")
20314 (search-backward "#+BEGIN_SRC" nil t))
20315 (match-beginning 0))
20316 (and (search-forward "#+END_SRC" nil t)
20317 (match-beginning 0))) clist))))
20318 (goto-char p)
20320 ;; Now the small context
20321 (cond
20322 ((org-at-timestamp-p)
20323 (push (org-point-in-group p 0 :timestamp) clist))
20324 ((memq 'org-link faces)
20325 (push (list :link
20326 (previous-single-property-change p 'face)
20327 (next-single-property-change p 'face)) clist))
20328 ((memq 'org-special-keyword faces)
20329 (push (list :keyword
20330 (previous-single-property-change p 'face)
20331 (next-single-property-change p 'face)) clist))
20332 ((org-at-target-p)
20333 (push (org-point-in-group p 0 :target) clist)
20334 (goto-char (1- (match-beginning 0)))
20335 (if (looking-at org-radio-target-regexp)
20336 (push (org-point-in-group p 0 :radio-target) clist))
20337 (goto-char p))
20338 ((setq o (car (delq nil
20339 (mapcar
20340 (lambda (x)
20341 (if (memq x org-latex-fragment-image-overlays) x))
20342 (overlays-at (point))))))
20343 (push (list :latex-fragment
20344 (overlay-start o) (overlay-end o)) clist)
20345 (push (list :latex-preview
20346 (overlay-start o) (overlay-end o)) clist))
20347 ((org-inside-LaTeX-fragment-p)
20348 ;; FIXME: positions wrong.
20349 (push (list :latex-fragment (point) (point)) clist)))
20351 (setq clist (nreverse (delq nil clist)))
20352 clist))
20354 ;; FIXME: Compare with at-regexp-p Do we need both?
20355 (defun org-in-regexp (re &optional nlines visually)
20356 "Check if point is inside a match of regexp.
20357 Normally only the current line is checked, but you can include NLINES extra
20358 lines both before and after point into the search.
20359 If VISUALLY is set, require that the cursor is not after the match but
20360 really on, so that the block visually is on the match."
20361 (catch 'exit
20362 (let ((pos (point))
20363 (eol (point-at-eol (+ 1 (or nlines 0))))
20364 (inc (if visually 1 0)))
20365 (save-excursion
20366 (beginning-of-line (- 1 (or nlines 0)))
20367 (while (re-search-forward re eol t)
20368 (if (and (<= (match-beginning 0) pos)
20369 (>= (+ inc (match-end 0)) pos))
20370 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20372 (defun org-at-regexp-p (regexp)
20373 "Is point inside a match of REGEXP in the current line?"
20374 (catch 'exit
20375 (save-excursion
20376 (let ((pos (point)) (end (point-at-eol)))
20377 (beginning-of-line 1)
20378 (while (re-search-forward regexp end t)
20379 (if (and (<= (match-beginning 0) pos)
20380 (>= (match-end 0) pos))
20381 (throw 'exit t)))
20382 nil))))
20384 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20385 "Non-nil when point is between matches of START-RE and END-RE.
20387 Also return a non-nil value when point is on one of the matches.
20389 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20390 buffer positions. Default values are the positions of headlines
20391 surrounding the point.
20393 The functions returns a cons cell whose car (resp. cdr) is the
20394 position before START-RE (resp. after END-RE)."
20395 (save-match-data
20396 (let ((pos (point))
20397 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20398 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20399 beg end)
20400 (save-excursion
20401 ;; Point is on a block when on START-RE or if START-RE can be
20402 ;; found before it...
20403 (and (or (org-at-regexp-p start-re)
20404 (re-search-backward start-re limit-up t))
20405 (setq beg (match-beginning 0))
20406 ;; ... and END-RE after it...
20407 (goto-char (match-end 0))
20408 (re-search-forward end-re limit-down t)
20409 (> (setq end (match-end 0)) pos)
20410 ;; ... without another START-RE in-between.
20411 (goto-char (match-beginning 0))
20412 (not (re-search-backward start-re (1+ beg) t))
20413 ;; Return value.
20414 (cons beg end))))))
20416 (defun org-in-block-p (names)
20417 "Non-nil when point belongs to a block whose name belongs to NAMES.
20419 NAMES is a list of strings containing names of blocks.
20421 Return first block name matched, or nil. Beware that in case of
20422 nested blocks, the returned name may not belong to the closest
20423 block from point."
20424 (save-match-data
20425 (catch 'exit
20426 (let ((case-fold-search t)
20427 (lim-up (save-excursion (outline-previous-heading)))
20428 (lim-down (save-excursion (outline-next-heading))))
20429 (mapc (lambda (name)
20430 (let ((n (regexp-quote name)))
20431 (when (org-between-regexps-p
20432 (concat "^[ \t]*#\\+begin_" n)
20433 (concat "^[ \t]*#\\+end_" n)
20434 lim-up lim-down)
20435 (throw 'exit n))))
20436 names))
20437 nil)))
20439 (defun org-occur-in-agenda-files (regexp &optional nlines)
20440 "Call `multi-occur' with buffers for all agenda files."
20441 (interactive "sOrg-files matching: \np")
20442 (let* ((files (org-agenda-files))
20443 (tnames (mapcar 'file-truename files))
20444 (extra org-agenda-text-search-extra-files)
20446 (when (eq (car extra) 'agenda-archives)
20447 (setq extra (cdr extra))
20448 (setq files (org-add-archive-files files)))
20449 (while (setq f (pop extra))
20450 (unless (member (file-truename f) tnames)
20451 (add-to-list 'files f 'append)
20452 (add-to-list 'tnames (file-truename f) 'append)))
20453 (multi-occur
20454 (mapcar (lambda (x)
20455 (with-current-buffer
20456 (or (get-file-buffer x) (find-file-noselect x))
20457 (widen)
20458 (current-buffer)))
20459 files)
20460 regexp)))
20462 (if (boundp 'occur-mode-find-occurrence-hook)
20463 ;; Emacs 23
20464 (add-hook 'occur-mode-find-occurrence-hook
20465 (lambda ()
20466 (when (derived-mode-p 'org-mode)
20467 (org-reveal))))
20468 ;; Emacs 22
20469 (defadvice occur-mode-goto-occurrence
20470 (after org-occur-reveal activate)
20471 (and (derived-mode-p 'org-mode) (org-reveal)))
20472 (defadvice occur-mode-goto-occurrence-other-window
20473 (after org-occur-reveal activate)
20474 (and (derived-mode-p 'org-mode) (org-reveal)))
20475 (defadvice occur-mode-display-occurrence
20476 (after org-occur-reveal activate)
20477 (when (derived-mode-p 'org-mode)
20478 (let ((pos (occur-mode-find-occurrence)))
20479 (with-current-buffer (marker-buffer pos)
20480 (save-excursion
20481 (goto-char pos)
20482 (org-reveal)))))))
20484 (defun org-occur-link-in-agenda-files ()
20485 "Create a link and search for it in the agendas.
20486 The link is not stored in `org-stored-links', it is just created
20487 for the search purpose."
20488 (interactive)
20489 (let ((link (condition-case nil
20490 (org-store-link nil)
20491 (error "Unable to create a link to here"))))
20492 (org-occur-in-agenda-files (regexp-quote link))))
20494 (defun org-uniquify (list)
20495 "Remove duplicate elements from LIST."
20496 (let (res)
20497 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20498 res))
20500 (defun org-delete-all (elts list)
20501 "Remove all elements in ELTS from LIST."
20502 (while elts
20503 (setq list (delete (pop elts) list)))
20504 list)
20506 (defun org-count (cl-item cl-seq)
20507 "Count the number of occurrences of ITEM in SEQ.
20508 Taken from `count' in cl-seq.el with all keyword arguments removed."
20509 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20510 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20511 (while (< cl-start cl-end)
20512 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20513 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20514 (setq cl-start (1+ cl-start)))
20515 cl-count))
20517 (defun org-remove-if (predicate seq)
20518 "Remove everything from SEQ that fulfills PREDICATE."
20519 (let (res e)
20520 (while seq
20521 (setq e (pop seq))
20522 (if (not (funcall predicate e)) (push e res)))
20523 (nreverse res)))
20525 (defun org-remove-if-not (predicate seq)
20526 "Remove everything from SEQ that does not fulfill PREDICATE."
20527 (let (res e)
20528 (while seq
20529 (setq e (pop seq))
20530 (if (funcall predicate e) (push e res)))
20531 (nreverse res)))
20533 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20534 "Reduce two-argument FUNCTION across SEQ.
20535 Taken from `reduce' in cl-seq.el with all keyword arguments but
20536 \":initial-value\" removed."
20537 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20538 (cadr (memq :initial-value cl-keys)))
20539 (cl-seq (pop cl-seq))
20540 (t (funcall cl-func)))))
20541 (while cl-seq
20542 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20543 cl-accum))
20545 (defun org-back-over-empty-lines ()
20546 "Move backwards over whitespace, to the beginning of the first empty line.
20547 Returns the number of empty lines passed."
20548 (let ((pos (point)))
20549 (if (cdr (assoc 'heading org-blank-before-new-entry))
20550 (skip-chars-backward " \t\n\r")
20551 (unless (eobp)
20552 (forward-line -1)))
20553 (beginning-of-line 2)
20554 (goto-char (min (point) pos))
20555 (count-lines (point) pos)))
20557 (defun org-skip-whitespace ()
20558 (skip-chars-forward " \t\n\r"))
20560 (defun org-point-in-group (point group &optional context)
20561 "Check if POINT is in match-group GROUP.
20562 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20563 match. If the match group does not exist or point is not inside it,
20564 return nil."
20565 (and (match-beginning group)
20566 (>= point (match-beginning group))
20567 (<= point (match-end group))
20568 (if context
20569 (list context (match-beginning group) (match-end group))
20570 t)))
20572 (defun org-switch-to-buffer-other-window (&rest args)
20573 "Switch to buffer in a second window on the current frame.
20574 In particular, do not allow pop-up frames.
20575 Returns the newly created buffer."
20576 (let (pop-up-frames special-display-buffer-names special-display-regexps
20577 special-display-function)
20578 (apply 'switch-to-buffer-other-window args)))
20580 (defun org-combine-plists (&rest plists)
20581 "Create a single property list from all plists in PLISTS.
20582 The process starts by copying the first list, and then setting properties
20583 from the other lists. Settings in the last list are the most significant
20584 ones and overrule settings in the other lists."
20585 (let ((rtn (copy-sequence (pop plists)))
20586 p v ls)
20587 (while plists
20588 (setq ls (pop plists))
20589 (while ls
20590 (setq p (pop ls) v (pop ls))
20591 (setq rtn (plist-put rtn p v))))
20592 rtn))
20594 (defun org-replace-escapes (string table)
20595 "Replace %-escapes in STRING with values in TABLE.
20596 TABLE is an association list with keys like \"%a\" and string values.
20597 The sequences in STRING may contain normal field width and padding information,
20598 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20599 so values can contain further %-escapes if they are define later in TABLE."
20600 (let ((tbl (copy-alist table))
20601 (case-fold-search nil)
20602 (pchg 0)
20603 e re rpl)
20604 (while (setq e (pop tbl))
20605 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20606 (when (and (cdr e) (string-match re (cdr e)))
20607 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20608 (safe "SREF"))
20609 (add-text-properties 0 3 (list 'sref sref) safe)
20610 (setcdr e (replace-match safe t t (cdr e)))))
20611 (while (string-match re string)
20612 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20613 (cdr e)))
20614 (setq string (replace-match rpl t t string))))
20615 (while (setq pchg (next-property-change pchg string))
20616 (let ((sref (get-text-property pchg 'sref string)))
20617 (when (and sref (string-match "SREF" string pchg))
20618 (setq string (replace-match sref t t string)))))
20619 string))
20621 (defun org-sublist (list start end)
20622 "Return a section of LIST, from START to END.
20623 Counting starts at 1."
20624 (let (rtn (c start))
20625 (setq list (nthcdr (1- start) list))
20626 (while (and list (<= c end))
20627 (push (pop list) rtn)
20628 (setq c (1+ c)))
20629 (nreverse rtn)))
20631 (defun org-find-base-buffer-visiting (file)
20632 "Like `find-buffer-visiting' but always return the base buffer and
20633 not an indirect buffer."
20634 (let ((buf (or (get-file-buffer file)
20635 (find-buffer-visiting file))))
20636 (if buf
20637 (or (buffer-base-buffer buf) buf)
20638 nil)))
20640 (defun org-image-file-name-regexp (&optional extensions)
20641 "Return regexp matching the file names of images.
20642 If EXTENSIONS is given, only match these."
20643 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20644 (image-file-name-regexp)
20645 (let ((image-file-name-extensions
20646 (or extensions
20647 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20648 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20649 (concat "\\."
20650 (regexp-opt (nconc (mapcar 'upcase
20651 image-file-name-extensions)
20652 image-file-name-extensions)
20654 "\\'"))))
20656 (defun org-file-image-p (file &optional extensions)
20657 "Return non-nil if FILE is an image."
20658 (save-match-data
20659 (string-match (org-image-file-name-regexp extensions) file)))
20661 (defun org-get-cursor-date ()
20662 "Return the date at cursor in as a time.
20663 This works in the calendar and in the agenda, anywhere else it just
20664 returns the current time."
20665 (let (date day defd)
20666 (cond
20667 ((eq major-mode 'calendar-mode)
20668 (setq date (calendar-cursor-to-date)
20669 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20670 ((eq major-mode 'org-agenda-mode)
20671 (setq day (get-text-property (point) 'day))
20672 (if day
20673 (setq date (calendar-gregorian-from-absolute day)
20674 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20675 (nth 2 date))))))
20676 (or defd (current-time))))
20678 (defun org-mark-subtree (&optional up)
20679 "Mark the current subtree.
20680 This puts point at the start of the current subtree, and mark at
20681 the end. If a numeric prefix UP is given, move up into the
20682 hierarchy of headlines by UP levels before marking the subtree."
20683 (interactive "P")
20684 (org-with-limited-levels
20685 (cond ((org-at-heading-p) (beginning-of-line))
20686 ((org-before-first-heading-p) (error "Not in a subtree"))
20687 (t (outline-previous-visible-heading 1))))
20688 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20689 (if (org-called-interactively-p 'any)
20690 (call-interactively 'org-mark-element)
20691 (org-mark-element)))
20693 ;;; Indentation
20695 (defun org-indent-line ()
20696 "Indent line depending on context."
20697 (interactive)
20698 (let* ((pos (point))
20699 (itemp (org-at-item-p))
20700 (case-fold-search t)
20701 (org-drawer-regexp (or org-drawer-regexp "\000"))
20702 (inline-task-p (and (featurep 'org-inlinetask)
20703 (org-inlinetask-in-task-p)))
20704 (inline-re (and inline-task-p
20705 (org-inlinetask-outline-regexp)))
20706 column)
20707 (if (and orgstruct-is-++ (eq pos (point)))
20708 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20709 (indent-according-to-mode))
20710 (beginning-of-line 1)
20711 (cond
20712 ;; Headings
20713 ((looking-at org-outline-regexp) (setq column 0))
20714 ;; Included files
20715 ((looking-at "#\\+include:") (setq column 0))
20716 ;; Footnote definition
20717 ((looking-at org-footnote-definition-re) (setq column 0))
20718 ;; Literal examples
20719 ((looking-at "[ \t]*:\\( \\|$\\)")
20720 (setq column (org-get-indentation))) ; do nothing
20721 ;; Lists
20722 ((ignore-errors (goto-char (org-in-item-p)))
20723 (setq column (if itemp
20724 (org-get-indentation)
20725 (org-list-item-body-column (point))))
20726 (goto-char pos))
20727 ;; Drawers
20728 ((and (looking-at "[ \t]*:END:")
20729 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20730 (save-excursion
20731 (goto-char (1- (match-beginning 1)))
20732 (setq column (current-column))))
20733 ;; Special blocks
20734 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20735 (save-excursion
20736 (re-search-backward
20737 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20738 (setq column (org-get-indentation (match-string 0))))
20739 ((and (not (looking-at "[ \t]*#\\+begin_"))
20740 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20741 (save-excursion
20742 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20743 (setq column
20744 (cond ((equal (downcase (match-string 1)) "src")
20745 ;; src blocks: let `org-edit-src-exit' handle them
20746 (org-get-indentation))
20747 ((equal (downcase (match-string 1)) "example")
20748 (max (org-get-indentation)
20749 (org-get-indentation (match-string 0))))
20751 (org-get-indentation (match-string 0))))))
20752 ;; This line has nothing special, look at the previous relevant
20753 ;; line to compute indentation
20755 (beginning-of-line 0)
20756 (while (and (not (bobp))
20757 (not (looking-at org-drawer-regexp))
20758 ;; When point started in an inline task, do not move
20759 ;; above task starting line.
20760 (not (and inline-task-p (looking-at inline-re)))
20761 ;; Skip drawers, blocks, empty lines, verbatim,
20762 ;; comments, tables, footnotes definitions, lists,
20763 ;; inline tasks.
20764 (or (and (looking-at "[ \t]*:END:")
20765 (re-search-backward org-drawer-regexp nil t))
20766 (and (looking-at "[ \t]*#\\+end_")
20767 (re-search-backward "[ \t]*#\\+begin_"nil t))
20768 (looking-at "[ \t]*[\n:#|]")
20769 (looking-at org-footnote-definition-re)
20770 (and (ignore-errors (goto-char (org-in-item-p)))
20771 (goto-char
20772 (org-list-get-top-point (org-list-struct))))
20773 (and (not inline-task-p)
20774 (featurep 'org-inlinetask)
20775 (org-inlinetask-in-task-p)
20776 (or (org-inlinetask-goto-beginning) t))))
20777 (beginning-of-line 0))
20778 (cond
20779 ;; There was an heading above.
20780 ((looking-at "\\*+[ \t]+")
20781 (if (not org-adapt-indentation)
20782 (setq column 0)
20783 (goto-char (match-end 0))
20784 (setq column (current-column))))
20785 ;; A drawer had started and is unfinished
20786 ((looking-at org-drawer-regexp)
20787 (goto-char (1- (match-beginning 1)))
20788 (setq column (current-column)))
20789 ;; Else, nothing noticeable found: get indentation and go on.
20790 (t (setq column (org-get-indentation))))))
20791 ;; Now apply indentation and move cursor accordingly
20792 (goto-char pos)
20793 (if (<= (current-column) (current-indentation))
20794 (org-indent-line-to column)
20795 (save-excursion (org-indent-line-to column)))
20796 ;; Special polishing for properties, see `org-property-format'
20797 (setq column (current-column))
20798 (beginning-of-line 1)
20799 (if (looking-at
20800 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20801 (replace-match (concat (match-string 1)
20802 (format org-property-format
20803 (match-string 2) (match-string 3)))
20804 t t))
20805 (org-move-to-column column))))
20807 (defun org-indent-drawer ()
20808 "Indent the drawer at point."
20809 (interactive)
20810 (let ((p (point))
20811 (e (and (save-excursion (re-search-forward ":END:" nil t))
20812 (match-end 0)))
20813 (folded
20814 (save-excursion
20815 (end-of-line)
20816 (when (overlays-at (point))
20817 (member 'invisible (overlay-properties
20818 (car (overlays-at (point)))))))))
20819 (when folded (org-cycle))
20820 (indent-for-tab-command)
20821 (while (and (move-beginning-of-line 2) (< (point) e))
20822 (indent-for-tab-command))
20823 (goto-char p)
20824 (when folded (org-cycle)))
20825 (message "Drawer at point indented"))
20827 (defun org-indent-block ()
20828 "Indent the block at point."
20829 (interactive)
20830 (let ((p (point))
20831 (case-fold-search t)
20832 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20833 (match-end 0)))
20834 (folded
20835 (save-excursion
20836 (end-of-line)
20837 (when (overlays-at (point))
20838 (member 'invisible (overlay-properties
20839 (car (overlays-at (point)))))))))
20840 (when folded (org-cycle))
20841 (indent-for-tab-command)
20842 (while (and (move-beginning-of-line 2) (< (point) e))
20843 (indent-for-tab-command))
20844 (goto-char p)
20845 (when folded (org-cycle)))
20846 (message "Block at point indented"))
20848 (defun org-indent-region (start end)
20849 "Indent region."
20850 (interactive "r")
20851 (save-excursion
20852 (let ((line-end (org-current-line end)))
20853 (goto-char start)
20854 (while (< (org-current-line) line-end)
20855 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20856 (t (call-interactively 'org-indent-line)))
20857 (move-beginning-of-line 2)))))
20860 ;;; Filling
20862 ;; We use our own fill-paragraph and auto-fill functions.
20864 ;; `org-fill-paragraph' relies on adaptive filling and context
20865 ;; checking. Appropriate `fill-prefix' is computed with
20866 ;; `org-adaptive-fill-function'.
20868 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20869 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20870 ;; `org-adaptive-fill-function' value. Internally,
20871 ;; `org-comment-line-break-function' breaks the line.
20873 ;; `org-setup-filling' installs filling and auto-filling related
20874 ;; variables during `org-mode' initialization.
20876 (defun org-setup-filling ()
20877 (interactive)
20878 ;; Prevent auto-fill from inserting unwanted new items.
20879 (when (boundp 'fill-nobreak-predicate)
20880 (org-set-local
20881 'fill-nobreak-predicate
20882 (org-uniquify
20883 (append fill-nobreak-predicate
20884 '(org-fill-paragraph-separate-nobreak-p
20885 org-fill-line-break-nobreak-p)))))
20886 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20887 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20888 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20889 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20891 (defvar org-element-paragraph-separate) ; org-element.el
20892 (defun org-fill-paragraph-separate-nobreak-p ()
20893 "Non-nil when a line break at point would insert a new item."
20894 (looking-at (substring org-element-paragraph-separate 1)))
20896 (defun org-fill-line-break-nobreak-p ()
20897 "Non-nil when a line break at point would create an Org line break."
20898 (save-excursion
20899 (skip-chars-backward "[ \t]")
20900 (skip-chars-backward "\\\\")
20901 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20903 (declare-function message-in-body-p "message" ())
20904 (defvar org-element--affiliated-re) ; From org-element.el
20905 (defun org-adaptive-fill-function ()
20906 "Compute a fill prefix for the current line.
20907 Return fill prefix, as a string, or nil if current line isn't
20908 meant to be filled."
20909 (org-with-wide-buffer
20910 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
20911 ;; FIXME: This is really the job of orgstruct++-mode
20912 (let* ((p (line-beginning-position))
20913 (element (save-excursion (beginning-of-line)
20914 (org-element-at-point)))
20915 (type (org-element-type element))
20916 (post-affiliated
20917 (save-excursion
20918 (goto-char (org-element-property :begin element))
20919 (while (looking-at org-element--affiliated-re) (forward-line))
20920 (point))))
20921 (unless (< p post-affiliated)
20922 (case type
20923 (comment (looking-at "[ \t]*# ?") (match-string 0))
20924 (footnote-definition "")
20925 ((item plain-list)
20926 (make-string (org-list-item-body-column post-affiliated) ? ))
20927 (paragraph
20928 ;; Fill prefix is usually the same as the current line,
20929 ;; except if the paragraph is at the beginning of an item.
20930 (let ((parent (org-element-property :parent element)))
20931 (cond ((eq (org-element-type parent) 'item)
20932 (make-string (org-list-item-body-column
20933 (org-element-property :begin parent))
20934 ? ))
20935 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20936 (match-string 0))
20937 (t ""))))
20938 (comment-block
20939 ;; Only fill contents if P is within block boundaries.
20940 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20941 (forward-line)
20942 (point)))
20943 (cend (save-excursion
20944 (goto-char (org-element-property :end element))
20945 (skip-chars-backward " \r\t\n")
20946 (line-beginning-position))))
20947 (when (and (>= p cbeg) (< p cend))
20948 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20949 (match-string 0)
20950 ""))))))))))
20952 (declare-function message-goto-body "message" ())
20953 (defvar message-cite-prefix-regexp) ; From message.el
20954 (defvar org-element-all-objects) ; From org-element.el
20955 (defun org-fill-paragraph (&optional justify)
20956 "Fill element at point, when applicable.
20958 This function only applies to comment blocks, comments, example
20959 blocks and paragraphs. Also, as a special case, re-align table
20960 when point is at one.
20962 If JUSTIFY is non-nil (interactively, with prefix argument),
20963 justify as well. If `sentence-end-double-space' is non-nil, then
20964 period followed by one space does not end a sentence, so don't
20965 break a line there. The variable `fill-column' controls the
20966 width for filling.
20968 For convenience, when point is at a plain list, an item or
20969 a footnote definition, try to fill the first paragraph within."
20970 ;; Falls back on message-fill-paragraph when necessary
20971 (interactive)
20972 (if (and (derived-mode-p 'message-mode)
20973 (or (not (message-in-body-p))
20974 (save-excursion (move-beginning-of-line 1)
20975 (looking-at message-cite-prefix-regexp))))
20976 (let ((fill-paragraph-function
20977 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
20978 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
20979 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
20980 (paragraph-separate
20981 (cadadr (assoc 'paragraph-separate org-fb-vars))))
20982 (fill-paragraph nil))
20983 (save-excursion
20984 ;; Move to end of line in order to get the first paragraph
20985 ;; within a plain list or a footnote definition.
20986 (end-of-line)
20987 (let ((element (org-element-at-point)))
20988 ;; First check if point is in a blank line at the beginning of
20989 ;; the buffer. In that case, ignore filling.
20990 (if (< (point) (org-element-property :begin element)) t
20991 (case (org-element-type element)
20992 ;; Align Org tables, leave table.el tables as-is.
20993 (table-row (org-table-align) t)
20994 (table
20995 (when (eq (org-element-property :type element) 'org)
20996 (org-table-align))
20998 (paragraph
20999 ;; Paragraphs may contain `line-break' type objects.
21000 (let ((beg (max (point-min)
21001 (org-element-property :contents-begin element)))
21002 (end (min (point-max)
21003 (org-element-property :contents-end element))))
21004 ;; Do nothing if point is at an affiliated keyword.
21005 (if (< (point) beg) t
21006 (when (derived-mode-p 'message-mode)
21007 ;; In `message-mode', do not fill following
21008 ;; citation in current paragraph nor text before
21009 ;; message body.
21010 (let ((body-start (save-excursion (message-goto-body))))
21011 (when body-start (setq beg (max body-start beg))))
21012 (when (save-excursion
21013 (re-search-forward
21014 (concat "^" message-cite-prefix-regexp) end t))
21015 (setq end (match-beginning 0))))
21016 ;; Fill paragraph, taking line breaks into
21017 ;; consideration. For that, slice the paragraph
21018 ;; using line breaks as separators, and fill the
21019 ;; parts in reverse order to avoid messing with
21020 ;; markers.
21021 (save-excursion
21022 (goto-char end)
21023 (mapc
21024 (lambda (pos)
21025 (fill-region-as-paragraph pos (point) justify)
21026 (goto-char pos))
21027 ;; Find the list of ending positions for line
21028 ;; breaks in the current paragraph. Add paragraph
21029 ;; beginning to include first slice.
21030 (nreverse
21031 (cons
21033 (org-element-map
21034 (org-element--parse-objects
21035 beg end nil org-element-all-objects)
21036 'line-break
21037 (lambda (lb) (org-element-property :end lb)))))))
21038 t)))
21039 ;; Contents of `comment-block' type elements should be
21040 ;; filled as plain text, but only if point is within block
21041 ;; markers.
21042 (comment-block
21043 (let* ((case-fold-search t)
21044 (beg (save-excursion
21045 (goto-char (org-element-property :begin element))
21046 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21047 (forward-line)
21048 (point)))
21049 (end (save-excursion
21050 (goto-char (org-element-property :end element))
21051 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21052 (line-beginning-position))))
21053 (when (and (>= (point) beg) (< (point) end))
21054 (fill-region-as-paragraph
21055 (save-excursion
21056 (end-of-line)
21057 (re-search-backward "^[ \t]*$" beg 'move)
21058 (line-beginning-position))
21059 (save-excursion
21060 (beginning-of-line)
21061 (re-search-forward "^[ \t]*$" end 'move)
21062 (line-beginning-position))
21063 justify)))
21065 ;; Fill comments.
21066 (comment (fill-comment-paragraph justify))
21067 ;; Ignore every other element.
21068 (otherwise t)))))))
21070 (defun org-auto-fill-function ()
21071 "Auto-fill function."
21072 ;; Check if auto-filling is meaningful.
21073 (let ((fc (current-fill-column)))
21074 (when (and fc (> (current-column) fc))
21075 (let* ((fill-prefix (org-adaptive-fill-function))
21076 ;; Enforce empty fill prefix, if required. Otherwise, it
21077 ;; will be computed again.
21078 (adaptive-fill-mode (not (equal fill-prefix ""))))
21079 (when fill-prefix (do-auto-fill))))))
21081 (defun org-comment-line-break-function (&optional soft)
21082 "Break line at point and indent, continuing comment if within one.
21083 The inserted newline is marked hard if variable
21084 `use-hard-newlines' is true, unless optional argument SOFT is
21085 non-nil."
21086 (if soft (insert-and-inherit ?\n) (newline 1))
21087 (save-excursion (forward-char -1) (delete-horizontal-space))
21088 (delete-horizontal-space)
21089 (indent-to-left-margin)
21090 (insert-before-markers-and-inherit fill-prefix))
21093 ;;; Comments
21095 ;; Org comments syntax is quite complex. It requires the entire line
21096 ;; to be just a comment. Also, even with the right syntax at the
21097 ;; beginning of line, some some elements (i.e. verse-block or
21098 ;; example-block) don't accept comments. Usual Emacs comment commands
21099 ;; cannot cope with those requirements. Therefore, Org replaces them.
21101 ;; Org still relies on `comment-dwim', but cannot trust
21102 ;; `comment-only-p'. So, `comment-region-function' and
21103 ;; `uncomment-region-function' both point
21104 ;; to`org-comment-or-uncomment-region'. Eventually,
21105 ;; `org-insert-comment' takes care of insertion of comments at the
21106 ;; beginning of line.
21108 ;; `org-setup-comments-handling' install comments related variables
21109 ;; during `org-mode' initialization.
21111 (defun org-setup-comments-handling ()
21112 (interactive)
21113 (org-set-local 'comment-use-syntax nil)
21114 (org-set-local 'comment-start "# ")
21115 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21116 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21117 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21118 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21120 (defun org-insert-comment ()
21121 "Insert an empty comment above current line.
21122 If the line is empty, insert comment at its beginning."
21123 (beginning-of-line)
21124 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21125 (org-indent-line)
21126 (insert "# "))
21128 (defvar comment-empty-lines) ; From newcomment.el.
21129 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21130 "Comment or uncomment each non-blank line in the region.
21131 Uncomment each non-blank line between BEG and END if it only
21132 contains commented lines. Otherwise, comment them."
21133 (save-restriction
21134 ;; Restrict region
21135 (narrow-to-region (save-excursion (goto-char beg)
21136 (skip-chars-forward " \r\t\n" end)
21137 (line-beginning-position))
21138 (save-excursion (goto-char end)
21139 (skip-chars-backward " \r\t\n" beg)
21140 (line-end-position)))
21141 (let ((uncommentp
21142 ;; UNCOMMENTP is non-nil when every non blank line between
21143 ;; BEG and END is a comment.
21144 (save-excursion
21145 (goto-char (point-min))
21146 (while (and (not (eobp))
21147 (let ((element (org-element-at-point)))
21148 (and (eq (org-element-type element) 'comment)
21149 (goto-char (min (point-max)
21150 (org-element-property
21151 :end element)))))))
21152 (eobp))))
21153 (if uncommentp
21154 ;; Only blank lines and comments in region: uncomment it.
21155 (save-excursion
21156 (goto-char (point-min))
21157 (while (not (eobp))
21158 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21159 (replace-match "" nil nil nil 1))
21160 (forward-line)))
21161 ;; Comment each line in region.
21162 (let ((min-indent (point-max)))
21163 ;; First find the minimum indentation across all lines.
21164 (save-excursion
21165 (goto-char (point-min))
21166 (while (and (not (eobp)) (not (zerop min-indent)))
21167 (unless (looking-at "[ \t]*$")
21168 (setq min-indent (min min-indent (current-indentation))))
21169 (forward-line)))
21170 ;; Then loop over all lines.
21171 (save-excursion
21172 (goto-char (point-min))
21173 (while (not (eobp))
21174 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21175 (org-move-to-column min-indent t)
21176 (insert comment-start))
21177 (forward-line))))))))
21180 ;;; Other stuff.
21182 (defun org-toggle-fixed-width-section (arg)
21183 "Toggle the fixed-width export.
21184 If there is no active region, the QUOTE keyword at the current headline is
21185 inserted or removed. When present, it causes the text between this headline
21186 and the next to be exported as fixed-width text, and unmodified.
21187 If there is an active region, this command adds or removes a colon as the
21188 first character of this line. If the first character of a line is a colon,
21189 this line is also exported in fixed-width font."
21190 (interactive "P")
21191 (let* ((cc 0)
21192 (regionp (org-region-active-p))
21193 (beg (if regionp (region-beginning) (point)))
21194 (end (if regionp (region-end)))
21195 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21196 (case-fold-search nil)
21197 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21198 off)
21199 (if regionp
21200 (save-excursion
21201 (goto-char beg)
21202 (setq cc (current-column))
21203 (beginning-of-line 1)
21204 (setq off (looking-at re))
21205 (while (> nlines 0)
21206 (setq nlines (1- nlines))
21207 (beginning-of-line 1)
21208 (cond
21209 (arg
21210 (org-move-to-column cc t)
21211 (insert ": \n")
21212 (forward-line -1))
21213 ((and off (looking-at re))
21214 (replace-match "" t t nil 1))
21215 ((not off) (org-move-to-column cc t) (insert ": ")))
21216 (forward-line 1)))
21217 (save-excursion
21218 (org-back-to-heading)
21219 (cond
21220 ((looking-at (format org-heading-keyword-regexp-format
21221 org-quote-string))
21222 (goto-char (match-end 1))
21223 (looking-at (concat " +" org-quote-string))
21224 (replace-match "" t t)
21225 (when (eolp) (insert " ")))
21226 ((looking-at org-outline-regexp)
21227 (goto-char (match-end 0))
21228 (insert org-quote-string " ")))))))
21230 (defun org-reftex-citation ()
21231 "Use reftex-citation to insert a citation into the buffer.
21232 This looks for a line like
21234 #+BIBLIOGRAPHY: foo plain option:-d
21236 and derives from it that foo.bib is the bibliography file relevant
21237 for this document. It then installs the necessary environment for RefTeX
21238 to work in this buffer and calls `reftex-citation' to insert a citation
21239 into the buffer.
21241 Export of such citations to both LaTeX and HTML is handled by the contributed
21242 package org-exp-bibtex by Taru Karttunen."
21243 (interactive)
21244 (let ((reftex-docstruct-symbol 'rds)
21245 (reftex-cite-format "\\cite{%l}")
21246 rds bib)
21247 (save-excursion
21248 (save-restriction
21249 (widen)
21250 (let ((case-fold-search t)
21251 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21252 (if (not (save-excursion
21253 (or (re-search-forward re nil t)
21254 (re-search-backward re nil t))))
21255 (error "No bibliography defined in file")
21256 (setq bib (concat (match-string 1) ".bib")
21257 rds (list (list 'bib bib)))))))
21258 (call-interactively 'reftex-citation)))
21260 ;;;; Functions extending outline functionality
21262 (defun org-beginning-of-line (&optional arg)
21263 "Go to the beginning of the current line. If that is invisible, continue
21264 to a visible line beginning. This makes the function of C-a more intuitive.
21265 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21266 first attempt, and only move to after the tags when the cursor is already
21267 beyond the end of the headline."
21268 (interactive "P")
21269 (let ((pos (point))
21270 (special (if (consp org-special-ctrl-a/e)
21271 (car org-special-ctrl-a/e)
21272 org-special-ctrl-a/e))
21273 refpos)
21274 (if (org-bound-and-true-p visual-line-mode)
21275 (beginning-of-visual-line 1)
21276 (beginning-of-line 1))
21277 (if (and arg (fboundp 'move-beginning-of-line))
21278 (call-interactively 'move-beginning-of-line)
21279 (if (bobp)
21281 (backward-char 1)
21282 (if (org-truely-invisible-p)
21283 (while (and (not (bobp)) (org-truely-invisible-p))
21284 (backward-char 1)
21285 (beginning-of-line 1))
21286 (forward-char 1))))
21287 (when special
21288 (cond
21289 ((and (looking-at org-complex-heading-regexp)
21290 (= (char-after (match-end 1)) ?\ ))
21291 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21292 (point-at-eol)))
21293 (goto-char
21294 (if (eq special t)
21295 (cond ((> pos refpos) refpos)
21296 ((= pos (point)) refpos)
21297 (t (point)))
21298 (cond ((> pos (point)) (point))
21299 ((not (eq last-command this-command)) (point))
21300 (t refpos)))))
21301 ((org-at-item-p)
21302 ;; Being at an item and not looking at an the item means point
21303 ;; was previously moved to beginning of a visual line, which
21304 ;; doesn't contain the item. Therefore, do nothing special,
21305 ;; just stay here.
21306 (when (looking-at org-list-full-item-re)
21307 ;; Set special position at first white space character after
21308 ;; bullet, and check-box, if any.
21309 (let ((after-bullet
21310 (let ((box (match-end 3)))
21311 (if (not box) (match-end 1)
21312 (let ((after (char-after box)))
21313 (if (and after (= after ? )) (1+ box) box))))))
21314 ;; Special case: Move point to special position when
21315 ;; currently after it or at beginning of line.
21316 (if (eq special t)
21317 (when (or (> pos after-bullet) (= (point) pos))
21318 (goto-char after-bullet))
21319 ;; Reversed case: Move point to special position when
21320 ;; point was already at beginning of line and command is
21321 ;; repeated.
21322 (when (and (= (point) pos) (eq last-command this-command))
21323 (goto-char after-bullet))))))))
21324 (org-no-warnings
21325 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21327 (defun org-end-of-line (&optional arg)
21328 "Go to the end of the line.
21329 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21330 tags on the first attempt, and only move to after the tags when
21331 the cursor is already beyond the end of the headline."
21332 (interactive "P")
21333 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21334 org-special-ctrl-a/e))
21335 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21336 'end-of-visual-line)
21337 ((fboundp 'move-end-of-line) 'move-end-of-line)
21338 (t 'end-of-line))))
21339 (if (or (not special) arg) (call-interactively move-fun)
21340 (let* ((element (save-excursion (beginning-of-line)
21341 (org-element-at-point)))
21342 (type (org-element-type element)))
21343 (cond
21344 ((memq type '(headline inlinetask))
21345 (let ((pos (point)))
21346 (beginning-of-line 1)
21347 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21348 (if (eq special t)
21349 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21350 (goto-char (match-beginning 1))
21351 (goto-char (match-end 0)))
21352 (if (or (< pos (match-end 0))
21353 (not (eq this-command last-command)))
21354 (goto-char (match-end 0))
21355 (goto-char (match-beginning 1))))
21356 (call-interactively move-fun))))
21357 ((org-element-property :hiddenp element)
21358 ;; If element is hidden, `move-end-of-line' would put point
21359 ;; after it. Use `end-of-line' to stay on current line.
21360 (call-interactively 'end-of-line))
21361 (t (call-interactively move-fun)))))
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 (org-bound-and-true-p 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