Run `bookmark-set' within `with-demoted-errors'.
[org-mode.git] / lisp / org.el
blob45dbe2754e87a61713dec52590d219ed1c82fd1c
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-timestamps-up "org-clock" ())
119 (declare-function org-clock-timestamps-down "org-clock" ())
120 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122 (declare-function orgtbl-mode "org-table" (&optional arg))
123 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
124 (declare-function org-beamer-mode "org-beamer" ())
125 (declare-function org-table-edit-field "org-table" (arg))
126 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
127 (declare-function org-id-get-create "org-id" (&optional force))
128 (declare-function org-id-find-id-file "org-id" (id))
129 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
130 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
131 (declare-function org-table-align "org-table" ())
132 (declare-function org-table-paste-rectangle "org-table" ())
133 (declare-function org-table-maybe-eval-formula "org-table" ())
134 (declare-function org-table-maybe-recalculate-line "org-table" ())
136 ;; load languages based on value of `org-babel-load-languages'
137 (defvar org-babel-load-languages)
139 ;;;###autoload
140 (defun org-babel-do-load-languages (sym value)
141 "Load the languages defined in `org-babel-load-languages'."
142 (set-default sym value)
143 (mapc (lambda (pair)
144 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
145 (if active
146 (progn
147 (require (intern (concat "ob-" lang))))
148 (progn
149 (funcall 'fmakunbound
150 (intern (concat "org-babel-execute:" lang)))
151 (funcall 'fmakunbound
152 (intern (concat "org-babel-expand-body:" lang)))))))
153 org-babel-load-languages))
155 (defcustom org-babel-load-languages '((emacs-lisp . t))
156 "Languages which can be evaluated in Org-mode buffers.
157 This list can be used to load support for any of the languages
158 below, note that each language will depend on a different set of
159 system executables and/or Emacs modes. When a language is
160 \"loaded\", then code blocks in that language can be evaluated
161 with `org-babel-execute-src-block' bound by default to C-c
162 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
163 be set to remove code block evaluation from the C-c C-c
164 keybinding. By default only Emacs Lisp (which has no
165 requirements) is loaded."
166 :group 'org-babel
167 :set 'org-babel-do-load-languages
168 :version "24.1"
169 :type '(alist :tag "Babel Languages"
170 :key-type
171 (choice
172 (const :tag "Awk" awk)
173 (const :tag "C" C)
174 (const :tag "R" R)
175 (const :tag "Asymptote" asymptote)
176 (const :tag "Calc" calc)
177 (const :tag "Clojure" clojure)
178 (const :tag "CSS" css)
179 (const :tag "Ditaa" ditaa)
180 (const :tag "Dot" dot)
181 (const :tag "Emacs Lisp" emacs-lisp)
182 (const :tag "Fortran" fortran)
183 (const :tag "Gnuplot" gnuplot)
184 (const :tag "Haskell" haskell)
185 (const :tag "IO" io)
186 (const :tag "Java" java)
187 (const :tag "Javascript" js)
188 (const :tag "LaTeX" latex)
189 (const :tag "Ledger" ledger)
190 (const :tag "Lilypond" lilypond)
191 (const :tag "Lisp" lisp)
192 (const :tag "Maxima" maxima)
193 (const :tag "Matlab" matlab)
194 (const :tag "Mscgen" mscgen)
195 (const :tag "Ocaml" ocaml)
196 (const :tag "Octave" octave)
197 (const :tag "Org" org)
198 (const :tag "Perl" perl)
199 (const :tag "Pico Lisp" picolisp)
200 (const :tag "PlantUML" plantuml)
201 (const :tag "Python" python)
202 (const :tag "Ruby" ruby)
203 (const :tag "Sass" sass)
204 (const :tag "Scala" scala)
205 (const :tag "Scheme" scheme)
206 (const :tag "Screen" screen)
207 (const :tag "Shell Script" sh)
208 (const :tag "Shen" shen)
209 (const :tag "Sql" sql)
210 (const :tag "Sqlite" sqlite))
211 :value-type (boolean :tag "Activate" :value t)))
213 ;;;; Customization variables
214 (defcustom org-clone-delete-id nil
215 "Remove ID property of clones of a subtree.
216 When non-nil, clones of a subtree don't inherit the ID property.
217 Otherwise they inherit the ID property with a new unique
218 identifier."
219 :type 'boolean
220 :version "24.1"
221 :group 'org-id)
223 ;;; Version
224 (require 'org-compat)
225 (org-check-version)
227 ;;;###autoload
228 (defun org-version (&optional here full message)
229 "Show the org-mode version in the echo area.
230 With prefix argument HERE, insert it at point.
231 When FULL is non-nil, use a verbose version string.
232 When MESSAGE is non-nil, display a message with the version."
233 (interactive "P")
234 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
235 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
236 (org-trash (or
237 (and (fboundp 'org-release) (fboundp 'org-git-version))
238 (load (concat org-dir "org-version.el")
239 'noerror 'nomessage 'nosuffix)))
240 (org-version (org-release))
241 (git-version (org-git-version))
242 (version (format "Org-mode version %s (%s @ %s)"
243 org-version
244 git-version
245 (if org-install-dir
246 (if (string= org-dir org-install-dir)
247 org-install-dir
248 (concat "mixed installation! " org-install-dir " and " org-dir))
249 "org-loaddefs.el can not be found!")))
250 (_version (if full version org-version)))
251 (if (org-called-interactively-p 'interactive)
252 (if here
253 (insert version)
254 (message version))
255 (if message (message _version))
256 _version)))
258 (defconst org-version (org-version))
260 ;;; Compatibility constants
262 ;;; The custom variables
264 (defgroup org nil
265 "Outline-based notes management and organizer."
266 :tag "Org"
267 :group 'outlines
268 :group 'calendar)
270 (defcustom org-mode-hook nil
271 "Mode hook for Org-mode, run after the mode was turned on."
272 :group 'org
273 :type 'hook)
275 (defcustom org-load-hook nil
276 "Hook that is run after org.el has been loaded."
277 :group 'org
278 :type 'hook)
280 (defcustom org-log-buffer-setup-hook nil
281 "Hook that is run after an Org log buffer is created."
282 :group 'org
283 :version "24.1"
284 :type 'hook)
286 (defvar org-modules) ; defined below
287 (defvar org-modules-loaded nil
288 "Have the modules been loaded already?")
290 (defun org-load-modules-maybe (&optional force)
291 "Load all extensions listed in `org-modules'."
292 (when (or force (not org-modules-loaded))
293 (mapc (lambda (ext)
294 (condition-case nil (require ext)
295 (error (message "Problems while trying to load feature `%s'" ext))))
296 org-modules)
297 (setq org-modules-loaded t)))
299 (defun org-set-modules (var value)
300 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
301 (set var value)
302 (when (featurep 'org)
303 (org-load-modules-maybe 'force)))
305 (when (org-bound-and-true-p org-modules)
306 (let ((a (member 'org-infojs org-modules)))
307 (and a (setcar a 'org-jsinfo))))
309 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
310 "Modules that should always be loaded together with org.el.
311 If a description starts with <C>, the file is not part of Emacs
312 and loading it will require that you have downloaded and properly installed
313 the org-mode distribution.
315 You can also use this system to load external packages (i.e. neither Org
316 core modules, nor modules from the CONTRIB directory). Just add symbols
317 to the end of the list. If the package is called org-xyz.el, then you need
318 to add the symbol `xyz', and the package must have a call to
320 (provide 'org-xyz)"
321 :group 'org
322 :set 'org-set-modules
323 :type
324 '(set :greedy t
325 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
326 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
327 (const :tag " crypt: Encryption of subtrees" org-crypt)
328 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
329 (const :tag " docview: Links to doc-view buffers" org-docview)
330 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
331 (const :tag " id: Global IDs for identifying entries" org-id)
332 (const :tag " info: Links to Info nodes" org-info)
333 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
334 (const :tag " habit: Track your consistency with habits" org-habit)
335 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
336 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
337 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
338 (const :tag " mew Links to Mew folders/messages" org-mew)
339 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
340 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
341 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
342 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
343 (const :tag " vm: Links to VM folders/messages" org-vm)
344 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
345 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
346 (const :tag " mouse: Additional mouse support" org-mouse)
347 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
349 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
350 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
351 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
352 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
353 (const :tag "C collector: Collect properties into tables" org-collector)
354 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
355 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
356 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
357 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
358 (const :tag "C eval: Include command output as text" org-eval)
359 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
360 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
361 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
362 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
363 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
365 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
367 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
368 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
369 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
370 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
371 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
372 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
373 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
374 (const :tag "C mtags: Support for muse-like tags" org-mtags)
375 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
376 (const :tag "C registry: A registry for Org-mode links" org-registry)
377 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
378 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
379 (const :tag "C secretary: Team management with org-mode" org-secretary)
380 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
381 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
382 (const :tag "C track: Keep up with Org-mode development" org-track)
383 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
384 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
385 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
387 (defcustom org-support-shift-select nil
388 "Non-nil means make shift-cursor commands select text when possible.
390 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
391 start selecting a region, or enlarge regions started in this way.
392 In Org-mode, in special contexts, these same keys are used for
393 other purposes, important enough to compete with shift selection.
394 Org tries to balance these needs by supporting `shift-select-mode'
395 outside these special contexts, under control of this variable.
397 The default of this variable is nil, to avoid confusing behavior. Shifted
398 cursor keys will then execute Org commands in the following contexts:
399 - on a headline, changing TODO state (left/right) and priority (up/down)
400 - on a time stamp, changing the time
401 - in a plain list item, changing the bullet type
402 - in a property definition line, switching between allowed values
403 - in the BEGIN line of a clock table (changing the time block).
404 Outside these contexts, the commands will throw an error.
406 When this variable is t and the cursor is not in a special
407 context, Org-mode will support shift-selection for making and
408 enlarging regions. To make this more effective, the bullet
409 cycling will no longer happen anywhere in an item line, but only
410 if the cursor is exactly on the bullet.
412 If you set this variable to the symbol `always', then the keys
413 will not be special in headlines, property lines, and item lines,
414 to make shift selection work there as well. If this is what you
415 want, you can use the following alternative commands: `C-c C-t'
416 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
417 can be used to switch TODO sets, `C-c -' to cycle item bullet
418 types, and properties can be edited by hand or in column view.
420 However, when the cursor is on a timestamp, shift-cursor commands
421 will still edit the time stamp - this is just too good to give up.
423 XEmacs user should have this variable set to nil, because
424 `shift-select-mode' is in Emacs 23 or later only."
425 :group 'org
426 :type '(choice
427 (const :tag "Never" nil)
428 (const :tag "When outside special context" t)
429 (const :tag "Everywhere except timestamps" always)))
431 (defcustom org-loop-over-headlines-in-active-region nil
432 "Shall some commands act upon headlines in the active region?
434 When set to `t', some commands will be performed in all headlines
435 within the active region.
437 When set to `start-level', some commands will be performed in all
438 headlines within the active region, provided that these headlines
439 are of the same level than the first one.
441 When set to a string, those commands will be performed on the
442 matching headlines within the active region. Such string must be
443 a tags/property/todo match as it is used in the agenda tags view.
445 The list of commands is: `org-schedule', `org-deadline',
446 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
447 `org-archive-to-archive-sibling'. The archiving commands skip
448 already archived entries."
449 :type '(choice (const :tag "Don't loop" nil)
450 (const :tag "All headlines in active region" t)
451 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
452 (string :tag "Tags/Property/Todo matcher"))
453 :version "24.1"
454 :group 'org-todo
455 :group 'org-archive)
457 (defgroup org-startup nil
458 "Options concerning startup of Org-mode."
459 :tag "Org Startup"
460 :group 'org)
462 (defcustom org-startup-folded t
463 "Non-nil means entering Org-mode will switch to OVERVIEW.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
467 #+STARTUP: fold (or `overview', this is equivalent)
468 #+STARTUP: nofold (or `showall', this is equivalent)
469 #+STARTUP: content
470 #+STARTUP: showeverything"
471 :group 'org-startup
472 :type '(choice
473 (const :tag "nofold: show all" nil)
474 (const :tag "fold: overview" t)
475 (const :tag "content: all headlines" content)
476 (const :tag "show everything, even drawers" showeverything)))
478 (defcustom org-startup-truncated t
479 "Non-nil means entering Org-mode will set `truncate-lines'.
480 This is useful since some lines containing links can be very long and
481 uninteresting. Also tables look terrible when wrapped."
482 :group 'org-startup
483 :type 'boolean)
485 (defcustom org-startup-indented nil
486 "Non-nil means turn on `org-indent-mode' on startup.
487 This can also be configured on a per-file basis by adding one of
488 the following lines anywhere in the buffer:
490 #+STARTUP: indent
491 #+STARTUP: noindent"
492 :group 'org-structure
493 :type '(choice
494 (const :tag "Not" nil)
495 (const :tag "Globally (slow on startup in large files)" t)))
497 (defcustom org-use-sub-superscripts t
498 "Non-nil means interpret \"_\" and \"^\" for export.
499 When this option is turned on, you can use TeX-like syntax for sub- and
500 superscripts. Several characters after \"_\" or \"^\" will be
501 considered as a single item - so grouping with {} is normally not
502 needed. For example, the following things will be parsed as single
503 sub- or superscripts.
505 10^24 or 10^tau several digits will be considered 1 item.
506 10^-12 or 10^-tau a leading sign with digits or a word
507 x^2-y^3 will be read as x^2 - y^3, because items are
508 terminated by almost any nonword/nondigit char.
509 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
511 Still, ambiguity is possible - so when in doubt use {} to enclose the
512 sub/superscript. If you set this variable to the symbol `{}',
513 the braces are *required* in order to trigger interpretations as
514 sub/superscript. This can be helpful in documents that need \"_\"
515 frequently in plain text.
517 Not all export backends support this, but HTML does.
519 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
520 :group 'org-startup
521 :group 'org-export-translation
522 :version "24.1"
523 :type '(choice
524 (const :tag "Always interpret" t)
525 (const :tag "Only with braces" {})
526 (const :tag "Never interpret" nil)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
532 (defcustom org-startup-with-beamer-mode nil
533 "Non-nil means turn on `org-beamer-mode' on startup.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
537 #+STARTUP: beamer"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-startup-align-all-tables nil
543 "Non-nil means align all tables when visiting a file.
544 This is useful when the column width in tables is forced with <N> cookies
545 in table fields. Such tables will look correct only after the first re-align.
546 This can also be configured on a per-file basis by adding one of
547 the following lines anywhere in the buffer:
548 #+STARTUP: align
549 #+STARTUP: noalign"
550 :group 'org-startup
551 :type 'boolean)
553 (defcustom org-startup-with-inline-images nil
554 "Non-nil means show inline images when loading a new Org file.
555 This can also be configured on a per-file basis by adding one of
556 the following lines anywhere in the buffer:
557 #+STARTUP: inlineimages
558 #+STARTUP: noinlineimages"
559 :group 'org-startup
560 :version "24.1"
561 :type 'boolean)
563 (defcustom org-insert-mode-line-in-empty-file nil
564 "Non-nil means insert the first line setting Org-mode in empty files.
565 When the function `org-mode' is called interactively in an empty file, this
566 normally means that the file name does not automatically trigger Org-mode.
567 To ensure that the file will always be in Org-mode in the future, a
568 line enforcing Org-mode will be inserted into the buffer, if this option
569 has been set."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-replace-disputed-keys nil
574 "Non-nil means use alternative key bindings for some keys.
575 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
576 These keys are also used by other packages like shift-selection-mode'
577 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
578 If you want to use Org-mode together with one of these other modes,
579 or more generally if you would like to move some Org-mode commands to
580 other keys, set this variable and configure the keys with the variable
581 `org-disputed-keys'.
583 This option is only relevant at load-time of Org-mode, and must be set
584 *before* org.el is loaded. Changing it requires a restart of Emacs to
585 become effective."
586 :group 'org-startup
587 :type 'boolean)
589 (defcustom org-use-extra-keys nil
590 "Non-nil means use extra key sequence definitions for certain commands.
591 This happens automatically if you run XEmacs or if `window-system'
592 is nil. This variable lets you do the same manually. You must
593 set it before loading org.
595 Example: on Carbon Emacs 22 running graphically, with an external
596 keyboard on a Powerbook, the default way of setting M-left might
597 not work for either Alt or ESC. Setting this variable will make
598 it work for ESC."
599 :group 'org-startup
600 :type 'boolean)
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
605 (defcustom org-disputed-keys
606 '(([(shift up)] . [(meta p)])
607 ([(shift down)] . [(meta n)])
608 ([(shift left)] . [(meta -)])
609 ([(shift right)] . [(meta +)])
610 ([(control shift right)] . [(meta shift +)])
611 ([(control shift left)] . [(meta shift -)]))
612 "Keys for which Org-mode and other modes compete.
613 This is an alist, cars are the default keys, second element specifies
614 the alternative to use when `org-replace-disputed-keys' is t.
616 Keys can be specified in any syntax supported by `define-key'.
617 The value of this option takes effect only at Org-mode's startup,
618 therefore you'll have to restart Emacs to apply it after changing."
619 :group 'org-startup
620 :type 'alist)
622 (defun org-key (key)
623 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
624 Or return the original if not disputed.
625 Also apply the translations defined in `org-xemacs-key-equivalents'."
626 (when org-replace-disputed-keys
627 (let* ((nkey (key-description key))
628 (x (org-find-if (lambda (x)
629 (equal (key-description (car x)) nkey))
630 org-disputed-keys)))
631 (setq key (if x (cdr x) key))))
632 (when (featurep 'xemacs)
633 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
634 key)
636 (defun org-find-if (predicate seq)
637 (catch 'exit
638 (while seq
639 (if (funcall predicate (car seq))
640 (throw 'exit (car seq))
641 (pop seq)))))
643 (defun org-defkey (keymap key def)
644 "Define a key, possibly translated, as returned by `org-key'."
645 (define-key keymap (org-key key) def))
647 (defcustom org-ellipsis nil
648 "The ellipsis to use in the Org-mode outline.
649 When nil, just use the standard three dots. When a string, use that instead,
650 When a face, use the standard 3 dots, but with the specified face.
651 The change affects only Org-mode (which will then use its own display table).
652 Changing this requires executing `M-x org-mode' in a buffer to become
653 effective."
654 :group 'org-startup
655 :type '(choice (const :tag "Default" nil)
656 (face :tag "Face" :value org-warning)
657 (string :tag "String" :value "...#")))
659 (defvar org-display-table nil
660 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
662 (defgroup org-keywords nil
663 "Keywords in Org-mode."
664 :tag "Org Keywords"
665 :group 'org)
667 (defcustom org-deadline-string "DEADLINE:"
668 "String to mark deadline entries.
669 A deadline is this string, followed by a time stamp. Should be a word,
670 terminated by a colon. You can insert a schedule keyword and
671 a timestamp with \\[org-deadline].
672 Changes become only effective after restarting Emacs."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-scheduled-string "SCHEDULED:"
677 "String to mark scheduled TODO entries.
678 A schedule is this string, followed by a time stamp. Should be a word,
679 terminated by a colon. You can insert a schedule keyword and
680 a timestamp with \\[org-schedule].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-closed-string "CLOSED:"
686 "String used as the prefix for timestamps logging closing a TODO entry."
687 :group 'org-keywords
688 :type 'string)
690 (defcustom org-clock-string "CLOCK:"
691 "String used as prefix for timestamps clocking work hours on an item."
692 :group 'org-keywords
693 :type 'string)
695 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
696 org-scheduled-string "\\|"
697 org-deadline-string "\\|"
698 org-closed-string "\\|"
699 org-clock-string "\\)")
700 "Matches a line with planning or clock info.")
702 (defcustom org-comment-string "COMMENT"
703 "Entries starting with this keyword will never be exported.
704 An entry can be toggled between COMMENT and normal with
705 \\[org-toggle-comment].
706 Changes become only effective after restarting Emacs."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-quote-string "QUOTE"
711 "Entries starting with this keyword will be exported in fixed-width font.
712 Quoting applies only to the text in the entry following the headline, and does
713 not extend beyond the next headline, even if that is lower level.
714 An entry can be toggled between QUOTE and normal with
715 \\[org-toggle-fixed-width-section]."
716 :group 'org-keywords
717 :type 'string)
719 (defconst org-repeat-re
720 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
721 "Regular expression for specifying repeated events.
722 After a match, group 1 contains the repeat expression.")
724 (defgroup org-structure nil
725 "Options concerning the general structure of Org-mode files."
726 :tag "Org Structure"
727 :group 'org)
729 (defgroup org-reveal-location nil
730 "Options about how to make context of a location visible."
731 :tag "Org Reveal Location"
732 :group 'org-structure)
734 (defconst org-context-choice
735 '(choice
736 (const :tag "Always" t)
737 (const :tag "Never" nil)
738 (repeat :greedy t :tag "Individual contexts"
739 (cons
740 (choice :tag "Context"
741 (const agenda)
742 (const org-goto)
743 (const occur-tree)
744 (const tags-tree)
745 (const link-search)
746 (const mark-goto)
747 (const bookmark-jump)
748 (const isearch)
749 (const default))
750 (boolean))))
751 "Contexts for the reveal options.")
753 (defcustom org-show-hierarchy-above '((default . t))
754 "Non-nil means show full hierarchy when revealing a location.
755 Org-mode often shows locations in an org-mode file which might have
756 been invisible before. When this is set, the hierarchy of headings
757 above the exposed location is shown.
758 Turning this off for example for sparse trees makes them very compact.
759 Instead of t, this can also be an alist specifying this option for different
760 contexts. Valid contexts are
761 agenda when exposing an entry from the agenda
762 org-goto when using the command `org-goto' on key C-c C-j
763 occur-tree when using the command `org-occur' on key C-c /
764 tags-tree when constructing a sparse tree based on tags matches
765 link-search when exposing search matches associated with a link
766 mark-goto when exposing the jump goal of a mark
767 bookmark-jump when exposing a bookmark location
768 isearch when exiting from an incremental search
769 default default for all contexts not set explicitly"
770 :group 'org-reveal-location
771 :type org-context-choice)
773 (defcustom org-show-following-heading '((default . nil))
774 "Non-nil means show following heading when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the heading following the
777 match is shown.
778 Turning this off for example for sparse trees makes them very compact,
779 but makes it harder to edit the location of the match. In such a case,
780 use the command \\[org-reveal] to show more context.
781 Instead of t, this can also be an alist specifying this option for different
782 contexts. See `org-show-hierarchy-above' for valid contexts."
783 :group 'org-reveal-location
784 :type org-context-choice)
786 (defcustom org-show-siblings '((default . nil) (isearch t))
787 "Non-nil means show all sibling heading when revealing a location.
788 Org-mode often shows locations in an org-mode file which might have
789 been invisible before. When this is set, the sibling of the current entry
790 heading are all made visible. If `org-show-hierarchy-above' is t,
791 the same happens on each level of the hierarchy above the current entry.
793 By default this is on for the isearch context, off for all other contexts.
794 Turning this off for example for sparse trees makes them very compact,
795 but makes it harder to edit the location of the match. In such a case,
796 use the command \\[org-reveal] to show more context.
797 Instead of t, this can also be an alist specifying this option for different
798 contexts. See `org-show-hierarchy-above' for valid contexts."
799 :group 'org-reveal-location
800 :type org-context-choice)
802 (defcustom org-show-entry-below '((default . nil))
803 "Non-nil means show the entry below a headline when revealing a location.
804 Org-mode often shows locations in an org-mode file which might have
805 been invisible before. When this is set, the text below the headline that is
806 exposed is also shown.
808 By default this is off for all contexts.
809 Instead of t, this can also be an alist specifying this option for different
810 contexts. See `org-show-hierarchy-above' for valid contexts."
811 :group 'org-reveal-location
812 :type org-context-choice)
814 (defcustom org-indirect-buffer-display 'other-window
815 "How should indirect tree buffers be displayed?
816 This applies to indirect buffers created with the commands
817 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
818 Valid values are:
819 current-window Display in the current window
820 other-window Just display in another window.
821 dedicated-frame Create one new frame, and re-use it each time.
822 new-frame Make a new frame each time. Note that in this case
823 previously-made indirect buffers are kept, and you need to
824 kill these buffers yourself."
825 :group 'org-structure
826 :group 'org-agenda-windows
827 :type '(choice
828 (const :tag "In current window" current-window)
829 (const :tag "In current frame, other window" other-window)
830 (const :tag "Each time a new frame" new-frame)
831 (const :tag "One dedicated frame" dedicated-frame)))
833 (defcustom org-use-speed-commands nil
834 "Non-nil means activate single letter commands at beginning of a headline.
835 This may also be a function to test for appropriate locations where speed
836 commands should be active."
837 :group 'org-structure
838 :type '(choice
839 (const :tag "Never" nil)
840 (const :tag "At beginning of headline stars" t)
841 (function)))
843 (defcustom org-speed-commands-user nil
844 "Alist of additional speed commands.
845 This list will be checked before `org-speed-commands-default'
846 when the variable `org-use-speed-commands' is non-nil
847 and when the cursor is at the beginning of a headline.
848 The car if each entry is a string with a single letter, which must
849 be assigned to `self-insert-command' in the global map.
850 The cdr is either a command to be called interactively, a function
851 to be called, or a form to be evaluated.
852 An entry that is just a list with a single string will be interpreted
853 as a descriptive headline that will be added when listing the speed
854 commands in the Help buffer using the `?' speed command."
855 :group 'org-structure
856 :type '(repeat :value ("k" . ignore)
857 (choice :value ("k" . ignore)
858 (list :tag "Descriptive Headline" (string :tag "Headline"))
859 (cons :tag "Letter and Command"
860 (string :tag "Command letter")
861 (choice
862 (function)
863 (sexp))))))
865 (defgroup org-cycle nil
866 "Options concerning visibility cycling in Org-mode."
867 :tag "Org Cycle"
868 :group 'org-structure)
870 (defcustom org-cycle-skip-children-state-if-no-children t
871 "Non-nil means skip CHILDREN state in entries that don't have any."
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-max-level nil
876 "Maximum level which should still be subject to visibility cycling.
877 Levels higher than this will, for cycling, be treated as text, not a headline.
878 When `org-odd-levels-only' is set, a value of N in this variable actually
879 means 2N-1 stars as the limiting headline.
880 When nil, cycle all levels.
881 Note that the limiting level of cycling is also influenced by
882 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
883 `org-inlinetask-min-level' is, cycling will be limited to levels one less
884 than its value."
885 :group 'org-cycle
886 :type '(choice
887 (const :tag "No limit" nil)
888 (integer :tag "Maximum level")))
890 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
891 "Names of drawers. Drawers are not opened by cycling on the headline above.
892 Drawers only open with a TAB on the drawer line itself. A drawer looks like
893 this:
894 :DRAWERNAME:
895 .....
896 :END:
897 The drawer \"PROPERTIES\" is special for capturing properties through
898 the property API.
900 Drawers can be defined on the per-file basis with a line like:
902 #+DRAWERS: HIDDEN STATE PROPERTIES"
903 :group 'org-structure
904 :group 'org-cycle
905 :type '(repeat (string :tag "Drawer Name")))
907 (defcustom org-hide-block-startup nil
908 "Non-nil means entering Org-mode will fold all blocks.
909 This can also be set in on a per-file basis with
911 #+STARTUP: hideblocks
912 #+STARTUP: showblocks"
913 :group 'org-startup
914 :group 'org-cycle
915 :type 'boolean)
917 (defcustom org-cycle-global-at-bob nil
918 "Cycle globally if cursor is at beginning of buffer and not at a headline.
919 This makes it possible to do global cycling without having to use S-TAB or
920 \\[universal-argument] TAB. For this special case to work, the first line
921 of the buffer must not be a headline -- it may be empty or some other text.
922 When used in this way, `org-cycle-hook' is disabled temporarily to make
923 sure the cursor stays at the beginning of the buffer. When this option is
924 nil, don't do anything special at the beginning of the buffer."
925 :group 'org-cycle
926 :type 'boolean)
928 (defcustom org-cycle-level-after-item/entry-creation t
929 "Non-nil means cycle entry level or item indentation in new empty entries.
931 When the cursor is at the end of an empty headline, i.e with only stars
932 and maybe a TODO keyword, TAB will then switch the entry to become a child,
933 and then all possible ancestor states, before returning to the original state.
934 This makes data entry extremely fast: M-RET to create a new headline,
935 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
937 When the cursor is at the end of an empty plain list item, one TAB will
938 make it a subitem, two or more tabs will back up to make this an item
939 higher up in the item hierarchy."
940 :group 'org-cycle
941 :type 'boolean)
943 (defcustom org-cycle-emulate-tab t
944 "Where should `org-cycle' emulate TAB.
945 nil Never
946 white Only in completely white lines
947 whitestart Only at the beginning of lines, before the first non-white char
948 t Everywhere except in headlines
949 exc-hl-bol Everywhere except at the start of a headline
950 If TAB is used in a place where it does not emulate TAB, the current subtree
951 visibility is cycled."
952 :group 'org-cycle
953 :type '(choice (const :tag "Never" nil)
954 (const :tag "Only in completely white lines" white)
955 (const :tag "Before first char in a line" whitestart)
956 (const :tag "Everywhere except in headlines" t)
957 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
960 (defcustom org-cycle-separator-lines 2
961 "Number of empty lines needed to keep an empty line between collapsed trees.
962 If you leave an empty line between the end of a subtree and the following
963 headline, this empty line is hidden when the subtree is folded.
964 Org-mode will leave (exactly) one empty line visible if the number of
965 empty lines is equal or larger to the number given in this variable.
966 So the default 2 means at least 2 empty lines after the end of a subtree
967 are needed to produce free space between a collapsed subtree and the
968 following headline.
970 If the number is negative, and the number of empty lines is at least -N,
971 all empty lines are shown.
973 Special case: when 0, never leave empty lines in collapsed view."
974 :group 'org-cycle
975 :type 'integer)
976 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
978 (defcustom org-pre-cycle-hook nil
979 "Hook that is run before visibility cycling is happening.
980 The function(s) in this hook must accept a single argument which indicates
981 the new state that will be set right after running this hook. The
982 argument is a symbol. Before a global state change, it can have the values
983 `overview', `content', or `all'. Before a local state change, it can have
984 the values `folded', `children', or `subtree'."
985 :group 'org-cycle
986 :type 'hook)
988 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
989 org-cycle-hide-drawers
990 org-cycle-show-empty-lines
991 org-optimize-window-after-visibility-change)
992 "Hook that is run after `org-cycle' has changed the buffer visibility.
993 The function(s) in this hook must accept a single argument which indicates
994 the new state that was set by the most recent `org-cycle' command. The
995 argument is a symbol. After a global state change, it can have the values
996 `overview', `contents', or `all'. After a local state change, it can have
997 the values `folded', `children', or `subtree'."
998 :group 'org-cycle
999 :type 'hook)
1001 (defgroup org-edit-structure nil
1002 "Options concerning structure editing in Org-mode."
1003 :tag "Org Edit Structure"
1004 :group 'org-structure)
1006 (defcustom org-odd-levels-only nil
1007 "Non-nil means skip even levels and only use odd levels for the outline.
1008 This has the effect that two stars are being added/taken away in
1009 promotion/demotion commands. It also influences how levels are
1010 handled by the exporters.
1011 Changing it requires restart of `font-lock-mode' to become effective
1012 for fontification also in regions already fontified.
1013 You may also set this on a per-file basis by adding one of the following
1014 lines to the buffer:
1016 #+STARTUP: odd
1017 #+STARTUP: oddeven"
1018 :group 'org-edit-structure
1019 :group 'org-appearance
1020 :type 'boolean)
1022 (defcustom org-adapt-indentation t
1023 "Non-nil means adapt indentation to outline node level.
1025 When this variable is set, Org assumes that you write outlines by
1026 indenting text in each node to align with the headline (after the stars).
1027 The following issues are influenced by this variable:
1029 - When this is set and the *entire* text in an entry is indented, the
1030 indentation is increased by one space in a demotion command, and
1031 decreased by one in a promotion command. If any line in the entry
1032 body starts with text at column 0, indentation is not changed at all.
1034 - Property drawers and planning information is inserted indented when
1035 this variable s set. When nil, they will not be indented.
1037 - TAB indents a line relative to context. The lines below a headline
1038 will be indented when this variable is set.
1040 Note that this is all about true indentation, by adding and removing
1041 space characters. See also `org-indent.el' which does level-dependent
1042 indentation in a virtual way, i.e. at display time in Emacs."
1043 :group 'org-edit-structure
1044 :type 'boolean)
1046 (defcustom org-special-ctrl-a/e nil
1047 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1049 When t, `C-a' will bring back the cursor to the beginning of the
1050 headline text, i.e. after the stars and after a possible TODO
1051 keyword. In an item, this will be the position after bullet and
1052 check-box, if any. When the cursor is already at that position,
1053 another `C-a' will bring it to the beginning of the line.
1055 `C-e' will jump to the end of the headline, ignoring the presence
1056 of tags in the headline. A second `C-e' will then jump to the
1057 true end of the line, after any tags. This also means that, when
1058 this variable is non-nil, `C-e' also will never jump beyond the
1059 end of the heading of a folded section, i.e. not after the
1060 ellipses.
1062 When set to the symbol `reversed', the first `C-a' or `C-e' works
1063 normally, going to the true line boundary first. Only a directly
1064 following, identical keypress will bring the cursor to the
1065 special positions.
1067 This may also be a cons cell where the behavior for `C-a' and
1068 `C-e' is set separately."
1069 :group 'org-edit-structure
1070 :type '(choice
1071 (const :tag "off" nil)
1072 (const :tag "on: after stars/bullet and before tags first" t)
1073 (const :tag "reversed: true line boundary first" reversed)
1074 (cons :tag "Set C-a and C-e separately"
1075 (choice :tag "Special C-a"
1076 (const :tag "off" nil)
1077 (const :tag "on: after stars/bullet first" t)
1078 (const :tag "reversed: before stars/bullet first" reversed))
1079 (choice :tag "Special C-e"
1080 (const :tag "off" nil)
1081 (const :tag "on: before tags first" t)
1082 (const :tag "reversed: after tags first" reversed)))))
1083 (if (fboundp 'defvaralias)
1084 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1086 (defcustom org-special-ctrl-k nil
1087 "Non-nil means `C-k' will behave specially in headlines.
1088 When nil, `C-k' will call the default `kill-line' command.
1089 When t, the following will happen while the cursor is in the headline:
1091 - When the cursor is at the beginning of a headline, kill the entire
1092 line and possible the folded subtree below the line.
1093 - When in the middle of the headline text, kill the headline up to the tags.
1094 - When after the headline text, kill the tags."
1095 :group 'org-edit-structure
1096 :type 'boolean)
1098 (defcustom org-ctrl-k-protect-subtree nil
1099 "Non-nil means, do not delete a hidden subtree with C-k.
1100 When set to the symbol `error', simply throw an error when C-k is
1101 used to kill (part-of) a headline that has hidden text behind it.
1102 Any other non-nil value will result in a query to the user, if it is
1103 OK to kill that hidden subtree. When nil, kill without remorse."
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not protect hidden subtrees" nil)
1108 (const :tag "Protect hidden subtrees with a security query" t)
1109 (const :tag "Never kill a hidden subtree with C-k" error)))
1111 (defcustom org-catch-invisible-edits nil
1112 "Check if in invisible region before inserting or deleting a character.
1113 Valid values are:
1115 nil Do not check, so just do invisible edits.
1116 error Throw an error and do nothing.
1117 show Make point visible, and do the requested edit.
1118 show-and-error Make point visible, then throw an error and abort the edit.
1119 smart Make point visible, and do insertion/deletion if it is
1120 adjacent to visible text and the change feels predictable.
1121 Never delete a previously invisible character or add in the
1122 middle or right after an invisible region. Basically, this
1123 allows insertion and backward-delete right before ellipses.
1124 FIXME: maybe in this case we should not even show?"
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not check" nil)
1129 (const :tag "Throw error when trying to edit" error)
1130 (const :tag "Unhide, but do not do the edit" show-and-error)
1131 (const :tag "Show invisible part and do the edit" show)
1132 (const :tag "Be smart and do the right thing" smart)))
1134 (defcustom org-yank-folded-subtrees t
1135 "Non-nil means when yanking subtrees, fold them.
1136 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1137 it starts with a heading and all other headings in it are either children
1138 or siblings, then fold all the subtrees. However, do this only if no
1139 text after the yank would be swallowed into a folded tree by this action."
1140 :group 'org-edit-structure
1141 :type 'boolean)
1143 (defcustom org-yank-adjusted-subtrees nil
1144 "Non-nil means when yanking subtrees, adjust the level.
1145 With this setting, `org-paste-subtree' is used to insert the subtree, see
1146 this function for details."
1147 :group 'org-edit-structure
1148 :type 'boolean)
1150 (defcustom org-M-RET-may-split-line '((default . t))
1151 "Non-nil means M-RET will split the line at the cursor position.
1152 When nil, it will go to the end of the line before making a
1153 new line.
1154 You may also set this option in a different way for different
1155 contexts. Valid contexts are:
1157 headline when creating a new headline
1158 item when creating a new item
1159 table in a table field
1160 default the value to be used for all contexts not explicitly
1161 customized"
1162 :group 'org-structure
1163 :group 'org-table
1164 :type '(choice
1165 (const :tag "Always" t)
1166 (const :tag "Never" nil)
1167 (repeat :greedy t :tag "Individual contexts"
1168 (cons
1169 (choice :tag "Context"
1170 (const headline)
1171 (const item)
1172 (const table)
1173 (const default))
1174 (boolean)))))
1177 (defcustom org-insert-heading-respect-content nil
1178 "Non-nil means insert new headings after the current subtree.
1179 When nil, the new heading is created directly after the current line.
1180 The commands \\[org-insert-heading-respect-content] and
1181 \\[org-insert-todo-heading-respect-content] turn this variable on
1182 for the duration of the command."
1183 :group 'org-structure
1184 :type 'boolean)
1186 (defcustom org-blank-before-new-entry '((heading . auto)
1187 (plain-list-item . auto))
1188 "Should `org-insert-heading' leave a blank line before new heading/item?
1189 The value is an alist, with `heading' and `plain-list-item' as CAR,
1190 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1191 which case Org will look at the surrounding headings/items and try to
1192 make an intelligent decision whether to insert a blank line or not.
1194 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1195 set, the setting here is ignored and no empty line is inserted, to avoid
1196 breaking the list structure."
1197 :group 'org-edit-structure
1198 :type '(list
1199 (cons (const heading)
1200 (choice (const :tag "Never" nil)
1201 (const :tag "Always" t)
1202 (const :tag "Auto" auto)))
1203 (cons (const plain-list-item)
1204 (choice (const :tag "Never" nil)
1205 (const :tag "Always" t)
1206 (const :tag "Auto" auto)))))
1208 (defcustom org-insert-heading-hook nil
1209 "Hook being run after inserting a new heading."
1210 :group 'org-edit-structure
1211 :type 'hook)
1213 (defcustom org-enable-fixed-width-editor t
1214 "Non-nil means lines starting with \":\" are treated as fixed-width.
1215 This currently only means they are never auto-wrapped.
1216 When nil, such lines will be treated like ordinary lines.
1217 See also the QUOTE keyword."
1218 :group 'org-edit-structure
1219 :type 'boolean)
1221 (defcustom org-goto-auto-isearch t
1222 "Non-nil means typing characters in `org-goto' starts incremental search."
1223 :group 'org-edit-structure
1224 :type 'boolean)
1226 (defgroup org-sparse-trees nil
1227 "Options concerning sparse trees in Org-mode."
1228 :tag "Org Sparse Trees"
1229 :group 'org-structure)
1231 (defcustom org-highlight-sparse-tree-matches t
1232 "Non-nil means highlight all matches that define a sparse tree.
1233 The highlights will automatically disappear the next time the buffer is
1234 changed by an edit command."
1235 :group 'org-sparse-trees
1236 :type 'boolean)
1238 (defcustom org-remove-highlights-with-change t
1239 "Non-nil means any change to the buffer will remove temporary highlights.
1240 Such highlights are created by `org-occur' and `org-clock-display'.
1241 When nil, `C-c C-c needs to be used to get rid of the highlights.
1242 The highlights created by `org-preview-latex-fragment' always need
1243 `C-c C-c' to be removed."
1244 :group 'org-sparse-trees
1245 :group 'org-time
1246 :type 'boolean)
1249 (defcustom org-occur-hook '(org-first-headline-recenter)
1250 "Hook that is run after `org-occur' has constructed a sparse tree.
1251 This can be used to recenter the window to show as much of the structure
1252 as possible."
1253 :group 'org-sparse-trees
1254 :type 'hook)
1256 (defgroup org-imenu-and-speedbar nil
1257 "Options concerning imenu and speedbar in Org-mode."
1258 :tag "Org Imenu and Speedbar"
1259 :group 'org-structure)
1261 (defcustom org-imenu-depth 2
1262 "The maximum level for Imenu access to Org-mode headlines.
1263 This also applied for speedbar access."
1264 :group 'org-imenu-and-speedbar
1265 :type 'integer)
1267 (defgroup org-table nil
1268 "Options concerning tables in Org-mode."
1269 :tag "Org Table"
1270 :group 'org)
1272 (defcustom org-enable-table-editor 'optimized
1273 "Non-nil means lines starting with \"|\" are handled by the table editor.
1274 When nil, such lines will be treated like ordinary lines.
1276 When equal to the symbol `optimized', the table editor will be optimized to
1277 do the following:
1278 - Automatic overwrite mode in front of whitespace in table fields.
1279 This makes the structure of the table stay in tact as long as the edited
1280 field does not exceed the column width.
1281 - Minimize the number of realigns. Normally, the table is aligned each time
1282 TAB or RET are pressed to move to another field. With optimization this
1283 happens only if changes to a field might have changed the column width.
1284 Optimization requires replacing the functions `self-insert-command',
1285 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1286 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1287 very good at guessing when a re-align will be necessary, but you can always
1288 force one with \\[org-ctrl-c-ctrl-c].
1290 If you would like to use the optimized version in Org-mode, but the
1291 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1293 This variable can be used to turn on and off the table editor during a session,
1294 but in order to toggle optimization, a restart is required.
1296 See also the variable `org-table-auto-blank-field'."
1297 :group 'org-table
1298 :type '(choice
1299 (const :tag "off" nil)
1300 (const :tag "on" t)
1301 (const :tag "on, optimized" optimized)))
1303 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1304 (version<= emacs-version "24.1"))
1305 "Non-nil means cluster self-insert commands for undo when possible.
1306 If this is set, then, like in the Emacs command loop, 20 consecutive
1307 characters will be undone together.
1308 This is configurable, because there is some impact on typing performance."
1309 :group 'org-table
1310 :type 'boolean)
1312 (defcustom org-table-tab-recognizes-table.el t
1313 "Non-nil means TAB will automatically notice a table.el table.
1314 When it sees such a table, it moves point into it and - if necessary -
1315 calls `table-recognize-table'."
1316 :group 'org-table-editing
1317 :type 'boolean)
1319 (defgroup org-link nil
1320 "Options concerning links in Org-mode."
1321 :tag "Org Link"
1322 :group 'org)
1324 (defvar org-link-abbrev-alist-local nil
1325 "Buffer-local version of `org-link-abbrev-alist', which see.
1326 The value of this is taken from the #+LINK lines.")
1327 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1329 (defcustom org-link-abbrev-alist nil
1330 "Alist of link abbreviations.
1331 The car of each element is a string, to be replaced at the start of a link.
1332 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1333 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1335 [[linkkey:tag][description]]
1337 The 'linkkey' must be a word word, starting with a letter, followed
1338 by letters, numbers, '-' or '_'.
1340 If REPLACE is a string, the tag will simply be appended to create the link.
1341 If the string contains \"%s\", the tag will be inserted there. If the string
1342 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1343 at that point (see the function `url-hexify-string'). If the string contains
1344 the specifier \"%(my-function)\", then the custom function `my-function' will
1345 be invoked: this function takes the tag as its only argument and must return
1346 a string.
1348 REPLACE may also be a function that will be called with the tag as the
1349 only argument to create the link, which should be returned as a string.
1351 See the manual for examples."
1352 :group 'org-link
1353 :type '(repeat
1354 (cons
1355 (string :tag "Protocol")
1356 (choice
1357 (string :tag "Format")
1358 (function)))))
1360 (defcustom org-descriptive-links t
1361 "Non-nil means Org will display descriptive links.
1362 E.g. [[http://orgmode.org][Org website]] will be displayed as
1363 \"Org Website\", hiding the link itself and just displaying its
1364 description. When set to `nil', Org will display the full links
1365 literally.
1367 You can interactively set the value of this variable by calling
1368 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1369 :group 'org-link
1370 :type 'boolean)
1372 (defcustom org-link-file-path-type 'adaptive
1373 "How the path name in file links should be stored.
1374 Valid values are:
1376 relative Relative to the current directory, i.e. the directory of the file
1377 into which the link is being inserted.
1378 absolute Absolute path, if possible with ~ for home directory.
1379 noabbrev Absolute path, no abbreviation of home directory.
1380 adaptive Use relative path for files in the current directory and sub-
1381 directories of it. For other files, use an absolute path."
1382 :group 'org-link
1383 :type '(choice
1384 (const relative)
1385 (const absolute)
1386 (const noabbrev)
1387 (const adaptive)))
1389 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1390 "Types of links that should be activated in Org-mode files.
1391 This is a list of symbols, each leading to the activation of a certain link
1392 type. In principle, it does not hurt to turn on most link types - there may
1393 be a small gain when turning off unused link types. The types are:
1395 bracket The recommended [[link][description]] or [[link]] links with hiding.
1396 angle Links in angular brackets that may contain whitespace like
1397 <bbdb:Carsten Dominik>.
1398 plain Plain links in normal text, no whitespace, like http://google.com.
1399 radio Text that is matched by a radio target, see manual for details.
1400 tag Tag settings in a headline (link to tag search).
1401 date Time stamps (link to calendar).
1402 footnote Footnote labels.
1404 Changing this variable requires a restart of Emacs to become effective."
1405 :group 'org-link
1406 :type '(set :greedy t
1407 (const :tag "Double bracket links" bracket)
1408 (const :tag "Angular bracket links" angle)
1409 (const :tag "Plain text links" plain)
1410 (const :tag "Radio target matches" radio)
1411 (const :tag "Tags" tag)
1412 (const :tag "Timestamps" date)
1413 (const :tag "Footnotes" footnote)))
1415 (defcustom org-make-link-description-function nil
1416 "Function to use for generating link descriptions from links.
1417 When nil, the link location will be used. This function must take
1418 two parameters: the first one is the link, the second one is the
1419 description generated by `org-insert-link'. The function should
1420 return the description to use."
1421 :group 'org-link
1422 :type 'function)
1424 (defgroup org-link-store nil
1425 "Options concerning storing links in Org-mode."
1426 :tag "Org Store Link"
1427 :group 'org-link)
1429 (defcustom org-url-hexify-p t
1430 "When non-nil, hexify URL when creating a link."
1431 :type 'boolean
1432 :version "24.3"
1433 :group 'org-link-store)
1435 (defcustom org-email-link-description-format "Email %c: %.30s"
1436 "Format of the description part of a link to an email or usenet message.
1437 The following %-escapes will be replaced by corresponding information:
1439 %F full \"From\" field
1440 %f name, taken from \"From\" field, address if no name
1441 %T full \"To\" field
1442 %t first name in \"To\" field, address if no name
1443 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1444 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1445 %s subject
1446 %d date
1447 %m message-id.
1449 You may use normal field width specification between the % and the letter.
1450 This is for example useful to limit the length of the subject.
1452 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1453 :group 'org-link-store
1454 :type 'string)
1456 (defcustom org-from-is-user-regexp
1457 (let (r1 r2)
1458 (when (and user-mail-address (not (string= user-mail-address "")))
1459 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1460 (when (and user-full-name (not (string= user-full-name "")))
1461 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1462 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1463 "Regexp matched against the \"From:\" header of an email or usenet message.
1464 It should match if the message is from the user him/herself."
1465 :group 'org-link-store
1466 :type 'regexp)
1468 (defcustom org-context-in-file-links t
1469 "Non-nil means file links from `org-store-link' contain context.
1470 A search string will be added to the file name with :: as separator and
1471 used to find the context when the link is activated by the command
1472 `org-open-at-point'. When this option is t, the entire active region
1473 will be placed in the search string of the file link. If set to a
1474 positive integer, only the first n lines of context will be stored.
1476 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1477 negates this setting for the duration of the command."
1478 :group 'org-link-store
1479 :type '(choice boolean integer))
1481 (defcustom org-keep-stored-link-after-insertion nil
1482 "Non-nil means keep link in list for entire session.
1484 The command `org-store-link' adds a link pointing to the current
1485 location to an internal list. These links accumulate during a session.
1486 The command `org-insert-link' can be used to insert links into any
1487 Org-mode file (offering completion for all stored links). When this
1488 option is nil, every link which has been inserted once using \\[org-insert-link]
1489 will be removed from the list, to make completing the unused links
1490 more efficient."
1491 :group 'org-link-store
1492 :type 'boolean)
1494 (defgroup org-link-follow nil
1495 "Options concerning following links in Org-mode."
1496 :tag "Org Follow Link"
1497 :group 'org-link)
1499 (defcustom org-link-translation-function nil
1500 "Function to translate links with different syntax to Org syntax.
1501 This can be used to translate links created for example by the Planner
1502 or emacs-wiki packages to Org syntax.
1503 The function must accept two parameters, a TYPE containing the link
1504 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1505 which is everything after the link protocol. It should return a cons
1506 with possibly modified values of type and path.
1507 Org contains a function for this, so if you set this variable to
1508 `org-translate-link-from-planner', you should be able follow many
1509 links created by planner."
1510 :group 'org-link-follow
1511 :type 'function)
1513 (defcustom org-follow-link-hook nil
1514 "Hook that is run after a link has been followed."
1515 :group 'org-link-follow
1516 :type 'hook)
1518 (defcustom org-tab-follows-link nil
1519 "Non-nil means on links TAB will follow the link.
1520 Needs to be set before org.el is loaded.
1521 This really should not be used, it does not make sense, and the
1522 implementation is bad."
1523 :group 'org-link-follow
1524 :type 'boolean)
1526 (defcustom org-return-follows-link nil
1527 "Non-nil means on links RET will follow the link."
1528 :group 'org-link-follow
1529 :type 'boolean)
1531 (defcustom org-mouse-1-follows-link
1532 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1533 "Non-nil means mouse-1 on a link will follow the link.
1534 A longer mouse click will still set point. Does not work on XEmacs.
1535 Needs to be set before org.el is loaded."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mark-ring-length 4
1540 "Number of different positions to be recorded in the ring.
1541 Changing this requires a restart of Emacs to work correctly."
1542 :group 'org-link-follow
1543 :type 'integer)
1545 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1546 "Non-nil means internal links in Org files must exactly match a headline.
1547 When nil, the link search tries to match a phrase with all words
1548 in the search text."
1549 :group 'org-link-follow
1550 :version "24.1"
1551 :type '(choice
1552 (const :tag "Use fuzzy text search" nil)
1553 (const :tag "Match only exact headline" t)
1554 (const :tag "Match exact headline or query to create it"
1555 query-to-create)))
1557 (defcustom org-link-frame-setup
1558 '((vm . vm-visit-folder-other-frame)
1559 (vm-imap . vm-visit-imap-folder-other-frame)
1560 (gnus . org-gnus-no-new-news)
1561 (file . find-file-other-window)
1562 (wl . wl-other-frame))
1563 "Setup the frame configuration for following links.
1564 When following a link with Emacs, it may often be useful to display
1565 this link in another window or frame. This variable can be used to
1566 set this up for the different types of links.
1567 For VM, use any of
1568 `vm-visit-folder'
1569 `vm-visit-folder-other-window'
1570 `vm-visit-folder-other-frame'
1571 For Gnus, use any of
1572 `gnus'
1573 `gnus-other-frame'
1574 `org-gnus-no-new-news'
1575 For FILE, use any of
1576 `find-file'
1577 `find-file-other-window'
1578 `find-file-other-frame'
1579 For Wanderlust use any of
1580 `wl'
1581 `wl-other-frame'
1582 For the calendar, use the variable `calendar-setup'.
1583 For BBDB, it is currently only possible to display the matches in
1584 another window."
1585 :group 'org-link-follow
1586 :type '(list
1587 (cons (const vm)
1588 (choice
1589 (const vm-visit-folder)
1590 (const vm-visit-folder-other-window)
1591 (const vm-visit-folder-other-frame)))
1592 (cons (const gnus)
1593 (choice
1594 (const gnus)
1595 (const gnus-other-frame)
1596 (const org-gnus-no-new-news)))
1597 (cons (const file)
1598 (choice
1599 (const find-file)
1600 (const find-file-other-window)
1601 (const find-file-other-frame)))
1602 (cons (const wl)
1603 (choice
1604 (const wl)
1605 (const wl-other-frame)))))
1607 (defcustom org-display-internal-link-with-indirect-buffer nil
1608 "Non-nil means use indirect buffer to display infile links.
1609 Activating internal links (from one location in a file to another location
1610 in the same file) normally just jumps to the location. When the link is
1611 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1612 is displayed in
1613 another window. When this option is set, the other window actually displays
1614 an indirect buffer clone of the current buffer, to avoid any visibility
1615 changes to the current buffer."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-open-non-existing-files nil
1620 "Non-nil means `org-open-file' will open non-existing files.
1621 When nil, an error will be generated.
1622 This variable applies only to external applications because they
1623 might choke on non-existing files. If the link is to a file that
1624 will be opened in Emacs, the variable is ignored."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-open-directory-means-index-dot-org nil
1629 "Non-nil means a link to a directory really means to index.org.
1630 When nil, following a directory link will run dired or open a finder/explorer
1631 window on that directory."
1632 :group 'org-link-follow
1633 :type 'boolean)
1635 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1636 "Function and arguments to call for following mailto links.
1637 This is a list with the first element being a Lisp function, and the
1638 remaining elements being arguments to the function. In string arguments,
1639 %a will be replaced by the address, and %s will be replaced by the subject
1640 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1641 :group 'org-link-follow
1642 :type '(choice
1643 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1644 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1645 (const :tag "message-mail" (message-mail "%a" "%s"))
1646 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1648 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1649 "Non-nil means ask for confirmation before executing shell links.
1650 Shell links can be dangerous: just think about a link
1652 [[shell:rm -rf ~/*][Google Search]]
1654 This link would show up in your Org-mode document as \"Google Search\",
1655 but really it would remove your entire home directory.
1656 Therefore we advise against setting this variable to nil.
1657 Just change it to `y-or-n-p' if you want to confirm with a
1658 single keystroke rather than having to type \"yes\"."
1659 :group 'org-link-follow
1660 :type '(choice
1661 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1662 (const :tag "with y-or-n (faster)" y-or-n-p)
1663 (const :tag "no confirmation (dangerous)" nil)))
1664 (put 'org-confirm-shell-link-function
1665 'safe-local-variable
1666 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1668 (defcustom org-confirm-shell-link-not-regexp ""
1669 "A regexp to skip confirmation for shell links."
1670 :group 'org-link-follow
1671 :version "24.1"
1672 :type 'regexp)
1674 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1675 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1676 Elisp links can be dangerous: just think about a link
1678 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1680 This link would show up in your Org-mode document as \"Google Search\",
1681 but really it would remove your entire home directory.
1682 Therefore we advise against setting this variable to nil.
1683 Just change it to `y-or-n-p' if you want to confirm with a
1684 single keystroke rather than having to type \"yes\"."
1685 :group 'org-link-follow
1686 :type '(choice
1687 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1688 (const :tag "with y-or-n (faster)" y-or-n-p)
1689 (const :tag "no confirmation (dangerous)" nil)))
1690 (put 'org-confirm-shell-link-function
1691 'safe-local-variable
1692 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1694 (defcustom org-confirm-elisp-link-not-regexp ""
1695 "A regexp to skip confirmation for Elisp links."
1696 :group 'org-link-follow
1697 :version "24.1"
1698 :type 'regexp)
1700 (defconst org-file-apps-defaults-gnu
1701 '((remote . emacs)
1702 (system . mailcap)
1703 (t . mailcap))
1704 "Default file applications on a UNIX or GNU/Linux system.
1705 See `org-file-apps'.")
1707 (defconst org-file-apps-defaults-macosx
1708 '((remote . emacs)
1709 (t . "open %s")
1710 (system . "open %s")
1711 ("ps.gz" . "gv %s")
1712 ("eps.gz" . "gv %s")
1713 ("dvi" . "xdvi %s")
1714 ("fig" . "xfig %s"))
1715 "Default file applications on a MacOS X system.
1716 The system \"open\" is known as a default, but we use X11 applications
1717 for some files for which the OS does not have a good default.
1718 See `org-file-apps'.")
1720 (defconst org-file-apps-defaults-windowsnt
1721 (list
1722 '(remote . emacs)
1723 (cons t
1724 (list (if (featurep 'xemacs)
1725 'mswindows-shell-execute
1726 'w32-shell-execute)
1727 "open" 'file))
1728 (cons 'system
1729 (list (if (featurep 'xemacs)
1730 'mswindows-shell-execute
1731 'w32-shell-execute)
1732 "open" 'file)))
1733 "Default file applications on a Windows NT system.
1734 The system \"open\" is used for most files.
1735 See `org-file-apps'.")
1737 (defcustom org-file-apps
1739 (auto-mode . emacs)
1740 ("\\.mm\\'" . default)
1741 ("\\.x?html?\\'" . default)
1742 ("\\.pdf\\'" . default)
1744 "External applications for opening `file:path' items in a document.
1745 Org-mode uses system defaults for different file types, but
1746 you can use this variable to set the application for a given file
1747 extension. The entries in this list are cons cells where the car identifies
1748 files and the cdr the corresponding command. Possible values for the
1749 file identifier are
1750 \"string\" A string as a file identifier can be interpreted in different
1751 ways, depending on its contents:
1753 - Alphanumeric characters only:
1754 Match links with this file extension.
1755 Example: (\"pdf\" . \"evince %s\")
1756 to open PDFs with evince.
1758 - Regular expression: Match links where the
1759 filename matches the regexp. If you want to
1760 use groups here, use shy groups.
1762 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1763 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1764 to open *.html and *.xhtml with firefox.
1766 - Regular expression which contains (non-shy) groups:
1767 Match links where the whole link, including \"::\", and
1768 anything after that, matches the regexp.
1769 In a custom command string, %1, %2, etc. are replaced with
1770 the parts of the link that were matched by the groups.
1771 For backwards compatibility, if a command string is given
1772 that does not use any of the group matches, this case is
1773 handled identically to the second one (i.e. match against
1774 file name only).
1775 In a custom lisp form, you can access the group matches with
1776 (match-string n link).
1778 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1779 to open [[file:document.pdf::5]] with evince at page 5.
1781 `directory' Matches a directory
1782 `remote' Matches a remote file, accessible through tramp or efs.
1783 Remote files most likely should be visited through Emacs
1784 because external applications cannot handle such paths.
1785 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1786 so all files Emacs knows how to handle. Using this with
1787 command `emacs' will open most files in Emacs. Beware that this
1788 will also open html files inside Emacs, unless you add
1789 (\"html\" . default) to the list as well.
1790 t Default for files not matched by any of the other options.
1791 `system' The system command to open files, like `open' on Windows
1792 and Mac OS X, and mailcap under GNU/Linux. This is the command
1793 that will be selected if you call `C-c C-o' with a double
1794 \\[universal-argument] \\[universal-argument] prefix.
1796 Possible values for the command are:
1797 `emacs' The file will be visited by the current Emacs process.
1798 `default' Use the default application for this file type, which is the
1799 association for t in the list, most likely in the system-specific
1800 part.
1801 This can be used to overrule an unwanted setting in the
1802 system-specific variable.
1803 `system' Use the system command for opening files, like \"open\".
1804 This command is specified by the entry whose car is `system'.
1805 Most likely, the system-specific version of this variable
1806 does define this command, but you can overrule/replace it
1807 here.
1808 string A command to be executed by a shell; %s will be replaced
1809 by the path to the file.
1810 sexp A Lisp form which will be evaluated. The file path will
1811 be available in the Lisp variable `file'.
1812 For more examples, see the system specific constants
1813 `org-file-apps-defaults-macosx'
1814 `org-file-apps-defaults-windowsnt'
1815 `org-file-apps-defaults-gnu'."
1816 :group 'org-link-follow
1817 :type '(repeat
1818 (cons (choice :value ""
1819 (string :tag "Extension")
1820 (const :tag "System command to open files" system)
1821 (const :tag "Default for unrecognized files" t)
1822 (const :tag "Remote file" remote)
1823 (const :tag "Links to a directory" directory)
1824 (const :tag "Any files that have Emacs modes"
1825 auto-mode))
1826 (choice :value ""
1827 (const :tag "Visit with Emacs" emacs)
1828 (const :tag "Use default" default)
1829 (const :tag "Use the system command" system)
1830 (string :tag "Command")
1831 (sexp :tag "Lisp form")))))
1833 (defcustom org-doi-server-url "http://dx.doi.org/"
1834 "The URL of the DOI server."
1835 :type 'string
1836 :version "24.3"
1837 :group 'org-link-follow)
1839 (defgroup org-refile nil
1840 "Options concerning refiling entries in Org-mode."
1841 :tag "Org Refile"
1842 :group 'org)
1844 (defcustom org-directory "~/org"
1845 "Directory with org files.
1846 This is just a default location to look for Org files. There is no need
1847 at all to put your files into this directory. It is only used in the
1848 following situations:
1850 1. When a capture template specifies a target file that is not an
1851 absolute path. The path will then be interpreted relative to
1852 `org-directory'
1853 2. When a capture note is filed away in an interactive way (when exiting the
1854 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1855 with `org-directory' as the default path."
1856 :group 'org-refile
1857 :group 'org-remember
1858 :group 'org-capture
1859 :type 'directory)
1861 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1862 "Default target for storing notes.
1863 Used as a fall back file for org-remember.el and org-capture.el, for
1864 templates that do not specify a target file."
1865 :group 'org-refile
1866 :group 'org-remember
1867 :group 'org-capture
1868 :type '(choice
1869 (const :tag "Default from remember-data-file" nil)
1870 file))
1872 (defcustom org-goto-interface 'outline
1873 "The default interface to be used for `org-goto'.
1874 Allowed values are:
1875 outline The interface shows an outline of the relevant file
1876 and the correct heading is found by moving through
1877 the outline or by searching with incremental search.
1878 outline-path-completion Headlines in the current buffer are offered via
1879 completion. This is the interface also used by
1880 the refile command."
1881 :group 'org-refile
1882 :type '(choice
1883 (const :tag "Outline" outline)
1884 (const :tag "Outline-path-completion" outline-path-completion)))
1886 (defcustom org-goto-max-level 5
1887 "Maximum target level when running `org-goto' with refile interface."
1888 :group 'org-refile
1889 :type 'integer)
1891 (defcustom org-reverse-note-order nil
1892 "Non-nil means store new notes at the beginning of a file or entry.
1893 When nil, new notes will be filed to the end of a file or entry.
1894 This can also be a list with cons cells of regular expressions that
1895 are matched against file names, and values."
1896 :group 'org-remember
1897 :group 'org-capture
1898 :group 'org-refile
1899 :type '(choice
1900 (const :tag "Reverse always" t)
1901 (const :tag "Reverse never" nil)
1902 (repeat :tag "By file name regexp"
1903 (cons regexp boolean))))
1905 (defcustom org-log-refile nil
1906 "Information to record when a task is refiled.
1908 Possible values are:
1910 nil Don't add anything
1911 time Add a time stamp to the task
1912 note Prompt for a note and add it with template `org-log-note-headings'
1914 This option can also be set with on a per-file-basis with
1916 #+STARTUP: nologrefile
1917 #+STARTUP: logrefile
1918 #+STARTUP: lognoterefile
1920 You can have local logging settings for a subtree by setting the LOGGING
1921 property to one or more of these keywords.
1923 When bulk-refiling from the agenda, the value `note' is forbidden and
1924 will temporarily be changed to `time'."
1925 :group 'org-refile
1926 :group 'org-progress
1927 :version "24.1"
1928 :type '(choice
1929 (const :tag "No logging" nil)
1930 (const :tag "Record timestamp" time)
1931 (const :tag "Record timestamp with note." note)))
1933 (defcustom org-refile-targets nil
1934 "Targets for refiling entries with \\[org-refile].
1935 This is a list of cons cells. Each cell contains:
1936 - a specification of the files to be considered, either a list of files,
1937 or a symbol whose function or variable value will be used to retrieve
1938 a file name or a list of file names. If you use `org-agenda-files' for
1939 that, all agenda files will be scanned for targets. Nil means consider
1940 headings in the current buffer.
1941 - A specification of how to find candidate refile targets. This may be
1942 any of:
1943 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1944 This tag has to be present in all target headlines, inheritance will
1945 not be considered.
1946 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1947 todo keyword.
1948 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1949 headlines that are refiling targets.
1950 - a cons cell (:level . N). Any headline of level N is considered a target.
1951 Note that, when `org-odd-levels-only' is set, level corresponds to
1952 order in hierarchy, not to the number of stars.
1953 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1954 Note that, when `org-odd-levels-only' is set, level corresponds to
1955 order in hierarchy, not to the number of stars.
1957 Each element of this list generates a set of possible targets.
1958 The union of these sets is presented (with completion) to
1959 the user by `org-refile'.
1961 You can set the variable `org-refile-target-verify-function' to a function
1962 to verify each headline found by the simple criteria above.
1964 When this variable is nil, all top-level headlines in the current buffer
1965 are used, equivalent to the value `((nil . (:level . 1))'."
1966 :group 'org-refile
1967 :type '(repeat
1968 (cons
1969 (choice :value org-agenda-files
1970 (const :tag "All agenda files" org-agenda-files)
1971 (const :tag "Current buffer" nil)
1972 (function) (variable) (file))
1973 (choice :tag "Identify target headline by"
1974 (cons :tag "Specific tag" (const :value :tag) (string))
1975 (cons :tag "TODO keyword" (const :value :todo) (string))
1976 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1977 (cons :tag "Level number" (const :value :level) (integer))
1978 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1980 (defcustom org-refile-target-verify-function nil
1981 "Function to verify if the headline at point should be a refile target.
1982 The function will be called without arguments, with point at the
1983 beginning of the headline. It should return t and leave point
1984 where it is if the headline is a valid target for refiling.
1986 If the target should not be selected, the function must return nil.
1987 In addition to this, it may move point to a place from where the search
1988 should be continued. For example, the function may decide that the entire
1989 subtree of the current entry should be excluded and move point to the end
1990 of the subtree."
1991 :group 'org-refile
1992 :type 'function)
1994 (defcustom org-refile-use-cache nil
1995 "Non-nil means cache refile targets to speed up the process.
1996 The cache for a particular file will be updated automatically when
1997 the buffer has been killed, or when any of the marker used for flagging
1998 refile targets no longer points at a live buffer.
1999 If you have added new entries to a buffer that might themselves be targets,
2000 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2001 find that easier, `C-u C-u C-u C-c C-w'."
2002 :group 'org-refile
2003 :version "24.1"
2004 :type 'boolean)
2006 (defcustom org-refile-use-outline-path nil
2007 "Non-nil means provide refile targets as paths.
2008 So a level 3 headline will be available as level1/level2/level3.
2010 When the value is `file', also include the file name (without directory)
2011 into the path. In this case, you can also stop the completion after
2012 the file name, to get entries inserted as top level in the file.
2014 When `full-file-path', include the full file path."
2015 :group 'org-refile
2016 :type '(choice
2017 (const :tag "Not" nil)
2018 (const :tag "Yes" t)
2019 (const :tag "Start with file name" file)
2020 (const :tag "Start with full file path" full-file-path)))
2022 (defcustom org-outline-path-complete-in-steps t
2023 "Non-nil means complete the outline path in hierarchical steps.
2024 When Org-mode uses the refile interface to select an outline path
2025 \(see variable `org-refile-use-outline-path'), the completion of
2026 the path can be done is a single go, or if can be done in steps down
2027 the headline hierarchy. Going in steps is probably the best if you
2028 do not use a special completion package like `ido' or `icicles'.
2029 However, when using these packages, going in one step can be very
2030 fast, while still showing the whole path to the entry."
2031 :group 'org-refile
2032 :type 'boolean)
2034 (defcustom org-refile-allow-creating-parent-nodes nil
2035 "Non-nil means allow to create new nodes as refile targets.
2036 New nodes are then created by adding \"/new node name\" to the completion
2037 of an existing node. When the value of this variable is `confirm',
2038 new node creation must be confirmed by the user (recommended)
2039 When nil, the completion must match an existing entry.
2041 Note that, if the new heading is not seen by the criteria
2042 listed in `org-refile-targets', multiple instances of the same
2043 heading would be created by trying again to file under the new
2044 heading."
2045 :group 'org-refile
2046 :type '(choice
2047 (const :tag "Never" nil)
2048 (const :tag "Always" t)
2049 (const :tag "Prompt for confirmation" confirm)))
2051 (defcustom org-refile-active-region-within-subtree nil
2052 "Non-nil means also refile active region within a subtree.
2054 By default `org-refile' doesn't allow refiling regions if they
2055 don't contain a set of subtrees, but it might be convenient to
2056 do so sometimes: in that case, the first line of the region is
2057 converted to a headline before refiling."
2058 :group 'org-refile
2059 :version "24.1"
2060 :type 'boolean)
2062 (defgroup org-todo nil
2063 "Options concerning TODO items in Org-mode."
2064 :tag "Org TODO"
2065 :group 'org)
2067 (defgroup org-progress nil
2068 "Options concerning Progress logging in Org-mode."
2069 :tag "Org Progress"
2070 :group 'org-time)
2072 (defvar org-todo-interpretation-widgets
2073 '((:tag "Sequence (cycling hits every state)" sequence)
2074 (:tag "Type (cycling directly to DONE)" type))
2075 "The available interpretation symbols for customizing `org-todo-keywords'.
2076 Interested libraries should add to this list.")
2078 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2079 "List of TODO entry keyword sequences and their interpretation.
2080 \\<org-mode-map>This is a list of sequences.
2082 Each sequence starts with a symbol, either `sequence' or `type',
2083 indicating if the keywords should be interpreted as a sequence of
2084 action steps, or as different types of TODO items. The first
2085 keywords are states requiring action - these states will select a headline
2086 for inclusion into the global TODO list Org-mode produces. If one of
2087 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2088 signify that no further action is necessary. If \"|\" is not found,
2089 the last keyword is treated as the only DONE state of the sequence.
2091 The command \\[org-todo] cycles an entry through these states, and one
2092 additional state where no keyword is present. For details about this
2093 cycling, see the manual.
2095 TODO keywords and interpretation can also be set on a per-file basis with
2096 the special #+SEQ_TODO and #+TYP_TODO lines.
2098 Each keyword can optionally specify a character for fast state selection
2099 \(in combination with the variable `org-use-fast-todo-selection')
2100 and specifiers for state change logging, using the same syntax that
2101 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2102 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2103 indicates to record a time stamp each time this state is selected.
2105 Each keyword may also specify if a timestamp or a note should be
2106 recorded when entering or leaving the state, by adding additional
2107 characters in the parenthesis after the keyword. This looks like this:
2108 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2109 record only the time of the state change. With X and Y being either
2110 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2111 Y when leaving the state if and only if the *target* state does not
2112 define X. You may omit any of the fast-selection key or X or /Y,
2113 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2115 For backward compatibility, this variable may also be just a list
2116 of keywords. In this case the interpretation (sequence or type) will be
2117 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2118 :group 'org-todo
2119 :group 'org-keywords
2120 :type '(choice
2121 (repeat :tag "Old syntax, just keywords"
2122 (string :tag "Keyword"))
2123 (repeat :tag "New syntax"
2124 (cons
2125 (choice
2126 :tag "Interpretation"
2127 ;;Quick and dirty way to see
2128 ;;`org-todo-interpretations'. This takes the
2129 ;;place of item arguments
2130 :convert-widget
2131 (lambda (widget)
2132 (widget-put widget
2133 :args (mapcar
2134 #'(lambda (x)
2135 (widget-convert
2136 (cons 'const x)))
2137 org-todo-interpretation-widgets))
2138 widget))
2139 (repeat
2140 (string :tag "Keyword"))))))
2142 (defvar org-todo-keywords-1 nil
2143 "All TODO and DONE keywords active in a buffer.")
2144 (make-variable-buffer-local 'org-todo-keywords-1)
2145 (defvar org-todo-keywords-for-agenda nil)
2146 (defvar org-done-keywords-for-agenda nil)
2147 (defvar org-drawers-for-agenda nil)
2148 (defvar org-todo-keyword-alist-for-agenda nil)
2149 (defvar org-tag-alist-for-agenda nil)
2150 (defvar org-agenda-contributing-files nil)
2151 (defvar org-not-done-keywords nil)
2152 (make-variable-buffer-local 'org-not-done-keywords)
2153 (defvar org-done-keywords nil)
2154 (make-variable-buffer-local 'org-done-keywords)
2155 (defvar org-todo-heads nil)
2156 (make-variable-buffer-local 'org-todo-heads)
2157 (defvar org-todo-sets nil)
2158 (make-variable-buffer-local 'org-todo-sets)
2159 (defvar org-todo-log-states nil)
2160 (make-variable-buffer-local 'org-todo-log-states)
2161 (defvar org-todo-kwd-alist nil)
2162 (make-variable-buffer-local 'org-todo-kwd-alist)
2163 (defvar org-todo-key-alist nil)
2164 (make-variable-buffer-local 'org-todo-key-alist)
2165 (defvar org-todo-key-trigger nil)
2166 (make-variable-buffer-local 'org-todo-key-trigger)
2168 (defcustom org-todo-interpretation 'sequence
2169 "Controls how TODO keywords are interpreted.
2170 This variable is in principle obsolete and is only used for
2171 backward compatibility, if the interpretation of todo keywords is
2172 not given already in `org-todo-keywords'. See that variable for
2173 more information."
2174 :group 'org-todo
2175 :group 'org-keywords
2176 :type '(choice (const sequence)
2177 (const type)))
2179 (defcustom org-use-fast-todo-selection t
2180 "Non-nil means use the fast todo selection scheme with C-c C-t.
2181 This variable describes if and under what circumstances the cycling
2182 mechanism for TODO keywords will be replaced by a single-key, direct
2183 selection scheme.
2185 When nil, fast selection is never used.
2187 When the symbol `prefix', it will be used when `org-todo' is called
2188 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2189 `C-u t' in an agenda buffer.
2191 When t, fast selection is used by default. In this case, the prefix
2192 argument forces cycling instead.
2194 In all cases, the special interface is only used if access keys have
2195 actually been assigned by the user, i.e. if keywords in the configuration
2196 are followed by a letter in parenthesis, like TODO(t)."
2197 :group 'org-todo
2198 :type '(choice
2199 (const :tag "Never" nil)
2200 (const :tag "By default" t)
2201 (const :tag "Only with C-u C-c C-t" prefix)))
2203 (defcustom org-provide-todo-statistics t
2204 "Non-nil means update todo statistics after insert and toggle.
2205 ALL-HEADLINES means update todo statistics by including headlines
2206 with no TODO keyword as well, counting them as not done.
2207 A list of TODO keywords means the same, but skip keywords that are
2208 not in this list.
2210 When this is set, todo statistics is updated in the parent of the
2211 current entry each time a todo state is changed."
2212 :group 'org-todo
2213 :type '(choice
2214 (const :tag "Yes, only for TODO entries" t)
2215 (const :tag "Yes, including all entries" 'all-headlines)
2216 (repeat :tag "Yes, for TODOs in this list"
2217 (string :tag "TODO keyword"))
2218 (other :tag "No TODO statistics" nil)))
2220 (defcustom org-hierarchical-todo-statistics t
2221 "Non-nil means TODO statistics covers just direct children.
2222 When nil, all entries in the subtree are considered.
2223 This has only an effect if `org-provide-todo-statistics' is set.
2224 To set this to nil for only a single subtree, use a COOKIE_DATA
2225 property and include the word \"recursive\" into the value."
2226 :group 'org-todo
2227 :type 'boolean)
2229 (defcustom org-after-todo-state-change-hook nil
2230 "Hook which is run after the state of a TODO item was changed.
2231 The new state (a string with a TODO keyword, or nil) is available in the
2232 Lisp variable `org-state'."
2233 :group 'org-todo
2234 :type 'hook)
2236 (defvar org-blocker-hook nil
2237 "Hook for functions that are allowed to block a state change.
2239 Each function gets as its single argument a property list, see
2240 `org-trigger-hook' for more information about this list.
2242 If any of the functions in this hook returns nil, the state change
2243 is blocked.")
2245 (defvar org-trigger-hook nil
2246 "Hook for functions that are triggered by a state change.
2248 Each function gets as its single argument a property list with at least
2249 the following elements:
2251 (:type type-of-change :position pos-at-entry-start
2252 :from old-state :to new-state)
2254 Depending on the type, more properties may be present.
2256 This mechanism is currently implemented for:
2258 TODO state changes
2259 ------------------
2260 :type todo-state-change
2261 :from previous state (keyword as a string), or nil, or a symbol
2262 'todo' or 'done', to indicate the general type of state.
2263 :to new state, like in :from")
2265 (defcustom org-enforce-todo-dependencies nil
2266 "Non-nil means undone TODO entries will block switching the parent to DONE.
2267 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2268 be blocked if any prior sibling is not yet done.
2269 Finally, if the parent is blocked because of ordered siblings of its own,
2270 the child will also be blocked."
2271 :set (lambda (var val)
2272 (set var val)
2273 (if val
2274 (add-hook 'org-blocker-hook
2275 'org-block-todo-from-children-or-siblings-or-parent)
2276 (remove-hook 'org-blocker-hook
2277 'org-block-todo-from-children-or-siblings-or-parent)))
2278 :group 'org-todo
2279 :type 'boolean)
2281 (defcustom org-enforce-todo-checkbox-dependencies nil
2282 "Non-nil means unchecked boxes will block switching the parent to DONE.
2283 When this is nil, checkboxes have no influence on switching TODO states.
2284 When non-nil, you first need to check off all check boxes before the TODO
2285 entry can be switched to DONE.
2286 This variable needs to be set before org.el is loaded, and you need to
2287 restart Emacs after a change to make the change effective. The only way
2288 to change is while Emacs is running is through the customize interface."
2289 :set (lambda (var val)
2290 (set var val)
2291 (if val
2292 (add-hook 'org-blocker-hook
2293 'org-block-todo-from-checkboxes)
2294 (remove-hook 'org-blocker-hook
2295 'org-block-todo-from-checkboxes)))
2296 :group 'org-todo
2297 :type 'boolean)
2299 (defcustom org-treat-insert-todo-heading-as-state-change nil
2300 "Non-nil means inserting a TODO heading is treated as state change.
2301 So when the command \\[org-insert-todo-heading] is used, state change
2302 logging will apply if appropriate. When nil, the new TODO item will
2303 be inserted directly, and no logging will take place."
2304 :group 'org-todo
2305 :type 'boolean)
2307 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2308 "Non-nil means switching TODO states with S-cursor counts as state change.
2309 This is the default behavior. However, setting this to nil allows a
2310 convenient way to select a TODO state and bypass any logging associated
2311 with that."
2312 :group 'org-todo
2313 :type 'boolean)
2315 (defcustom org-todo-state-tags-triggers nil
2316 "Tag changes that should be triggered by TODO state changes.
2317 This is a list. Each entry is
2319 (state-change (tag . flag) .......)
2321 State-change can be a string with a state, and empty string to indicate the
2322 state that has no TODO keyword, or it can be one of the symbols `todo'
2323 or `done', meaning any not-done or done state, respectively."
2324 :group 'org-todo
2325 :group 'org-tags
2326 :type '(repeat
2327 (cons (choice :tag "When changing to"
2328 (const :tag "Not-done state" todo)
2329 (const :tag "Done state" done)
2330 (string :tag "State"))
2331 (repeat
2332 (cons :tag "Tag action"
2333 (string :tag "Tag")
2334 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2336 (defcustom org-log-done nil
2337 "Information to record when a task moves to the DONE state.
2339 Possible values are:
2341 nil Don't add anything, just change the keyword
2342 time Add a time stamp to the task
2343 note Prompt for a note and add it with template `org-log-note-headings'
2345 This option can also be set with on a per-file-basis with
2347 #+STARTUP: nologdone
2348 #+STARTUP: logdone
2349 #+STARTUP: lognotedone
2351 You can have local logging settings for a subtree by setting the LOGGING
2352 property to one or more of these keywords."
2353 :group 'org-todo
2354 :group 'org-progress
2355 :type '(choice
2356 (const :tag "No logging" nil)
2357 (const :tag "Record CLOSED timestamp" time)
2358 (const :tag "Record CLOSED timestamp with note." note)))
2360 ;; Normalize old uses of org-log-done.
2361 (cond
2362 ((eq org-log-done t) (setq org-log-done 'time))
2363 ((and (listp org-log-done) (memq 'done org-log-done))
2364 (setq org-log-done 'note)))
2366 (defcustom org-log-reschedule nil
2367 "Information to record when the scheduling date of a tasks is modified.
2369 Possible values are:
2371 nil Don't add anything, just change the date
2372 time Add a time stamp to the task
2373 note Prompt for a note and add it with template `org-log-note-headings'
2375 This option can also be set with on a per-file-basis with
2377 #+STARTUP: nologreschedule
2378 #+STARTUP: logreschedule
2379 #+STARTUP: lognotereschedule"
2380 :group 'org-todo
2381 :group 'org-progress
2382 :type '(choice
2383 (const :tag "No logging" nil)
2384 (const :tag "Record timestamp" time)
2385 (const :tag "Record timestamp with note." note)))
2387 (defcustom org-log-redeadline nil
2388 "Information to record when the deadline date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologredeadline
2399 #+STARTUP: logredeadline
2400 #+STARTUP: lognoteredeadline
2402 You can have local logging settings for a subtree by setting the LOGGING
2403 property to one or more of these keywords."
2404 :group 'org-todo
2405 :group 'org-progress
2406 :type '(choice
2407 (const :tag "No logging" nil)
2408 (const :tag "Record timestamp" time)
2409 (const :tag "Record timestamp with note." note)))
2411 (defcustom org-log-note-clock-out nil
2412 "Non-nil means record a note when clocking out of an item.
2413 This can also be configured on a per-file basis by adding one of
2414 the following lines anywhere in the buffer:
2416 #+STARTUP: lognoteclock-out
2417 #+STARTUP: nolognoteclock-out"
2418 :group 'org-todo
2419 :group 'org-progress
2420 :type 'boolean)
2422 (defcustom org-log-done-with-time t
2423 "Non-nil means the CLOSED time stamp will contain date and time.
2424 When nil, only the date will be recorded."
2425 :group 'org-progress
2426 :type 'boolean)
2428 (defcustom org-log-note-headings
2429 '((done . "CLOSING NOTE %t")
2430 (state . "State %-12s from %-12S %t")
2431 (note . "Note taken on %t")
2432 (reschedule . "Rescheduled from %S on %t")
2433 (delschedule . "Not scheduled, was %S on %t")
2434 (redeadline . "New deadline from %S on %t")
2435 (deldeadline . "Removed deadline, was %S on %t")
2436 (refile . "Refiled on %t")
2437 (clock-out . ""))
2438 "Headings for notes added to entries.
2439 The value is an alist, with the car being a symbol indicating the note
2440 context, and the cdr is the heading to be used. The heading may also be the
2441 empty string.
2442 %t in the heading will be replaced by a time stamp.
2443 %T will be an active time stamp instead the default inactive one
2444 %d will be replaced by a short-format time stamp.
2445 %D will be replaced by an active short-format time stamp.
2446 %s will be replaced by the new TODO state, in double quotes.
2447 %S will be replaced by the old TODO state, in double quotes.
2448 %u will be replaced by the user name.
2449 %U will be replaced by the full user name.
2451 In fact, it is not a good idea to change the `state' entry, because
2452 agenda log mode depends on the format of these entries."
2453 :group 'org-todo
2454 :group 'org-progress
2455 :type '(list :greedy t
2456 (cons (const :tag "Heading when closing an item" done) string)
2457 (cons (const :tag
2458 "Heading when changing todo state (todo sequence only)"
2459 state) string)
2460 (cons (const :tag "Heading when just taking a note" note) string)
2461 (cons (const :tag "Heading when clocking out" clock-out) string)
2462 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2463 (cons (const :tag "Heading when rescheduling" reschedule) string)
2464 (cons (const :tag "Heading when changing deadline" redeadline) string)
2465 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2466 (cons (const :tag "Heading when refiling" refile) string)))
2468 (unless (assq 'note org-log-note-headings)
2469 (push '(note . "%t") org-log-note-headings))
2471 (defcustom org-log-into-drawer nil
2472 "Non-nil means insert state change notes and time stamps into a drawer.
2473 When nil, state changes notes will be inserted after the headline and
2474 any scheduling and clock lines, but not inside a drawer.
2476 The value of this variable should be the name of the drawer to use.
2477 LOGBOOK is proposed as the default drawer for this purpose, you can
2478 also set this to a string to define the drawer of your choice.
2480 A value of t is also allowed, representing \"LOGBOOK\".
2482 If this variable is set, `org-log-state-notes-insert-after-drawers'
2483 will be ignored.
2485 You can set the property LOG_INTO_DRAWER to overrule this setting for
2486 a subtree."
2487 :group 'org-todo
2488 :group 'org-progress
2489 :type '(choice
2490 (const :tag "Not into a drawer" nil)
2491 (const :tag "LOGBOOK" t)
2492 (string :tag "Other")))
2494 (if (fboundp 'defvaralias)
2495 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2497 (defun org-log-into-drawer ()
2498 "Return the value of `org-log-into-drawer', but let properties overrule.
2499 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2500 used instead of the default value."
2501 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2502 (cond
2503 ((or (not p) (equal p "nil")) org-log-into-drawer)
2504 ((equal p "t") "LOGBOOK")
2505 (t p))))
2507 (defcustom org-log-state-notes-insert-after-drawers nil
2508 "Non-nil means insert state change notes after any drawers in entry.
2509 Only the drawers that *immediately* follow the headline and the
2510 deadline/scheduled line are skipped.
2511 When nil, insert notes right after the heading and perhaps the line
2512 with deadline/scheduling if present.
2514 This variable will have no effect if `org-log-into-drawer' is
2515 set."
2516 :group 'org-todo
2517 :group 'org-progress
2518 :type 'boolean)
2520 (defcustom org-log-states-order-reversed t
2521 "Non-nil means the latest state note will be directly after heading.
2522 When nil, the state change notes will be ordered according to time."
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type 'boolean)
2527 (defcustom org-todo-repeat-to-state nil
2528 "The TODO state to which a repeater should return the repeating task.
2529 By default this is the first task in a TODO sequence, or the previous state
2530 in a TODO_TYP set. But you can specify another task here.
2531 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2532 :group 'org-todo
2533 :version "24.1"
2534 :type '(choice (const :tag "Head of sequence" nil)
2535 (string :tag "Specific state")))
2537 (defcustom org-log-repeat 'time
2538 "Non-nil means record moving through the DONE state when triggering repeat.
2539 An auto-repeating task is immediately switched back to TODO when
2540 marked DONE. If you are not logging state changes (by adding \"@\"
2541 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2542 record a closing note, there will be no record of the task moving
2543 through DONE. This variable forces taking a note anyway.
2545 nil Don't force a record
2546 time Record a time stamp
2547 note Prompt for a note and add it with template `org-log-note-headings'
2549 This option can also be set with on a per-file-basis with
2551 #+STARTUP: nologrepeat
2552 #+STARTUP: logrepeat
2553 #+STARTUP: lognoterepeat
2555 You can have local logging settings for a subtree by setting the LOGGING
2556 property to one or more of these keywords."
2557 :group 'org-todo
2558 :group 'org-progress
2559 :type '(choice
2560 (const :tag "Don't force a record" nil)
2561 (const :tag "Force recording the DONE state" time)
2562 (const :tag "Force recording a note with the DONE state" note)))
2565 (defgroup org-priorities nil
2566 "Priorities in Org-mode."
2567 :tag "Org Priorities"
2568 :group 'org-todo)
2570 (defcustom org-enable-priority-commands t
2571 "Non-nil means priority commands are active.
2572 When nil, these commands will be disabled, so that you never accidentally
2573 set a priority."
2574 :group 'org-priorities
2575 :type 'boolean)
2577 (defcustom org-highest-priority ?A
2578 "The highest priority of TODO items. A character like ?A, ?B etc.
2579 Must have a smaller ASCII number than `org-lowest-priority'."
2580 :group 'org-priorities
2581 :type 'character)
2583 (defcustom org-lowest-priority ?C
2584 "The lowest priority of TODO items. A character like ?A, ?B etc.
2585 Must have a larger ASCII number than `org-highest-priority'."
2586 :group 'org-priorities
2587 :type 'character)
2589 (defcustom org-default-priority ?B
2590 "The default priority of TODO items.
2591 This is the priority an item gets if no explicit priority is given.
2592 When starting to cycle on an empty priority the first step in the cycle
2593 depends on `org-priority-start-cycle-with-default'. The resulting first
2594 step priority must not exceed the range from `org-highest-priority' to
2595 `org-lowest-priority' which means that `org-default-priority' has to be
2596 in this range exclusive or inclusive the range boundaries. Else the
2597 first step refuses to set the default and the second will fall back
2598 to (depending on the command used) the highest or lowest priority."
2599 :group 'org-priorities
2600 :type 'character)
2602 (defcustom org-priority-start-cycle-with-default t
2603 "Non-nil means start with default priority when starting to cycle.
2604 When this is nil, the first step in the cycle will be (depending on the
2605 command used) one higher or lower than the default priority.
2606 See also `org-default-priority'."
2607 :group 'org-priorities
2608 :type 'boolean)
2610 (defcustom org-get-priority-function nil
2611 "Function to extract the priority from a string.
2612 The string is normally the headline. If this is nil Org computes the
2613 priority from the priority cookie like [#A] in the headline. It returns
2614 an integer, increasing by 1000 for each priority level.
2615 The user can set a different function here, which should take a string
2616 as an argument and return the numeric priority."
2617 :group 'org-priorities
2618 :version "24.1"
2619 :type 'function)
2621 (defgroup org-time nil
2622 "Options concerning time stamps and deadlines in Org-mode."
2623 :tag "Org Time"
2624 :group 'org)
2626 (defcustom org-insert-labeled-timestamps-at-point nil
2627 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2628 When nil, these labeled time stamps are forces into the second line of an
2629 entry, just after the headline. When scheduling from the global TODO list,
2630 the time stamp will always be forced into the second line."
2631 :group 'org-time
2632 :type 'boolean)
2634 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2635 "Formats for `format-time-string' which are used for time stamps.
2636 It is not recommended to change this constant.")
2638 (defcustom org-time-stamp-rounding-minutes '(0 5)
2639 "Number of minutes to round time stamps to.
2640 These are two values, the first applies when first creating a time stamp.
2641 The second applies when changing it with the commands `S-up' and `S-down'.
2642 When changing the time stamp, this means that it will change in steps
2643 of N minutes, as given by the second value.
2645 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2646 numbers should be factors of 60, so for example 5, 10, 15.
2648 When this is larger than 1, you can still force an exact time stamp by using
2649 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2650 and by using a prefix arg to `S-up/down' to specify the exact number
2651 of minutes to shift."
2652 :group 'org-time
2653 :get #'(lambda (var) ; Make sure both elements are there
2654 (if (integerp (default-value var))
2655 (list (default-value var) 5)
2656 (default-value var)))
2657 :type '(list
2658 (integer :tag "when inserting times")
2659 (integer :tag "when modifying times")))
2661 ;; Normalize old customizations of this variable.
2662 (when (integerp org-time-stamp-rounding-minutes)
2663 (setq org-time-stamp-rounding-minutes
2664 (list org-time-stamp-rounding-minutes
2665 org-time-stamp-rounding-minutes)))
2667 (defcustom org-display-custom-times nil
2668 "Non-nil means overlay custom formats over all time stamps.
2669 The formats are defined through the variable `org-time-stamp-custom-formats'.
2670 To turn this on on a per-file basis, insert anywhere in the file:
2671 #+STARTUP: customtime"
2672 :group 'org-time
2673 :set 'set-default
2674 :type 'sexp)
2675 (make-variable-buffer-local 'org-display-custom-times)
2677 (defcustom org-time-stamp-custom-formats
2678 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2679 "Custom formats for time stamps. See `format-time-string' for the syntax.
2680 These are overlaid over the default ISO format if the variable
2681 `org-display-custom-times' is set. Time like %H:%M should be at the
2682 end of the second format. The custom formats are also honored by export
2683 commands, if custom time display is turned on at the time of export."
2684 :group 'org-time
2685 :type 'sexp)
2687 (defun org-time-stamp-format (&optional long inactive)
2688 "Get the right format for a time string."
2689 (let ((f (if long (cdr org-time-stamp-formats)
2690 (car org-time-stamp-formats))))
2691 (if inactive
2692 (concat "[" (substring f 1 -1) "]")
2693 f)))
2695 (defcustom org-time-clocksum-format "%d:%02d"
2696 "The format string used when creating CLOCKSUM lines.
2697 This is also used when org-mode generates a time duration."
2698 :group 'org-time
2699 :type 'string)
2701 (defcustom org-time-clocksum-use-fractional nil
2702 "If non-nil, \\[org-clock-display] uses fractional times.
2703 org-mode generates a time duration."
2704 :group 'org-time
2705 :type 'boolean)
2707 (defcustom org-time-clocksum-fractional-format "%.2f"
2708 "The format string used when creating CLOCKSUM lines, or when
2709 org-mode generates a time duration."
2710 :group 'org-time
2711 :type 'string)
2713 (defcustom org-deadline-warning-days 14
2714 "No. of days before expiration during which a deadline becomes active.
2715 This variable governs the display in sparse trees and in the agenda.
2716 When 0 or negative, it means use this number (the absolute value of it)
2717 even if a deadline has a different individual lead time specified.
2719 Custom commands can set this variable in the options section."
2720 :group 'org-time
2721 :group 'org-agenda-daily/weekly
2722 :type 'integer)
2724 (defcustom org-read-date-prefer-future t
2725 "Non-nil means assume future for incomplete date input from user.
2726 This affects the following situations:
2727 1. The user gives a month but not a year.
2728 For example, if it is April and you enter \"feb 2\", this will be read
2729 as Feb 2, *next* year. \"May 5\", however, will be this year.
2730 2. The user gives a day, but no month.
2731 For example, if today is the 15th, and you enter \"3\", Org-mode will
2732 read this as the third of *next* month. However, if you enter \"17\",
2733 it will be considered as *this* month.
2735 If you set this variable to the symbol `time', then also the following
2736 will work:
2738 3. If the user gives a time.
2739 If the time is before now, it will be interpreted as tomorrow.
2741 Currently none of this works for ISO week specifications.
2743 When this option is nil, the current day, month and year will always be
2744 used as defaults.
2746 See also `org-agenda-jump-prefer-future'."
2747 :group 'org-time
2748 :type '(choice
2749 (const :tag "Never" nil)
2750 (const :tag "Check month and day" t)
2751 (const :tag "Check month, day, and time" time)))
2753 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2754 "Should the agenda jump command prefer the future for incomplete dates?
2755 The default is to do the same as configured in `org-read-date-prefer-future'.
2756 But you can also set a deviating value here.
2757 This may t or nil, or the symbol `org-read-date-prefer-future'."
2758 :group 'org-agenda
2759 :group 'org-time
2760 :version "24.1"
2761 :type '(choice
2762 (const :tag "Use org-read-date-prefer-future"
2763 org-read-date-prefer-future)
2764 (const :tag "Never" nil)
2765 (const :tag "Always" t)))
2767 (defcustom org-read-date-force-compatible-dates t
2768 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2770 Depending on the system Emacs is running on, certain dates cannot
2771 be represented with the type used internally to represent time.
2772 Dates between 1970-1-1 and 2038-1-1 can always be represented
2773 correctly. Some systems allow for earlier dates, some for later,
2774 some for both. One way to find out it to insert any date into an
2775 Org buffer, putting the cursor on the year and hitting S-up and
2776 S-down to test the range.
2778 When this variable is set to t, the date/time prompt will not let
2779 you specify dates outside the 1970-2037 range, so it is certain that
2780 these dates will work in whatever version of Emacs you are
2781 running, and also that you can move a file from one Emacs implementation
2782 to another. WHenever Org is forcing the year for you, it will display
2783 a message and beep.
2785 When this variable is nil, Org will check if the date is
2786 representable in the specific Emacs implementation you are using.
2787 If not, it will force a year, usually the current year, and beep
2788 to remind you. Currently this setting is not recommended because
2789 the likelihood that you will open your Org files in an Emacs that
2790 has limited date range is not negligible.
2792 A workaround for this problem is to use diary sexp dates for time
2793 stamps outside of this range."
2794 :group 'org-time
2795 :version "24.1"
2796 :type 'boolean)
2798 (defcustom org-read-date-display-live t
2799 "Non-nil means display current interpretation of date prompt live.
2800 This display will be in an overlay, in the minibuffer."
2801 :group 'org-time
2802 :type 'boolean)
2804 (defcustom org-read-date-popup-calendar t
2805 "Non-nil means pop up a calendar when prompting for a date.
2806 In the calendar, the date can be selected with mouse-1. However, the
2807 minibuffer will also be active, and you can simply enter the date as well.
2808 When nil, only the minibuffer will be available."
2809 :group 'org-time
2810 :type 'boolean)
2811 (if (fboundp 'defvaralias)
2812 (defvaralias 'org-popup-calendar-for-date-prompt
2813 'org-read-date-popup-calendar))
2815 (defcustom org-read-date-minibuffer-setup-hook nil
2816 "Hook to be used to set up keys for the date/time interface.
2817 Add key definitions to `minibuffer-local-map', which will be a temporary
2818 copy."
2819 :group 'org-time
2820 :type 'hook)
2822 (defcustom org-extend-today-until 0
2823 "The hour when your day really ends. Must be an integer.
2824 This has influence for the following applications:
2825 - When switching the agenda to \"today\". It it is still earlier than
2826 the time given here, the day recognized as TODAY is actually yesterday.
2827 - When a date is read from the user and it is still before the time given
2828 here, the current date and time will be assumed to be yesterday, 23:59.
2829 Also, timestamps inserted in capture templates follow this rule.
2831 IMPORTANT: This is a feature whose implementation is and likely will
2832 remain incomplete. Really, it is only here because past midnight seems to
2833 be the favorite working time of John Wiegley :-)"
2834 :group 'org-time
2835 :type 'integer)
2837 (defcustom org-use-effective-time nil
2838 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2839 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2840 \"effective time\" of any timestamps between midnight and 8am will be
2841 23:59 of the previous day."
2842 :group 'org-time
2843 :version "24.1"
2844 :type 'boolean)
2846 (defcustom org-edit-timestamp-down-means-later nil
2847 "Non-nil means S-down will increase the time in a time stamp.
2848 When nil, S-up will increase."
2849 :group 'org-time
2850 :type 'boolean)
2852 (defcustom org-calendar-follow-timestamp-change t
2853 "Non-nil means make the calendar window follow timestamp changes.
2854 When a timestamp is modified and the calendar window is visible, it will be
2855 moved to the new date."
2856 :group 'org-time
2857 :type 'boolean)
2859 (defgroup org-tags nil
2860 "Options concerning tags in Org-mode."
2861 :tag "Org Tags"
2862 :group 'org)
2864 (defcustom org-tag-alist nil
2865 "List of tags allowed in Org-mode files.
2866 When this list is nil, Org-mode will base TAG input on what is already in the
2867 buffer.
2868 The value of this variable is an alist, the car of each entry must be a
2869 keyword as a string, the cdr may be a character that is used to select
2870 that tag through the fast-tag-selection interface.
2871 See the manual for details."
2872 :group 'org-tags
2873 :type '(repeat
2874 (choice
2875 (cons (string :tag "Tag name")
2876 (character :tag "Access char"))
2877 (list :tag "Start radio group"
2878 (const :startgroup)
2879 (option (string :tag "Group description")))
2880 (list :tag "End radio group"
2881 (const :endgroup)
2882 (option (string :tag "Group description")))
2883 (const :tag "New line" (:newline)))))
2885 (defcustom org-tag-persistent-alist nil
2886 "List of tags that will always appear in all Org-mode files.
2887 This is in addition to any in buffer settings or customizations
2888 of `org-tag-alist'.
2889 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2890 The value of this variable is an alist, the car of each entry must be a
2891 keyword as a string, the cdr may be a character that is used to select
2892 that tag through the fast-tag-selection interface.
2893 See the manual for details.
2894 To disable these tags on a per-file basis, insert anywhere in the file:
2895 #+STARTUP: noptag"
2896 :group 'org-tags
2897 :type '(repeat
2898 (choice
2899 (cons (string :tag "Tag name")
2900 (character :tag "Access char"))
2901 (const :tag "Start radio group" (:startgroup))
2902 (const :tag "End radio group" (:endgroup))
2903 (const :tag "New line" (:newline)))))
2905 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2906 "If non-nil, always offer completion for all tags of all agenda files.
2907 Instead of customizing this variable directly, you might want to
2908 set it locally for capture buffers, because there no list of
2909 tags in that file can be created dynamically (there are none).
2911 (add-hook 'org-capture-mode-hook
2912 (lambda ()
2913 (set (make-local-variable
2914 'org-complete-tags-always-offer-all-agenda-tags)
2915 t)))"
2916 :group 'org-tags
2917 :version "24.1"
2918 :type 'boolean)
2920 (defvar org-file-tags nil
2921 "List of tags that can be inherited by all entries in the file.
2922 The tags will be inherited if the variable `org-use-tag-inheritance'
2923 says they should be.
2924 This variable is populated from #+FILETAGS lines.")
2926 (defcustom org-use-fast-tag-selection 'auto
2927 "Non-nil means use fast tag selection scheme.
2928 This is a special interface to select and deselect tags with single keys.
2929 When nil, fast selection is never used.
2930 When the symbol `auto', fast selection is used if and only if selection
2931 characters for tags have been configured, either through the variable
2932 `org-tag-alist' or through a #+TAGS line in the buffer.
2933 When t, fast selection is always used and selection keys are assigned
2934 automatically if necessary."
2935 :group 'org-tags
2936 :type '(choice
2937 (const :tag "Always" t)
2938 (const :tag "Never" nil)
2939 (const :tag "When selection characters are configured" 'auto)))
2941 (defcustom org-fast-tag-selection-single-key nil
2942 "Non-nil means fast tag selection exits after first change.
2943 When nil, you have to press RET to exit it.
2944 During fast tag selection, you can toggle this flag with `C-c'.
2945 This variable can also have the value `expert'. In this case, the window
2946 displaying the tags menu is not even shown, until you press C-c again."
2947 :group 'org-tags
2948 :type '(choice
2949 (const :tag "No" nil)
2950 (const :tag "Yes" t)
2951 (const :tag "Expert" expert)))
2953 (defvar org-fast-tag-selection-include-todo nil
2954 "Non-nil means fast tags selection interface will also offer TODO states.
2955 This is an undocumented feature, you should not rely on it.")
2957 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2958 "The column to which tags should be indented in a headline.
2959 If this number is positive, it specifies the column. If it is negative,
2960 it means that the tags should be flushright to that column. For example,
2961 -80 works well for a normal 80 character screen.
2962 When 0, place tags directly after headline text, with only one space in
2963 between."
2964 :group 'org-tags
2965 :type 'integer)
2967 (defcustom org-auto-align-tags t
2968 "Non-nil keeps tags aligned when modifying headlines.
2969 Some operations (i.e. demoting) change the length of a headline and
2970 therefore shift the tags around. With this option turned on, after
2971 each such operation the tags are again aligned to `org-tags-column'."
2972 :group 'org-tags
2973 :type 'boolean)
2975 (defcustom org-use-tag-inheritance t
2976 "Non-nil means tags in levels apply also for sublevels.
2977 When nil, only the tags directly given in a specific line apply there.
2978 This may also be a list of tags that should be inherited, or a regexp that
2979 matches tags that should be inherited. Additional control is possible
2980 with the variable `org-tags-exclude-from-inheritance' which gives an
2981 explicit list of tags to be excluded from inheritance., even if the value of
2982 `org-use-tag-inheritance' would select it for inheritance.
2984 If this option is t, a match early-on in a tree can lead to a large
2985 number of matches in the subtree when constructing the agenda or creating
2986 a sparse tree. If you only want to see the first match in a tree during
2987 a search, check out the variable `org-tags-match-list-sublevels'."
2988 :group 'org-tags
2989 :type '(choice
2990 (const :tag "Not" nil)
2991 (const :tag "Always" t)
2992 (repeat :tag "Specific tags" (string :tag "Tag"))
2993 (regexp :tag "Tags matched by regexp")))
2995 (defcustom org-tags-exclude-from-inheritance nil
2996 "List of tags that should never be inherited.
2997 This is a way to exclude a few tags from inheritance. For way to do
2998 the opposite, to actively allow inheritance for selected tags,
2999 see the variable `org-use-tag-inheritance'."
3000 :group 'org-tags
3001 :type '(repeat (string :tag "Tag")))
3003 (defun org-tag-inherit-p (tag)
3004 "Check if TAG is one that should be inherited."
3005 (cond
3006 ((member tag org-tags-exclude-from-inheritance) nil)
3007 ((eq org-use-tag-inheritance t) t)
3008 ((not org-use-tag-inheritance) nil)
3009 ((stringp org-use-tag-inheritance)
3010 (string-match org-use-tag-inheritance tag))
3011 ((listp org-use-tag-inheritance)
3012 (member tag org-use-tag-inheritance))
3013 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3015 (defcustom org-tags-match-list-sublevels t
3016 "Non-nil means list also sublevels of headlines matching a search.
3017 This variable applies to tags/property searches, and also to stuck
3018 projects because this search is based on a tags match as well.
3020 When set to the symbol `indented', sublevels are indented with
3021 leading dots.
3023 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3024 the sublevels of a headline matching a tag search often also match
3025 the same search. Listing all of them can create very long lists.
3026 Setting this variable to nil causes subtrees of a match to be skipped.
3028 This variable is semi-obsolete and probably should always be true. It
3029 is better to limit inheritance to certain tags using the variables
3030 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3031 :group 'org-tags
3032 :type '(choice
3033 (const :tag "No, don't list them" nil)
3034 (const :tag "Yes, do list them" t)
3035 (const :tag "List them, indented with leading dots" indented)))
3037 (defcustom org-tags-sort-function nil
3038 "When set, tags are sorted using this function as a comparator."
3039 :group 'org-tags
3040 :type '(choice
3041 (const :tag "No sorting" nil)
3042 (const :tag "Alphabetical" string<)
3043 (const :tag "Reverse alphabetical" string>)
3044 (function :tag "Custom function" nil)))
3046 (defvar org-tags-history nil
3047 "History of minibuffer reads for tags.")
3048 (defvar org-last-tags-completion-table nil
3049 "The last used completion table for tags.")
3050 (defvar org-after-tags-change-hook nil
3051 "Hook that is run after the tags in a line have changed.")
3053 (defgroup org-properties nil
3054 "Options concerning properties in Org-mode."
3055 :tag "Org Properties"
3056 :group 'org)
3058 (defcustom org-property-format "%-10s %s"
3059 "How property key/value pairs should be formatted by `indent-line'.
3060 When `indent-line' hits a property definition, it will format the line
3061 according to this format, mainly to make sure that the values are
3062 lined-up with respect to each other."
3063 :group 'org-properties
3064 :type 'string)
3066 (defcustom org-properties-postprocess-alist nil
3067 "Alist of properties and functions to adjust inserted values.
3068 Elements of this alist must be of the form
3070 ([string] [function])
3072 where [string] must be a property name and [function] must be a
3073 lambda expression: this lambda expression must take one argument,
3074 the value to adjust, and return the new value as a string.
3076 For example, this element will allow the property \"Remaining\"
3077 to be updated wrt the relation between the \"Effort\" property
3078 and the clock summary:
3080 ((\"Remaining\" (lambda(value)
3081 (let ((clocksum (org-clock-sum-current-item))
3082 (effort (org-duration-string-to-minutes
3083 (org-entry-get (point) \"Effort\"))))
3084 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3085 :group 'org-properties
3086 :version "24.1"
3087 :type '(alist :key-type (string :tag "Property")
3088 :value-type (function :tag "Function")))
3090 (defcustom org-use-property-inheritance nil
3091 "Non-nil means properties apply also for sublevels.
3093 This setting is chiefly used during property searches. Turning it on can
3094 cause significant overhead when doing a search, which is why it is not
3095 on by default.
3097 When nil, only the properties directly given in the current entry count.
3098 When t, every property is inherited. The value may also be a list of
3099 properties that should have inheritance, or a regular expression matching
3100 properties that should be inherited.
3102 However, note that some special properties use inheritance under special
3103 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3104 and the properties ending in \"_ALL\" when they are used as descriptor
3105 for valid values of a property.
3107 Note for programmers:
3108 When querying an entry with `org-entry-get', you can control if inheritance
3109 should be used. By default, `org-entry-get' looks only at the local
3110 properties. You can request inheritance by setting the inherit argument
3111 to t (to force inheritance) or to `selective' (to respect the setting
3112 in this variable)."
3113 :group 'org-properties
3114 :type '(choice
3115 (const :tag "Not" nil)
3116 (const :tag "Always" t)
3117 (repeat :tag "Specific properties" (string :tag "Property"))
3118 (regexp :tag "Properties matched by regexp")))
3120 (defun org-property-inherit-p (property)
3121 "Check if PROPERTY is one that should be inherited."
3122 (cond
3123 ((eq org-use-property-inheritance t) t)
3124 ((not org-use-property-inheritance) nil)
3125 ((stringp org-use-property-inheritance)
3126 (string-match org-use-property-inheritance property))
3127 ((listp org-use-property-inheritance)
3128 (member property org-use-property-inheritance))
3129 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3131 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3132 "The default column format, if no other format has been defined.
3133 This variable can be set on the per-file basis by inserting a line
3135 #+COLUMNS: %25ITEM ....."
3136 :group 'org-properties
3137 :type 'string)
3139 (defcustom org-columns-ellipses ".."
3140 "The ellipses to be used when a field in column view is truncated.
3141 When this is the empty string, as many characters as possible are shown,
3142 but then there will be no visual indication that the field has been truncated.
3143 When this is a string of length N, the last N characters of a truncated
3144 field are replaced by this string. If the column is narrower than the
3145 ellipses string, only part of the ellipses string will be shown."
3146 :group 'org-properties
3147 :type 'string)
3149 (defcustom org-columns-modify-value-for-display-function nil
3150 "Function that modifies values for display in column view.
3151 For example, it can be used to cut out a certain part from a time stamp.
3152 The function must take 2 arguments:
3154 column-title The title of the column (*not* the property name)
3155 value The value that should be modified.
3157 The function should return the value that should be displayed,
3158 or nil if the normal value should be used."
3159 :group 'org-properties
3160 :type 'function)
3162 (defcustom org-effort-property "Effort"
3163 "The property that is being used to keep track of effort estimates.
3164 Effort estimates given in this property need to have the format H:MM."
3165 :group 'org-properties
3166 :group 'org-progress
3167 :type '(string :tag "Property"))
3169 (defconst org-global-properties-fixed
3170 '(("VISIBILITY_ALL" . "folded children content all")
3171 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3172 "List of property/value pairs that can be inherited by any entry.
3174 These are fixed values, for the preset properties. The user variable
3175 that can be used to add to this list is `org-global-properties'.
3177 The entries in this list are cons cells where the car is a property
3178 name and cdr is a string with the value. If the value represents
3179 multiple items like an \"_ALL\" property, separate the items by
3180 spaces.")
3182 (defcustom org-global-properties nil
3183 "List of property/value pairs that can be inherited by any entry.
3185 This list will be combined with the constant `org-global-properties-fixed'.
3187 The entries in this list are cons cells where the car is a property
3188 name and cdr is a string with the value.
3190 You can set buffer-local values for the same purpose in the variable
3191 `org-file-properties' this by adding lines like
3193 #+PROPERTY: NAME VALUE"
3194 :group 'org-properties
3195 :type '(repeat
3196 (cons (string :tag "Property")
3197 (string :tag "Value"))))
3199 (defvar org-file-properties nil
3200 "List of property/value pairs that can be inherited by any entry.
3201 Valid for the current buffer.
3202 This variable is populated from #+PROPERTY lines.")
3203 (make-variable-buffer-local 'org-file-properties)
3205 (defgroup org-agenda nil
3206 "Options concerning agenda views in Org-mode."
3207 :tag "Org Agenda"
3208 :group 'org)
3210 (defvar org-category nil
3211 "Variable used by org files to set a category for agenda display.
3212 Such files should use a file variable to set it, for example
3214 # -*- mode: org; org-category: \"ELisp\"
3216 or contain a special line
3218 #+CATEGORY: ELisp
3220 If the file does not specify a category, then file's base name
3221 is used instead.")
3222 (make-variable-buffer-local 'org-category)
3223 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3225 (defcustom org-agenda-files nil
3226 "The files to be used for agenda display.
3227 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3228 \\[org-remove-file]. You can also use customize to edit the list.
3230 If an entry is a directory, all files in that directory that are matched by
3231 `org-agenda-file-regexp' will be part of the file list.
3233 If the value of the variable is not a list but a single file name, then
3234 the list of agenda files is actually stored and maintained in that file, one
3235 agenda file per line. In this file paths can be given relative to
3236 `org-directory'. Tilde expansion and environment variable substitution
3237 are also made."
3238 :group 'org-agenda
3239 :type '(choice
3240 (repeat :tag "List of files and directories" file)
3241 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3243 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3244 "Regular expression to match files for `org-agenda-files'.
3245 If any element in the list in that variable contains a directory instead
3246 of a normal file, all files in that directory that are matched by this
3247 regular expression will be included."
3248 :group 'org-agenda
3249 :type 'regexp)
3251 (defcustom org-agenda-text-search-extra-files nil
3252 "List of extra files to be searched by text search commands.
3253 These files will be search in addition to the agenda files by the
3254 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3255 Note that these files will only be searched for text search commands,
3256 not for the other agenda views like todo lists, tag searches or the weekly
3257 agenda. This variable is intended to list notes and possibly archive files
3258 that should also be searched by these two commands.
3259 In fact, if the first element in the list is the symbol `agenda-archives',
3260 than all archive files of all agenda files will be added to the search
3261 scope."
3262 :group 'org-agenda
3263 :type '(set :greedy t
3264 (const :tag "Agenda Archives" agenda-archives)
3265 (repeat :inline t (file))))
3267 (if (fboundp 'defvaralias)
3268 (defvaralias 'org-agenda-multi-occur-extra-files
3269 'org-agenda-text-search-extra-files))
3271 (defcustom org-agenda-skip-unavailable-files nil
3272 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3273 A nil value means to remove them, after a query, from the list."
3274 :group 'org-agenda
3275 :type 'boolean)
3277 (defcustom org-calendar-to-agenda-key [?c]
3278 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3279 The command `org-calendar-goto-agenda' will be bound to this key. The
3280 default is the character `c' because then `c' can be used to switch back and
3281 forth between agenda and calendar."
3282 :group 'org-agenda
3283 :type 'sexp)
3285 (defcustom org-calendar-insert-diary-entry-key [?i]
3286 "The key to be installed in `calendar-mode-map' for adding diary entries.
3287 This option is irrelevant until `org-agenda-diary-file' has been configured
3288 to point to an Org-mode file. When that is the case, the command
3289 `org-agenda-diary-entry' will be bound to the key given here, by default
3290 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3291 if you want to continue doing this, you need to change this to a different
3292 key."
3293 :group 'org-agenda
3294 :type 'sexp)
3296 (defcustom org-agenda-diary-file 'diary-file
3297 "File to which to add new entries with the `i' key in agenda and calendar.
3298 When this is the symbol `diary-file', the functionality in the Emacs
3299 calendar will be used to add entries to the `diary-file'. But when this
3300 points to a file, `org-agenda-diary-entry' will be used instead."
3301 :group 'org-agenda
3302 :type '(choice
3303 (const :tag "The standard Emacs diary file" diary-file)
3304 (file :tag "Special Org file diary entries")))
3306 (eval-after-load "calendar"
3307 '(progn
3308 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3309 'org-calendar-goto-agenda)
3310 (add-hook 'calendar-mode-hook
3311 (lambda ()
3312 (unless (eq org-agenda-diary-file 'diary-file)
3313 (define-key calendar-mode-map
3314 org-calendar-insert-diary-entry-key
3315 'org-agenda-diary-entry))))))
3317 (defgroup org-latex nil
3318 "Options for embedding LaTeX code into Org-mode."
3319 :tag "Org LaTeX"
3320 :group 'org)
3322 (defcustom org-format-latex-options
3323 '(:foreground default :background default :scale 1.0
3324 :html-foreground "Black" :html-background "Transparent"
3325 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3326 "Options for creating images from LaTeX fragments.
3327 This is a property list with the following properties:
3328 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3329 `default' means use the foreground of the default face.
3330 :background the background color, or \"Transparent\".
3331 `default' means use the background of the default face.
3332 :scale a scaling factor for the size of the images, to get more pixels
3333 :html-foreground, :html-background, :html-scale
3334 the same numbers for HTML export.
3335 :matchers a list indicating which matchers should be used to
3336 find LaTeX fragments. Valid members of this list are:
3337 \"begin\" find environments
3338 \"$1\" find single characters surrounded by $.$
3339 \"$\" find math expressions surrounded by $...$
3340 \"$$\" find math expressions surrounded by $$....$$
3341 \"\\(\" find math expressions surrounded by \\(...\\)
3342 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3343 :group 'org-latex
3344 :type 'plist)
3346 (defcustom org-format-latex-signal-error t
3347 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3348 When nil, just push out a message."
3349 :group 'org-latex
3350 :version "24.1"
3351 :type 'boolean)
3353 (defcustom org-latex-to-mathml-jar-file nil
3354 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3355 Use this to specify additional executable file say a jar file.
3357 When using MathToWeb as the converter, specify the full-path to
3358 your mathtoweb.jar file."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type '(choice
3362 (const :tag "None" nil)
3363 (file :tag "JAR file" :must-match t)))
3365 (defcustom org-latex-to-mathml-convert-command nil
3366 "Command to convert LaTeX fragments to MathML.
3367 Replace format-specifiers in the command as noted below and use
3368 `shell-command' to convert LaTeX to MathML.
3369 %j: Executable file in fully expanded form as specified by
3370 `org-latex-to-mathml-jar-file'.
3371 %I: Input LaTeX file in fully expanded form
3372 %o: Output MathML file
3373 This command is used by `org-create-math-formula'.
3375 When using MathToWeb as the converter, set this to
3376 \"java -jar %j -unicode -force -df %o %I\"."
3377 :group 'org-latex
3378 :version "24.1"
3379 :type '(choice
3380 (const :tag "None" nil)
3381 (string :tag "\nShell command")))
3383 (defcustom org-latex-create-formula-image-program 'dvipng
3384 "Program to convert LaTeX fragments with.
3386 dvipng Process the LaTeX fragments to dvi file, then convert
3387 dvi files to png files using dvipng.
3388 This will also include processing of non-math environments.
3389 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3390 to convert pdf files to png files"
3391 :group 'org-latex
3392 :version "24.1"
3393 :type '(choice
3394 (const :tag "dvipng" dvipng)
3395 (const :tag "imagemagick" imagemagick)))
3397 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3398 "Path to store latex preview images. A relative path here creates many
3399 directories relative to the processed org files paths. An absolute path
3400 puts all preview images at the same place."
3401 :group 'org-latex
3402 :version "24.3"
3403 :type 'string)
3405 (defun org-format-latex-mathml-available-p ()
3406 "Return t if `org-latex-to-mathml-convert-command' is usable."
3407 (save-match-data
3408 (when (and (boundp 'org-latex-to-mathml-convert-command)
3409 org-latex-to-mathml-convert-command)
3410 (let ((executable (car (split-string
3411 org-latex-to-mathml-convert-command))))
3412 (when (executable-find executable)
3413 (if (string-match
3414 "%j" org-latex-to-mathml-convert-command)
3415 (file-readable-p org-latex-to-mathml-jar-file)
3416 t))))))
3418 (defcustom org-format-latex-header "\\documentclass{article}
3419 \\usepackage[usenames]{color}
3420 \\usepackage{amsmath}
3421 \\usepackage[mathscr]{eucal}
3422 \\pagestyle{empty} % do not remove
3423 \[PACKAGES]
3424 \[DEFAULT-PACKAGES]
3425 % The settings below are copied from fullpage.sty
3426 \\setlength{\\textwidth}{\\paperwidth}
3427 \\addtolength{\\textwidth}{-3cm}
3428 \\setlength{\\oddsidemargin}{1.5cm}
3429 \\addtolength{\\oddsidemargin}{-2.54cm}
3430 \\setlength{\\evensidemargin}{\\oddsidemargin}
3431 \\setlength{\\textheight}{\\paperheight}
3432 \\addtolength{\\textheight}{-\\headheight}
3433 \\addtolength{\\textheight}{-\\headsep}
3434 \\addtolength{\\textheight}{-\\footskip}
3435 \\addtolength{\\textheight}{-3cm}
3436 \\setlength{\\topmargin}{1.5cm}
3437 \\addtolength{\\topmargin}{-2.54cm}"
3438 "The document header used for processing LaTeX fragments.
3439 It is imperative that this header make sure that no page number
3440 appears on the page. The package defined in the variables
3441 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3442 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3443 will be appended."
3444 :group 'org-latex
3445 :type 'string)
3447 (defvar org-format-latex-header-extra nil)
3449 (defun org-set-packages-alist (var val)
3450 "Set the packages alist and make sure it has 3 elements per entry."
3451 (set var (mapcar (lambda (x)
3452 (if (and (consp x) (= (length x) 2))
3453 (list (car x) (nth 1 x) t)
3455 val)))
3457 (defun org-get-packages-alist (var)
3459 "Get the packages alist and make sure it has 3 elements per entry."
3460 (mapcar (lambda (x)
3461 (if (and (consp x) (= (length x) 2))
3462 (list (car x) (nth 1 x) t)
3464 (default-value var)))
3466 ;; The following variables are defined here because is it also used
3467 ;; when formatting latex fragments. Originally it was part of the
3468 ;; LaTeX exporter, which is why the name includes "export".
3469 (defcustom org-export-latex-default-packages-alist
3470 '(("AUTO" "inputenc" t)
3471 ("T1" "fontenc" t)
3472 ("" "fixltx2e" nil)
3473 ("" "graphicx" t)
3474 ("" "longtable" nil)
3475 ("" "float" nil)
3476 ("" "wrapfig" nil)
3477 ("" "soul" t)
3478 ("" "textcomp" t)
3479 ("" "marvosym" t)
3480 ("" "wasysym" t)
3481 ("" "latexsym" t)
3482 ("" "amssymb" t)
3483 ("" "hyperref" nil)
3484 "\\tolerance=1000"
3486 "Alist of default packages to be inserted in the header.
3487 Change this only if one of the packages here causes an incompatibility
3488 with another package you are using.
3489 The packages in this list are needed by one part or another of Org-mode
3490 to function properly.
3492 - inputenc, fontenc: for basic font and character selection
3493 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3494 for interpreting the entities in `org-entities'. You can skip some of these
3495 packages if you don't use any of the symbols in it.
3496 - graphicx: for including images
3497 - float, wrapfig: for figure placement
3498 - longtable: for long tables
3499 - hyperref: for cross references
3501 Therefore you should not modify this variable unless you know what you
3502 are doing. The one reason to change it anyway is that you might be loading
3503 some other package that conflicts with one of the default packages.
3504 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3505 If SNIPPET-FLAG is t, the package also needs to be included when
3506 compiling LaTeX snippets into images for inclusion into HTML."
3507 :group 'org-export-latex
3508 :set 'org-set-packages-alist
3509 :get 'org-get-packages-alist
3510 :version "24.1"
3511 :type '(repeat
3512 (choice
3513 (list :tag "options/package pair"
3514 (string :tag "options")
3515 (string :tag "package")
3516 (boolean :tag "Snippet"))
3517 (string :tag "A line of LaTeX"))))
3519 (defcustom org-export-latex-packages-alist nil
3520 "Alist of packages to be inserted in every LaTeX header.
3521 These will be inserted after `org-export-latex-default-packages-alist'.
3522 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3523 SNIPPET-FLAG, when t, indicates that this package is also needed when
3524 turning LaTeX snippets into images for inclusion into HTML.
3525 Make sure that you only list packages here which:
3526 - you want in every file
3527 - do not conflict with the default packages in
3528 `org-export-latex-default-packages-alist'
3529 - do not conflict with the setup in `org-format-latex-header'."
3530 :group 'org-export-latex
3531 :set 'org-set-packages-alist
3532 :get 'org-get-packages-alist
3533 :type '(repeat
3534 (choice
3535 (list :tag "options/package pair"
3536 (string :tag "options")
3537 (string :tag "package")
3538 (boolean :tag "Snippet"))
3539 (string :tag "A line of LaTeX"))))
3542 (defgroup org-appearance nil
3543 "Settings for Org-mode appearance."
3544 :tag "Org Appearance"
3545 :group 'org)
3547 (defcustom org-level-color-stars-only nil
3548 "Non-nil means fontify only the stars in each headline.
3549 When nil, the entire headline is fontified.
3550 Changing it requires restart of `font-lock-mode' to become effective
3551 also in regions already fontified."
3552 :group 'org-appearance
3553 :type 'boolean)
3555 (defcustom org-hide-leading-stars nil
3556 "Non-nil means hide the first N-1 stars in a headline.
3557 This works by using the face `org-hide' for these stars. This
3558 face is white for a light background, and black for a dark
3559 background. You may have to customize the face `org-hide' to
3560 make this work.
3561 Changing it requires restart of `font-lock-mode' to become effective
3562 also in regions already fontified.
3563 You may also set this on a per-file basis by adding one of the following
3564 lines to the buffer:
3566 #+STARTUP: hidestars
3567 #+STARTUP: showstars"
3568 :group 'org-appearance
3569 :type 'boolean)
3571 (defcustom org-hidden-keywords nil
3572 "List of symbols corresponding to keywords to be hidden the org buffer.
3573 For example, a value '(title) for this list will make the document's title
3574 appear in the buffer without the initial #+TITLE: keyword."
3575 :group 'org-appearance
3576 :version "24.1"
3577 :type '(set (const :tag "#+AUTHOR" author)
3578 (const :tag "#+DATE" date)
3579 (const :tag "#+EMAIL" email)
3580 (const :tag "#+TITLE" title)))
3582 (defcustom org-custom-properties nil
3583 "List of properties (as strings) with a special meaning.
3584 The default use of these custom properties is to let the user
3585 hide them with `org-toggle-custom-properties-visibility'."
3586 :group 'org-properties
3587 :group 'org-appearance
3588 :version "24.3"
3589 :type '(repeat (string :tag "Property Name")))
3591 (defcustom org-fontify-done-headline nil
3592 "Non-nil means change the face of a headline if it is marked DONE.
3593 Normally, only the TODO/DONE keyword indicates the state of a headline.
3594 When this is non-nil, the headline after the keyword is set to the
3595 `org-headline-done' as an additional indication."
3596 :group 'org-appearance
3597 :type 'boolean)
3599 (defcustom org-fontify-emphasized-text t
3600 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3601 Changing this variable requires a restart of Emacs to take effect."
3602 :group 'org-appearance
3603 :type 'boolean)
3605 (defcustom org-fontify-whole-heading-line nil
3606 "Non-nil means fontify the whole line for headings.
3607 This is useful when setting a background color for the
3608 org-level-* faces."
3609 :group 'org-appearance
3610 :type 'boolean)
3612 (defcustom org-highlight-latex-fragments-and-specials nil
3613 "Non-nil means fontify what is treated specially by the exporters."
3614 :group 'org-appearance
3615 :type 'boolean)
3617 (defcustom org-hide-emphasis-markers nil
3618 "Non-nil mean font-lock should hide the emphasis marker characters."
3619 :group 'org-appearance
3620 :type 'boolean)
3622 (defcustom org-pretty-entities nil
3623 "Non-nil means show entities as UTF8 characters.
3624 When nil, the \\name form remains in the buffer."
3625 :group 'org-appearance
3626 :version "24.1"
3627 :type 'boolean)
3629 (defcustom org-pretty-entities-include-sub-superscripts t
3630 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3631 :group 'org-appearance
3632 :version "24.1"
3633 :type 'boolean)
3635 (defvar org-emph-re nil
3636 "Regular expression for matching emphasis.
3637 After a match, the match groups contain these elements:
3638 0 The match of the full regular expression, including the characters
3639 before and after the proper match
3640 1 The character before the proper match, or empty at beginning of line
3641 2 The proper match, including the leading and trailing markers
3642 3 The leading marker like * or /, indicating the type of highlighting
3643 4 The text between the emphasis markers, not including the markers
3644 5 The character after the match, empty at the end of a line")
3645 (defvar org-verbatim-re nil
3646 "Regular expression for matching verbatim text.")
3647 (defvar org-emphasis-regexp-components) ; defined just below
3648 (defvar org-emphasis-alist) ; defined just below
3649 (defun org-set-emph-re (var val)
3650 "Set variable and compute the emphasis regular expression."
3651 (set var val)
3652 (when (and (boundp 'org-emphasis-alist)
3653 (boundp 'org-emphasis-regexp-components)
3654 org-emphasis-alist org-emphasis-regexp-components)
3655 (let* ((e org-emphasis-regexp-components)
3656 (pre (car e))
3657 (post (nth 1 e))
3658 (border (nth 2 e))
3659 (body (nth 3 e))
3660 (nl (nth 4 e))
3661 (body1 (concat body "*?"))
3662 (markers (mapconcat 'car org-emphasis-alist ""))
3663 (vmarkers (mapconcat
3664 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3665 org-emphasis-alist "")))
3666 ;; make sure special characters appear at the right position in the class
3667 (if (string-match "\\^" markers)
3668 (setq markers (concat (replace-match "" t t markers) "^")))
3669 (if (string-match "-" markers)
3670 (setq markers (concat (replace-match "" t t markers) "-")))
3671 (if (string-match "\\^" vmarkers)
3672 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3673 (if (string-match "-" vmarkers)
3674 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3675 (if (> nl 0)
3676 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3677 (int-to-string nl) "\\}")))
3678 ;; Make the regexp
3679 (setq org-emph-re
3680 (concat "\\([" pre "]\\|^\\)"
3681 "\\("
3682 "\\([" markers "]\\)"
3683 "\\("
3684 "[^" border "]\\|"
3685 "[^" border "]"
3686 body1
3687 "[^" border "]"
3688 "\\)"
3689 "\\3\\)"
3690 "\\([" post "]\\|$\\)"))
3691 (setq org-verbatim-re
3692 (concat "\\([" pre "]\\|^\\)"
3693 "\\("
3694 "\\([" vmarkers "]\\)"
3695 "\\("
3696 "[^" border "]\\|"
3697 "[^" border "]"
3698 body1
3699 "[^" border "]"
3700 "\\)"
3701 "\\3\\)"
3702 "\\([" post "]\\|$\\)")))))
3704 (defcustom org-emphasis-regexp-components
3705 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3706 "Components used to build the regular expression for emphasis.
3707 This is a list with five entries. Terminology: In an emphasis string
3708 like \" *strong word* \", we call the initial space PREMATCH, the final
3709 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3710 and \"trong wor\" is the body. The different components in this variable
3711 specify what is allowed/forbidden in each part:
3713 pre Chars allowed as prematch. Beginning of line will be allowed too.
3714 post Chars allowed as postmatch. End of line will be allowed too.
3715 border The chars *forbidden* as border characters.
3716 body-regexp A regexp like \".\" to match a body character. Don't use
3717 non-shy groups here, and don't allow newline here.
3718 newline The maximum number of newlines allowed in an emphasis exp.
3720 Use customize to modify this, or restart Emacs after changing it."
3721 :group 'org-appearance
3722 :set 'org-set-emph-re
3723 :type '(list
3724 (sexp :tag "Allowed chars in pre ")
3725 (sexp :tag "Allowed chars in post ")
3726 (sexp :tag "Forbidden chars in border ")
3727 (sexp :tag "Regexp for body ")
3728 (integer :tag "number of newlines allowed")
3729 (option (boolean :tag "Please ignore this button"))))
3731 (defcustom org-emphasis-alist
3732 `(("*" bold "<b>" "</b>")
3733 ("/" italic "<i>" "</i>")
3734 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3735 ("=" org-code "<code>" "</code>" verbatim)
3736 ("~" org-verbatim "<code>" "</code>" verbatim)
3737 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3738 "<del>" "</del>")
3740 "Special syntax for emphasized text.
3741 Text starting and ending with a special character will be emphasized, for
3742 example *bold*, _underlined_ and /italic/. This variable sets the marker
3743 characters, the face to be used by font-lock for highlighting in Org-mode
3744 Emacs buffers, and the HTML tags to be used for this.
3745 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3746 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3747 Use customize to modify this, or restart Emacs after changing it."
3748 :group 'org-appearance
3749 :set 'org-set-emph-re
3750 :type '(repeat
3751 (list
3752 (string :tag "Marker character")
3753 (choice
3754 (face :tag "Font-lock-face")
3755 (plist :tag "Face property list"))
3756 (string :tag "HTML start tag")
3757 (string :tag "HTML end tag")
3758 (option (const verbatim)))))
3760 (defvar org-protecting-blocks
3761 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3762 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3763 This is needed for font-lock setup.")
3765 ;;; Miscellaneous options
3767 (defgroup org-completion nil
3768 "Completion in Org-mode."
3769 :tag "Org Completion"
3770 :group 'org)
3772 (defcustom org-completion-use-ido nil
3773 "Non-nil means use ido completion wherever possible.
3774 Note that `ido-mode' must be active for this variable to be relevant.
3775 If you decide to turn this variable on, you might well want to turn off
3776 `org-outline-path-complete-in-steps'.
3777 See also `org-completion-use-iswitchb'."
3778 :group 'org-completion
3779 :type 'boolean)
3781 (defcustom org-completion-use-iswitchb nil
3782 "Non-nil means use iswitchb completion wherever possible.
3783 Note that `iswitchb-mode' must be active for this variable to be relevant.
3784 If you decide to turn this variable on, you might well want to turn off
3785 `org-outline-path-complete-in-steps'.
3786 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3787 :group 'org-completion
3788 :type 'boolean)
3790 (defcustom org-completion-fallback-command 'hippie-expand
3791 "The expansion command called by \\[pcomplete] in normal context.
3792 Normal means, no org-mode-specific context."
3793 :group 'org-completion
3794 :type 'function)
3796 ;;; Functions and variables from their packages
3797 ;; Declared here to avoid compiler warnings
3799 ;; XEmacs only
3800 (defvar outline-mode-menu-heading)
3801 (defvar outline-mode-menu-show)
3802 (defvar outline-mode-menu-hide)
3803 (defvar zmacs-regions) ; XEmacs regions
3805 ;; Emacs only
3806 (defvar mark-active)
3808 ;; Various packages
3809 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3810 (declare-function calendar-forward-day "cal-move" (arg))
3811 (declare-function calendar-goto-date "cal-move" (date))
3812 (declare-function calendar-goto-today "cal-move" ())
3813 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3814 (defvar calc-embedded-close-formula)
3815 (defvar calc-embedded-open-formula)
3816 (declare-function cdlatex-tab "ext:cdlatex" ())
3817 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3818 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3819 (defvar font-lock-unfontify-region-function)
3820 (declare-function iswitchb-read-buffer "iswitchb"
3821 (prompt &optional default require-match start matches-set))
3822 (defvar iswitchb-temp-buflist)
3823 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3824 (defvar org-agenda-tags-todo-honor-ignore-options)
3825 (declare-function org-agenda-skip "org-agenda" ())
3826 (declare-function
3827 org-agenda-format-item "org-agenda"
3828 (extra txt &optional category tags dotime noprefix remove-re habitp))
3829 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3830 (declare-function org-agenda-change-all-lines "org-agenda"
3831 (newhead hdmarker &optional fixface just-this))
3832 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3833 (declare-function org-agenda-maybe-redo "org-agenda" ())
3834 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3835 (beg end))
3836 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3837 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3838 "org-agenda" (&optional end))
3839 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3840 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3841 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3842 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3843 (declare-function org-indent-mode "org-indent" (&optional arg))
3844 (declare-function parse-time-string "parse-time" (string))
3845 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3846 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3847 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3848 (defvar remember-data-file)
3849 (defvar texmathp-why)
3850 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3851 (declare-function table--at-cell-p "table" (position &optional object at-column))
3853 (defvar w3m-current-url)
3854 (defvar w3m-current-title)
3856 (defvar org-latex-regexps)
3858 ;;; Autoload and prepare some org modules
3860 ;; Some table stuff that needs to be defined here, because it is used
3861 ;; by the functions setting up org-mode or checking for table context.
3863 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3864 "Detect an org-type or table-type table.")
3865 (defconst org-table-line-regexp "^[ \t]*|"
3866 "Detect an org-type table line.")
3867 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3868 "Detect an org-type table line.")
3869 (defconst org-table-hline-regexp "^[ \t]*|-"
3870 "Detect an org-type table hline.")
3871 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3872 "Detect a table-type table hline.")
3873 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3874 "Detect the first line outside a table when searching from within it.
3875 This works for both table types.")
3877 ;; Autoload the functions in org-table.el that are needed by functions here.
3879 (eval-and-compile
3880 (org-autoload "org-table"
3881 '(org-table-begin org-table-blank-field org-table-end)))
3883 ;;;###autoload
3884 (defun turn-on-orgtbl ()
3885 "Unconditionally turn on `orgtbl-mode'."
3886 (require 'org-table)
3887 (orgtbl-mode 1))
3889 (defun org-at-table-p (&optional table-type)
3890 "Return t if the cursor is inside an org-type table.
3891 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3892 (if org-enable-table-editor
3893 (save-excursion
3894 (beginning-of-line 1)
3895 (looking-at (if table-type org-table-any-line-regexp
3896 org-table-line-regexp)))
3897 nil))
3898 (defsubst org-table-p () (org-at-table-p))
3900 (defun org-at-table.el-p ()
3901 "Return t if and only if we are at a table.el table."
3902 (and (org-at-table-p 'any)
3903 (save-excursion
3904 (goto-char (org-table-begin 'any))
3905 (looking-at org-table1-hline-regexp))))
3906 (defun org-table-recognize-table.el ()
3907 "If there is a table.el table nearby, recognize it and move into it."
3908 (if org-table-tab-recognizes-table.el
3909 (if (org-at-table.el-p)
3910 (progn
3911 (beginning-of-line 1)
3912 (if (looking-at org-table-dataline-regexp)
3914 (if (looking-at org-table1-hline-regexp)
3915 (progn
3916 (beginning-of-line 2)
3917 (if (looking-at org-table-any-border-regexp)
3918 (beginning-of-line -1)))))
3919 (if (re-search-forward "|" (org-table-end t) t)
3920 (progn
3921 (require 'table)
3922 (if (table--at-cell-p (point))
3924 (message "recognizing table.el table...")
3925 (table-recognize-table)
3926 (message "recognizing table.el table...done")))
3927 (error "This should not happen"))
3929 nil)
3930 nil))
3932 (defun org-at-table-hline-p ()
3933 "Return t if the cursor is inside a hline in a table."
3934 (if org-enable-table-editor
3935 (save-excursion
3936 (beginning-of-line 1)
3937 (looking-at org-table-hline-regexp))
3938 nil))
3940 (defvar org-table-clean-did-remove-column nil)
3942 (defun org-table-map-tables (function &optional quietly)
3943 "Apply FUNCTION to the start of all tables in the buffer."
3944 (save-excursion
3945 (save-restriction
3946 (widen)
3947 (goto-char (point-min))
3948 (while (re-search-forward org-table-any-line-regexp nil t)
3949 (unless quietly
3950 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3951 (beginning-of-line 1)
3952 (when (and (looking-at org-table-line-regexp)
3953 ;; Exclude tables in src/example/verbatim/clocktable blocks
3954 (not (org-in-block-p '("src" "example"))))
3955 (save-excursion (funcall function))
3956 (or (looking-at org-table-line-regexp)
3957 (forward-char 1)))
3958 (re-search-forward org-table-any-border-regexp nil 1))))
3959 (unless quietly (message "Mapping tables: done")))
3961 ;; Declare and autoload functions from org-exp.el & Co
3963 (declare-function org-default-export-plist "org-exp")
3964 (declare-function org-infile-export-plist "org-exp")
3965 (declare-function org-get-current-options "org-exp")
3967 ;; Declare and autoload functions from org-agenda.el
3969 (eval-and-compile
3970 (org-autoload "org-agenda"
3971 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3973 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3974 (declare-function org-clock-update-mode-line "org-clock" ())
3975 (declare-function org-resolve-clocks "org-clock"
3976 (&optional also-non-dangling-p prompt last-valid))
3977 (defvar org-clock-start-time)
3978 (defvar org-clock-marker (make-marker)
3979 "Marker recording the last clock-in.")
3980 (defvar org-clock-hd-marker (make-marker)
3981 "Marker recording the last clock-in, but the headline position.")
3982 (defvar org-clock-heading ""
3983 "The heading of the current clock entry.")
3984 (defun org-clock-is-active ()
3985 "Return non-nil if clock is currently running.
3986 The return value is actually the clock marker."
3987 (marker-buffer org-clock-marker))
3989 (eval-and-compile
3990 (org-autoload "org-clock" '(org-clock-remove-overlays
3991 org-clock-update-time-maybe
3992 org-clocktable-shift)))
3994 (defun org-check-running-clock ()
3995 "Check if the current buffer contains the running clock.
3996 If yes, offer to stop it and to save the buffer with the changes."
3997 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3998 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3999 (buffer-name))))
4000 (org-clock-out)
4001 (when (y-or-n-p "Save changed buffer?")
4002 (save-buffer))))
4004 (defun org-clocktable-try-shift (dir n)
4005 "Check if this line starts a clock table, if yes, shift the time block."
4006 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4007 (org-clocktable-shift dir n)))
4009 ;;;###autoload
4010 (defun org-clock-persistence-insinuate ()
4011 "Set up hooks for clock persistence."
4012 (require 'org-clock)
4013 (add-hook 'org-mode-hook 'org-clock-load)
4014 (add-hook 'kill-emacs-hook 'org-clock-save))
4016 ;; Define the variable already here, to make sure we have it.
4017 (defvar org-indent-mode nil
4018 "Non-nil if Org-Indent mode is enabled.
4019 Use the command `org-indent-mode' to change this variable.")
4021 ;; Autoload archiving code
4022 ;; The stuff that is needed for cycling and tags has to be defined here.
4024 (defgroup org-archive nil
4025 "Options concerning archiving in Org-mode."
4026 :tag "Org Archive"
4027 :group 'org-structure)
4029 (defcustom org-archive-location "%s_archive::"
4030 "The location where subtrees should be archived.
4032 The value of this variable is a string, consisting of two parts,
4033 separated by a double-colon. The first part is a filename and
4034 the second part is a headline.
4036 When the filename is omitted, archiving happens in the same file.
4037 %s in the filename will be replaced by the current file
4038 name (without the directory part). Archiving to a different file
4039 is useful to keep archived entries from contributing to the
4040 Org-mode Agenda.
4042 The archived entries will be filed as subtrees of the specified
4043 headline. When the headline is omitted, the subtrees are simply
4044 filed away at the end of the file, as top-level entries. Also in
4045 the heading you can use %s to represent the file name, this can be
4046 useful when using the same archive for a number of different files.
4048 Here are a few examples:
4049 \"%s_archive::\"
4050 If the current file is Projects.org, archive in file
4051 Projects.org_archive, as top-level trees. This is the default.
4053 \"::* Archived Tasks\"
4054 Archive in the current file, under the top-level headline
4055 \"* Archived Tasks\".
4057 \"~/org/archive.org::\"
4058 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4060 \"~/org/archive.org::* From %s\"
4061 Archive in file ~/org/archive.org (absolute path), under headlines
4062 \"From FILENAME\" where file name is the current file name.
4064 \"~/org/datetree.org::datetree/* Finished Tasks\"
4065 The \"datetree/\" string is special, signifying to archive
4066 items to the datetree. Items are placed in either the CLOSED
4067 date of the item, or the current date if there is no CLOSED date.
4068 The heading will be a subentry to the current date. There doesn't
4069 need to be a heading, but there always needs to be a slash after
4070 datetree. For example, to store archived items directly in the
4071 datetree, use \"~/org/datetree.org::datetree/\".
4073 \"basement::** Finished Tasks\"
4074 Archive in file ./basement (relative path), as level 3 trees
4075 below the level 2 heading \"** Finished Tasks\".
4077 You may set this option on a per-file basis by adding to the buffer a
4078 line like
4080 #+ARCHIVE: basement::** Finished Tasks
4082 You may also define it locally for a subtree by setting an ARCHIVE property
4083 in the entry. If such a property is found in an entry, or anywhere up
4084 the hierarchy, it will be used."
4085 :group 'org-archive
4086 :type 'string)
4088 (defcustom org-archive-tag "ARCHIVE"
4089 "The tag that marks a subtree as archived.
4090 An archived subtree does not open during visibility cycling, and does
4091 not contribute to the agenda listings.
4092 After changing this, font-lock must be restarted in the relevant buffers to
4093 get the proper fontification."
4094 :group 'org-archive
4095 :group 'org-keywords
4096 :type 'string)
4098 (defcustom org-agenda-skip-archived-trees t
4099 "Non-nil means the agenda will skip any items located in archived trees.
4100 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4101 variable is no longer recommended, you should leave it at the value t.
4102 Instead, use the key `v' to cycle the archives-mode in the agenda."
4103 :group 'org-archive
4104 :group 'org-agenda-skip
4105 :type 'boolean)
4107 (defcustom org-columns-skip-archived-trees t
4108 "Non-nil means ignore archived trees when creating column view."
4109 :group 'org-archive
4110 :group 'org-properties
4111 :type 'boolean)
4113 (defcustom org-cycle-open-archived-trees nil
4114 "Non-nil means `org-cycle' will open archived trees.
4115 An archived tree is a tree marked with the tag ARCHIVE.
4116 When nil, archived trees will stay folded. You can still open them with
4117 normal outline commands like `show-all', but not with the cycling commands."
4118 :group 'org-archive
4119 :group 'org-cycle
4120 :type 'boolean)
4122 (defcustom org-sparse-tree-open-archived-trees nil
4123 "Non-nil means sparse tree construction shows matches in archived trees.
4124 When nil, matches in these trees are highlighted, but the trees are kept in
4125 collapsed state."
4126 :group 'org-archive
4127 :group 'org-sparse-trees
4128 :type 'boolean)
4130 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4131 "The default date type when building a sparse tree.
4132 When this is nil, a date is a scheduled or a deadline timestamp.
4133 Otherwise, these types are allowed:
4135 all: all timestamps
4136 active: only active timestamps (<...>)
4137 inactive: only inactive timestamps (<...)
4138 scheduled: only scheduled timestamps
4139 deadline: only deadline timestamps"
4140 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4141 (const :tag "All timestamps" all)
4142 (const :tag "Only active timestamps" active)
4143 (const :tag "Only inactive timestamps" inactive)
4144 (const :tag "Only scheduled timestamps" scheduled)
4145 (const :tag "Only deadline timestamps" deadline))
4146 :version "24.3"
4147 :group 'org-sparse-trees)
4149 (defun org-cycle-hide-archived-subtrees (state)
4150 "Re-hide all archived subtrees after a visibility state change."
4151 (when (and (not org-cycle-open-archived-trees)
4152 (not (memq state '(overview folded))))
4153 (save-excursion
4154 (let* ((globalp (memq state '(contents all)))
4155 (beg (if globalp (point-min) (point)))
4156 (end (if globalp (point-max) (org-end-of-subtree t))))
4157 (org-hide-archived-subtrees beg end)
4158 (goto-char beg)
4159 (if (looking-at (concat ".*:" org-archive-tag ":"))
4160 (message "%s" (substitute-command-keys
4161 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4163 (defun org-force-cycle-archived ()
4164 "Cycle subtree even if it is archived."
4165 (interactive)
4166 (setq this-command 'org-cycle)
4167 (let ((org-cycle-open-archived-trees t))
4168 (call-interactively 'org-cycle)))
4170 (defun org-hide-archived-subtrees (beg end)
4171 "Re-hide all archived subtrees after a visibility state change."
4172 (save-excursion
4173 (let* ((re (concat ":" org-archive-tag ":")))
4174 (goto-char beg)
4175 (while (re-search-forward re end t)
4176 (when (org-at-heading-p)
4177 (org-flag-subtree t)
4178 (org-end-of-subtree t))))))
4180 (declare-function outline-end-of-heading "outline" ())
4181 (declare-function outline-flag-region "outline" (from to flag))
4182 (defun org-flag-subtree (flag)
4183 (save-excursion
4184 (org-back-to-heading t)
4185 (outline-end-of-heading)
4186 (outline-flag-region (point)
4187 (progn (org-end-of-subtree t) (point))
4188 flag)))
4190 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4192 (eval-and-compile
4193 (org-autoload "org-archive"
4194 '(org-add-archive-files)))
4196 ;; Autoload Column View Code
4198 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4199 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4200 (declare-function org-columns-compute "org-colview" (property))
4202 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4203 '(org-columns-number-to-string
4204 org-columns-get-format-and-top-level
4205 org-columns-compute
4206 org-columns-remove-overlays))
4208 ;; Autoload ID code
4210 (declare-function org-id-store-link "org-id")
4211 (declare-function org-id-locations-load "org-id")
4212 (declare-function org-id-locations-save "org-id")
4213 (defvar org-id-track-globally)
4214 (org-autoload "org-id"
4215 '(org-id-new
4216 org-id-copy
4217 org-id-get-with-outline-path-completion
4218 org-id-get-with-outline-drilling))
4220 ;;; Variables for pre-computed regular expressions, all buffer local
4222 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4223 "Matches first line of a hidden block.")
4224 (make-variable-buffer-local 'org-drawer-regexp)
4225 (defvar org-todo-regexp nil
4226 "Matches any of the TODO state keywords.")
4227 (make-variable-buffer-local 'org-todo-regexp)
4228 (defvar org-not-done-regexp nil
4229 "Matches any of the TODO state keywords except the last one.")
4230 (make-variable-buffer-local 'org-not-done-regexp)
4231 (defvar org-not-done-heading-regexp nil
4232 "Matches a TODO headline that is not done.")
4233 (make-variable-buffer-local 'org-not-done-regexp)
4234 (defvar org-todo-line-regexp nil
4235 "Matches a headline and puts TODO state into group 2 if present.")
4236 (make-variable-buffer-local 'org-todo-line-regexp)
4237 (defvar org-complex-heading-regexp nil
4238 "Matches a headline and puts everything into groups:
4239 group 1: the stars
4240 group 2: The todo keyword, maybe
4241 group 3: Priority cookie
4242 group 4: True headline
4243 group 5: Tags")
4244 (make-variable-buffer-local 'org-complex-heading-regexp)
4245 (defvar org-complex-heading-regexp-format nil
4246 "Printf format to make regexp to match an exact headline.
4247 This regexp will match the headline of any node which has the
4248 exact headline text that is put into the format, but may have any
4249 TODO state, priority and tags.")
4250 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4251 (defvar org-todo-line-tags-regexp nil
4252 "Matches a headline and puts TODO state into group 2 if present.
4253 Also put tags into group 4 if tags are present.")
4254 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4255 (defvar org-ds-keyword-length 12
4256 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4257 (make-variable-buffer-local 'org-ds-keyword-length)
4258 (defvar org-deadline-regexp nil
4259 "Matches the DEADLINE keyword.")
4260 (make-variable-buffer-local 'org-deadline-regexp)
4261 (defvar org-deadline-time-regexp nil
4262 "Matches the DEADLINE keyword together with a time stamp.")
4263 (make-variable-buffer-local 'org-deadline-time-regexp)
4264 (defvar org-deadline-line-regexp nil
4265 "Matches the DEADLINE keyword and the rest of the line.")
4266 (make-variable-buffer-local 'org-deadline-line-regexp)
4267 (defvar org-scheduled-regexp nil
4268 "Matches the SCHEDULED keyword.")
4269 (make-variable-buffer-local 'org-scheduled-regexp)
4270 (defvar org-scheduled-time-regexp nil
4271 "Matches the SCHEDULED keyword together with a time stamp.")
4272 (make-variable-buffer-local 'org-scheduled-time-regexp)
4273 (defvar org-closed-time-regexp nil
4274 "Matches the CLOSED keyword together with a time stamp.")
4275 (make-variable-buffer-local 'org-closed-time-regexp)
4277 (defvar org-keyword-time-regexp nil
4278 "Matches any of the 4 keywords, together with the time stamp.")
4279 (make-variable-buffer-local 'org-keyword-time-regexp)
4280 (defvar org-keyword-time-not-clock-regexp nil
4281 "Matches any of the 3 keywords, together with the time stamp.")
4282 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4283 (defvar org-maybe-keyword-time-regexp nil
4284 "Matches a timestamp, possibly preceded by a keyword.")
4285 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4286 (defvar org-all-time-keywords nil
4287 "List of time keywords.")
4288 (make-variable-buffer-local 'org-all-time-keywords)
4290 (defconst org-plain-time-of-day-regexp
4291 (concat
4292 "\\(\\<[012]?[0-9]"
4293 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4294 "\\(--?"
4295 "\\(\\<[012]?[0-9]"
4296 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4297 "\\)?")
4298 "Regular expression to match a plain time or time range.
4299 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4300 groups carry important information:
4301 0 the full match
4302 1 the first time, range or not
4303 8 the second time, if it is a range.")
4305 (defconst org-plain-time-extension-regexp
4306 (concat
4307 "\\(\\<[012]?[0-9]"
4308 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4309 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4310 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4311 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4312 groups carry important information:
4313 0 the full match
4314 7 hours of duration
4315 9 minutes of duration")
4317 (defconst org-stamp-time-of-day-regexp
4318 (concat
4319 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4320 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4321 "\\(--?"
4322 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4323 "Regular expression to match a timestamp time or time range.
4324 After a match, the following groups carry important information:
4325 0 the full match
4326 1 date plus weekday, for back referencing to make sure both times are on the same day
4327 2 the first time, range or not
4328 4 the second time, if it is a range.")
4330 (defconst org-startup-options
4331 '(("fold" org-startup-folded t)
4332 ("overview" org-startup-folded t)
4333 ("nofold" org-startup-folded nil)
4334 ("showall" org-startup-folded nil)
4335 ("showeverything" org-startup-folded showeverything)
4336 ("content" org-startup-folded content)
4337 ("indent" org-startup-indented t)
4338 ("noindent" org-startup-indented nil)
4339 ("hidestars" org-hide-leading-stars t)
4340 ("showstars" org-hide-leading-stars nil)
4341 ("odd" org-odd-levels-only t)
4342 ("oddeven" org-odd-levels-only nil)
4343 ("align" org-startup-align-all-tables t)
4344 ("noalign" org-startup-align-all-tables nil)
4345 ("inlineimages" org-startup-with-inline-images t)
4346 ("noinlineimages" org-startup-with-inline-images nil)
4347 ("customtime" org-display-custom-times t)
4348 ("logdone" org-log-done time)
4349 ("lognotedone" org-log-done note)
4350 ("nologdone" org-log-done nil)
4351 ("lognoteclock-out" org-log-note-clock-out t)
4352 ("nolognoteclock-out" org-log-note-clock-out nil)
4353 ("logrepeat" org-log-repeat state)
4354 ("lognoterepeat" org-log-repeat note)
4355 ("nologrepeat" org-log-repeat nil)
4356 ("logreschedule" org-log-reschedule time)
4357 ("lognotereschedule" org-log-reschedule note)
4358 ("nologreschedule" org-log-reschedule nil)
4359 ("logredeadline" org-log-redeadline time)
4360 ("lognoteredeadline" org-log-redeadline note)
4361 ("nologredeadline" org-log-redeadline nil)
4362 ("logrefile" org-log-refile time)
4363 ("lognoterefile" org-log-refile note)
4364 ("nologrefile" org-log-refile nil)
4365 ("fninline" org-footnote-define-inline t)
4366 ("nofninline" org-footnote-define-inline nil)
4367 ("fnlocal" org-footnote-section nil)
4368 ("fnauto" org-footnote-auto-label t)
4369 ("fnprompt" org-footnote-auto-label nil)
4370 ("fnconfirm" org-footnote-auto-label confirm)
4371 ("fnplain" org-footnote-auto-label plain)
4372 ("fnadjust" org-footnote-auto-adjust t)
4373 ("nofnadjust" org-footnote-auto-adjust nil)
4374 ("constcgs" constants-unit-system cgs)
4375 ("constSI" constants-unit-system SI)
4376 ("noptag" org-tag-persistent-alist nil)
4377 ("hideblocks" org-hide-block-startup t)
4378 ("nohideblocks" org-hide-block-startup nil)
4379 ("beamer" org-startup-with-beamer-mode t)
4380 ("entitiespretty" org-pretty-entities t)
4381 ("entitiesplain" org-pretty-entities nil))
4382 "Variable associated with STARTUP options for org-mode.
4383 Each element is a list of three items: the startup options (as written
4384 in the #+STARTUP line), the corresponding variable, and the value to set
4385 this variable to if the option is found. An optional forth element PUSH
4386 means to push this value onto the list in the variable.")
4388 (defun org-update-property-plist (key val props)
4389 "Update PROPS with KEY and VAL."
4390 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4391 (key (if appending (substring key 0 (- (length key) 1)) key))
4392 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4393 (previous (cdr (assoc key props))))
4394 (if appending
4395 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4396 (cons (cons key val) remainder))))
4398 (defconst org-block-regexp
4399 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4400 "Regular expression for hiding blocks.")
4401 (defconst org-heading-keyword-regexp-format
4402 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4403 "Printf format for a regexp matching an headline with some keyword.
4404 This regexp will match the headline of any node which has the
4405 exact keyword that is put into the format. The keyword isn't in
4406 any group by default, but the stars and the body are.")
4407 (defconst org-heading-keyword-maybe-regexp-format
4408 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4409 "Printf format for a regexp matching an headline, possibly with some keyword.
4410 This regexp can match any headline with the specified keyword, or
4411 without a keyword. The keyword isn't in any group by default,
4412 but the stars and the body are.")
4414 (defun org-set-regexps-and-options ()
4415 "Precompute regular expressions for current buffer."
4416 (when (derived-mode-p 'org-mode)
4417 (org-set-local 'org-todo-kwd-alist nil)
4418 (org-set-local 'org-todo-key-alist nil)
4419 (org-set-local 'org-todo-key-trigger nil)
4420 (org-set-local 'org-todo-keywords-1 nil)
4421 (org-set-local 'org-done-keywords nil)
4422 (org-set-local 'org-todo-heads nil)
4423 (org-set-local 'org-todo-sets nil)
4424 (org-set-local 'org-todo-log-states nil)
4425 (org-set-local 'org-file-properties nil)
4426 (org-set-local 'org-file-tags nil)
4427 (let ((re (org-make-options-regexp
4428 '("CATEGORY" "TODO" "COLUMNS"
4429 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4430 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4431 "OPTIONS")
4432 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4433 (splitre "[ \t]+")
4434 (scripts org-use-sub-superscripts)
4435 kwds kws0 kwsa key log value cat arch tags const links hw dws
4436 tail sep kws1 prio props ftags drawers beamer-p
4437 ext-setup-or-nil setup-contents (start 0))
4438 (save-excursion
4439 (save-restriction
4440 (widen)
4441 (goto-char (point-min))
4442 (while (or (and ext-setup-or-nil
4443 (string-match re ext-setup-or-nil start)
4444 (setq start (match-end 0)))
4445 (and (setq ext-setup-or-nil nil start 0)
4446 (re-search-forward re nil t)))
4447 (setq key (upcase (match-string 1 ext-setup-or-nil))
4448 value (org-match-string-no-properties 2 ext-setup-or-nil))
4449 (if (stringp value) (setq value (org-trim value)))
4450 (cond
4451 ((equal key "CATEGORY")
4452 (setq cat value))
4453 ((member key '("SEQ_TODO" "TODO"))
4454 (push (cons 'sequence (org-split-string value splitre)) kwds))
4455 ((equal key "TYP_TODO")
4456 (push (cons 'type (org-split-string value splitre)) kwds))
4457 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4458 ;; general TODO-like setup
4459 (push (cons (intern (downcase (match-string 1 key)))
4460 (org-split-string value splitre)) kwds))
4461 ((equal key "TAGS")
4462 (setq tags (append tags (if tags '("\\n") nil)
4463 (org-split-string value splitre))))
4464 ((equal key "COLUMNS")
4465 (org-set-local 'org-columns-default-format value))
4466 ((equal key "LINK")
4467 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4468 (push (cons (match-string 1 value)
4469 (org-trim (match-string 2 value)))
4470 links)))
4471 ((equal key "PRIORITIES")
4472 (setq prio (org-split-string value " +")))
4473 ((equal key "PROPERTY")
4474 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4475 (setq props (org-update-property-plist (match-string 1 value)
4476 (match-string 2 value)
4477 props))))
4478 ((equal key "FILETAGS")
4479 (when (string-match "\\S-" value)
4480 (setq ftags
4481 (append
4482 ftags
4483 (apply 'append
4484 (mapcar (lambda (x) (org-split-string x ":"))
4485 (org-split-string value)))))))
4486 ((equal key "DRAWERS")
4487 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4488 ((equal key "CONSTANTS")
4489 (setq const (append const (org-split-string value splitre))))
4490 ((equal key "STARTUP")
4491 (let ((opts (org-split-string value splitre))
4492 l var val)
4493 (while (setq l (pop opts))
4494 (when (setq l (assoc l org-startup-options))
4495 (setq var (nth 1 l) val (nth 2 l))
4496 (if (not (nth 3 l))
4497 (set (make-local-variable var) val)
4498 (if (not (listp (symbol-value var)))
4499 (set (make-local-variable var) nil))
4500 (set (make-local-variable var) (symbol-value var))
4501 (add-to-list var val))))))
4502 ((equal key "ARCHIVE")
4503 (setq arch value)
4504 (remove-text-properties 0 (length arch)
4505 '(face t fontified t) arch))
4506 ((equal key "LATEX_CLASS")
4507 (setq beamer-p (equal value "beamer")))
4508 ((equal key "OPTIONS")
4509 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4510 (setq scripts (read (match-string 2 value)))))
4511 ((equal key "SETUPFILE")
4512 (setq setup-contents (org-file-contents
4513 (expand-file-name
4514 (org-remove-double-quotes value))
4515 'noerror))
4516 (if (not ext-setup-or-nil)
4517 (setq ext-setup-or-nil setup-contents start 0)
4518 (setq ext-setup-or-nil
4519 (concat (substring ext-setup-or-nil 0 start)
4520 "\n" setup-contents "\n"
4521 (substring ext-setup-or-nil start)))))))
4522 ;; search for property blocks
4523 (goto-char (point-min))
4524 (while (re-search-forward org-block-regexp nil t)
4525 (when (equal "PROPERTY" (upcase (match-string 1)))
4526 (setq value (replace-regexp-in-string
4527 "[\n\r]" " " (match-string 4)))
4528 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4529 (setq props (org-update-property-plist (match-string 1 value)
4530 (match-string 2 value)
4531 props)))))))
4532 (org-set-local 'org-use-sub-superscripts scripts)
4533 (when cat
4534 (org-set-local 'org-category (intern cat))
4535 (push (cons "CATEGORY" cat) props))
4536 (when prio
4537 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4538 (setq prio (mapcar 'string-to-char prio))
4539 (org-set-local 'org-highest-priority (nth 0 prio))
4540 (org-set-local 'org-lowest-priority (nth 1 prio))
4541 (org-set-local 'org-default-priority (nth 2 prio)))
4542 (and props (org-set-local 'org-file-properties (nreverse props)))
4543 (and ftags (org-set-local 'org-file-tags
4544 (mapcar 'org-add-prop-inherited ftags)))
4545 (and drawers (org-set-local 'org-drawers drawers))
4546 (and arch (org-set-local 'org-archive-location arch))
4547 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4548 ;; Process the TODO keywords
4549 (unless kwds
4550 ;; Use the global values as if they had been given locally.
4551 (setq kwds (default-value 'org-todo-keywords))
4552 (if (stringp (car kwds))
4553 (setq kwds (list (cons org-todo-interpretation
4554 (default-value 'org-todo-keywords)))))
4555 (setq kwds (reverse kwds)))
4556 (setq kwds (nreverse kwds))
4557 (let (inter kws kw)
4558 (while (setq kws (pop kwds))
4559 (let ((kws (or
4560 (run-hook-with-args-until-success
4561 'org-todo-setup-filter-hook kws)
4562 kws)))
4563 (setq inter (pop kws) sep (member "|" kws)
4564 kws0 (delete "|" (copy-sequence kws))
4565 kwsa nil
4566 kws1 (mapcar
4567 (lambda (x)
4568 ;; 1 2
4569 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4570 (progn
4571 (setq kw (match-string 1 x)
4572 key (and (match-end 2) (match-string 2 x))
4573 log (org-extract-log-state-settings x))
4574 (push (cons kw (and key (string-to-char key))) kwsa)
4575 (and log (push log org-todo-log-states))
4577 (error "Invalid TODO keyword %s" x)))
4578 kws0)
4579 kwsa (if kwsa (append '((:startgroup))
4580 (nreverse kwsa)
4581 '((:endgroup))))
4582 hw (car kws1)
4583 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4584 tail (list inter hw (car dws) (org-last dws))))
4585 (add-to-list 'org-todo-heads hw 'append)
4586 (push kws1 org-todo-sets)
4587 (setq org-done-keywords (append org-done-keywords dws nil))
4588 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4589 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4590 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4591 (setq org-todo-sets (nreverse org-todo-sets)
4592 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4593 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4594 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4595 ;; Process the constants
4596 (when const
4597 (let (e cst)
4598 (while (setq e (pop const))
4599 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4600 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4601 (setq org-table-formula-constants-local cst)))
4603 ;; Process the tags.
4604 (when tags
4605 (let (e tgs)
4606 (while (setq e (pop tags))
4607 (cond
4608 ((equal e "{") (push '(:startgroup) tgs))
4609 ((equal e "}") (push '(:endgroup) tgs))
4610 ((equal e "\\n") (push '(:newline) tgs))
4611 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4612 (push (cons (match-string 1 e)
4613 (string-to-char (match-string 2 e)))
4614 tgs))
4615 (t (push (list e) tgs))))
4616 (org-set-local 'org-tag-alist nil)
4617 (while (setq e (pop tgs))
4618 (or (and (stringp (car e))
4619 (assoc (car e) org-tag-alist))
4620 (push e org-tag-alist)))))
4622 ;; Compute the regular expressions and other local variables.
4623 ;; Using `org-outline-regexp-bol' would complicate them much,
4624 ;; because of the fixed white space at the end of that string.
4625 (if (not org-done-keywords)
4626 (setq org-done-keywords (and org-todo-keywords-1
4627 (list (org-last org-todo-keywords-1)))))
4628 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4629 (length org-scheduled-string)
4630 (length org-clock-string)
4631 (length org-closed-string)))
4632 org-drawer-regexp
4633 (concat "^[ \t]*:\\("
4634 (mapconcat 'regexp-quote org-drawers "\\|")
4635 "\\):[ \t]*$")
4636 org-not-done-keywords
4637 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4638 org-todo-regexp
4639 (concat "\\("
4640 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4641 "\\)")
4642 org-not-done-regexp
4643 (concat "\\("
4644 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4645 "\\)")
4646 org-not-done-heading-regexp
4647 (format org-heading-keyword-regexp-format org-not-done-regexp)
4648 org-todo-line-regexp
4649 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4650 org-complex-heading-regexp
4651 (concat "^\\(\\*+\\)"
4652 "\\(?: +" org-todo-regexp "\\)?"
4653 "\\(?: +\\(\\[#.\\]\\)\\)?"
4654 "\\(?: +\\(.*?\\)\\)??"
4655 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4656 "[ \t]*$")
4657 org-complex-heading-regexp-format
4658 (concat "^\\(\\*+\\)"
4659 "\\(?: +" org-todo-regexp "\\)?"
4660 "\\(?: +\\(\\[#.\\]\\)\\)?"
4661 "\\(?: +"
4662 ;; Stats cookies can be stuck to body.
4663 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4664 "\\(%s\\)"
4665 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4666 "\\)"
4667 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4668 "[ \t]*$")
4669 org-todo-line-tags-regexp
4670 (concat "^\\(\\*+\\)"
4671 "\\(?: +" org-todo-regexp "\\)?"
4672 "\\(?: +\\(.*?\\)\\)??"
4673 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4674 "[ \t]*$")
4675 org-deadline-regexp (concat "\\<" org-deadline-string)
4676 org-deadline-time-regexp
4677 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4678 org-deadline-line-regexp
4679 (concat "\\<\\(" org-deadline-string "\\).*")
4680 org-scheduled-regexp
4681 (concat "\\<" org-scheduled-string)
4682 org-scheduled-time-regexp
4683 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4684 org-closed-time-regexp
4685 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4686 org-keyword-time-regexp
4687 (concat "\\<\\(" org-scheduled-string
4688 "\\|" org-deadline-string
4689 "\\|" org-closed-string
4690 "\\|" org-clock-string "\\)"
4691 " *[[<]\\([^]>]+\\)[]>]")
4692 org-keyword-time-not-clock-regexp
4693 (concat "\\<\\(" org-scheduled-string
4694 "\\|" org-deadline-string
4695 "\\|" org-closed-string
4696 "\\)"
4697 " *[[<]\\([^]>]+\\)[]>]")
4698 org-maybe-keyword-time-regexp
4699 (concat "\\(\\<\\(" org-scheduled-string
4700 "\\|" org-deadline-string
4701 "\\|" org-closed-string
4702 "\\|" org-clock-string "\\)\\)?"
4703 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4704 org-all-time-keywords
4705 (mapcar (lambda (w) (substring w 0 -1))
4706 (list org-scheduled-string org-deadline-string
4707 org-clock-string org-closed-string))
4709 (org-compute-latex-and-specials-regexp)
4710 (org-set-font-lock-defaults))))
4712 (defun org-file-contents (file &optional noerror)
4713 "Return the contents of FILE, as a string."
4714 (if (or (not file)
4715 (not (file-readable-p file)))
4716 (if noerror
4717 (progn
4718 (message "Cannot read file \"%s\"" file)
4719 (ding) (sit-for 2)
4721 (error "Cannot read file \"%s\"" file))
4722 (with-temp-buffer
4723 (insert-file-contents file)
4724 (buffer-string))))
4726 (defun org-extract-log-state-settings (x)
4727 "Extract the log state setting from a TODO keyword string.
4728 This will extract info from a string like \"WAIT(w@/!)\"."
4729 (let (kw key log1 log2)
4730 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4731 (setq kw (match-string 1 x)
4732 key (and (match-end 2) (match-string 2 x))
4733 log1 (and (match-end 3) (match-string 3 x))
4734 log2 (and (match-end 4) (match-string 4 x)))
4735 (and (or log1 log2)
4736 (list kw
4737 (and log1 (if (equal log1 "!") 'time 'note))
4738 (and log2 (if (equal log2 "!") 'time 'note)))))))
4740 (defun org-remove-keyword-keys (list)
4741 "Remove a pair of parenthesis at the end of each string in LIST."
4742 (mapcar (lambda (x)
4743 (if (string-match "(.*)$" x)
4744 (substring x 0 (match-beginning 0))
4746 list))
4748 (defun org-assign-fast-keys (alist)
4749 "Assign fast keys to a keyword-key alist.
4750 Respect keys that are already there."
4751 (let (new e (alt ?0))
4752 (while (setq e (pop alist))
4753 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4754 (cdr e)) ;; Key already assigned.
4755 (push e new)
4756 (let ((clist (string-to-list (downcase (car e))))
4757 (used (append new alist)))
4758 (when (= (car clist) ?@)
4759 (pop clist))
4760 (while (and clist (rassoc (car clist) used))
4761 (pop clist))
4762 (unless clist
4763 (while (rassoc alt used)
4764 (incf alt)))
4765 (push (cons (car e) (or (car clist) alt)) new))))
4766 (nreverse new)))
4768 ;;; Some variables used in various places
4770 (defvar org-window-configuration nil
4771 "Used in various places to store a window configuration.")
4772 (defvar org-selected-window nil
4773 "Used in various places to store a window configuration.")
4774 (defvar org-finish-function nil
4775 "Function to be called when `C-c C-c' is used.
4776 This is for getting out of special buffers like capture.")
4779 ;; FIXME: Occasionally check by commenting these, to make sure
4780 ;; no other functions uses these, forgetting to let-bind them.
4781 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4782 (defvar org-last-state)
4783 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4785 ;; Defined somewhere in this file, but used before definition.
4786 (defvar org-entities) ;; defined in org-entities.el
4787 (defvar org-struct-menu)
4788 (defvar org-org-menu)
4789 (defvar org-tbl-menu)
4791 ;;;; Define the Org-mode
4793 ;; We use a before-change function to check if a table might need
4794 ;; an update.
4795 (defvar org-table-may-need-update t
4796 "Indicates that a table might need an update.
4797 This variable is set by `org-before-change-function'.
4798 `org-table-align' sets it back to nil.")
4799 (defun org-before-change-function (beg end)
4800 "Every change indicates that a table might need an update."
4801 (setq org-table-may-need-update t))
4802 (defvar org-mode-map)
4803 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4804 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4805 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4806 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4807 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4808 (defvar org-table-buffer-is-an nil)
4810 (defvar bidi-paragraph-direction)
4811 (defvar buffer-face-mode-face)
4813 (require 'outline)
4814 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4815 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4816 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4818 ;; Other stuff we need.
4819 (require 'time-date)
4820 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4821 (require 'easymenu)
4822 (require 'overlay)
4824 (require 'org-macs)
4825 (require 'org-entities)
4826 ;; (require 'org-compat) moved higher up in the file before it is first used
4827 (require 'org-faces)
4828 (require 'org-list)
4829 (require 'org-pcomplete)
4830 (require 'org-src)
4831 (require 'org-footnote)
4833 ;; babel
4834 (require 'ob)
4835 (require 'ob-table)
4836 (require 'ob-lob)
4837 (require 'ob-ref)
4838 (require 'ob-tangle)
4839 (require 'ob-comint)
4840 (require 'ob-keys)
4842 ;;;###autoload
4843 (define-derived-mode org-mode outline-mode "Org"
4844 "Outline-based notes management and organizer, alias
4845 \"Carsten's outline-mode for keeping track of everything.\"
4847 Org-mode develops organizational tasks around a NOTES file which
4848 contains information about projects as plain text. Org-mode is
4849 implemented on top of outline-mode, which is ideal to keep the content
4850 of large files well structured. It supports ToDo items, deadlines and
4851 time stamps, which magically appear in the diary listing of the Emacs
4852 calendar. Tables are easily created with a built-in table editor.
4853 Plain text URL-like links connect to websites, emails (VM), Usenet
4854 messages (Gnus), BBDB entries, and any files related to the project.
4855 For printing and sharing of notes, an Org-mode file (or a part of it)
4856 can be exported as a structured ASCII or HTML file.
4858 The following commands are available:
4860 \\{org-mode-map}"
4862 ;; Get rid of Outline menus, they are not needed
4863 ;; Need to do this here because define-derived-mode sets up
4864 ;; the keymap so late. Still, it is a waste to call this each time
4865 ;; we switch another buffer into org-mode.
4866 (if (featurep 'xemacs)
4867 (when (boundp 'outline-mode-menu-heading)
4868 ;; Assume this is Greg's port, it uses easymenu
4869 (easy-menu-remove outline-mode-menu-heading)
4870 (easy-menu-remove outline-mode-menu-show)
4871 (easy-menu-remove outline-mode-menu-hide))
4872 (define-key org-mode-map [menu-bar headings] 'undefined)
4873 (define-key org-mode-map [menu-bar hide] 'undefined)
4874 (define-key org-mode-map [menu-bar show] 'undefined))
4876 (org-load-modules-maybe)
4877 (easy-menu-add org-org-menu)
4878 (easy-menu-add org-tbl-menu)
4879 (org-install-agenda-files-menu)
4880 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4881 (add-to-invisibility-spec '(org-cwidth))
4882 (add-to-invisibility-spec '(org-hide-block . t))
4883 (when (featurep 'xemacs)
4884 (org-set-local 'line-move-ignore-invisible t))
4885 (org-set-local 'outline-regexp org-outline-regexp)
4886 (org-set-local 'outline-level 'org-outline-level)
4887 (setq bidi-paragraph-direction 'left-to-right)
4888 (when (and org-ellipsis
4889 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4890 (fboundp 'make-glyph-code))
4891 (unless org-display-table
4892 (setq org-display-table (make-display-table)))
4893 (set-display-table-slot
4894 org-display-table 4
4895 (vconcat (mapcar
4896 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4897 org-ellipsis)))
4898 (if (stringp org-ellipsis) org-ellipsis "..."))))
4899 (setq buffer-display-table org-display-table))
4900 (org-set-regexps-and-options)
4901 (when (and org-tag-faces (not org-tags-special-faces-re))
4902 ;; tag faces set outside customize.... force initialization.
4903 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4904 ;; Calc embedded
4905 (org-set-local 'calc-embedded-open-mode "# ")
4906 (modify-syntax-entry ?@ "w")
4907 (if org-startup-truncated (setq truncate-lines t))
4908 (org-set-local 'font-lock-unfontify-region-function
4909 'org-unfontify-region)
4910 ;; Activate before-change-function
4911 (org-set-local 'org-table-may-need-update t)
4912 (org-add-hook 'before-change-functions 'org-before-change-function nil
4913 'local)
4914 ;; Check for running clock before killing a buffer
4915 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4916 ;; Indentation.
4917 (org-set-local 'indent-line-function 'org-indent-line)
4918 (org-set-local 'indent-region-function 'org-indent-region)
4919 ;; Initialize radio targets.
4920 (org-update-radio-target-regexp)
4921 ;; Filling and auto-filling.
4922 (org-setup-filling)
4923 ;; Comments.
4924 (org-setup-comments-handling)
4925 ;; Beginning/end of defun
4926 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4927 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4928 ;; Next error for sparse trees
4929 (org-set-local 'next-error-function 'org-occur-next-match)
4930 ;; Make sure dependence stuff works reliably, even for users who set it
4931 ;; too late :-(
4932 (if org-enforce-todo-dependencies
4933 (add-hook 'org-blocker-hook
4934 'org-block-todo-from-children-or-siblings-or-parent)
4935 (remove-hook 'org-blocker-hook
4936 'org-block-todo-from-children-or-siblings-or-parent))
4937 (if org-enforce-todo-checkbox-dependencies
4938 (add-hook 'org-blocker-hook
4939 'org-block-todo-from-checkboxes)
4940 (remove-hook 'org-blocker-hook
4941 'org-block-todo-from-checkboxes))
4943 ;; Align options lines
4944 (org-set-local
4945 'align-mode-rules-list
4946 '((org-in-buffer-settings
4947 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4948 (modes . '(org-mode)))))
4950 ;; Imenu
4951 (org-set-local 'imenu-create-index-function
4952 'org-imenu-get-tree)
4954 ;; Make isearch reveal context
4955 (if (or (featurep 'xemacs)
4956 (not (boundp 'outline-isearch-open-invisible-function)))
4957 ;; Emacs 21 and XEmacs make use of the hook
4958 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4959 ;; Emacs 22 deals with this through a special variable
4960 (org-set-local 'outline-isearch-open-invisible-function
4961 (lambda (&rest ignore) (org-show-context 'isearch))))
4963 ;; Turn on org-beamer-mode?
4964 (and org-startup-with-beamer-mode (org-beamer-mode))
4966 ;; Setup the pcomplete hooks
4967 (set (make-local-variable 'pcomplete-command-completion-function)
4968 'org-pcomplete-initial)
4969 (set (make-local-variable 'pcomplete-command-name-function)
4970 'org-command-at-point)
4971 (set (make-local-variable 'pcomplete-default-completion-function)
4972 'ignore)
4973 (set (make-local-variable 'pcomplete-parse-arguments-function)
4974 'org-parse-arguments)
4975 (set (make-local-variable 'pcomplete-termination-string) "")
4976 (when (>= emacs-major-version 23)
4977 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4979 ;; If empty file that did not turn on org-mode automatically, make it to.
4980 (if (and org-insert-mode-line-in-empty-file
4981 (org-called-interactively-p 'any)
4982 (= (point-min) (point-max)))
4983 (insert "# -*- mode: org -*-\n\n"))
4984 (unless org-inhibit-startup
4985 (when org-startup-align-all-tables
4986 (let ((bmp (buffer-modified-p)))
4987 (org-table-map-tables 'org-table-align 'quietly)
4988 (set-buffer-modified-p bmp)))
4989 (when org-startup-with-inline-images
4990 (org-display-inline-images))
4991 (when org-startup-indented
4992 (require 'org-indent)
4993 (org-indent-mode 1))
4994 (unless org-inhibit-startup-visibility-stuff
4995 (org-set-startup-visibility)))
4996 ;; Try to set org-hide correctly
4997 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
4999 (when (fboundp 'abbrev-table-put)
5000 (abbrev-table-put org-mode-abbrev-table
5001 :parents (list text-mode-abbrev-table)))
5003 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5006 (defun org-find-invisible-foreground ()
5007 (let ((candidates (remove
5008 "unspecified-bg"
5009 (list
5010 (face-background 'default)
5011 (face-background 'org-default)
5012 (cdr (assoc 'background-color default-frame-alist))
5013 (cdr (assoc 'background-color initial-frame-alist))
5014 (cdr (assoc 'background-color window-system-default-frame-alist))
5015 (face-foreground 'org-hide)))))
5016 (car (remove nil candidates))))
5018 (defun org-current-time ()
5019 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5020 (if (> (car org-time-stamp-rounding-minutes) 1)
5021 (let ((r (car org-time-stamp-rounding-minutes))
5022 (time (decode-time)))
5023 (apply 'encode-time
5024 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5025 (nthcdr 2 time))))
5026 (current-time)))
5028 (defun org-today ()
5029 "Return today date, considering `org-extend-today-until'."
5030 (time-to-days
5031 (time-subtract (current-time)
5032 (list 0 (* 3600 org-extend-today-until) 0))))
5034 ;;;; Font-Lock stuff, including the activators
5036 (defvar org-mouse-map (make-sparse-keymap))
5037 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5038 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5039 (when org-mouse-1-follows-link
5040 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5041 (when org-tab-follows-link
5042 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5043 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5045 (require 'font-lock)
5047 (defconst org-non-link-chars "]\t\n\r<>")
5048 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5049 "shell" "elisp" "doi" "message"))
5050 (defvar org-link-types-re nil
5051 "Matches a link that has a url-like prefix like \"http:\"")
5052 (defvar org-link-re-with-space nil
5053 "Matches a link with spaces, optional angular brackets around it.")
5054 (defvar org-link-re-with-space2 nil
5055 "Matches a link with spaces, optional angular brackets around it.")
5056 (defvar org-link-re-with-space3 nil
5057 "Matches a link with spaces, only for internal part in bracket links.")
5058 (defvar org-angle-link-re nil
5059 "Matches link with angular brackets, spaces are allowed.")
5060 (defvar org-plain-link-re nil
5061 "Matches plain link, without spaces.")
5062 (defvar org-bracket-link-regexp nil
5063 "Matches a link in double brackets.")
5064 (defvar org-bracket-link-analytic-regexp nil
5065 "Regular expression used to analyze links.
5066 Here is what the match groups contain after a match:
5067 1: http:
5068 2: http
5069 3: path
5070 4: [desc]
5071 5: desc")
5072 (defvar org-bracket-link-analytic-regexp++ nil
5073 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5074 (defvar org-any-link-re nil
5075 "Regular expression matching any link.")
5077 (defcustom org-match-sexp-depth 3
5078 "Number of stacked braces for sub/superscript matching.
5079 This has to be set before loading org.el to be effective."
5080 :group 'org-export-translation ; ??????????????????????????/
5081 :type 'integer)
5083 (defun org-create-multibrace-regexp (left right n)
5084 "Create a regular expression which will match a balanced sexp.
5085 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5086 as single character strings.
5087 The regexp returned will match the entire expression including the
5088 delimiters. It will also define a single group which contains the
5089 match except for the outermost delimiters. The maximum depth of
5090 stacked delimiters is N. Escaping delimiters is not possible."
5091 (let* ((nothing (concat "[^" left right "]*?"))
5092 (or "\\|")
5093 (re nothing)
5094 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5095 (while (> n 1)
5096 (setq n (1- n)
5097 re (concat re or next)
5098 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5099 (concat left "\\(" re "\\)" right)))
5101 (defvar org-match-substring-regexp
5102 (concat
5103 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5104 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5105 "\\|"
5106 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5107 "\\|"
5108 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5109 "The regular expression matching a sub- or superscript.")
5111 (defvar org-match-substring-with-braces-regexp
5112 (concat
5113 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5114 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5115 "\\)")
5116 "The regular expression matching a sub- or superscript, forcing braces.")
5118 (defun org-make-link-regexps ()
5119 "Update the link regular expressions.
5120 This should be called after the variable `org-link-types' has changed."
5121 (setq org-link-types-re
5122 (concat
5123 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5124 org-link-re-with-space
5125 (concat
5126 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5127 "\\([^" org-non-link-chars " ]"
5128 "[^" org-non-link-chars "]*"
5129 "[^" org-non-link-chars " ]\\)>?")
5130 org-link-re-with-space2
5131 (concat
5132 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5133 "\\([^" org-non-link-chars " ]"
5134 "[^\t\n\r]*"
5135 "[^" org-non-link-chars " ]\\)>?")
5136 org-link-re-with-space3
5137 (concat
5138 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5139 "\\([^" org-non-link-chars " ]"
5140 "[^\t\n\r]*\\)")
5141 org-angle-link-re
5142 (concat
5143 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5144 "\\([^" org-non-link-chars " ]"
5145 "[^" org-non-link-chars "]*"
5146 "\\)>")
5147 org-plain-link-re
5148 (concat
5149 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5150 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5151 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5152 org-bracket-link-regexp
5153 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5154 org-bracket-link-analytic-regexp
5155 (concat
5156 "\\[\\["
5157 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5158 "\\([^]]+\\)"
5159 "\\]"
5160 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5161 "\\]")
5162 org-bracket-link-analytic-regexp++
5163 (concat
5164 "\\[\\["
5165 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5166 "\\([^]]+\\)"
5167 "\\]"
5168 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5169 "\\]")
5170 org-any-link-re
5171 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5172 org-angle-link-re "\\)\\|\\("
5173 org-plain-link-re "\\)")))
5175 (org-make-link-regexps)
5177 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5178 "Regular expression for fast time stamp matching.")
5179 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5180 "Regular expression for fast time stamp matching.")
5181 (defconst org-ts-regexp0
5182 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5183 "Regular expression matching time strings for analysis.
5184 This one does not require the space after the date, so it can be used
5185 on a string that terminates immediately after the date.")
5186 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5187 "Regular expression matching time strings for analysis.")
5188 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5189 "Regular expression matching time stamps, with groups.")
5190 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5191 "Regular expression matching time stamps (also [..]), with groups.")
5192 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5193 "Regular expression matching a time stamp range.")
5194 (defconst org-tr-regexp-both
5195 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5196 "Regular expression matching a time stamp range.")
5197 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5198 org-ts-regexp "\\)?")
5199 "Regular expression matching a time stamp or time stamp range.")
5200 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5201 org-ts-regexp-both "\\)?")
5202 "Regular expression matching a time stamp or time stamp range.
5203 The time stamps may be either active or inactive.")
5205 (defvar org-emph-face nil)
5207 (defun org-do-emphasis-faces (limit)
5208 "Run through the buffer and add overlays to emphasized strings."
5209 (let (rtn a)
5210 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5211 (if (not (= (char-after (match-beginning 3))
5212 (char-after (match-beginning 4))))
5213 (progn
5214 (setq rtn t)
5215 (setq a (assoc (match-string 3) org-emphasis-alist))
5216 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5217 'face
5218 (nth 1 a))
5219 (and (nth 4 a)
5220 (org-remove-flyspell-overlays-in
5221 (match-beginning 0) (match-end 0)))
5222 (add-text-properties (match-beginning 2) (match-end 2)
5223 '(font-lock-multiline t org-emphasis t))
5224 (when org-hide-emphasis-markers
5225 (add-text-properties (match-end 4) (match-beginning 5)
5226 '(invisible org-link))
5227 (add-text-properties (match-beginning 3) (match-end 3)
5228 '(invisible org-link)))))
5229 (backward-char 1))
5230 rtn))
5232 (defun org-emphasize (&optional char)
5233 "Insert or change an emphasis, i.e. a font like bold or italic.
5234 If there is an active region, change that region to a new emphasis.
5235 If there is no region, just insert the marker characters and position
5236 the cursor between them.
5237 CHAR should be either the marker character, or the first character of the
5238 HTML tag associated with that emphasis. If CHAR is a space, the means
5239 to remove the emphasis of the selected region.
5240 If char is not given (for example in an interactive call) it
5241 will be prompted for."
5242 (interactive)
5243 (let ((eal org-emphasis-alist) e det
5244 (erc org-emphasis-regexp-components)
5245 (prompt "")
5246 (string "") beg end move tag c s)
5247 (if (org-region-active-p)
5248 (setq beg (region-beginning) end (region-end)
5249 string (buffer-substring beg end))
5250 (setq move t))
5252 (while (setq e (pop eal))
5253 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5254 c (aref tag 0))
5255 (push (cons c (string-to-char (car e))) det)
5256 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5257 (substring tag 1)))))
5258 (setq det (nreverse det))
5259 (unless char
5260 (message "%s" (concat "Emphasis marker or tag:" prompt))
5261 (setq char (read-char-exclusive)))
5262 (setq char (or (cdr (assoc char det)) char))
5263 (if (equal char ?\ )
5264 (setq s "" move nil)
5265 (unless (assoc (char-to-string char) org-emphasis-alist)
5266 (error "No such emphasis marker: \"%c\"" char))
5267 (setq s (char-to-string char)))
5268 (while (and (> (length string) 1)
5269 (equal (substring string 0 1) (substring string -1))
5270 (assoc (substring string 0 1) org-emphasis-alist))
5271 (setq string (substring string 1 -1)))
5272 (setq string (concat s string s))
5273 (if beg (delete-region beg end))
5274 (unless (or (bolp)
5275 (string-match (concat "[" (nth 0 erc) "\n]")
5276 (char-to-string (char-before (point)))))
5277 (insert " "))
5278 (unless (or (eobp)
5279 (string-match (concat "[" (nth 1 erc) "\n]")
5280 (char-to-string (char-after (point)))))
5281 (insert " ") (backward-char 1))
5282 (insert string)
5283 (and move (backward-char 1))))
5285 (defconst org-nonsticky-props
5286 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5288 (defsubst org-rear-nonsticky-at (pos)
5289 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5291 (defun org-activate-plain-links (limit)
5292 "Run through the buffer and add overlays to links."
5293 (catch 'exit
5294 (let (f)
5295 (when (re-search-forward (concat org-plain-link-re) limit t)
5296 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5297 (setq f (get-text-property (match-beginning 0) 'face))
5298 (if (or (eq f 'org-tag)
5299 (and (listp f) (memq 'org-tag f)))
5301 (add-text-properties (match-beginning 0) (match-end 0)
5302 (list 'mouse-face 'highlight
5303 'face 'org-link
5304 'keymap org-mouse-map))
5305 (org-rear-nonsticky-at (match-end 0)))
5306 t))))
5308 (defun org-activate-code (limit)
5309 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5310 (progn
5311 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5312 (remove-text-properties (match-beginning 0) (match-end 0)
5313 '(display t invisible t intangible t))
5314 t)))
5316 (defcustom org-src-fontify-natively nil
5317 "When non-nil, fontify code in code blocks."
5318 :type 'boolean
5319 :version "24.1"
5320 :group 'org-appearance
5321 :group 'org-babel)
5323 (defcustom org-allow-promoting-top-level-subtree nil
5324 "When non-nil, allow promoting a top level subtree.
5325 The leading star of the top level headline will be replaced
5326 by a #."
5327 :type 'boolean
5328 :version "24.1"
5329 :group 'org-appearance)
5331 (defun org-fontify-meta-lines-and-blocks (limit)
5332 (condition-case nil
5333 (org-fontify-meta-lines-and-blocks-1 limit)
5334 (error (message "org-mode fontification error"))))
5336 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5337 "Fontify #+ lines and blocks, in the correct ways."
5338 (let ((case-fold-search t))
5339 (if (re-search-forward
5340 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5341 limit t)
5342 (let ((beg (match-beginning 0))
5343 (block-start (match-end 0))
5344 (block-end nil)
5345 (lang (match-string 7))
5346 (beg1 (line-beginning-position 2))
5347 (dc1 (downcase (match-string 2)))
5348 (dc3 (downcase (match-string 3)))
5349 end end1 quoting block-type ovl)
5350 (cond
5351 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5352 ;; a single line of backend-specific content
5353 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5354 (remove-text-properties (match-beginning 0) (match-end 0)
5355 '(display t invisible t intangible t))
5356 (add-text-properties (match-beginning 1) (match-end 3)
5357 '(font-lock-fontified t face org-meta-line))
5358 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5359 '(font-lock-fontified t face org-block))
5360 ; for backend-specific code
5362 ((and (match-end 4) (equal dc3 "+begin"))
5363 ;; Truly a block
5364 (setq block-type (downcase (match-string 5))
5365 quoting (member block-type org-protecting-blocks))
5366 (when (re-search-forward
5367 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5368 nil t) ;; on purpose, we look further than LIMIT
5369 (setq end (min (point-max) (match-end 0))
5370 end1 (min (point-max) (1- (match-beginning 0))))
5371 (setq block-end (match-beginning 0))
5372 (when quoting
5373 (remove-text-properties beg end
5374 '(display t invisible t intangible t)))
5375 (add-text-properties
5376 beg end
5377 '(font-lock-fontified t font-lock-multiline t))
5378 (add-text-properties beg beg1 '(face org-meta-line))
5379 (add-text-properties end1 (min (point-max) (1+ end))
5380 '(face org-meta-line)) ; for end_src
5381 (cond
5382 ((and lang (not (string= lang "")) org-src-fontify-natively)
5383 (org-src-font-lock-fontify-block lang block-start block-end)
5384 ;; remove old background overlays
5385 (mapc (lambda (ov)
5386 (if (eq (overlay-get ov 'face) 'org-block-background)
5387 (delete-overlay ov)))
5388 (overlays-at (/ (+ beg1 block-end) 2)))
5389 ;; add a background overlay
5390 (setq ovl (make-overlay beg1 block-end))
5391 (overlay-put ovl 'face 'org-block-background)
5392 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5393 (quoting
5394 (add-text-properties beg1 (min (point-max) (1+ end1))
5395 '(face org-block))) ; end of source block
5396 ((not org-fontify-quote-and-verse-blocks))
5397 ((string= block-type "quote")
5398 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5399 ((string= block-type "verse")
5400 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5401 (add-text-properties beg beg1 '(face org-block-begin-line))
5402 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5403 '(face org-block-end-line))
5405 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5406 (add-text-properties
5407 beg (match-end 3)
5408 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5409 '(font-lock-fontified t invisible t)
5410 '(font-lock-fontified t face org-document-info-keyword)))
5411 (add-text-properties
5412 (match-beginning 6) (match-end 6)
5413 (if (string-equal dc1 "+title:")
5414 '(font-lock-fontified t face org-document-title)
5415 '(font-lock-fontified t face org-document-info))))
5416 ((or (equal dc1 "+results")
5417 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5418 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5419 "+call:" "+header:" "+headers:" "+name:"))
5420 (and (match-end 4) (equal dc3 "+attr")))
5421 (add-text-properties
5422 beg (match-end 0)
5423 '(font-lock-fontified t face org-meta-line))
5425 ((member dc3 '(" " ""))
5426 (add-text-properties
5427 beg (match-end 0)
5428 '(font-lock-fontified t face font-lock-comment-face)))
5429 ((not (member (char-after beg) '(?\ ?\t)))
5430 ;; just any other in-buffer setting, but not indented
5431 (add-text-properties
5432 beg (match-end 0)
5433 '(font-lock-fontified t face org-meta-line))
5435 (t nil))))))
5437 (defun org-activate-angle-links (limit)
5438 "Run through the buffer and add overlays to links."
5439 (if (re-search-forward org-angle-link-re limit t)
5440 (progn
5441 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5442 (add-text-properties (match-beginning 0) (match-end 0)
5443 (list 'mouse-face 'highlight
5444 'keymap org-mouse-map))
5445 (org-rear-nonsticky-at (match-end 0))
5446 t)))
5448 (defun org-activate-footnote-links (limit)
5449 "Run through the buffer and add overlays to footnotes."
5450 (let ((fn (org-footnote-next-reference-or-definition limit)))
5451 (when fn
5452 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5453 (org-remove-flyspell-overlays-in beg end)
5454 (add-text-properties beg end
5455 (list 'mouse-face 'highlight
5456 'keymap org-mouse-map
5457 'help-echo
5458 (if (= (point-at-bol) beg)
5459 "Footnote definition"
5460 "Footnote reference")
5461 'font-lock-fontified t
5462 'font-lock-multiline t
5463 'face 'org-footnote))))))
5465 (defun org-activate-bracket-links (limit)
5466 "Run through the buffer and add overlays to bracketed links."
5467 (if (re-search-forward org-bracket-link-regexp limit t)
5468 (let* ((help (concat "LINK: "
5469 (org-match-string-no-properties 1)))
5470 ;; FIXME: above we should remove the escapes.
5471 ;; but that requires another match, protecting match data,
5472 ;; a lot of overhead for font-lock.
5473 (ip (org-maybe-intangible
5474 (list 'invisible 'org-link
5475 'keymap org-mouse-map 'mouse-face 'highlight
5476 'font-lock-multiline t 'help-echo help)))
5477 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5478 'font-lock-multiline t 'help-echo help)))
5479 ;; We need to remove the invisible property here. Table narrowing
5480 ;; may have made some of this invisible.
5481 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5482 (remove-text-properties (match-beginning 0) (match-end 0)
5483 '(invisible nil))
5484 (if (match-end 3)
5485 (progn
5486 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5487 (org-rear-nonsticky-at (match-beginning 3))
5488 (add-text-properties (match-beginning 3) (match-end 3) vp)
5489 (org-rear-nonsticky-at (match-end 3))
5490 (add-text-properties (match-end 3) (match-end 0) ip)
5491 (org-rear-nonsticky-at (match-end 0)))
5492 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5493 (org-rear-nonsticky-at (match-beginning 1))
5494 (add-text-properties (match-beginning 1) (match-end 1) vp)
5495 (org-rear-nonsticky-at (match-end 1))
5496 (add-text-properties (match-end 1) (match-end 0) ip)
5497 (org-rear-nonsticky-at (match-end 0)))
5498 t)))
5500 (defun org-activate-dates (limit)
5501 "Run through the buffer and add overlays to dates."
5502 (if (re-search-forward org-tsr-regexp-both limit t)
5503 (progn
5504 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5505 (add-text-properties (match-beginning 0) (match-end 0)
5506 (list 'mouse-face 'highlight
5507 'keymap org-mouse-map))
5508 (org-rear-nonsticky-at (match-end 0))
5509 (when org-display-custom-times
5510 (if (match-end 3)
5511 (org-display-custom-time (match-beginning 3) (match-end 3)))
5512 (org-display-custom-time (match-beginning 1) (match-end 1)))
5513 t)))
5515 (defvar org-target-link-regexp nil
5516 "Regular expression matching radio targets in plain text.")
5517 (make-variable-buffer-local 'org-target-link-regexp)
5518 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5519 "Regular expression matching a link target.")
5520 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5521 "Regular expression matching a radio target.")
5522 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5523 "Regular expression matching any target.")
5525 (defun org-activate-target-links (limit)
5526 "Run through the buffer and add overlays to target matches."
5527 (when org-target-link-regexp
5528 (let ((case-fold-search t))
5529 (if (re-search-forward org-target-link-regexp limit t)
5530 (progn
5531 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5532 (add-text-properties (match-beginning 0) (match-end 0)
5533 (list 'mouse-face 'highlight
5534 'keymap org-mouse-map
5535 'help-echo "Radio target link"
5536 'org-linked-text t))
5537 (org-rear-nonsticky-at (match-end 0))
5538 t)))))
5540 (defun org-update-radio-target-regexp ()
5541 "Find all radio targets in this file and update the regular expression."
5542 (interactive)
5543 (when (memq 'radio org-activate-links)
5544 (setq org-target-link-regexp
5545 (org-make-target-link-regexp (org-all-targets 'radio)))
5546 (org-restart-font-lock)))
5548 (defun org-hide-wide-columns (limit)
5549 (let (s e)
5550 (setq s (text-property-any (point) (or limit (point-max))
5551 'org-cwidth t))
5552 (when s
5553 (setq e (next-single-property-change s 'org-cwidth))
5554 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5555 (goto-char e)
5556 t)))
5558 (defvar org-latex-and-specials-regexp nil
5559 "Regular expression for highlighting export special stuff.")
5560 (defvar org-match-substring-regexp)
5561 (defvar org-match-substring-with-braces-regexp)
5563 ;; This should be with the exporter code, but we also use if for font-locking
5564 (defconst org-export-html-special-string-regexps
5565 '(("\\\\-" . "&shy;")
5566 ("---\\([^-]\\)" . "&mdash;\\1")
5567 ("--\\([^-]\\)" . "&ndash;\\1")
5568 ("\\.\\.\\." . "&hellip;"))
5569 "Regular expressions for special string conversion.")
5572 (defun org-compute-latex-and-specials-regexp ()
5573 "Compute regular expression for stuff treated specially by exporters."
5574 (if (not org-highlight-latex-fragments-and-specials)
5575 (org-set-local 'org-latex-and-specials-regexp nil)
5576 (require 'org-exp)
5577 (let*
5578 ((matchers (plist-get org-format-latex-options :matchers))
5579 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5580 org-latex-regexps)))
5581 (org-export-allow-BIND nil)
5582 (options (org-combine-plists (org-default-export-plist)
5583 (org-infile-export-plist)))
5584 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5585 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5586 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5587 (org-export-html-expand (plist-get options :expand-quoted-html))
5588 (org-export-with-special-strings (plist-get options :special-strings))
5589 (re-sub
5590 (cond
5591 ((equal org-export-with-sub-superscripts '{})
5592 (list org-match-substring-with-braces-regexp))
5593 (org-export-with-sub-superscripts
5594 (list org-match-substring-regexp))))
5595 (re-latex
5596 (if org-export-with-LaTeX-fragments
5597 (mapcar (lambda (x) (nth 1 x)) latexs)))
5598 (re-macros
5599 (if org-export-with-TeX-macros
5600 (list (concat "\\\\"
5601 (regexp-opt
5602 (append
5604 (delq nil
5605 (mapcar 'car-safe
5606 (append org-entities-user
5607 org-entities)))
5608 (if (boundp 'org-latex-entities)
5609 (mapcar (lambda (x)
5610 (or (car-safe x) x))
5611 org-latex-entities)
5612 nil))
5613 'words))) ; FIXME
5615 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5616 (re-special (if org-export-with-special-strings
5617 (mapcar (lambda (x) (car x))
5618 org-export-html-special-string-regexps)))
5619 (re-rest
5620 (delq nil
5621 (list
5622 (if org-export-html-expand "@<[^>\n]+>")
5623 ))))
5624 (org-set-local
5625 'org-latex-and-specials-regexp
5626 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5627 re-rest) "\\|")))))
5629 (defun org-do-latex-and-special-faces (limit)
5630 "Run through the buffer and add overlays to links."
5631 (when org-latex-and-specials-regexp
5632 (let (rtn d)
5633 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5634 limit t))
5635 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5636 'face))
5637 '(org-code org-verbatim underline)))
5638 (progn
5639 (setq rtn t
5640 d (cond ((member (char-after (1+ (match-beginning 0)))
5641 '(?_ ?^)) 1)
5642 (t 0)))
5643 (font-lock-prepend-text-property
5644 (+ d (match-beginning 0)) (match-end 0)
5645 'face 'org-latex-and-export-specials)
5646 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5647 '(font-lock-multiline t)))))
5648 rtn)))
5650 (defun org-restart-font-lock ()
5651 "Restart `font-lock-mode', to force refontification."
5652 (when (and (boundp 'font-lock-mode) font-lock-mode)
5653 (font-lock-mode -1)
5654 (font-lock-mode 1)))
5656 (defun org-all-targets (&optional radio)
5657 "Return a list of all targets in this file.
5658 With optional argument RADIO, only find radio targets."
5659 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5660 rtn)
5661 (save-excursion
5662 (goto-char (point-min))
5663 (while (re-search-forward re nil t)
5664 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5665 rtn)))
5667 (defun org-make-target-link-regexp (targets)
5668 "Make regular expression matching all strings in TARGETS.
5669 The regular expression finds the targets also if there is a line break
5670 between words."
5671 (and targets
5672 (concat
5673 "\\<\\("
5674 (mapconcat
5675 (lambda (x)
5676 (setq x (regexp-quote x))
5677 (while (string-match " +" x)
5678 (setq x (replace-match "\\s-+" t t x)))
5680 targets
5681 "\\|")
5682 "\\)\\>")))
5684 (defun org-activate-tags (limit)
5685 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5686 (progn
5687 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5688 (add-text-properties (match-beginning 1) (match-end 1)
5689 (list 'mouse-face 'highlight
5690 'keymap org-mouse-map))
5691 (org-rear-nonsticky-at (match-end 1))
5692 t)))
5694 (defun org-outline-level ()
5695 "Compute the outline level of the heading at point.
5696 This function assumes that the cursor is at the beginning of a line matched
5697 by `outline-regexp'. Otherwise it returns garbage.
5698 If this is called at a normal headline, the level is the number of stars.
5699 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5700 (save-excursion
5701 (looking-at org-outline-regexp)
5702 (1- (- (match-end 0) (match-beginning 0)))))
5704 (defvar org-font-lock-keywords nil)
5706 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5707 "Regular expression matching a property line.")
5709 (defvar org-font-lock-hook nil
5710 "Functions to be called for special font lock stuff.")
5712 (defvar org-font-lock-set-keywords-hook nil
5713 "Functions that can manipulate `org-font-lock-extra-keywords'.
5714 This is called after `org-font-lock-extra-keywords' is defined, but before
5715 it is installed to be used by font lock. This can be useful if something
5716 needs to be inserted at a specific position in the font-lock sequence.")
5718 (defun org-font-lock-hook (limit)
5719 "Run `org-font-lock-hook' within LIMIT."
5720 (run-hook-with-args 'org-font-lock-hook limit))
5722 (defun org-set-font-lock-defaults ()
5723 "Set font lock defaults for the current buffer."
5724 (let* ((em org-fontify-emphasized-text)
5725 (lk org-activate-links)
5726 (org-font-lock-extra-keywords
5727 (list
5728 ;; Call the hook
5729 '(org-font-lock-hook)
5730 ;; Headlines
5731 `(,(if org-fontify-whole-heading-line
5732 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5733 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5734 (1 (org-get-level-face 1))
5735 (2 (org-get-level-face 2))
5736 (3 (org-get-level-face 3)))
5737 ;; Table lines
5738 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5739 (1 'org-table t))
5740 ;; Table internals
5741 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5742 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5743 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5744 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5745 ;; Drawers
5746 (list org-drawer-regexp '(0 'org-special-keyword t))
5747 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5748 ;; Properties
5749 (list org-property-re
5750 '(1 'org-special-keyword t)
5751 '(3 'org-property-value t))
5752 ;; Links
5753 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5754 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5755 (if (memq 'plain lk) '(org-activate-plain-links))
5756 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5757 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5758 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5759 (if (memq 'footnote lk) '(org-activate-footnote-links))
5760 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5761 '(org-hide-wide-columns (0 nil append))
5762 ;; TODO keyword
5763 (list (format org-heading-keyword-regexp-format
5764 org-todo-regexp)
5765 '(2 (org-get-todo-face 2) t))
5766 ;; DONE
5767 (if org-fontify-done-headline
5768 (list (format org-heading-keyword-regexp-format
5769 (concat
5770 "\\(?:"
5771 (mapconcat 'regexp-quote org-done-keywords "\\|")
5772 "\\)"))
5773 '(2 'org-headline-done t))
5774 nil)
5775 ;; Priorities
5776 '(org-font-lock-add-priority-faces)
5777 ;; Tags
5778 '(org-font-lock-add-tag-faces)
5779 ;; Special keywords
5780 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5781 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5782 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5783 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5784 ;; Emphasis
5785 (if em
5786 (if (featurep 'xemacs)
5787 '(org-do-emphasis-faces (0 nil append))
5788 '(org-do-emphasis-faces)))
5789 ;; Checkboxes
5790 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5791 1 'org-checkbox prepend)
5792 (if (cdr (assq 'checkbox org-list-automatic-rules))
5793 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5794 (0 (org-get-checkbox-statistics-face) t)))
5795 ;; Description list items
5796 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5797 1 'org-list-dt prepend)
5798 ;; ARCHIVEd headings
5799 (list (concat
5800 org-outline-regexp-bol
5801 "\\(.*:" org-archive-tag ":.*\\)")
5802 '(1 'org-archived prepend))
5803 ;; Specials
5804 '(org-do-latex-and-special-faces)
5805 '(org-fontify-entities)
5806 '(org-raise-scripts)
5807 ;; Code
5808 '(org-activate-code (1 'org-code t))
5809 ;; COMMENT
5810 (list (format org-heading-keyword-regexp-format
5811 (concat "\\("
5812 org-comment-string "\\|" org-quote-string
5813 "\\)"))
5814 '(2 'org-special-keyword t))
5815 ;; Blocks and meta lines
5816 '(org-fontify-meta-lines-and-blocks)
5818 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5819 (run-hooks 'org-font-lock-set-keywords-hook)
5820 ;; Now set the full font-lock-keywords
5821 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5822 (org-set-local 'font-lock-defaults
5823 '(org-font-lock-keywords t nil nil backward-paragraph))
5824 (kill-local-variable 'font-lock-keywords) nil))
5826 (defun org-toggle-pretty-entities ()
5827 "Toggle the composition display of entities as UTF8 characters."
5828 (interactive)
5829 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5830 (org-restart-font-lock)
5831 (if org-pretty-entities
5832 (message "Entities are displayed as UTF8 characters")
5833 (save-restriction
5834 (widen)
5835 (org-decompose-region (point-min) (point-max))
5836 (message "Entities are displayed plain"))))
5838 (defvar org-custom-properties-overlays nil
5839 "List of overlays used for custom properties.")
5840 (make-variable-buffer-local 'org-custom-properties-overlays)
5842 (defun org-toggle-custom-properties-visibility ()
5843 "Display or hide properties in `org-custom-properties'."
5844 (interactive)
5845 (if org-custom-properties-overlays
5846 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5847 (setq org-custom-properties-overlays nil))
5848 (unless (not org-custom-properties)
5849 (save-excursion
5850 (save-restriction
5851 (widen)
5852 (goto-char (point-min))
5853 (while (re-search-forward org-property-re nil t)
5854 (mapc (lambda(p)
5855 (when (equal p (substring (match-string 1) 1 -1))
5856 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5857 (overlay-put o 'invisible t)
5858 (overlay-put o 'org-custom-property t)
5859 (push o org-custom-properties-overlays))))
5860 org-custom-properties)))))))
5862 (defun org-fontify-entities (limit)
5863 "Find an entity to fontify."
5864 (let (ee)
5865 (when org-pretty-entities
5866 (catch 'match
5867 (while (re-search-forward
5868 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5869 limit t)
5870 (if (and (not (org-in-indented-comment-line))
5871 (setq ee (org-entity-get (match-string 1)))
5872 (= (length (nth 6 ee)) 1))
5873 (let*
5874 ((end (if (equal (match-string 2) "{}")
5875 (match-end 2)
5876 (match-end 1))))
5877 (add-text-properties
5878 (match-beginning 0) end
5879 (list 'font-lock-fontified t))
5880 (compose-region (match-beginning 0) end
5881 (nth 6 ee) nil)
5882 (backward-char 1)
5883 (throw 'match t))))
5884 nil))))
5886 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5887 "Fontify string S like in Org-mode."
5888 (with-temp-buffer
5889 (insert s)
5890 (let ((org-odd-levels-only odd-levels))
5891 (org-mode)
5892 (font-lock-fontify-buffer)
5893 (buffer-string))))
5895 (defvar org-m nil)
5896 (defvar org-l nil)
5897 (defvar org-f nil)
5898 (defun org-get-level-face (n)
5899 "Get the right face for match N in font-lock matching of headlines."
5900 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5901 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5902 (if org-cycle-level-faces
5903 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5904 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5905 (cond
5906 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5907 ((eq n 2) org-f)
5908 (t (if org-level-color-stars-only nil org-f))))
5911 (defun org-get-todo-face (kwd)
5912 "Get the right face for a TODO keyword KWD.
5913 If KWD is a number, get the corresponding match group."
5914 (if (numberp kwd) (setq kwd (match-string kwd)))
5915 (or (org-face-from-face-or-color
5916 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5917 (and (member kwd org-done-keywords) 'org-done)
5918 'org-todo))
5920 (defun org-face-from-face-or-color (context inherit face-or-color)
5921 "Create a face list that inherits INHERIT, but sets the foreground color.
5922 When FACE-OR-COLOR is not a string, just return it."
5923 (if (stringp face-or-color)
5924 (list :inherit inherit
5925 (cdr (assoc context org-faces-easy-properties))
5926 face-or-color)
5927 face-or-color))
5929 (defun org-font-lock-add-tag-faces (limit)
5930 "Add the special tag faces."
5931 (when (and org-tag-faces org-tags-special-faces-re)
5932 (while (re-search-forward org-tags-special-faces-re limit t)
5933 (add-text-properties (match-beginning 1) (match-end 1)
5934 (list 'face (org-get-tag-face 1)
5935 'font-lock-fontified t))
5936 (backward-char 1))))
5938 (defun org-font-lock-add-priority-faces (limit)
5939 "Add the special priority faces."
5940 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5941 (when (save-match-data (org-at-heading-p))
5942 (add-text-properties
5943 (match-beginning 0) (match-end 0)
5944 (list 'face (or (org-face-from-face-or-color
5945 'priority 'org-special-keyword
5946 (cdr (assoc (char-after (match-beginning 1))
5947 org-priority-faces)))
5948 'org-special-keyword)
5949 'font-lock-fontified t)))))
5951 (defun org-get-tag-face (kwd)
5952 "Get the right face for a TODO keyword KWD.
5953 If KWD is a number, get the corresponding match group."
5954 (if (numberp kwd) (setq kwd (match-string kwd)))
5955 (or (org-face-from-face-or-color
5956 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5957 'org-tag))
5959 (defun org-unfontify-region (beg end &optional maybe_loudly)
5960 "Remove fontification and activation overlays from links."
5961 (font-lock-default-unfontify-region beg end)
5962 (let* ((buffer-undo-list t)
5963 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5964 (inhibit-modification-hooks t)
5965 deactivate-mark buffer-file-name buffer-file-truename)
5966 (org-decompose-region beg end)
5967 (remove-text-properties beg end
5968 '(mouse-face t keymap t org-linked-text t
5969 invisible t intangible t
5970 org-no-flyspell t org-emphasis t))
5971 (org-remove-font-lock-display-properties beg end)))
5973 (defconst org-script-display '(((raise -0.3) (height 0.7))
5974 ((raise 0.3) (height 0.7))
5975 ((raise -0.5))
5976 ((raise 0.5)))
5977 "Display properties for showing superscripts and subscripts.")
5979 (defun org-remove-font-lock-display-properties (beg end)
5980 "Remove specific display properties that have been added by font lock.
5981 The will remove the raise properties that are used to show superscripts
5982 and subscripts."
5983 (let (next prop)
5984 (while (< beg end)
5985 (setq next (next-single-property-change beg 'display nil end)
5986 prop (get-text-property beg 'display))
5987 (if (member prop org-script-display)
5988 (put-text-property beg next 'display nil))
5989 (setq beg next))))
5991 (defun org-raise-scripts (limit)
5992 "Add raise properties to sub/superscripts."
5993 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5994 (if (re-search-forward
5995 (if (eq org-use-sub-superscripts t)
5996 org-match-substring-regexp
5997 org-match-substring-with-braces-regexp)
5998 limit t)
5999 (let* ((pos (point)) table-p comment-p
6000 (mpos (match-beginning 3))
6001 (emph-p (get-text-property mpos 'org-emphasis))
6002 (link-p (get-text-property mpos 'mouse-face))
6003 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6004 (goto-char (point-at-bol))
6005 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6006 comment-p (org-looking-at-p "[ \t]*#"))
6007 (goto-char pos)
6008 ;; FIXME: Should we go back one character here, for a_b^c
6009 ;; (goto-char (1- pos)) ;????????????????????
6010 (if (or comment-p emph-p link-p keyw-p)
6012 (put-text-property (match-beginning 3) (match-end 0)
6013 'display
6014 (if (equal (char-after (match-beginning 2)) ?^)
6015 (nth (if table-p 3 1) org-script-display)
6016 (nth (if table-p 2 0) org-script-display)))
6017 (add-text-properties (match-beginning 2) (match-end 2)
6018 (list 'invisible t
6019 'org-dwidth t 'org-dwidth-n 1))
6020 (if (and (eq (char-after (match-beginning 3)) ?{)
6021 (eq (char-before (match-end 3)) ?}))
6022 (progn
6023 (add-text-properties
6024 (match-beginning 3) (1+ (match-beginning 3))
6025 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6026 (add-text-properties
6027 (1- (match-end 3)) (match-end 3)
6028 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6029 t)))))
6031 ;;;; Visibility cycling, including org-goto and indirect buffer
6033 ;;; Cycling
6035 (defvar org-cycle-global-status nil)
6036 (make-variable-buffer-local 'org-cycle-global-status)
6037 (defvar org-cycle-subtree-status nil)
6038 (make-variable-buffer-local 'org-cycle-subtree-status)
6040 (defvar org-inlinetask-min-level)
6042 ;;;###autoload
6043 (defun org-cycle (&optional arg)
6044 "TAB-action and visibility cycling for Org-mode.
6046 This is the command invoked in Org-mode by the TAB key. Its main purpose
6047 is outline visibility cycling, but it also invokes other actions
6048 in special contexts.
6050 - When this function is called with a prefix argument, rotate the entire
6051 buffer through 3 states (global cycling)
6052 1. OVERVIEW: Show only top-level headlines.
6053 2. CONTENTS: Show all headlines of all levels, but no body text.
6054 3. SHOW ALL: Show everything.
6055 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6056 determined by the variable `org-startup-folded', and by any VISIBILITY
6057 properties in the buffer.
6058 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6059 including any drawers.
6061 - When inside a table, re-align the table and move to the next field.
6063 - When point is at the beginning of a headline, rotate the subtree started
6064 by this line through 3 different states (local cycling)
6065 1. FOLDED: Only the main headline is shown.
6066 2. CHILDREN: The main headline and the direct children are shown.
6067 From this state, you can move to one of the children
6068 and zoom in further.
6069 3. SUBTREE: Show the entire subtree, including body text.
6070 If there is no subtree, switch directly from CHILDREN to FOLDED.
6072 - When point is at the beginning of an empty headline and the variable
6073 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6074 of the headline by demoting and promoting it to likely levels. This
6075 speeds up creation document structure by pressing TAB once or several
6076 times right after creating a new headline.
6078 - When there is a numeric prefix, go up to a heading with level ARG, do
6079 a `show-subtree' and return to the previous cursor position. If ARG
6080 is negative, go up that many levels.
6082 - When point is not at the beginning of a headline, execute the global
6083 binding for TAB, which is re-indenting the line. See the option
6084 `org-cycle-emulate-tab' for details.
6086 - Special case: if point is at the beginning of the buffer and there is
6087 no headline in line 1, this function will act as if called with prefix arg
6088 (C-u TAB, same as S-TAB) also when called without prefix arg.
6089 But only if also the variable `org-cycle-global-at-bob' is t."
6090 (interactive "P")
6091 (org-load-modules-maybe)
6092 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6093 (and org-cycle-level-after-item/entry-creation
6094 (or (org-cycle-level)
6095 (org-cycle-item-indentation))))
6096 (let* ((limit-level
6097 (or org-cycle-max-level
6098 (and (boundp 'org-inlinetask-min-level)
6099 org-inlinetask-min-level
6100 (1- org-inlinetask-min-level))))
6101 (nstars (and limit-level
6102 (if org-odd-levels-only
6103 (and limit-level (1- (* limit-level 2)))
6104 limit-level)))
6105 (org-outline-regexp
6106 (if (not (derived-mode-p 'org-mode))
6107 outline-regexp
6108 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6109 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6110 (not (looking-at org-outline-regexp))))
6111 (org-cycle-hook
6112 (if bob-special
6113 (delq 'org-optimize-window-after-visibility-change
6114 (copy-sequence org-cycle-hook))
6115 org-cycle-hook))
6116 (pos (point)))
6118 (if (or bob-special (equal arg '(4)))
6119 ;; special case: use global cycling
6120 (setq arg t))
6122 (cond
6124 ((equal arg '(16))
6125 (setq last-command 'dummy)
6126 (org-set-startup-visibility)
6127 (message "Startup visibility, plus VISIBILITY properties"))
6129 ((equal arg '(64))
6130 (show-all)
6131 (message "Entire buffer visible, including drawers"))
6133 ;; Table: enter it or move to the next field.
6134 ((org-at-table-p 'any)
6135 (if (org-at-table.el-p)
6136 (message "Use C-c ' to edit table.el tables")
6137 (if arg (org-table-edit-field t)
6138 (org-table-justify-field-maybe)
6139 (call-interactively 'org-table-next-field))))
6141 ((run-hook-with-args-until-success
6142 'org-tab-after-check-for-table-hook))
6144 ;; Global cycling: delegate to `org-cycle-internal-global'.
6145 ((eq arg t) (org-cycle-internal-global))
6147 ;; Drawers: delegate to `org-flag-drawer'.
6148 ((and org-drawers org-drawer-regexp
6149 (save-excursion
6150 (beginning-of-line 1)
6151 (looking-at org-drawer-regexp)))
6152 (org-flag-drawer ; toggle block visibility
6153 (not (get-char-property (match-end 0) 'invisible))))
6155 ;; Show-subtree, ARG levels up from here.
6156 ((integerp arg)
6157 (save-excursion
6158 (org-back-to-heading)
6159 (outline-up-heading (if (< arg 0) (- arg)
6160 (- (funcall outline-level) arg)))
6161 (org-show-subtree)))
6163 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6164 ((and (featurep 'org-inlinetask)
6165 (org-inlinetask-at-task-p)
6166 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6167 (org-inlinetask-toggle-visibility))
6169 ((org-try-cdlatex-tab))
6171 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6172 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6173 (save-excursion (beginning-of-line 1)
6174 (looking-at org-outline-regexp)))
6175 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6176 (org-cycle-internal-local))
6178 ;; From there: TAB emulation and template completion.
6179 (buffer-read-only (org-back-to-heading))
6181 ((run-hook-with-args-until-success
6182 'org-tab-after-check-for-cycling-hook))
6184 ((org-try-structure-completion))
6186 ((run-hook-with-args-until-success
6187 'org-tab-before-tab-emulation-hook))
6189 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6190 (or (not (bolp))
6191 (not (looking-at org-outline-regexp))))
6192 (call-interactively (global-key-binding "\t")))
6194 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6195 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6196 (or (and (eq org-cycle-emulate-tab 'white)
6197 (= (match-end 0) (point-at-eol)))
6198 (and (eq org-cycle-emulate-tab 'whitestart)
6199 (>= (match-end 0) pos))))
6201 (eq org-cycle-emulate-tab t))
6202 (call-interactively (global-key-binding "\t")))
6204 (t (save-excursion
6205 (org-back-to-heading)
6206 (org-cycle)))))))
6208 (defun org-cycle-internal-global ()
6209 "Do the global cycling action."
6210 ;; Hack to avoid display of messages for .org attachments in Gnus
6211 (let ((ga (string-match "\\*fontification" (buffer-name))))
6212 (cond
6213 ((and (eq last-command this-command)
6214 (eq org-cycle-global-status 'overview))
6215 ;; We just created the overview - now do table of contents
6216 ;; This can be slow in very large buffers, so indicate action
6217 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6218 (unless ga (message "CONTENTS..."))
6219 (org-content)
6220 (unless ga (message "CONTENTS...done"))
6221 (setq org-cycle-global-status 'contents)
6222 (run-hook-with-args 'org-cycle-hook 'contents))
6224 ((and (eq last-command this-command)
6225 (eq org-cycle-global-status 'contents))
6226 ;; We just showed the table of contents - now show everything
6227 (run-hook-with-args 'org-pre-cycle-hook 'all)
6228 (show-all)
6229 (unless ga (message "SHOW ALL"))
6230 (setq org-cycle-global-status 'all)
6231 (run-hook-with-args 'org-cycle-hook 'all))
6234 ;; Default action: go to overview
6235 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6236 (org-overview)
6237 (unless ga (message "OVERVIEW"))
6238 (setq org-cycle-global-status 'overview)
6239 (run-hook-with-args 'org-cycle-hook 'overview)))))
6241 (defun org-cycle-internal-local ()
6242 "Do the local cycling action."
6243 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6244 ;; First, determine end of headline (EOH), end of subtree or item
6245 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6246 (save-excursion
6247 (if (org-at-item-p)
6248 (progn
6249 (beginning-of-line)
6250 (setq struct (org-list-struct))
6251 (setq eoh (point-at-eol))
6252 (setq eos (org-list-get-item-end-before-blank (point) struct))
6253 (setq has-children (org-list-has-child-p (point) struct)))
6254 (org-back-to-heading)
6255 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6256 (setq eos (save-excursion
6257 (org-end-of-subtree t)
6258 (unless (eobp)
6259 (skip-chars-forward " \t\n"))
6260 (if (eobp) (point) (1- (point)))))
6261 (setq has-children
6262 (or (save-excursion
6263 (let ((level (funcall outline-level)))
6264 (outline-next-heading)
6265 (and (org-at-heading-p t)
6266 (> (funcall outline-level) level))))
6267 (save-excursion
6268 (org-list-search-forward (org-item-beginning-re) eos t)))))
6269 ;; Determine end invisible part of buffer (EOL)
6270 (beginning-of-line 2)
6271 ;; XEmacs doesn't have `next-single-char-property-change'
6272 (if (featurep 'xemacs)
6273 (while (and (not (eobp)) ;; this is like `next-line'
6274 (get-char-property (1- (point)) 'invisible))
6275 (beginning-of-line 2))
6276 (while (and (not (eobp)) ;; this is like `next-line'
6277 (get-char-property (1- (point)) 'invisible))
6278 (goto-char (next-single-char-property-change (point) 'invisible))
6279 (and (eolp) (beginning-of-line 2))))
6280 (setq eol (point)))
6281 ;; Find out what to do next and set `this-command'
6282 (cond
6283 ((= eos eoh)
6284 ;; Nothing is hidden behind this heading
6285 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6286 (message "EMPTY ENTRY")
6287 (setq org-cycle-subtree-status nil)
6288 (save-excursion
6289 (goto-char eos)
6290 (outline-next-heading)
6291 (if (outline-invisible-p) (org-flag-heading nil))))
6292 ((and (or (>= eol eos)
6293 (not (string-match "\\S-" (buffer-substring eol eos))))
6294 (or has-children
6295 (not (setq children-skipped
6296 org-cycle-skip-children-state-if-no-children))))
6297 ;; Entire subtree is hidden in one line: children view
6298 (run-hook-with-args 'org-pre-cycle-hook 'children)
6299 (if (org-at-item-p)
6300 (org-list-set-item-visibility (point-at-bol) struct 'children)
6301 (org-show-entry)
6302 (org-with-limited-levels (show-children))
6303 ;; FIXME: This slows down the func way too much.
6304 ;; How keep drawers hidden in subtree anyway?
6305 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6306 ;; (org-cycle-hide-drawers 'subtree))
6308 ;; Fold every list in subtree to top-level items.
6309 (when (eq org-cycle-include-plain-lists 'integrate)
6310 (save-excursion
6311 (org-back-to-heading)
6312 (while (org-list-search-forward (org-item-beginning-re) eos t)
6313 (beginning-of-line 1)
6314 (let* ((struct (org-list-struct))
6315 (prevs (org-list-prevs-alist struct))
6316 (end (org-list-get-bottom-point struct)))
6317 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6318 (org-list-get-all-items (point) struct prevs))
6319 (goto-char end))))))
6320 (message "CHILDREN")
6321 (save-excursion
6322 (goto-char eos)
6323 (outline-next-heading)
6324 (if (outline-invisible-p) (org-flag-heading nil)))
6325 (setq org-cycle-subtree-status 'children)
6326 (run-hook-with-args 'org-cycle-hook 'children))
6327 ((or children-skipped
6328 (and (eq last-command this-command)
6329 (eq org-cycle-subtree-status 'children)))
6330 ;; We just showed the children, or no children are there,
6331 ;; now show everything.
6332 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6333 (outline-flag-region eoh eos nil)
6334 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6335 (setq org-cycle-subtree-status 'subtree)
6336 (run-hook-with-args 'org-cycle-hook 'subtree))
6338 ;; Default action: hide the subtree.
6339 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6340 (outline-flag-region eoh eos t)
6341 (message "FOLDED")
6342 (setq org-cycle-subtree-status 'folded)
6343 (run-hook-with-args 'org-cycle-hook 'folded)))))
6345 ;;;###autoload
6346 (defun org-global-cycle (&optional arg)
6347 "Cycle the global visibility. For details see `org-cycle'.
6348 With \\[universal-argument] prefix arg, switch to startup visibility.
6349 With a numeric prefix, show all headlines up to that level."
6350 (interactive "P")
6351 (let ((org-cycle-include-plain-lists
6352 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6353 (cond
6354 ((integerp arg)
6355 (show-all)
6356 (hide-sublevels arg)
6357 (setq org-cycle-global-status 'contents))
6358 ((equal arg '(4))
6359 (org-set-startup-visibility)
6360 (message "Startup visibility, plus VISIBILITY properties."))
6362 (org-cycle '(4))))))
6364 (defun org-set-startup-visibility ()
6365 "Set the visibility required by startup options and properties."
6366 (cond
6367 ((eq org-startup-folded t)
6368 (org-cycle '(4)))
6369 ((eq org-startup-folded 'content)
6370 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6371 (org-cycle '(4)) (org-cycle '(4)))))
6372 (unless (eq org-startup-folded 'showeverything)
6373 (if org-hide-block-startup (org-hide-block-all))
6374 (org-set-visibility-according-to-property 'no-cleanup)
6375 (org-cycle-hide-archived-subtrees 'all)
6376 (org-cycle-hide-drawers 'all)
6377 (org-cycle-show-empty-lines t)))
6379 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6380 "Switch subtree visibilities according to :VISIBILITY: property."
6381 (interactive)
6382 (let (org-show-entry-below state)
6383 (save-excursion
6384 (goto-char (point-min))
6385 (while (re-search-forward
6386 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6387 nil t)
6388 (setq state (match-string 1))
6389 (save-excursion
6390 (org-back-to-heading t)
6391 (hide-subtree)
6392 (org-reveal)
6393 (cond
6394 ((equal state '("fold" "folded"))
6395 (hide-subtree))
6396 ((equal state "children")
6397 (org-show-hidden-entry)
6398 (show-children))
6399 ((equal state "content")
6400 (save-excursion
6401 (save-restriction
6402 (org-narrow-to-subtree)
6403 (org-content))))
6404 ((member state '("all" "showall"))
6405 (show-subtree)))))
6406 (unless no-cleanup
6407 (org-cycle-hide-archived-subtrees 'all)
6408 (org-cycle-hide-drawers 'all)
6409 (org-cycle-show-empty-lines 'all)))))
6411 ;; This function uses outline-regexp instead of the more fundamental
6412 ;; org-outline-regexp so that org-cycle-global works outside of Org
6413 ;; buffers, where outline-regexp is needed.
6414 (defun org-overview ()
6415 "Switch to overview mode, showing only top-level headlines.
6416 Really, this shows all headlines with level equal or greater than the level
6417 of the first headline in the buffer. This is important, because if the
6418 first headline is not level one, then (hide-sublevels 1) gives confusing
6419 results."
6420 (interactive)
6421 (let ((level (save-excursion
6422 (goto-char (point-min))
6423 (if (re-search-forward (concat "^" outline-regexp) nil t)
6424 (progn
6425 (goto-char (match-beginning 0))
6426 (funcall outline-level))))))
6427 (and level (hide-sublevels level))))
6429 (defun org-content (&optional arg)
6430 "Show all headlines in the buffer, like a table of contents.
6431 With numerical argument N, show content up to level N."
6432 (interactive "P")
6433 (save-excursion
6434 ;; Visit all headings and show their offspring
6435 (and (integerp arg) (org-overview))
6436 (goto-char (point-max))
6437 (catch 'exit
6438 (while (and (progn (condition-case nil
6439 (outline-previous-visible-heading 1)
6440 (error (goto-char (point-min))))
6442 (looking-at org-outline-regexp))
6443 (if (integerp arg)
6444 (show-children (1- arg))
6445 (show-branches))
6446 (if (bobp) (throw 'exit nil))))))
6449 (defun org-optimize-window-after-visibility-change (state)
6450 "Adjust the window after a change in outline visibility.
6451 This function is the default value of the hook `org-cycle-hook'."
6452 (when (get-buffer-window (current-buffer))
6453 (cond
6454 ((eq state 'content) nil)
6455 ((eq state 'all) nil)
6456 ((eq state 'folded) nil)
6457 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6458 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6460 (defun org-remove-empty-overlays-at (pos)
6461 "Remove outline overlays that do not contain non-white stuff."
6462 (mapc
6463 (lambda (o)
6464 (and (eq 'outline (overlay-get o 'invisible))
6465 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6466 (overlay-end o))))
6467 (delete-overlay o)))
6468 (overlays-at pos)))
6470 (defun org-clean-visibility-after-subtree-move ()
6471 "Fix visibility issues after moving a subtree."
6472 ;; First, find a reasonable region to look at:
6473 ;; Start two siblings above, end three below
6474 (let* ((beg (save-excursion
6475 (and (org-get-last-sibling)
6476 (org-get-last-sibling))
6477 (point)))
6478 (end (save-excursion
6479 (and (org-get-next-sibling)
6480 (org-get-next-sibling)
6481 (org-get-next-sibling))
6482 (if (org-at-heading-p)
6483 (point-at-eol)
6484 (point))))
6485 (level (looking-at "\\*+"))
6486 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6487 (save-excursion
6488 (save-restriction
6489 (narrow-to-region beg end)
6490 (when re
6491 ;; Properly fold already folded siblings
6492 (goto-char (point-min))
6493 (while (re-search-forward re nil t)
6494 (if (and (not (outline-invisible-p))
6495 (save-excursion
6496 (goto-char (point-at-eol)) (outline-invisible-p)))
6497 (hide-entry))))
6498 (org-cycle-show-empty-lines 'overview)
6499 (org-cycle-hide-drawers 'overview)))))
6501 (defun org-cycle-show-empty-lines (state)
6502 "Show empty lines above all visible headlines.
6503 The region to be covered depends on STATE when called through
6504 `org-cycle-hook'. Lisp program can use t for STATE to get the
6505 entire buffer covered. Note that an empty line is only shown if there
6506 are at least `org-cycle-separator-lines' empty lines before the headline."
6507 (when (not (= org-cycle-separator-lines 0))
6508 (save-excursion
6509 (let* ((n (abs org-cycle-separator-lines))
6510 (re (cond
6511 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6512 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6513 (t (let ((ns (number-to-string (- n 2))))
6514 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6515 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6516 beg end b e)
6517 (cond
6518 ((memq state '(overview contents t))
6519 (setq beg (point-min) end (point-max)))
6520 ((memq state '(children folded))
6521 (setq beg (point) end (progn (org-end-of-subtree t t)
6522 (beginning-of-line 2)
6523 (point)))))
6524 (when beg
6525 (goto-char beg)
6526 (while (re-search-forward re end t)
6527 (unless (get-char-property (match-end 1) 'invisible)
6528 (setq e (match-end 1))
6529 (if (< org-cycle-separator-lines 0)
6530 (setq b (save-excursion
6531 (goto-char (match-beginning 0))
6532 (org-back-over-empty-lines)
6533 (if (save-excursion
6534 (goto-char (max (point-min) (1- (point))))
6535 (org-at-heading-p))
6536 (1- (point))
6537 (point))))
6538 (setq b (match-beginning 1)))
6539 (outline-flag-region b e nil)))))))
6540 ;; Never hide empty lines at the end of the file.
6541 (save-excursion
6542 (goto-char (point-max))
6543 (outline-previous-heading)
6544 (outline-end-of-heading)
6545 (if (and (looking-at "[ \t\n]+")
6546 (= (match-end 0) (point-max)))
6547 (outline-flag-region (point) (match-end 0) nil))))
6549 (defun org-show-empty-lines-in-parent ()
6550 "Move to the parent and re-show empty lines before visible headlines."
6551 (save-excursion
6552 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6553 (org-cycle-show-empty-lines context))))
6555 (defun org-files-list ()
6556 "Return `org-agenda-files' list, plus all open org-mode files.
6557 This is useful for operations that need to scan all of a user's
6558 open and agenda-wise Org files."
6559 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6560 (dolist (buf (buffer-list))
6561 (with-current-buffer buf
6562 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6563 (let ((file (expand-file-name (buffer-file-name))))
6564 (unless (member file files)
6565 (push file files))))))
6566 files))
6568 (defsubst org-entry-beginning-position ()
6569 "Return the beginning position of the current entry."
6570 (save-excursion (outline-back-to-heading t) (point)))
6572 (defsubst org-entry-end-position ()
6573 "Return the end position of the current entry."
6574 (save-excursion (outline-next-heading) (point)))
6576 (defun org-cycle-hide-drawers (state)
6577 "Re-hide all drawers after a visibility state change."
6578 (when (and (derived-mode-p 'org-mode)
6579 (not (memq state '(overview folded contents))))
6580 (save-excursion
6581 (let* ((globalp (memq state '(contents all)))
6582 (beg (if globalp (point-min) (point)))
6583 (end (if globalp (point-max)
6584 (if (eq state 'children)
6585 (save-excursion (outline-next-heading) (point))
6586 (org-end-of-subtree t)))))
6587 (goto-char beg)
6588 (while (re-search-forward org-drawer-regexp end t)
6589 (org-flag-drawer t))))))
6591 (defun org-flag-drawer (flag)
6592 "When FLAG is non-nil, hide the drawer we are within.
6593 Otherwise make it visible."
6594 (save-excursion
6595 (beginning-of-line 1)
6596 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6597 (let ((b (match-end 0)))
6598 (if (re-search-forward
6599 "^[ \t]*:END:"
6600 (save-excursion (outline-next-heading) (point)) t)
6601 (outline-flag-region b (point-at-eol) flag)
6602 (error ":END: line missing at position %s" b))))))
6604 (defun org-subtree-end-visible-p ()
6605 "Is the end of the current subtree visible?"
6606 (pos-visible-in-window-p
6607 (save-excursion (org-end-of-subtree t) (point))))
6609 (defun org-first-headline-recenter (&optional N)
6610 "Move cursor to the first headline and recenter the headline.
6611 Optional argument N means put the headline into the Nth line of the window."
6612 (goto-char (point-min))
6613 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6614 (beginning-of-line)
6615 (recenter (prefix-numeric-value N))))
6617 ;;; Saving and restoring visibility
6619 (defun org-outline-overlay-data (&optional use-markers)
6620 "Return a list of the locations of all outline overlays.
6621 These are overlays with the `invisible' property value `outline'.
6622 The return value is a list of cons cells, with start and stop
6623 positions for each overlay.
6624 If USE-MARKERS is set, return the positions as markers."
6625 (let (beg end)
6626 (save-excursion
6627 (save-restriction
6628 (widen)
6629 (delq nil
6630 (mapcar (lambda (o)
6631 (when (eq (overlay-get o 'invisible) 'outline)
6632 (setq beg (overlay-start o)
6633 end (overlay-end o))
6634 (and beg end (> end beg)
6635 (if use-markers
6636 (cons (move-marker (make-marker) beg)
6637 (move-marker (make-marker) end))
6638 (cons beg end)))))
6639 (overlays-in (point-min) (point-max))))))))
6641 (defun org-set-outline-overlay-data (data)
6642 "Create visibility overlays for all positions in DATA.
6643 DATA should have been made by `org-outline-overlay-data'."
6644 (let (o)
6645 (save-excursion
6646 (save-restriction
6647 (widen)
6648 (show-all)
6649 (mapc (lambda (c)
6650 (outline-flag-region (car c) (cdr c) t))
6651 data)))))
6653 ;;; Folding of blocks
6655 (defvar org-hide-block-overlays nil
6656 "Overlays hiding blocks.")
6657 (make-variable-buffer-local 'org-hide-block-overlays)
6659 (defun org-block-map (function &optional start end)
6660 "Call FUNCTION at the head of all source blocks in the current buffer.
6661 Optional arguments START and END can be used to limit the range."
6662 (let ((start (or start (point-min)))
6663 (end (or end (point-max))))
6664 (save-excursion
6665 (goto-char start)
6666 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6667 (save-excursion
6668 (save-match-data
6669 (goto-char (match-beginning 0))
6670 (funcall function)))))))
6672 (defun org-hide-block-toggle-all ()
6673 "Toggle the visibility of all blocks in the current buffer."
6674 (org-block-map #'org-hide-block-toggle))
6676 (defun org-hide-block-all ()
6677 "Fold all blocks in the current buffer."
6678 (interactive)
6679 (org-show-block-all)
6680 (org-block-map #'org-hide-block-toggle-maybe))
6682 (defun org-show-block-all ()
6683 "Unfold all blocks in the current buffer."
6684 (interactive)
6685 (mapc 'delete-overlay org-hide-block-overlays)
6686 (setq org-hide-block-overlays nil))
6688 (defun org-hide-block-toggle-maybe ()
6689 "Toggle visibility of block at point."
6690 (interactive)
6691 (let ((case-fold-search t))
6692 (if (save-excursion
6693 (beginning-of-line 1)
6694 (looking-at org-block-regexp))
6695 (progn (org-hide-block-toggle)
6696 t) ;; to signal that we took action
6697 nil))) ;; to signal that we did not
6699 (defun org-hide-block-toggle (&optional force)
6700 "Toggle the visibility of the current block."
6701 (interactive)
6702 (save-excursion
6703 (beginning-of-line)
6704 (if (re-search-forward org-block-regexp nil t)
6705 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6706 (end (match-end 0)) ;; end of entire body
6708 (if (memq t (mapcar (lambda (overlay)
6709 (eq (overlay-get overlay 'invisible)
6710 'org-hide-block))
6711 (overlays-at start)))
6712 (if (or (not force) (eq force 'off))
6713 (mapc (lambda (ov)
6714 (when (member ov org-hide-block-overlays)
6715 (setq org-hide-block-overlays
6716 (delq ov org-hide-block-overlays)))
6717 (when (eq (overlay-get ov 'invisible)
6718 'org-hide-block)
6719 (delete-overlay ov)))
6720 (overlays-at start)))
6721 (setq ov (make-overlay start end))
6722 (overlay-put ov 'invisible 'org-hide-block)
6723 ;; make the block accessible to isearch
6724 (overlay-put
6725 ov 'isearch-open-invisible
6726 (lambda (ov)
6727 (when (member ov org-hide-block-overlays)
6728 (setq org-hide-block-overlays
6729 (delq ov org-hide-block-overlays)))
6730 (when (eq (overlay-get ov 'invisible)
6731 'org-hide-block)
6732 (delete-overlay ov))))
6733 (push ov org-hide-block-overlays)))
6734 (error "Not looking at a source block"))))
6736 ;; org-tab-after-check-for-cycling-hook
6737 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6738 ;; Remove overlays when changing major mode
6739 (add-hook 'org-mode-hook
6740 (lambda () (org-add-hook 'change-major-mode-hook
6741 'org-show-block-all 'append 'local)))
6743 ;;; Org-goto
6745 (defvar org-goto-window-configuration nil)
6746 (defvar org-goto-marker nil)
6747 (defvar org-goto-map
6748 (let ((map (make-sparse-keymap)))
6749 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6750 (while (setq cmd (pop cmds))
6751 (substitute-key-definition cmd cmd map global-map)))
6752 (suppress-keymap map)
6753 (org-defkey map "\C-m" 'org-goto-ret)
6754 (org-defkey map [(return)] 'org-goto-ret)
6755 (org-defkey map [(left)] 'org-goto-left)
6756 (org-defkey map [(right)] 'org-goto-right)
6757 (org-defkey map [(control ?g)] 'org-goto-quit)
6758 (org-defkey map "\C-i" 'org-cycle)
6759 (org-defkey map [(tab)] 'org-cycle)
6760 (org-defkey map [(down)] 'outline-next-visible-heading)
6761 (org-defkey map [(up)] 'outline-previous-visible-heading)
6762 (if org-goto-auto-isearch
6763 (if (fboundp 'define-key-after)
6764 (define-key-after map [t] 'org-goto-local-auto-isearch)
6765 nil)
6766 (org-defkey map "q" 'org-goto-quit)
6767 (org-defkey map "n" 'outline-next-visible-heading)
6768 (org-defkey map "p" 'outline-previous-visible-heading)
6769 (org-defkey map "f" 'outline-forward-same-level)
6770 (org-defkey map "b" 'outline-backward-same-level)
6771 (org-defkey map "u" 'outline-up-heading))
6772 (org-defkey map "/" 'org-occur)
6773 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6774 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6775 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6776 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6777 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6778 map))
6780 (defconst org-goto-help
6781 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6782 RET=jump to location [Q]uit and return to previous location
6783 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6785 (defvar org-goto-start-pos) ; dynamically scoped parameter
6787 ;; FIXME: Docstring does not mention both interfaces
6788 (defun org-goto (&optional alternative-interface)
6789 "Look up a different location in the current file, keeping current visibility.
6791 When you want look-up or go to a different location in a
6792 document, the fastest way is often to fold the entire buffer and
6793 then dive into the tree. This method has the disadvantage, that
6794 the previous location will be folded, which may not be what you
6795 want.
6797 This command works around this by showing a copy of the current
6798 buffer in an indirect buffer, in overview mode. You can dive
6799 into the tree in that copy, use org-occur and incremental search
6800 to find a location. When pressing RET or `Q', the command
6801 returns to the original buffer in which the visibility is still
6802 unchanged. After RET it will also jump to the location selected
6803 in the indirect buffer and expose the headline hierarchy above.
6805 With a prefix argument, use the alternative interface: e.g. if
6806 `org-goto-interface' is 'outline use 'outline-path-completion."
6807 (interactive "P")
6808 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6809 (org-refile-use-outline-path t)
6810 (org-refile-target-verify-function nil)
6811 (interface
6812 (if (not alternative-interface)
6813 org-goto-interface
6814 (if (eq org-goto-interface 'outline)
6815 'outline-path-completion
6816 'outline)))
6817 (org-goto-start-pos (point))
6818 (selected-point
6819 (if (eq interface 'outline)
6820 (car (org-get-location (current-buffer) org-goto-help))
6821 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6822 (org-refile-check-position pa)
6823 (nth 3 pa)))))
6824 (if selected-point
6825 (progn
6826 (org-mark-ring-push org-goto-start-pos)
6827 (goto-char selected-point)
6828 (if (or (outline-invisible-p) (org-invisible-p2))
6829 (org-show-context 'org-goto)))
6830 (message "Quit"))))
6832 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6833 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6834 (defvar org-goto-local-auto-isearch-map) ; defined below
6836 (defun org-get-location (buf help)
6837 "Let the user select a location in the Org-mode buffer BUF.
6838 This function uses a recursive edit. It returns the selected position
6839 or nil."
6840 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6841 (isearch-hide-immediately nil)
6842 (isearch-search-fun-function
6843 (lambda () 'org-goto-local-search-headings))
6844 (org-goto-selected-point org-goto-exit-command)
6845 (pop-up-frames nil)
6846 (special-display-buffer-names nil)
6847 (special-display-regexps nil)
6848 (special-display-function nil))
6849 (save-excursion
6850 (save-window-excursion
6851 (delete-other-windows)
6852 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6853 (org-pop-to-buffer-same-window
6854 (condition-case nil
6855 (make-indirect-buffer (current-buffer) "*org-goto*")
6856 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6857 (with-output-to-temp-buffer "*Help*"
6858 (princ help))
6859 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6860 (setq buffer-read-only nil)
6861 (let ((org-startup-truncated t)
6862 (org-startup-folded nil)
6863 (org-startup-align-all-tables nil))
6864 (org-mode)
6865 (org-overview))
6866 (setq buffer-read-only t)
6867 (if (and (boundp 'org-goto-start-pos)
6868 (integer-or-marker-p org-goto-start-pos))
6869 (let ((org-show-hierarchy-above t)
6870 (org-show-siblings t)
6871 (org-show-following-heading t))
6872 (goto-char org-goto-start-pos)
6873 (and (outline-invisible-p) (org-show-context)))
6874 (goto-char (point-min)))
6875 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6876 (message "Select location and press RET")
6877 (use-local-map org-goto-map)
6878 (recursive-edit)
6880 (kill-buffer "*org-goto*")
6881 (cons org-goto-selected-point org-goto-exit-command)))
6883 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6884 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6885 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6886 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6888 (defun org-goto-local-search-headings (string bound noerror)
6889 "Search and make sure that any matches are in headlines."
6890 (catch 'return
6891 (while (if isearch-forward
6892 (search-forward string bound noerror)
6893 (search-backward string bound noerror))
6894 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6895 (and (member :headline context)
6896 (not (member :tags context))))
6897 (throw 'return (point))))))
6899 (defun org-goto-local-auto-isearch ()
6900 "Start isearch."
6901 (interactive)
6902 (goto-char (point-min))
6903 (let ((keys (this-command-keys)))
6904 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6905 (isearch-mode t)
6906 (isearch-process-search-char (string-to-char keys)))))
6908 (defun org-goto-ret (&optional arg)
6909 "Finish `org-goto' by going to the new location."
6910 (interactive "P")
6911 (setq org-goto-selected-point (point)
6912 org-goto-exit-command 'return)
6913 (throw 'exit nil))
6915 (defun org-goto-left ()
6916 "Finish `org-goto' by going to the new location."
6917 (interactive)
6918 (if (org-at-heading-p)
6919 (progn
6920 (beginning-of-line 1)
6921 (setq org-goto-selected-point (point)
6922 org-goto-exit-command 'left)
6923 (throw 'exit nil))
6924 (error "Not on a heading")))
6926 (defun org-goto-right ()
6927 "Finish `org-goto' by going to the new location."
6928 (interactive)
6929 (if (org-at-heading-p)
6930 (progn
6931 (setq org-goto-selected-point (point)
6932 org-goto-exit-command 'right)
6933 (throw 'exit nil))
6934 (error "Not on a heading")))
6936 (defun org-goto-quit ()
6937 "Finish `org-goto' without cursor motion."
6938 (interactive)
6939 (setq org-goto-selected-point nil)
6940 (setq org-goto-exit-command 'quit)
6941 (throw 'exit nil))
6943 ;;; Indirect buffer display of subtrees
6945 (defvar org-indirect-dedicated-frame nil
6946 "This is the frame being used for indirect tree display.")
6947 (defvar org-last-indirect-buffer nil)
6949 (defun org-tree-to-indirect-buffer (&optional arg)
6950 "Create indirect buffer and narrow it to current subtree.
6951 With a numerical prefix ARG, go up to this level and then take that tree.
6952 If ARG is negative, go up that many levels.
6954 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6955 indirect buffer previously made with this command, to avoid proliferation of
6956 indirect buffers. However, when you call the command with a \
6957 \\[universal-argument] prefix, or
6958 when `org-indirect-buffer-display' is `new-frame', the last buffer
6959 is kept so that you can work with several indirect buffers at the same time.
6960 If `org-indirect-buffer-display' is `dedicated-frame', the \
6961 \\[universal-argument] prefix also
6962 requests that a new frame be made for the new buffer, so that the dedicated
6963 frame is not changed."
6964 (interactive "P")
6965 (let ((cbuf (current-buffer))
6966 (cwin (selected-window))
6967 (pos (point))
6968 beg end level heading ibuf)
6969 (save-excursion
6970 (org-back-to-heading t)
6971 (when (numberp arg)
6972 (setq level (org-outline-level))
6973 (if (< arg 0) (setq arg (+ level arg)))
6974 (while (> (setq level (org-outline-level)) arg)
6975 (org-up-heading-safe)))
6976 (setq beg (point)
6977 heading (org-get-heading))
6978 (org-end-of-subtree t t)
6979 (if (org-at-heading-p) (backward-char 1))
6980 (setq end (point)))
6981 (if (and (buffer-live-p org-last-indirect-buffer)
6982 (not (eq org-indirect-buffer-display 'new-frame))
6983 (not arg))
6984 (kill-buffer org-last-indirect-buffer))
6985 (setq ibuf (org-get-indirect-buffer cbuf)
6986 org-last-indirect-buffer ibuf)
6987 (cond
6988 ((or (eq org-indirect-buffer-display 'new-frame)
6989 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6990 (select-frame (make-frame))
6991 (delete-other-windows)
6992 (org-pop-to-buffer-same-window ibuf)
6993 (org-set-frame-title heading))
6994 ((eq org-indirect-buffer-display 'dedicated-frame)
6995 (raise-frame
6996 (select-frame (or (and org-indirect-dedicated-frame
6997 (frame-live-p org-indirect-dedicated-frame)
6998 org-indirect-dedicated-frame)
6999 (setq org-indirect-dedicated-frame (make-frame)))))
7000 (delete-other-windows)
7001 (org-pop-to-buffer-same-window ibuf)
7002 (org-set-frame-title (concat "Indirect: " heading)))
7003 ((eq org-indirect-buffer-display 'current-window)
7004 (org-pop-to-buffer-same-window ibuf))
7005 ((eq org-indirect-buffer-display 'other-window)
7006 (pop-to-buffer ibuf))
7007 (t (error "Invalid value")))
7008 (if (featurep 'xemacs)
7009 (save-excursion (org-mode) (turn-on-font-lock)))
7010 (narrow-to-region beg end)
7011 (show-all)
7012 (goto-char pos)
7013 (run-hook-with-args 'org-cycle-hook 'all)
7014 (and (window-live-p cwin) (select-window cwin))))
7016 (defun org-get-indirect-buffer (&optional buffer)
7017 (setq buffer (or buffer (current-buffer)))
7018 (let ((n 1) (base (buffer-name buffer)) bname)
7019 (while (buffer-live-p
7020 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7021 (setq n (1+ n)))
7022 (condition-case nil
7023 (make-indirect-buffer buffer bname 'clone)
7024 (error (make-indirect-buffer buffer bname)))))
7026 (defun org-set-frame-title (title)
7027 "Set the title of the current frame to the string TITLE."
7028 ;; FIXME: how to name a single frame in XEmacs???
7029 (unless (featurep 'xemacs)
7030 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7032 ;;;; Structure editing
7034 ;;; Inserting headlines
7036 (defun org-previous-line-empty-p ()
7037 (save-excursion
7038 (and (not (bobp))
7039 (or (beginning-of-line 0) t)
7040 (save-match-data
7041 (looking-at "[ \t]*$")))))
7043 (defun org-insert-heading (&optional force-heading invisible-ok)
7044 "Insert a new heading or item with same depth at point.
7045 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7046 If point is at the beginning of a headline, insert a sibling before the
7047 current headline. If point is not at the beginning, split the line,
7048 create the new headline with the text in the current line after point
7049 \(but see also the variable `org-M-RET-may-split-line').
7051 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7052 This is important for non-interactive uses of the command."
7053 (interactive "P")
7054 (if (or (= (buffer-size) 0)
7055 (and (not (save-excursion
7056 (and (ignore-errors (org-back-to-heading invisible-ok))
7057 (org-at-heading-p))))
7058 (or force-heading (not (org-in-item-p)))))
7059 (progn
7060 (insert "\n* ")
7061 (run-hooks 'org-insert-heading-hook))
7062 (when (or force-heading (not (org-insert-item)))
7063 (let* ((empty-line-p nil)
7064 (level nil)
7065 (on-heading (org-at-heading-p))
7066 (head (save-excursion
7067 (condition-case nil
7068 (progn
7069 (org-back-to-heading invisible-ok)
7070 (when (and (not on-heading)
7071 (featurep 'org-inlinetask)
7072 (integerp org-inlinetask-min-level)
7073 (>= (length (match-string 0))
7074 org-inlinetask-min-level))
7075 ;; Find a heading level before the inline task
7076 (while (and (setq level (org-up-heading-safe))
7077 (>= level org-inlinetask-min-level)))
7078 (if (org-at-heading-p)
7079 (org-back-to-heading invisible-ok)
7080 (error "This should not happen")))
7081 (setq empty-line-p (org-previous-line-empty-p))
7082 (match-string 0))
7083 (error "*"))))
7084 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7085 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7086 pos hide-previous previous-pos)
7087 (cond
7088 ((and (org-at-heading-p) (bolp)
7089 (or (bobp)
7090 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7091 ;; insert before the current line
7092 (open-line (if blank 2 1)))
7093 ((and (bolp)
7094 (not org-insert-heading-respect-content)
7095 (or (bobp)
7096 (save-excursion
7097 (backward-char 1) (not (outline-invisible-p)))))
7098 ;; insert right here
7099 nil)
7101 ;; somewhere in the line
7102 (save-excursion
7103 (setq previous-pos (point-at-bol))
7104 (end-of-line)
7105 (setq hide-previous (outline-invisible-p)))
7106 (and org-insert-heading-respect-content (org-show-subtree))
7107 (let ((split
7108 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7109 (save-excursion
7110 (let ((p (point)))
7111 (goto-char (point-at-bol))
7112 (and (looking-at org-complex-heading-regexp)
7113 (match-beginning 4)
7114 (> p (match-beginning 4)))))))
7115 tags pos)
7116 (cond
7117 (org-insert-heading-respect-content
7118 (org-end-of-subtree nil t)
7119 (when (featurep 'org-inlinetask)
7120 (while (and (not (eobp))
7121 (looking-at "\\(\\*+\\)[ \t]+")
7122 (>= (length (match-string 1))
7123 org-inlinetask-min-level))
7124 (org-end-of-subtree nil t)))
7125 (or (bolp) (newline))
7126 (or (org-previous-line-empty-p)
7127 (and blank (newline)))
7128 (open-line 1))
7129 ((org-at-heading-p)
7130 (when hide-previous
7131 (show-children)
7132 (org-show-entry))
7133 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7134 (setq tags (and (match-end 2) (match-string 2)))
7135 (and (match-end 1)
7136 (delete-region (match-beginning 1) (match-end 1)))
7137 (setq pos (point-at-bol))
7138 (or split (end-of-line 1))
7139 (delete-horizontal-space)
7140 (if (string-match "\\`\\*+\\'"
7141 (buffer-substring (point-at-bol) (point)))
7142 (insert " "))
7143 (newline (if blank 2 1))
7144 (when tags
7145 (save-excursion
7146 (goto-char pos)
7147 (end-of-line 1)
7148 (insert " " tags)
7149 (org-set-tags nil 'align))))
7151 (or split (end-of-line 1))
7152 (newline (if blank 2 1)))))))
7153 (insert head) (just-one-space)
7154 (setq pos (point))
7155 (end-of-line 1)
7156 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7157 (when (and org-insert-heading-respect-content hide-previous)
7158 (save-excursion
7159 (goto-char previous-pos)
7160 (hide-subtree)))
7161 (run-hooks 'org-insert-heading-hook)))))
7163 (defun org-get-heading (&optional no-tags no-todo)
7164 "Return the heading of the current entry, without the stars.
7165 When NO-TAGS is non-nil, don't include tags.
7166 When NO-TODO is non-nil, don't include TODO keywords."
7167 (save-excursion
7168 (org-back-to-heading t)
7169 (cond
7170 ((and no-tags no-todo)
7171 (looking-at org-complex-heading-regexp)
7172 (match-string 4))
7173 (no-tags
7174 (looking-at (concat org-outline-regexp
7175 "\\(.*?\\)"
7176 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7177 (match-string 1))
7178 (no-todo
7179 (looking-at org-todo-line-regexp)
7180 (match-string 3))
7181 (t (looking-at org-heading-regexp)
7182 (match-string 2)))))
7184 (defun org-heading-components ()
7185 "Return the components of the current heading.
7186 This is a list with the following elements:
7187 - the level as an integer
7188 - the reduced level, different if `org-odd-levels-only' is set.
7189 - the TODO keyword, or nil
7190 - the priority character, like ?A, or nil if no priority is given
7191 - the headline text itself, or the tags string if no headline text
7192 - the tags string, or nil."
7193 (save-excursion
7194 (org-back-to-heading t)
7195 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7196 (list (length (match-string 1))
7197 (org-reduced-level (length (match-string 1)))
7198 (org-match-string-no-properties 2)
7199 (and (match-end 3) (aref (match-string 3) 2))
7200 (org-match-string-no-properties 4)
7201 (org-match-string-no-properties 5)))))
7203 (defun org-get-entry ()
7204 "Get the entry text, after heading, entire subtree."
7205 (save-excursion
7206 (org-back-to-heading t)
7207 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7209 (defun org-insert-heading-after-current ()
7210 "Insert a new heading with same level as current, after current subtree."
7211 (interactive)
7212 (org-back-to-heading)
7213 (org-insert-heading)
7214 (org-move-subtree-down)
7215 (end-of-line 1))
7217 (defun org-insert-heading-respect-content ()
7218 (interactive)
7219 (let ((org-insert-heading-respect-content t))
7220 (org-insert-heading t)))
7222 (defun org-insert-todo-heading-respect-content (&optional force-state)
7223 (interactive "P")
7224 (let ((org-insert-heading-respect-content t))
7225 (org-insert-todo-heading force-state t)))
7227 (defun org-insert-todo-heading (arg &optional force-heading)
7228 "Insert a new heading with the same level and TODO state as current heading.
7229 If the heading has no TODO state, or if the state is DONE, use the first
7230 state (TODO by default). Also with prefix arg, force first state."
7231 (interactive "P")
7232 (when (or force-heading (not (org-insert-item 'checkbox)))
7233 (org-insert-heading force-heading)
7234 (save-excursion
7235 (org-back-to-heading)
7236 (outline-previous-heading)
7237 (looking-at org-todo-line-regexp))
7238 (let*
7239 ((new-mark-x
7240 (if (or arg
7241 (not (match-beginning 2))
7242 (member (match-string 2) org-done-keywords))
7243 (car org-todo-keywords-1)
7244 (match-string 2)))
7245 (new-mark
7247 (run-hook-with-args-until-success
7248 'org-todo-get-default-hook new-mark-x nil)
7249 new-mark-x)))
7250 (beginning-of-line 1)
7251 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7252 (if org-treat-insert-todo-heading-as-state-change
7253 (org-todo new-mark)
7254 (insert new-mark " "))))
7255 (when org-provide-todo-statistics
7256 (org-update-parent-todo-statistics))))
7258 (defun org-insert-subheading (arg)
7259 "Insert a new subheading and demote it.
7260 Works for outline headings and for plain lists alike."
7261 (interactive "P")
7262 (org-insert-heading arg)
7263 (cond
7264 ((org-at-heading-p) (org-do-demote))
7265 ((org-at-item-p) (org-indent-item))))
7267 (defun org-insert-todo-subheading (arg)
7268 "Insert a new subheading with TODO keyword or checkbox and demote it.
7269 Works for outline headings and for plain lists alike."
7270 (interactive "P")
7271 (org-insert-todo-heading arg)
7272 (cond
7273 ((org-at-heading-p) (org-do-demote))
7274 ((org-at-item-p) (org-indent-item))))
7276 ;;; Promotion and Demotion
7278 (defvar org-after-demote-entry-hook nil
7279 "Hook run after an entry has been demoted.
7280 The cursor will be at the beginning of the entry.
7281 When a subtree is being demoted, the hook will be called for each node.")
7283 (defvar org-after-promote-entry-hook nil
7284 "Hook run after an entry has been promoted.
7285 The cursor will be at the beginning of the entry.
7286 When a subtree is being promoted, the hook will be called for each node.")
7288 (defun org-promote-subtree ()
7289 "Promote the entire subtree.
7290 See also `org-promote'."
7291 (interactive)
7292 (save-excursion
7293 (org-with-limited-levels (org-map-tree 'org-promote)))
7294 (org-fix-position-after-promote))
7296 (defun org-demote-subtree ()
7297 "Demote the entire subtree. See `org-demote'.
7298 See also `org-promote'."
7299 (interactive)
7300 (save-excursion
7301 (org-with-limited-levels (org-map-tree 'org-demote)))
7302 (org-fix-position-after-promote))
7305 (defun org-do-promote ()
7306 "Promote the current heading higher up the tree.
7307 If the region is active in `transient-mark-mode', promote all headings
7308 in the region."
7309 (interactive)
7310 (save-excursion
7311 (if (org-region-active-p)
7312 (org-map-region 'org-promote (region-beginning) (region-end))
7313 (org-promote)))
7314 (org-fix-position-after-promote))
7316 (defun org-do-demote ()
7317 "Demote the current heading lower down the tree.
7318 If the region is active in `transient-mark-mode', demote all headings
7319 in the region."
7320 (interactive)
7321 (save-excursion
7322 (if (org-region-active-p)
7323 (org-map-region 'org-demote (region-beginning) (region-end))
7324 (org-demote)))
7325 (org-fix-position-after-promote))
7327 (defun org-fix-position-after-promote ()
7328 "Make sure that after pro/demotion cursor position is right."
7329 (let ((pos (point)))
7330 (when (save-excursion
7331 (beginning-of-line 1)
7332 (looking-at org-todo-line-regexp)
7333 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7334 (cond ((eobp) (insert " "))
7335 ((eolp) (insert " "))
7336 ((equal (char-after) ?\ ) (forward-char 1))))))
7338 (defun org-current-level ()
7339 "Return the level of the current entry, or nil if before the first headline.
7340 The level is the number of stars at the beginning of the headline."
7341 (save-excursion
7342 (org-with-limited-levels
7343 (if (ignore-errors (org-back-to-heading t))
7344 (funcall outline-level)))))
7346 (defun org-get-previous-line-level ()
7347 "Return the outline depth of the last headline before the current line.
7348 Returns 0 for the first headline in the buffer, and nil if before the
7349 first headline."
7350 (let ((current-level (org-current-level))
7351 (prev-level (when (> (line-number-at-pos) 1)
7352 (save-excursion
7353 (beginning-of-line 0)
7354 (org-current-level)))))
7355 (cond ((null current-level) nil) ; Before first headline
7356 ((null prev-level) 0) ; At first headline
7357 (prev-level))))
7359 (defun org-reduced-level (l)
7360 "Compute the effective level of a heading.
7361 This takes into account the setting of `org-odd-levels-only'."
7362 (cond
7363 ((zerop l) 0)
7364 (org-odd-levels-only (1+ (floor (/ l 2))))
7365 (t l)))
7367 (defun org-level-increment ()
7368 "Return the number of stars that will be added or removed at a
7369 time to headlines when structure editing, based on the value of
7370 `org-odd-levels-only'."
7371 (if org-odd-levels-only 2 1))
7373 (defun org-get-valid-level (level &optional change)
7374 "Rectify a level change under the influence of `org-odd-levels-only'
7375 LEVEL is a current level, CHANGE is by how much the level should be
7376 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7377 even level numbers will become the next higher odd number."
7378 (if org-odd-levels-only
7379 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7380 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7381 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7382 (max 1 (+ level (or change 0)))))
7384 (if (boundp 'define-obsolete-function-alias)
7385 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7386 (define-obsolete-function-alias 'org-get-legal-level
7387 'org-get-valid-level)
7388 (define-obsolete-function-alias 'org-get-legal-level
7389 'org-get-valid-level "23.1")))
7391 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7392 ;; ̀org-with-limited-levels'
7393 (defun org-promote ()
7394 "Promote the current heading higher up the tree.
7395 If the region is active in `transient-mark-mode', promote all headings
7396 in the region."
7397 (org-back-to-heading t)
7398 (let* ((level (save-match-data (funcall outline-level)))
7399 (after-change-functions (remove 'flyspell-after-change-function
7400 after-change-functions))
7401 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7402 (diff (abs (- level (length up-head) -1))))
7403 (cond ((and (= level 1) org-called-with-limited-levels
7404 org-allow-promoting-top-level-subtree)
7405 (replace-match "# " nil t))
7406 ((= level 1)
7407 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7408 (t (replace-match up-head nil t)))
7409 ;; Fixup tag positioning
7410 (unless (= level 1)
7411 (and org-auto-align-tags (org-set-tags nil t))
7412 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7413 (run-hooks 'org-after-promote-entry-hook)))
7415 (defun org-demote ()
7416 "Demote the current heading lower down the tree.
7417 If the region is active in `transient-mark-mode', demote all headings
7418 in the region."
7419 (org-back-to-heading t)
7420 (let* ((level (save-match-data (funcall outline-level)))
7421 (after-change-functions (remove 'flyspell-after-change-function
7422 after-change-functions))
7423 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7424 (diff (abs (- level (length down-head) -1))))
7425 (replace-match down-head nil t)
7426 ;; Fixup tag positioning
7427 (and org-auto-align-tags (org-set-tags nil t))
7428 (if org-adapt-indentation (org-fixup-indentation diff))
7429 (run-hooks 'org-after-demote-entry-hook)))
7431 (defun org-cycle-level ()
7432 "Cycle the level of an empty headline through possible states.
7433 This goes first to child, then to parent, level, then up the hierarchy.
7434 After top level, it switches back to sibling level."
7435 (interactive)
7436 (let ((org-adapt-indentation nil))
7437 (when (org-point-at-end-of-empty-headline)
7438 (setq this-command 'org-cycle-level) ; Only needed for caching
7439 (let ((cur-level (org-current-level))
7440 (prev-level (org-get-previous-line-level)))
7441 (cond
7442 ;; If first headline in file, promote to top-level.
7443 ((= prev-level 0)
7444 (loop repeat (/ (- cur-level 1) (org-level-increment))
7445 do (org-do-promote)))
7446 ;; If same level as prev, demote one.
7447 ((= prev-level cur-level)
7448 (org-do-demote))
7449 ;; If parent is top-level, promote to top level if not already.
7450 ((= prev-level 1)
7451 (loop repeat (/ (- cur-level 1) (org-level-increment))
7452 do (org-do-promote)))
7453 ;; If top-level, return to prev-level.
7454 ((= cur-level 1)
7455 (loop repeat (/ (- prev-level 1) (org-level-increment))
7456 do (org-do-demote)))
7457 ;; If less than prev-level, promote one.
7458 ((< cur-level prev-level)
7459 (org-do-promote))
7460 ;; If deeper than prev-level, promote until higher than
7461 ;; prev-level.
7462 ((> cur-level prev-level)
7463 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7464 do (org-do-promote))))
7465 t))))
7467 (defun org-map-tree (fun)
7468 "Call FUN for every heading underneath the current one."
7469 (org-back-to-heading)
7470 (let ((level (funcall outline-level)))
7471 (save-excursion
7472 (funcall fun)
7473 (while (and (progn
7474 (outline-next-heading)
7475 (> (funcall outline-level) level))
7476 (not (eobp)))
7477 (funcall fun)))))
7479 (defun org-map-region (fun beg end)
7480 "Call FUN for every heading between BEG and END."
7481 (let ((org-ignore-region t))
7482 (save-excursion
7483 (setq end (copy-marker end))
7484 (goto-char beg)
7485 (if (and (re-search-forward org-outline-regexp-bol nil t)
7486 (< (point) end))
7487 (funcall fun))
7488 (while (and (progn
7489 (outline-next-heading)
7490 (< (point) end))
7491 (not (eobp)))
7492 (funcall fun)))))
7494 (defvar org-property-end-re) ; silence byte-compiler
7495 (defun org-fixup-indentation (diff)
7496 "Change the indentation in the current entry by DIFF.
7497 However, if any line in the current entry has no indentation, or if it
7498 would end up with no indentation after the change, nothing at all is done."
7499 (save-excursion
7500 (let ((end (save-excursion (outline-next-heading)
7501 (point-marker)))
7502 (prohibit (if (> diff 0)
7503 "^\\S-"
7504 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7505 col)
7506 (unless (save-excursion (end-of-line 1)
7507 (re-search-forward prohibit end t))
7508 (while (and (< (point) end)
7509 (re-search-forward "^[ \t]+" end t))
7510 (goto-char (match-end 0))
7511 (setq col (current-column))
7512 (if (< diff 0) (replace-match ""))
7513 (org-indent-to-column (+ diff col))))
7514 (move-marker end nil))))
7516 (defun org-convert-to-odd-levels ()
7517 "Convert an org-mode file with all levels allowed to one with odd levels.
7518 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7519 level 5 etc."
7520 (interactive)
7521 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7522 (let ((outline-level 'org-outline-level)
7523 (org-odd-levels-only nil) n)
7524 (save-excursion
7525 (goto-char (point-min))
7526 (while (re-search-forward "^\\*\\*+ " nil t)
7527 (setq n (- (length (match-string 0)) 2))
7528 (while (>= (setq n (1- n)) 0)
7529 (org-demote))
7530 (end-of-line 1))))))
7532 (defun org-convert-to-oddeven-levels ()
7533 "Convert an org-mode file with only odd levels to one with odd/even levels.
7534 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7535 file contains a section with an even level, conversion would
7536 destroy the structure of the file. An error is signaled in this
7537 case."
7538 (interactive)
7539 (goto-char (point-min))
7540 ;; First check if there are no even levels
7541 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7542 (org-show-context t)
7543 (error "Not all levels are odd in this file. Conversion not possible"))
7544 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7545 (let ((outline-regexp org-outline-regexp)
7546 (outline-level 'org-outline-level)
7547 (org-odd-levels-only nil) n)
7548 (save-excursion
7549 (goto-char (point-min))
7550 (while (re-search-forward "^\\*\\*+ " nil t)
7551 (setq n (/ (1- (length (match-string 0))) 2))
7552 (while (>= (setq n (1- n)) 0)
7553 (org-promote))
7554 (end-of-line 1))))))
7556 (defun org-tr-level (n)
7557 "Make N odd if required."
7558 (if org-odd-levels-only (1+ (/ n 2)) n))
7560 ;;; Vertical tree motion, cutting and pasting of subtrees
7562 (defun org-move-subtree-up (&optional arg)
7563 "Move the current subtree up past ARG headlines of the same level."
7564 (interactive "p")
7565 (org-move-subtree-down (- (prefix-numeric-value arg))))
7567 (defun org-move-subtree-down (&optional arg)
7568 "Move the current subtree down past ARG headlines of the same level."
7569 (interactive "p")
7570 (setq arg (prefix-numeric-value arg))
7571 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7572 'org-get-last-sibling))
7573 (ins-point (make-marker))
7574 (cnt (abs arg))
7575 (col (current-column))
7576 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7577 ;; Select the tree
7578 (org-back-to-heading)
7579 (setq beg0 (point))
7580 (save-excursion
7581 (setq ne-beg (org-back-over-empty-lines))
7582 (setq beg (point)))
7583 (save-match-data
7584 (save-excursion (outline-end-of-heading)
7585 (setq folded (outline-invisible-p)))
7586 (outline-end-of-subtree))
7587 (outline-next-heading)
7588 (setq ne-end (org-back-over-empty-lines))
7589 (setq end (point))
7590 (goto-char beg0)
7591 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7592 ;; include less whitespace
7593 (save-excursion
7594 (goto-char beg)
7595 (forward-line (- ne-beg ne-end))
7596 (setq beg (point))))
7597 ;; Find insertion point, with error handling
7598 (while (> cnt 0)
7599 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7600 (progn (goto-char beg0)
7601 (error "Cannot move past superior level or buffer limit")))
7602 (setq cnt (1- cnt)))
7603 (if (> arg 0)
7604 ;; Moving forward - still need to move over subtree
7605 (progn (org-end-of-subtree t t)
7606 (save-excursion
7607 (org-back-over-empty-lines)
7608 (or (bolp) (newline)))))
7609 (setq ne-ins (org-back-over-empty-lines))
7610 (move-marker ins-point (point))
7611 (setq txt (buffer-substring beg end))
7612 (org-save-markers-in-region beg end)
7613 (delete-region beg end)
7614 (org-remove-empty-overlays-at beg)
7615 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7616 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7617 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7618 (let ((bbb (point)))
7619 (insert-before-markers txt)
7620 (org-reinstall-markers-in-region bbb)
7621 (move-marker ins-point bbb))
7622 (or (bolp) (insert "\n"))
7623 (setq ins-end (point))
7624 (goto-char ins-point)
7625 (org-skip-whitespace)
7626 (when (and (< arg 0)
7627 (org-first-sibling-p)
7628 (> ne-ins ne-beg))
7629 ;; Move whitespace back to beginning
7630 (save-excursion
7631 (goto-char ins-end)
7632 (let ((kill-whole-line t))
7633 (kill-line (- ne-ins ne-beg)) (point)))
7634 (insert (make-string (- ne-ins ne-beg) ?\n)))
7635 (move-marker ins-point nil)
7636 (if folded
7637 (hide-subtree)
7638 (org-show-entry)
7639 (show-children)
7640 (org-cycle-hide-drawers 'children))
7641 (org-clean-visibility-after-subtree-move)
7642 ;; move back to the initial column we were at
7643 (move-to-column col)))
7645 (defvar org-subtree-clip ""
7646 "Clipboard for cut and paste of subtrees.
7647 This is actually only a copy of the kill, because we use the normal kill
7648 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7650 (defvar org-subtree-clip-folded nil
7651 "Was the last copied subtree folded?
7652 This is used to fold the tree back after pasting.")
7654 (defun org-cut-subtree (&optional n)
7655 "Cut the current subtree into the clipboard.
7656 With prefix arg N, cut this many sequential subtrees.
7657 This is a short-hand for marking the subtree and then cutting it."
7658 (interactive "p")
7659 (org-copy-subtree n 'cut))
7661 (defun org-copy-subtree (&optional n cut force-store-markers)
7662 "Cut the current subtree into the clipboard.
7663 With prefix arg N, cut this many sequential subtrees.
7664 This is a short-hand for marking the subtree and then copying it.
7665 If CUT is non-nil, actually cut the subtree.
7666 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7667 of some markers in the region, even if CUT is non-nil. This is
7668 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7669 (interactive "p")
7670 (let (beg end folded (beg0 (point)))
7671 (if (org-called-interactively-p 'any)
7672 (org-back-to-heading nil) ; take what looks like a subtree
7673 (org-back-to-heading t)) ; take what is really there
7674 (org-back-over-empty-lines)
7675 (setq beg (point))
7676 (skip-chars-forward " \t\r\n")
7677 (save-match-data
7678 (save-excursion (outline-end-of-heading)
7679 (setq folded (outline-invisible-p)))
7680 (condition-case nil
7681 (org-forward-heading-same-level (1- n) t)
7682 (error nil))
7683 (org-end-of-subtree t t))
7684 (org-back-over-empty-lines)
7685 (setq end (point))
7686 (goto-char beg0)
7687 (when (> end beg)
7688 (setq org-subtree-clip-folded folded)
7689 (when (or cut force-store-markers)
7690 (org-save-markers-in-region beg end))
7691 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7692 (setq org-subtree-clip (current-kill 0))
7693 (message "%s: Subtree(s) with %d characters"
7694 (if cut "Cut" "Copied")
7695 (length org-subtree-clip)))))
7697 (defun org-paste-subtree (&optional level tree for-yank)
7698 "Paste the clipboard as a subtree, with modification of headline level.
7699 The entire subtree is promoted or demoted in order to match a new headline
7700 level.
7702 If the cursor is at the beginning of a headline, the same level as
7703 that headline is used to paste the tree
7705 If not, the new level is derived from the *visible* headings
7706 before and after the insertion point, and taken to be the inferior headline
7707 level of the two. So if the previous visible heading is level 3 and the
7708 next is level 4 (or vice versa), level 4 will be used for insertion.
7709 This makes sure that the subtree remains an independent subtree and does
7710 not swallow low level entries.
7712 You can also force a different level, either by using a numeric prefix
7713 argument, or by inserting the heading marker by hand. For example, if the
7714 cursor is after \"*****\", then the tree will be shifted to level 5.
7716 If optional TREE is given, use this text instead of the kill ring.
7718 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7719 move back over whitespace before inserting, and move point to the end of
7720 the inserted text when done."
7721 (interactive "P")
7722 (setq tree (or tree (and kill-ring (current-kill 0))))
7723 (unless (org-kill-is-subtree-p tree)
7724 (error "%s"
7725 (substitute-command-keys
7726 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7727 (org-with-limited-levels
7728 (let* ((visp (not (outline-invisible-p)))
7729 (txt tree)
7730 (^re_ "\\(\\*+\\)[ \t]*")
7731 (old-level (if (string-match org-outline-regexp-bol txt)
7732 (- (match-end 0) (match-beginning 0) 1)
7733 -1))
7734 (force-level (cond (level (prefix-numeric-value level))
7735 ((and (looking-at "[ \t]*$")
7736 (string-match
7737 "^\\*+$" (buffer-substring
7738 (point-at-bol) (point))))
7739 (- (match-end 1) (match-beginning 1)))
7740 ((and (bolp)
7741 (looking-at org-outline-regexp))
7742 (- (match-end 0) (point) 1))))
7743 (previous-level (save-excursion
7744 (condition-case nil
7745 (progn
7746 (outline-previous-visible-heading 1)
7747 (if (looking-at ^re_)
7748 (- (match-end 0) (match-beginning 0) 1)
7750 (error 1))))
7751 (next-level (save-excursion
7752 (condition-case nil
7753 (progn
7754 (or (looking-at org-outline-regexp)
7755 (outline-next-visible-heading 1))
7756 (if (looking-at ^re_)
7757 (- (match-end 0) (match-beginning 0) 1)
7759 (error 1))))
7760 (new-level (or force-level (max previous-level next-level)))
7761 (shift (if (or (= old-level -1)
7762 (= new-level -1)
7763 (= old-level new-level))
7765 (- new-level old-level)))
7766 (delta (if (> shift 0) -1 1))
7767 (func (if (> shift 0) 'org-demote 'org-promote))
7768 (org-odd-levels-only nil)
7769 beg end newend)
7770 ;; Remove the forced level indicator
7771 (if force-level
7772 (delete-region (point-at-bol) (point)))
7773 ;; Paste
7774 (beginning-of-line (if (bolp) 1 2))
7775 (unless for-yank (org-back-over-empty-lines))
7776 (setq beg (point))
7777 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7778 (insert-before-markers txt)
7779 (unless (string-match "\n\\'" txt) (insert "\n"))
7780 (setq newend (point))
7781 (org-reinstall-markers-in-region beg)
7782 (setq end (point))
7783 (goto-char beg)
7784 (skip-chars-forward " \t\n\r")
7785 (setq beg (point))
7786 (if (and (outline-invisible-p) visp)
7787 (save-excursion (outline-show-heading)))
7788 ;; Shift if necessary
7789 (unless (= shift 0)
7790 (save-restriction
7791 (narrow-to-region beg end)
7792 (while (not (= shift 0))
7793 (org-map-region func (point-min) (point-max))
7794 (setq shift (+ delta shift)))
7795 (goto-char (point-min))
7796 (setq newend (point-max))))
7797 (when (or (org-called-interactively-p 'interactive) for-yank)
7798 (message "Clipboard pasted as level %d subtree" new-level))
7799 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7800 kill-ring
7801 (eq org-subtree-clip (current-kill 0))
7802 org-subtree-clip-folded)
7803 ;; The tree was folded before it was killed/copied
7804 (hide-subtree))
7805 (and for-yank (goto-char newend)))))
7807 (defun org-kill-is-subtree-p (&optional txt)
7808 "Check if the current kill is an outline subtree, or a set of trees.
7809 Returns nil if kill does not start with a headline, or if the first
7810 headline level is not the largest headline level in the tree.
7811 So this will actually accept several entries of equal levels as well,
7812 which is OK for `org-paste-subtree'.
7813 If optional TXT is given, check this string instead of the current kill."
7814 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7815 (re (org-get-limited-outline-regexp))
7816 (^re (concat "^" re))
7817 (start-level (and kill
7818 (string-match
7819 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7820 kill)
7821 (- (match-end 2) (match-beginning 2) 1)))
7822 (start (1+ (or (match-beginning 2) -1))))
7823 (if (not start-level)
7824 (progn
7825 nil) ;; does not even start with a heading
7826 (catch 'exit
7827 (while (setq start (string-match ^re kill (1+ start)))
7828 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7829 (throw 'exit nil)))
7830 t))))
7832 (defvar org-markers-to-move nil
7833 "Markers that should be moved with a cut-and-paste operation.
7834 Those markers are stored together with their positions relative to
7835 the start of the region.")
7837 (defun org-save-markers-in-region (beg end)
7838 "Check markers in region.
7839 If these markers are between BEG and END, record their position relative
7840 to BEG, so that after moving the block of text, we can put the markers back
7841 into place.
7842 This function gets called just before an entry or tree gets cut from the
7843 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7844 called immediately, to move the markers with the entries."
7845 (setq org-markers-to-move nil)
7846 (when (featurep 'org-clock)
7847 (org-clock-save-markers-for-cut-and-paste beg end))
7848 (when (featurep 'org-agenda)
7849 (org-agenda-save-markers-for-cut-and-paste beg end)))
7851 (defun org-check-and-save-marker (marker beg end)
7852 "Check if MARKER is between BEG and END.
7853 If yes, remember the marker and the distance to BEG."
7854 (when (and (marker-buffer marker)
7855 (equal (marker-buffer marker) (current-buffer)))
7856 (if (and (>= marker beg) (< marker end))
7857 (push (cons marker (- marker beg)) org-markers-to-move))))
7859 (defun org-reinstall-markers-in-region (beg)
7860 "Move all remembered markers to their position relative to BEG."
7861 (mapc (lambda (x)
7862 (move-marker (car x) (+ beg (cdr x))))
7863 org-markers-to-move)
7864 (setq org-markers-to-move nil))
7866 (defun org-narrow-to-subtree ()
7867 "Narrow buffer to the current subtree."
7868 (interactive)
7869 (save-excursion
7870 (save-match-data
7871 (org-with-limited-levels
7872 (narrow-to-region
7873 (progn (org-back-to-heading t) (point))
7874 (progn (org-end-of-subtree t t)
7875 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7876 (point)))))))
7878 (defun org-narrow-to-block ()
7879 "Narrow buffer to the current block."
7880 (interactive)
7881 (let* ((case-fold-search t)
7882 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7883 "^[ \t]*#\\+end_.*")))
7884 (if blockp
7885 (narrow-to-region (car blockp) (cdr blockp))
7886 (error "Not in a block"))))
7888 (eval-when-compile
7889 (defvar org-property-drawer-re))
7891 (defvar org-property-start-re) ;; defined below
7892 (defun org-clone-subtree-with-time-shift (n &optional shift)
7893 "Clone the task (subtree) at point N times.
7894 The clones will be inserted as siblings.
7896 In interactive use, the user will be prompted for the number of
7897 clones to be produced, and for a time SHIFT, which may be a
7898 repeater as used in time stamps, for example `+3d'.
7900 When a valid repeater is given and the entry contains any time
7901 stamps, the clones will become a sequence in time, with time
7902 stamps in the subtree shifted for each clone produced. If SHIFT
7903 is nil or the empty string, time stamps will be left alone. The
7904 ID property of the original subtree is removed.
7906 If the original subtree did contain time stamps with a repeater,
7907 the following will happen:
7908 - the repeater will be removed in each clone
7909 - an additional clone will be produced, with the current, unshifted
7910 date(s) in the entry.
7911 - the original entry will be placed *after* all the clones, with
7912 repeater intact.
7913 - the start days in the repeater in the original entry will be shifted
7914 to past the last clone.
7915 In this way you can spell out a number of instances of a repeating task,
7916 and still retain the repeater to cover future instances of the task."
7917 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7918 (let (beg end template task idprop
7919 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7920 (drawer-re org-drawer-regexp))
7921 (if (not (and (integerp n) (> n 0)))
7922 (error "Invalid number of replications %s" n))
7923 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7924 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7925 shift)))
7926 (error "Invalid shift specification %s" shift))
7927 (when doshift
7928 (setq shift-n (string-to-number (match-string 1 shift))
7929 shift-what (cdr (assoc (match-string 2 shift)
7930 '(("d" . day) ("w" . week)
7931 ("m" . month) ("y" . year))))))
7932 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7933 (setq nmin 1 nmax n)
7934 (org-back-to-heading t)
7935 (setq beg (point))
7936 (setq idprop (org-entry-get nil "ID"))
7937 (org-end-of-subtree t t)
7938 (or (bolp) (insert "\n"))
7939 (setq end (point))
7940 (setq template (buffer-substring beg end))
7941 (when (and doshift
7942 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7943 (delete-region beg end)
7944 (setq end beg)
7945 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7946 (goto-char end)
7947 (loop for n from nmin to nmax do
7948 ;; prepare clone
7949 (with-temp-buffer
7950 (insert template)
7951 (org-mode)
7952 (goto-char (point-min))
7953 (org-show-subtree)
7954 (and idprop (if org-clone-delete-id
7955 (org-entry-delete nil "ID")
7956 (org-id-get-create t)))
7957 (unless (= n 0)
7958 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7959 (kill-whole-line))
7960 (goto-char (point-min))
7961 (while (re-search-forward drawer-re nil t)
7962 (mapc (lambda (d)
7963 (org-remove-empty-drawer-at d (point))) org-drawers)))
7964 (goto-char (point-min))
7965 (when doshift
7966 (while (re-search-forward org-ts-regexp-both nil t)
7967 (org-timestamp-change (* n shift-n) shift-what))
7968 (unless (= n n-no-remove)
7969 (goto-char (point-min))
7970 (while (re-search-forward org-ts-regexp nil t)
7971 (save-excursion
7972 (goto-char (match-beginning 0))
7973 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7974 (delete-region (match-beginning 1) (match-end 1)))))))
7975 (setq task (buffer-string)))
7976 (insert task))
7977 (goto-char beg)))
7979 ;;; Outline Sorting
7981 (defun org-sort (with-case)
7982 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7983 Optional argument WITH-CASE means sort case-sensitively."
7984 (interactive "P")
7985 (cond
7986 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7987 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7989 (org-call-with-arg 'org-sort-entries with-case))))
7991 (defun org-sort-remove-invisible (s)
7992 (remove-text-properties 0 (length s) org-rm-props s)
7993 (while (string-match org-bracket-link-regexp s)
7994 (setq s (replace-match (if (match-end 2)
7995 (match-string 3 s)
7996 (match-string 1 s)) t t s)))
7999 (defvar org-priority-regexp) ; defined later in the file
8001 (defvar org-after-sorting-entries-or-items-hook nil
8002 "Hook that is run after a bunch of entries or items have been sorted.
8003 When children are sorted, the cursor is in the parent line when this
8004 hook gets called. When a region or a plain list is sorted, the cursor
8005 will be in the first entry of the sorted region/list.")
8007 (defun org-sort-entries
8008 (&optional with-case sorting-type getkey-func compare-func property)
8009 "Sort entries on a certain level of an outline tree.
8010 If there is an active region, the entries in the region are sorted.
8011 Else, if the cursor is before the first entry, sort the top-level items.
8012 Else, the children of the entry at point are sorted.
8014 Sorting can be alphabetically, numerically, by date/time as given by
8015 a time stamp, by a property or by priority.
8017 The command prompts for the sorting type unless it has been given to the
8018 function through the SORTING-TYPE argument, which needs to be a character,
8019 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8020 precise meaning of each character:
8022 n Numerically, by converting the beginning of the entry/item to a number.
8023 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8024 t By date/time, either the first active time stamp in the entry, or, if
8025 none exist, by the first inactive one.
8026 s By the scheduled date/time.
8027 d By deadline date/time.
8028 c By creation time, which is assumed to be the first inactive time stamp
8029 at the beginning of a line.
8030 p By priority according to the cookie.
8031 r By the value of a property.
8033 Capital letters will reverse the sort order.
8035 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8036 called with point at the beginning of the record. It must return either
8037 a string or a number that should serve as the sorting key for that record.
8039 Comparing entries ignores case by default. However, with an optional argument
8040 WITH-CASE, the sorting considers case as well."
8041 (interactive "P")
8042 (let ((case-func (if with-case 'identity 'downcase))
8043 start beg end stars re re2
8044 txt what tmp)
8045 ;; Find beginning and end of region to sort
8046 (cond
8047 ((org-region-active-p)
8048 ;; we will sort the region
8049 (setq end (region-end)
8050 what "region")
8051 (goto-char (region-beginning))
8052 (if (not (org-at-heading-p)) (outline-next-heading))
8053 (setq start (point)))
8054 ((or (org-at-heading-p)
8055 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8056 ;; we will sort the children of the current headline
8057 (org-back-to-heading)
8058 (setq start (point)
8059 end (progn (org-end-of-subtree t t)
8060 (or (bolp) (insert "\n"))
8061 (org-back-over-empty-lines)
8062 (point))
8063 what "children")
8064 (goto-char start)
8065 (show-subtree)
8066 (outline-next-heading))
8068 ;; we will sort the top-level entries in this file
8069 (goto-char (point-min))
8070 (or (org-at-heading-p) (outline-next-heading))
8071 (setq start (point))
8072 (goto-char (point-max))
8073 (beginning-of-line 1)
8074 (when (looking-at ".*?\\S-")
8075 ;; File ends in a non-white line
8076 (end-of-line 1)
8077 (insert "\n"))
8078 (setq end (point-max))
8079 (setq what "top-level")
8080 (goto-char start)
8081 (show-all)))
8083 (setq beg (point))
8084 (if (>= beg end) (error "Nothing to sort"))
8086 (looking-at "\\(\\*+\\)")
8087 (setq stars (match-string 1)
8088 re (concat "^" (regexp-quote stars) " +")
8089 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8090 txt (buffer-substring beg end))
8091 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8092 (if (and (not (equal stars "*")) (string-match re2 txt))
8093 (error "Region to sort contains a level above the first entry"))
8095 (unless sorting-type
8096 (message
8097 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8098 [t]ime [s]cheduled [d]eadline [c]reated
8099 A/N/T/S/D/C/P/O/F means reversed:"
8100 what)
8101 (setq sorting-type (read-char-exclusive))
8103 (and (= (downcase sorting-type) ?f)
8104 (setq getkey-func
8105 (org-icompleting-read "Sort using function: "
8106 obarray 'fboundp t nil nil))
8107 (setq getkey-func (intern getkey-func)))
8109 (and (= (downcase sorting-type) ?r)
8110 (setq property
8111 (org-icompleting-read "Property: "
8112 (mapcar 'list (org-buffer-property-keys t))
8113 nil t))))
8115 (message "Sorting entries...")
8117 (save-restriction
8118 (narrow-to-region start end)
8119 (let ((dcst (downcase sorting-type))
8120 (case-fold-search nil)
8121 (now (current-time)))
8122 (sort-subr
8123 (/= dcst sorting-type)
8124 ;; This function moves to the beginning character of the "record" to
8125 ;; be sorted.
8126 (lambda nil
8127 (if (re-search-forward re nil t)
8128 (goto-char (match-beginning 0))
8129 (goto-char (point-max))))
8130 ;; This function moves to the last character of the "record" being
8131 ;; sorted.
8132 (lambda nil
8133 (save-match-data
8134 (condition-case nil
8135 (outline-forward-same-level 1)
8136 (error
8137 (goto-char (point-max))))))
8138 ;; This function returns the value that gets sorted against.
8139 (lambda nil
8140 (cond
8141 ((= dcst ?n)
8142 (if (looking-at org-complex-heading-regexp)
8143 (string-to-number (match-string 4))
8144 nil))
8145 ((= dcst ?a)
8146 (if (looking-at org-complex-heading-regexp)
8147 (funcall case-func (match-string 4))
8148 nil))
8149 ((= dcst ?t)
8150 (let ((end (save-excursion (outline-next-heading) (point))))
8151 (if (or (re-search-forward org-ts-regexp end t)
8152 (re-search-forward org-ts-regexp-both end t))
8153 (org-time-string-to-seconds (match-string 0))
8154 (org-float-time now))))
8155 ((= dcst ?c)
8156 (let ((end (save-excursion (outline-next-heading) (point))))
8157 (if (re-search-forward
8158 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8159 end t)
8160 (org-time-string-to-seconds (match-string 0))
8161 (org-float-time now))))
8162 ((= dcst ?s)
8163 (let ((end (save-excursion (outline-next-heading) (point))))
8164 (if (re-search-forward org-scheduled-time-regexp end t)
8165 (org-time-string-to-seconds (match-string 1))
8166 (org-float-time now))))
8167 ((= dcst ?d)
8168 (let ((end (save-excursion (outline-next-heading) (point))))
8169 (if (re-search-forward org-deadline-time-regexp end t)
8170 (org-time-string-to-seconds (match-string 1))
8171 (org-float-time now))))
8172 ((= dcst ?p)
8173 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8174 (string-to-char (match-string 2))
8175 org-default-priority))
8176 ((= dcst ?r)
8177 (or (org-entry-get nil property) ""))
8178 ((= dcst ?o)
8179 (if (looking-at org-complex-heading-regexp)
8180 (- 9999 (length (member (match-string 2)
8181 org-todo-keywords-1)))))
8182 ((= dcst ?f)
8183 (if getkey-func
8184 (progn
8185 (setq tmp (funcall getkey-func))
8186 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8187 tmp)
8188 (error "Invalid key function `%s'" getkey-func)))
8189 (t (error "Invalid sorting type `%c'" sorting-type))))
8191 (cond
8192 ((= dcst ?a) 'string<)
8193 ((= dcst ?f) compare-func)
8194 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8195 (run-hooks 'org-after-sorting-entries-or-items-hook)
8196 (message "Sorting entries...done")))
8198 (defun org-do-sort (table what &optional with-case sorting-type)
8199 "Sort TABLE of WHAT according to SORTING-TYPE.
8200 The user will be prompted for the SORTING-TYPE if the call to this
8201 function does not specify it. WHAT is only for the prompt, to indicate
8202 what is being sorted. The sorting key will be extracted from
8203 the car of the elements of the table.
8204 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8205 (unless sorting-type
8206 (message
8207 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8208 what)
8209 (setq sorting-type (read-char-exclusive)))
8210 (let ((dcst (downcase sorting-type))
8211 extractfun comparefun)
8212 ;; Define the appropriate functions
8213 (cond
8214 ((= dcst ?n)
8215 (setq extractfun 'string-to-number
8216 comparefun (if (= dcst sorting-type) '< '>)))
8217 ((= dcst ?a)
8218 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8219 (lambda(x) (downcase (org-sort-remove-invisible x))))
8220 comparefun (if (= dcst sorting-type)
8221 'string<
8222 (lambda (a b) (and (not (string< a b))
8223 (not (string= a b)))))))
8224 ((= dcst ?t)
8225 (setq extractfun
8226 (lambda (x)
8227 (if (or (string-match org-ts-regexp x)
8228 (string-match org-ts-regexp-both x))
8229 (org-float-time
8230 (org-time-string-to-time (match-string 0 x)))
8232 comparefun (if (= dcst sorting-type) '< '>)))
8233 (t (error "Invalid sorting type `%c'" sorting-type)))
8235 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8236 table)
8237 (lambda (a b) (funcall comparefun (car a) (car b))))))
8240 ;;; The orgstruct minor mode
8242 ;; Define a minor mode which can be used in other modes in order to
8243 ;; integrate the org-mode structure editing commands.
8245 ;; This is really a hack, because the org-mode structure commands use
8246 ;; keys which normally belong to the major mode. Here is how it
8247 ;; works: The minor mode defines all the keys necessary to operate the
8248 ;; structure commands, but wraps the commands into a function which
8249 ;; tests if the cursor is currently at a headline or a plain list
8250 ;; item. If that is the case, the structure command is used,
8251 ;; temporarily setting many Org-mode variables like regular
8252 ;; expressions for filling etc. However, when any of those keys is
8253 ;; used at a different location, function uses `key-binding' to look
8254 ;; up if the key has an associated command in another currently active
8255 ;; keymap (minor modes, major mode, global), and executes that
8256 ;; command. There might be problems if any of the keys is otherwise
8257 ;; used as a prefix key.
8259 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8260 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8261 ;; addresses this by checking explicitly for both bindings.
8263 (defvar orgstruct-mode-map (make-sparse-keymap)
8264 "Keymap for the minor `orgstruct-mode'.")
8266 (defvar org-local-vars nil
8267 "List of local variables, for use by `orgstruct-mode'.")
8269 ;;;###autoload
8270 (define-minor-mode orgstruct-mode
8271 "Toggle the minor mode `orgstruct-mode'.
8272 This mode is for using Org-mode structure commands in other
8273 modes. The following keys behave as if Org-mode were active, if
8274 the cursor is on a headline, or on a plain list item (both as
8275 defined by Org-mode).
8277 M-up Move entry/item up
8278 M-down Move entry/item down
8279 M-left Promote
8280 M-right Demote
8281 M-S-up Move entry/item up
8282 M-S-down Move entry/item down
8283 M-S-left Promote subtree
8284 M-S-right Demote subtree
8285 M-q Fill paragraph and items like in Org-mode
8286 C-c ^ Sort entries
8287 C-c - Cycle list bullet
8288 TAB Cycle item visibility
8289 M-RET Insert new heading/item
8290 S-M-RET Insert new TODO heading / Checkbox item
8291 C-c C-c Set tags / toggle checkbox"
8292 nil " OrgStruct" nil
8293 (org-load-modules-maybe)
8294 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8296 ;;;###autoload
8297 (defun turn-on-orgstruct ()
8298 "Unconditionally turn on `orgstruct-mode'."
8299 (orgstruct-mode 1))
8301 (defvar org-fb-vars nil)
8302 (make-variable-buffer-local 'org-fb-vars)
8303 (defun orgstruct++-mode (&optional arg)
8304 "Toggle `orgstruct-mode', the enhanced version of it.
8305 In addition to setting orgstruct-mode, this also exports all
8306 indentation and autofilling variables from org-mode into the
8307 buffer. It will also recognize item context in multiline items."
8308 (interactive "P")
8309 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8310 (if (< arg 1)
8311 (progn (orgstruct-mode -1)
8312 (mapc (lambda(v)
8313 (org-set-local (car v)
8314 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8315 org-fb-vars))
8316 (orgstruct-mode 1)
8317 (setq org-fb-vars nil)
8318 (let (var val)
8319 (mapc
8320 (lambda (x)
8321 (when (string-match
8322 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8323 (symbol-name (car x)))
8324 (setq var (car x) val (nth 1 x))
8325 (push (list var `(quote ,(eval var))) org-fb-vars)
8326 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8327 org-local-vars)
8328 (org-set-local 'orgstruct-is-++ t))))
8330 (defvar orgstruct-is-++ nil
8331 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8332 (make-variable-buffer-local 'orgstruct-is-++)
8334 ;;;###autoload
8335 (defun turn-on-orgstruct++ ()
8336 "Unconditionally turn on `orgstruct++-mode'."
8337 (orgstruct++-mode 1))
8339 (defun orgstruct-error ()
8340 "Error when there is no default binding for a structure key."
8341 (interactive)
8342 (error "This key has no function outside structure elements"))
8344 (defun orgstruct-setup ()
8345 "Setup orgstruct keymaps."
8346 (let ((nfunc 0)
8347 (bindings
8348 (list
8349 '([(meta up)] org-metaup)
8350 '([(meta down)] org-metadown)
8351 '([(meta left)] org-metaleft)
8352 '([(meta right)] org-metaright)
8353 '([(meta shift up)] org-shiftmetaup)
8354 '([(meta shift down)] org-shiftmetadown)
8355 '([(meta shift left)] org-shiftmetaleft)
8356 '([(meta shift right)] org-shiftmetaright)
8357 '([?\e (up)] org-metaup)
8358 '([?\e (down)] org-metadown)
8359 '([?\e (left)] org-metaleft)
8360 '([?\e (right)] org-metaright)
8361 '([?\e (shift up)] org-shiftmetaup)
8362 '([?\e (shift down)] org-shiftmetadown)
8363 '([?\e (shift left)] org-shiftmetaleft)
8364 '([?\e (shift right)] org-shiftmetaright)
8365 '([(shift up)] org-shiftup)
8366 '([(shift down)] org-shiftdown)
8367 '([(shift left)] org-shiftleft)
8368 '([(shift right)] org-shiftright)
8369 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8370 '("\M-q" fill-paragraph)
8371 '("\C-c^" org-sort)
8372 '("\C-c-" org-cycle-list-bullet)))
8373 elt key fun cmd)
8374 (while (setq elt (pop bindings))
8375 (setq nfunc (1+ nfunc))
8376 (setq key (org-key (car elt))
8377 fun (nth 1 elt)
8378 cmd (orgstruct-make-binding fun nfunc key))
8379 (org-defkey orgstruct-mode-map key cmd))
8381 ;; Prevent an error for users who forgot to make autoloads
8382 (require 'org-element)
8384 ;; Special treatment needed for TAB and RET
8385 (org-defkey orgstruct-mode-map [(tab)]
8386 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8387 (org-defkey orgstruct-mode-map "\C-i"
8388 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8390 (org-defkey orgstruct-mode-map "\M-\C-m"
8391 (orgstruct-make-binding 'org-insert-heading 105
8392 "\M-\C-m" [(meta return)]))
8393 (org-defkey orgstruct-mode-map [(meta return)]
8394 (orgstruct-make-binding 'org-insert-heading 106
8395 [(meta return)] "\M-\C-m"))
8397 (org-defkey orgstruct-mode-map [(shift meta return)]
8398 (orgstruct-make-binding 'org-insert-todo-heading 107
8399 [(meta return)] "\M-\C-m"))
8401 (org-defkey orgstruct-mode-map "\e\C-m"
8402 (orgstruct-make-binding 'org-insert-heading 108
8403 "\e\C-m" [?\e (return)]))
8404 (org-defkey orgstruct-mode-map [?\e (return)]
8405 (orgstruct-make-binding 'org-insert-heading 109
8406 [?\e (return)] "\e\C-m"))
8407 (org-defkey orgstruct-mode-map [?\e (shift return)]
8408 (orgstruct-make-binding 'org-insert-todo-heading 110
8409 [?\e (return)] "\e\C-m"))
8411 (unless org-local-vars
8412 (setq org-local-vars (org-get-local-variables)))
8416 (defun orgstruct-make-binding (fun n &rest keys)
8417 "Create a function for binding in the structure minor mode.
8418 FUN is the command to call inside a table. N is used to create a unique
8419 command name. KEYS are keys that should be checked in for a command
8420 to execute outside of tables."
8421 (eval
8422 (list 'defun
8423 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8424 '(arg)
8425 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8426 "Outside of structure, run the binding of `"
8427 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8428 "'.")
8429 '(interactive "p")
8430 (list 'if
8431 `(org-context-p 'headline 'item
8432 (and orgstruct-is-++
8433 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8434 'item-body))
8435 (list 'org-run-like-in-org-mode (list 'quote fun))
8436 (list 'let '(orgstruct-mode)
8437 (list 'call-interactively
8438 (append '(or)
8439 (mapcar (lambda (k)
8440 (list 'key-binding k))
8441 keys)
8442 '('orgstruct-error))))))))
8444 (defun org-contextualize-keys (alist contexts)
8445 "Return valid elements in ALIST depending on CONTEXTS.
8447 `org-agenda-custom-commands' or `org-capture-templates' are the
8448 values used for ALIST, and `org-agenda-custom-commands-contexts'
8449 or `org-capture-templates-contexts' are the associated contexts
8450 definitions."
8451 (let ((contexts
8452 ;; normalize contexts
8453 (mapcar
8454 (lambda(c) (cond ((listp (cadr c))
8455 (list (car c) (car c) (cadr c)))
8456 ((string= "" (cadr c))
8457 (list (car c) (car c) (caddr c)))
8458 (t c))) contexts))
8459 (a alist) c r s)
8460 ;; loop over all commands or templates
8461 (while (setq c (pop a))
8462 (let (vrules repl)
8463 (cond
8464 ((not (assoc (car c) contexts))
8465 (push c r))
8466 ((and (assoc (car c) contexts)
8467 (setq vrules (org-contextualize-validate-key
8468 (car c) contexts)))
8469 (mapc (lambda (vr)
8470 (when (not (equal (car vr) (cadr vr)))
8471 (setq repl vr))) vrules)
8472 (if (not repl) (push c r)
8473 (push (cadr repl) s)
8474 (push
8475 (cons (car c)
8476 (cdr (or (assoc (cadr repl) alist)
8477 (error "Undefined key `%s' as contextual replacement for `%s'"
8478 (cadr repl) (car c)))))
8479 r))))))
8480 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8481 (delq
8483 (delete-dups
8484 (mapcar (lambda (x)
8485 (let ((tpl (car x)))
8486 (when (not (delq
8488 (mapcar (lambda(y)
8489 (equal y tpl)) s))) x)))
8490 (reverse r))))))
8492 (defun org-contextualize-validate-key (key contexts)
8493 "Check CONTEXTS for agenda or capture KEY."
8494 (let (r rr res)
8495 (while (setq r (pop contexts))
8496 (mapc
8497 (lambda (rr)
8498 (when
8499 (and (equal key (car r))
8500 (if (functionp rr) (funcall rr)
8501 (or (and (eq (car rr) 'in-file)
8502 (buffer-file-name)
8503 (string-match (cdr rr) (buffer-file-name)))
8504 (and (eq (car rr) 'in-mode)
8505 (string-match (cdr rr) (symbol-name major-mode)))
8506 (when (and (eq (car rr) 'not-in-file)
8507 (buffer-file-name))
8508 (not (string-match (cdr rr) (buffer-file-name))))
8509 (when (eq (car rr) 'not-in-mode)
8510 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8511 (push r res)))
8512 (car (last r))))
8513 (delete-dups (delq nil res))))
8515 (defun org-context-p (&rest contexts)
8516 "Check if local context is any of CONTEXTS.
8517 Possible values in the list of contexts are `table', `headline', and `item'."
8518 (let ((pos (point)))
8519 (goto-char (point-at-bol))
8520 (prog1 (or (and (memq 'table contexts)
8521 (looking-at "[ \t]*|"))
8522 (and (memq 'headline contexts)
8523 (looking-at org-outline-regexp))
8524 (and (memq 'item contexts)
8525 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8526 (and (memq 'item-body contexts)
8527 (org-in-item-p)))
8528 (goto-char pos))))
8530 (defun org-get-local-variables ()
8531 "Return a list of all local variables in an Org mode buffer."
8532 (let (varlist)
8533 (with-current-buffer (get-buffer-create "*Org tmp*")
8534 (erase-buffer)
8535 (org-mode)
8536 (setq varlist (buffer-local-variables)))
8537 (kill-buffer "*Org tmp*")
8538 (delq nil
8539 (mapcar
8540 (lambda (x)
8541 (setq x
8542 (if (symbolp x)
8543 (list x)
8544 (list (car x) (list 'quote (cdr x)))))
8545 (if (string-match
8546 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8547 (symbol-name (car x)))
8548 x nil))
8549 varlist))))
8551 (defun org-clone-local-variables (from-buffer &optional regexp)
8552 "Clone local variables from FROM-BUFFER.
8553 Optional argument REGEXP selects variables to clone."
8554 (mapc
8555 (lambda (pair)
8556 (and (symbolp (car pair))
8557 (or (null regexp)
8558 (string-match regexp (symbol-name (car pair))))
8559 (set (make-local-variable (car pair))
8560 (cdr pair))))
8561 (buffer-local-variables from-buffer)))
8563 ;;;###autoload
8564 (defun org-run-like-in-org-mode (cmd)
8565 "Run a command, pretending that the current buffer is in Org-mode.
8566 This will temporarily bind local variables that are typically bound in
8567 Org-mode to the values they have in Org-mode, and then interactively
8568 call CMD."
8569 (org-load-modules-maybe)
8570 (unless org-local-vars
8571 (setq org-local-vars (org-get-local-variables)))
8572 (eval (list 'let org-local-vars
8573 (list 'call-interactively (list 'quote cmd)))))
8575 ;;;; Archiving
8577 (defun org-get-category (&optional pos force-refresh)
8578 "Get the category applying to position POS."
8579 (save-match-data
8580 (if force-refresh (org-refresh-category-properties))
8581 (let ((pos (or pos (point))))
8582 (or (get-text-property pos 'org-category)
8583 (progn (org-refresh-category-properties)
8584 (get-text-property pos 'org-category))))))
8586 (defun org-refresh-category-properties ()
8587 "Refresh category text properties in the buffer."
8588 (let ((case-fold-search t)
8589 (inhibit-read-only t)
8590 (def-cat (cond
8591 ((null org-category)
8592 (if buffer-file-name
8593 (file-name-sans-extension
8594 (file-name-nondirectory buffer-file-name))
8595 "???"))
8596 ((symbolp org-category) (symbol-name org-category))
8597 (t org-category)))
8598 beg end cat pos optionp)
8599 (org-unmodified
8600 (save-excursion
8601 (save-restriction
8602 (widen)
8603 (goto-char (point-min))
8604 (put-text-property (point) (point-max) 'org-category def-cat)
8605 (while (re-search-forward
8606 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8607 (setq pos (match-end 0)
8608 optionp (equal (char-after (match-beginning 0)) ?#)
8609 cat (org-trim (match-string 2)))
8610 (if optionp
8611 (setq beg (point-at-bol) end (point-max))
8612 (org-back-to-heading t)
8613 (setq beg (point) end (org-end-of-subtree t t)))
8614 (put-text-property beg end 'org-category cat)
8615 (put-text-property beg end 'org-category-position beg)
8616 (goto-char pos)))))))
8619 ;;;; Link Stuff
8621 ;;; Link abbreviations
8623 (defun org-link-expand-abbrev (link)
8624 "Apply replacements as defined in `org-link-abbrev-alist'."
8625 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8626 (let* ((key (match-string 1 link))
8627 (as (or (assoc key org-link-abbrev-alist-local)
8628 (assoc key org-link-abbrev-alist)))
8629 (tag (and (match-end 2) (match-string 3 link)))
8630 rpl)
8631 (if (not as)
8632 link
8633 (setq rpl (cdr as))
8634 (cond
8635 ((symbolp rpl) (funcall rpl tag))
8636 ((string-match "%(\\([^)]+\\))" rpl)
8637 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8638 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8639 ((string-match "%h" rpl)
8640 (replace-match (url-hexify-string (or tag "")) t t rpl))
8641 (t (concat rpl tag)))))
8642 link))
8644 ;;; Storing and inserting links
8646 (defvar org-insert-link-history nil
8647 "Minibuffer history for links inserted with `org-insert-link'.")
8649 (defvar org-stored-links nil
8650 "Contains the links stored with `org-store-link'.")
8652 (defvar org-store-link-plist nil
8653 "Plist with info about the most recently link created with `org-store-link'.")
8655 (defvar org-link-protocols nil
8656 "Link protocols added to Org-mode using `org-add-link-type'.")
8658 (defvar org-store-link-functions nil
8659 "List of functions that are called to create and store a link.
8660 Each function will be called in turn until one returns a non-nil
8661 value. Each function should check if it is responsible for creating
8662 this link (for example by looking at the major mode).
8663 If not, it must exit and return nil.
8664 If yes, it should return a non-nil value after a calling
8665 `org-store-link-props' with a list of properties and values.
8666 Special properties are:
8668 :type The link prefix, like \"http\". This must be given.
8669 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8670 This is obligatory as well.
8671 :description Optional default description for the second pair
8672 of brackets in an Org-mode link. The user can still change
8673 this when inserting this link into an Org-mode buffer.
8675 In addition to these, any additional properties can be specified
8676 and then used in capture templates.")
8678 (defun org-add-link-type (type &optional follow export)
8679 "Add TYPE to the list of `org-link-types'.
8680 Re-compute all regular expressions depending on `org-link-types'
8682 FOLLOW and EXPORT are two functions.
8684 FOLLOW should take the link path as the single argument and do whatever
8685 is necessary to follow the link, for example find a file or display
8686 a mail message.
8688 EXPORT should format the link path for export to one of the export formats.
8689 It should be a function accepting three arguments:
8691 path the path of the link, the text after the prefix (like \"http:\")
8692 desc the description of the link, if any, or a description added by
8693 org-export-normalize-links if there is none
8694 format the export format, a symbol like `html' or `latex' or `ascii'..
8696 The function may use the FORMAT information to return different values
8697 depending on the format. The return value will be put literally into
8698 the exported file. If the return value is nil, this means Org should
8699 do what it normally does with links which do not have EXPORT defined.
8701 Org-mode has a built-in default for exporting links. If you are happy with
8702 this default, there is no need to define an export function for the link
8703 type. For a simple example of an export function, see `org-bbdb.el'."
8704 (add-to-list 'org-link-types type t)
8705 (org-make-link-regexps)
8706 (if (assoc type org-link-protocols)
8707 (setcdr (assoc type org-link-protocols) (list follow export))
8708 (push (list type follow export) org-link-protocols)))
8710 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8711 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8713 ;;;###autoload
8714 (defun org-store-link (arg)
8715 "\\<org-mode-map>Store an org-link to the current location.
8716 This link is added to `org-stored-links' and can later be inserted
8717 into an org-buffer with \\[org-insert-link].
8719 For some link types, a prefix arg is interpreted:
8720 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8721 For file links, arg negates `org-context-in-file-links'."
8722 (interactive "P")
8723 (org-load-modules-maybe)
8724 (setq org-store-link-plist nil) ; reset
8725 (org-with-limited-levels
8726 (let (link cpltxt desc description search txt custom-id agenda-link)
8727 (cond
8729 ((run-hook-with-args-until-success 'org-store-link-functions)
8730 (setq link (plist-get org-store-link-plist :link)
8731 desc (or (plist-get org-store-link-plist :description) link)))
8733 ((org-src-edit-buffer-p)
8734 (let (label gc)
8735 (while (or (not label)
8736 (save-excursion
8737 (save-restriction
8738 (widen)
8739 (goto-char (point-min))
8740 (re-search-forward
8741 (regexp-quote (format org-coderef-label-format label))
8742 nil t))))
8743 (when label (message "Label exists already") (sit-for 2))
8744 (setq label (read-string "Code line label: " label)))
8745 (end-of-line 1)
8746 (setq link (format org-coderef-label-format label))
8747 (setq gc (- 79 (length link)))
8748 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8749 (insert link)
8750 (setq link (concat "(" label ")") desc nil)))
8752 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8753 ;; We are in the agenda, link to referenced location
8754 (let ((m (or (get-text-property (point) 'org-hd-marker)
8755 (get-text-property (point) 'org-marker))))
8756 (when m
8757 (org-with-point-at m
8758 (setq agenda-link
8759 (if (org-called-interactively-p 'any)
8760 (call-interactively 'org-store-link)
8761 (org-store-link nil)))))))
8763 ((eq major-mode 'calendar-mode)
8764 (let ((cd (calendar-cursor-to-date)))
8765 (setq link
8766 (format-time-string
8767 (car org-time-stamp-formats)
8768 (apply 'encode-time
8769 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8770 nil nil nil))))
8771 (org-store-link-props :type "calendar" :date cd)))
8773 ((eq major-mode 'help-mode)
8774 (setq link (concat "help:" (save-excursion
8775 (goto-char (point-min))
8776 (looking-at "^[^ ]+")
8777 (match-string 0))))
8778 (org-store-link-props :type "help"))
8780 ((eq major-mode 'w3-mode)
8781 (setq cpltxt (if (and (buffer-name)
8782 (not (string-match "Untitled" (buffer-name))))
8783 (buffer-name)
8784 (url-view-url t))
8785 link (url-view-url t))
8786 (org-store-link-props :type "w3" :url (url-view-url t)))
8788 ((eq major-mode 'w3m-mode)
8789 (setq cpltxt (or w3m-current-title w3m-current-url)
8790 link w3m-current-url)
8791 (org-store-link-props :type "w3m" :url (url-view-url t)))
8793 ((setq search (run-hook-with-args-until-success
8794 'org-create-file-search-functions))
8795 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8796 "::" search))
8797 (setq cpltxt (or description link)))
8799 ((eq major-mode 'image-mode)
8800 (setq cpltxt (concat "file:"
8801 (abbreviate-file-name buffer-file-name))
8802 link cpltxt)
8803 (org-store-link-props :type "image" :file buffer-file-name))
8805 ((eq major-mode 'dired-mode)
8806 ;; link to the file in the current line
8807 (let ((file (dired-get-filename nil t)))
8808 (setq file (if file
8809 (abbreviate-file-name
8810 (expand-file-name (dired-get-filename nil t)))
8811 ;; otherwise, no file so use current directory.
8812 default-directory))
8813 (setq cpltxt (concat "file:" file)
8814 link cpltxt)))
8816 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8817 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8818 (cond
8819 ((org-in-regexp "<<\\(.*?\\)>>")
8820 (setq cpltxt
8821 (concat "file:"
8822 (abbreviate-file-name
8823 (buffer-file-name (buffer-base-buffer)))
8824 "::" (match-string 1))
8825 link cpltxt))
8826 ((and (featurep 'org-id)
8827 (or (eq org-link-to-org-use-id t)
8828 (and (org-called-interactively-p 'any)
8829 (or (eq org-link-to-org-use-id 'create-if-interactive)
8830 (and (eq org-link-to-org-use-id
8831 'create-if-interactive-and-no-custom-id)
8832 (not custom-id))))
8833 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8834 ;; We can make a link using the ID.
8835 (setq link (condition-case nil
8836 (prog1 (org-id-store-link)
8837 (setq desc (plist-get org-store-link-plist :description)))
8838 (error
8839 ;; probably before first headline, link to file only
8840 (concat "file:"
8841 (abbreviate-file-name
8842 (buffer-file-name (buffer-base-buffer))))))))
8844 ;; Just link to current headline
8845 (setq cpltxt (concat "file:"
8846 (abbreviate-file-name
8847 (buffer-file-name (buffer-base-buffer)))))
8848 ;; Add a context search string
8849 (when (org-xor org-context-in-file-links arg)
8850 (setq txt (cond
8851 ((org-at-heading-p) nil)
8852 ((org-region-active-p)
8853 (buffer-substring (region-beginning) (region-end)))))
8854 (when (or (null txt) (string-match "\\S-" txt))
8855 (setq cpltxt
8856 (concat cpltxt "::"
8857 (condition-case nil
8858 (org-make-org-heading-search-string txt)
8859 (error "")))
8860 desc (or (nth 4 (ignore-errors
8861 (org-heading-components))) "NONE"))))
8862 (if (string-match "::\\'" cpltxt)
8863 (setq cpltxt (substring cpltxt 0 -2)))
8864 (setq link cpltxt))))
8866 ((buffer-file-name (buffer-base-buffer))
8867 ;; Just link to this file here.
8868 (setq cpltxt (concat "file:"
8869 (abbreviate-file-name
8870 (buffer-file-name (buffer-base-buffer)))))
8871 ;; Add a context string
8872 (when (org-xor org-context-in-file-links arg)
8873 (setq txt (if (org-region-active-p)
8874 (buffer-substring (region-beginning) (region-end))
8875 (buffer-substring (point-at-bol) (point-at-eol))))
8876 ;; Only use search option if there is some text.
8877 (when (string-match "\\S-" txt)
8878 (setq cpltxt
8879 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8880 desc "NONE")))
8881 (setq link cpltxt))
8883 ((org-called-interactively-p 'interactive)
8884 (error "Cannot link to a buffer which is not visiting a file"))
8886 (t (setq link nil)))
8888 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8889 (setq link (or link cpltxt)
8890 desc (or desc cpltxt))
8891 (if (equal desc "NONE") (setq desc nil))
8893 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8894 (progn
8895 (setq org-stored-links
8896 (cons (list link desc) org-stored-links))
8897 (message "Stored: %s" (or desc link))
8898 (when custom-id
8899 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8900 "::#" custom-id))
8901 (setq org-stored-links
8902 (cons (list link desc) org-stored-links))))
8903 (or agenda-link (and link (org-make-link-string link desc)))))))
8905 (defun org-store-link-props (&rest plist)
8906 "Store link properties, extract names and addresses."
8907 (let (x adr)
8908 (when (setq x (plist-get plist :from))
8909 (setq adr (mail-extract-address-components x))
8910 (setq plist (plist-put plist :fromname (car adr)))
8911 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8912 (when (setq x (plist-get plist :to))
8913 (setq adr (mail-extract-address-components x))
8914 (setq plist (plist-put plist :toname (car adr)))
8915 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8916 (let ((from (plist-get plist :from))
8917 (to (plist-get plist :to)))
8918 (when (and from to org-from-is-user-regexp)
8919 (setq plist
8920 (plist-put plist :fromto
8921 (if (string-match org-from-is-user-regexp from)
8922 (concat "to %t")
8923 (concat "from %f"))))))
8924 (setq org-store-link-plist plist))
8926 (defun org-add-link-props (&rest plist)
8927 "Add these properties to the link property list."
8928 (let (key value)
8929 (while plist
8930 (setq key (pop plist) value (pop plist))
8931 (setq org-store-link-plist
8932 (plist-put org-store-link-plist key value)))))
8934 (defun org-email-link-description (&optional fmt)
8935 "Return the description part of an email link.
8936 This takes information from `org-store-link-plist' and formats it
8937 according to FMT (default from `org-email-link-description-format')."
8938 (setq fmt (or fmt org-email-link-description-format))
8939 (let* ((p org-store-link-plist)
8940 (to (plist-get p :toaddress))
8941 (from (plist-get p :fromaddress))
8942 (table
8943 (list
8944 (cons "%c" (plist-get p :fromto))
8945 (cons "%F" (plist-get p :from))
8946 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8947 (cons "%T" (plist-get p :to))
8948 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8949 (cons "%s" (plist-get p :subject))
8950 (cons "%d" (plist-get p :date))
8951 (cons "%m" (plist-get p :message-id)))))
8952 (when (string-match "%c" fmt)
8953 ;; Check if the user wrote this message
8954 (if (and org-from-is-user-regexp from to
8955 (save-match-data (string-match org-from-is-user-regexp from)))
8956 (setq fmt (replace-match "to %t" t t fmt))
8957 (setq fmt (replace-match "from %f" t t fmt))))
8958 (org-replace-escapes fmt table)))
8960 (defun org-make-org-heading-search-string (&optional string heading)
8961 "Make search string for STRING or current headline."
8962 (interactive)
8963 (let ((s (or string (org-get-heading)))
8964 (lines org-context-in-file-links))
8965 (unless (and string (not heading))
8966 ;; We are using a headline, clean up garbage in there.
8967 (if (string-match org-todo-regexp s)
8968 (setq s (replace-match "" t t s)))
8969 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8970 (setq s (replace-match "" t t s)))
8971 (setq s (org-trim s))
8972 (if (string-match (concat "^\\(" org-quote-string "\\|"
8973 org-comment-string "\\)") s)
8974 (setq s (replace-match "" t t s)))
8975 (while (string-match org-ts-regexp s)
8976 (setq s (replace-match "" t t s))))
8977 (or string (setq s (concat "*" s))) ; Add * for headlines
8978 (when (and string (integerp lines) (> lines 0))
8979 (let ((slines (org-split-string s "\n")))
8980 (when (< lines (length slines))
8981 (setq s (mapconcat
8982 'identity
8983 (reverse (nthcdr (- (length slines) lines)
8984 (reverse slines))) "\n")))))
8985 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8987 (defun org-make-link-string (link &optional description)
8988 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8989 (unless (string-match "\\S-" link)
8990 (error "Empty link"))
8991 (when (and description
8992 (stringp description)
8993 (not (string-match "\\S-" description)))
8994 (setq description nil))
8995 (when (stringp description)
8996 ;; Remove brackets from the description, they are fatal.
8997 (while (string-match "\\[" description)
8998 (setq description (replace-match "{" t t description)))
8999 (while (string-match "\\]" description)
9000 (setq description (replace-match "}" t t description))))
9001 (when (equal link description)
9002 ;; No description needed, it is identical
9003 (setq description nil))
9004 (when (and (not description)
9005 (not (string-match (org-image-file-name-regexp) link))
9006 (not (equal link (org-link-escape link))))
9007 (setq description (org-extract-attributes link)))
9008 (setq link
9009 (cond ((string-match (org-image-file-name-regexp) link) link)
9010 ((string-match org-link-types-re link)
9011 (concat (match-string 1 link)
9012 (org-link-escape (substring link (match-end 1)))))
9013 (t (org-link-escape link))))
9014 (concat "[[" link "]"
9015 (if description (concat "[" description "]") "")
9016 "]"))
9018 (defconst org-link-escape-chars
9019 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9020 "List of characters that should be escaped in link.
9021 This is the list that is used for internal purposes.")
9023 (defconst org-link-escape-chars-browser
9024 '(?\ )
9025 "List of escapes for characters that are problematic in links.
9026 This is the list that is used before handing over to the browser.")
9028 (defun org-link-escape (text &optional table merge)
9029 "Return percent escaped representation of TEXT.
9030 TEXT is a string with the text to escape.
9031 Optional argument TABLE is a list with characters that should be
9032 escaped. When nil, `org-link-escape-chars' is used.
9033 If optional argument MERGE is set, merge TABLE into
9034 `org-link-escape-chars'."
9035 (cond
9036 ((and table merge)
9037 (mapc (lambda (defchr)
9038 (unless (member defchr table)
9039 (setq table (cons defchr table)))) org-link-escape-chars))
9040 ((null table)
9041 (setq table org-link-escape-chars)))
9042 (mapconcat
9043 (lambda (char)
9044 (if (or (member char table)
9045 (and (or (< char 32) (= char 37) (> char 126))
9046 org-url-hexify-p))
9047 (mapconcat (lambda (sequence-element)
9048 (format "%%%.2X" sequence-element))
9049 (or (encode-coding-char char 'utf-8)
9050 (error "Unable to percent escape character: %s"
9051 (char-to-string char))) "")
9052 (char-to-string char))) text ""))
9054 (defun org-link-unescape (str)
9055 "Unhex hexified Unicode strings as returned from the JavaScript function
9056 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9057 (unless (and (null str) (string= "" str))
9058 (let ((pos 0) (case-fold-search t) unhexed)
9059 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9060 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9061 (setq str (replace-match unhexed t t str))
9062 (setq pos (+ pos (length unhexed))))))
9063 str)
9065 (defun org-link-unescape-compound (hex)
9066 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9067 Note: this function also decodes single byte encodings like
9068 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9069 (save-match-data
9070 (let* ((bytes (cdr (split-string hex "%")))
9071 (ret "")
9072 (eat 0)
9073 (sum 0))
9074 (while bytes
9075 (let* ((val (string-to-number (pop bytes) 16))
9076 (shift-xor
9077 (if (= 0 eat)
9078 (cond
9079 ((>= val 252) (cons 6 252))
9080 ((>= val 248) (cons 5 248))
9081 ((>= val 240) (cons 4 240))
9082 ((>= val 224) (cons 3 224))
9083 ((>= val 192) (cons 2 192))
9084 (t (cons 0 0)))
9085 (cons 6 128))))
9086 (if (>= val 192) (setq eat (car shift-xor)))
9087 (setq val (logxor val (cdr shift-xor)))
9088 (setq sum (+ (lsh sum (car shift-xor)) val))
9089 (if (> eat 0) (setq eat (- eat 1)))
9090 (cond
9091 ((= 0 eat) ;multi byte
9092 (setq ret (concat ret (org-char-to-string sum)))
9093 (setq sum 0))
9094 ((not bytes) ; single byte(s)
9095 (setq ret (org-link-unescape-single-byte-sequence hex))))
9096 )) ;; end (while bytes
9097 ret )))
9099 (defun org-link-unescape-single-byte-sequence (hex)
9100 "Unhexify hex-encoded single byte character sequences."
9101 (mapconcat (lambda (byte)
9102 (char-to-string (string-to-number byte 16)))
9103 (cdr (split-string hex "%")) ""))
9105 (defun org-xor (a b)
9106 "Exclusive or."
9107 (if a (not b) b))
9109 (defun org-fixup-message-id-for-http (s)
9110 "Replace special characters in a message id, so it can be used in an http query."
9111 (when (string-match "%" s)
9112 (setq s (mapconcat (lambda (c)
9113 (if (eq c ?%)
9114 "%25"
9115 (char-to-string c)))
9116 s "")))
9117 (while (string-match "<" s)
9118 (setq s (replace-match "%3C" t t s)))
9119 (while (string-match ">" s)
9120 (setq s (replace-match "%3E" t t s)))
9121 (while (string-match "@" s)
9122 (setq s (replace-match "%40" t t s)))
9125 (defun org-link-prettify (link)
9126 "Return a human-readable representation of LINK.
9127 The car of LINK must be a raw link the cdr of LINK must be either
9128 a link description or nil."
9129 (let ((desc (or (cadr link) "<no description>")))
9130 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9131 "<" (car link) ">")))
9133 ;;;###autoload
9134 (defun org-insert-link-global ()
9135 "Insert a link like Org-mode does.
9136 This command can be called in any mode to insert a link in Org-mode syntax."
9137 (interactive)
9138 (org-load-modules-maybe)
9139 (org-run-like-in-org-mode 'org-insert-link))
9141 (defun org-insert-all-links (&optional keep)
9142 "Insert all links in `org-stored-links'."
9143 (interactive "P")
9144 (let ((links (copy-sequence org-stored-links)) l)
9145 (while (setq l (if keep (pop links) (pop org-stored-links)))
9146 (insert "- ")
9147 (org-insert-link nil (car l) (cadr l))
9148 (insert "\n"))))
9150 (defun org-link-fontify-links-to-this-file ()
9151 "Fontify links to the current file in `org-stored-links'."
9152 (let ((f (buffer-file-name)) a b)
9153 (setq a (mapcar (lambda(l)
9154 (let ((ll (car l)))
9155 (when (and (string-match "^file:\\(.+\\)::" ll)
9156 (equal f (expand-file-name (match-string 1 ll))))
9157 ll)))
9158 org-stored-links))
9159 (when (featurep 'org-id)
9160 (setq b (mapcar (lambda(l)
9161 (let ((ll (car l)))
9162 (when (and (string-match "^id:\\(.+\\)$" ll)
9163 (equal f (expand-file-name
9164 (or (org-id-find-id-file
9165 (match-string 1 ll)) ""))))
9166 ll)))
9167 org-stored-links)))
9168 (mapcar (lambda(l)
9169 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9170 (delq nil (append a b)))))
9172 (defvar org-link-links-in-this-file nil)
9173 (defun org-insert-link (&optional complete-file link-location default-description)
9174 "Insert a link. At the prompt, enter the link.
9176 Completion can be used to insert any of the link protocol prefixes like
9177 http or ftp in use.
9179 The history can be used to select a link previously stored with
9180 `org-store-link'. When the empty string is entered (i.e. if you just
9181 press RET at the prompt), the link defaults to the most recently
9182 stored link. As SPC triggers completion in the minibuffer, you need to
9183 use M-SPC or C-q SPC to force the insertion of a space character.
9185 You will also be prompted for a description, and if one is given, it will
9186 be displayed in the buffer instead of the link.
9188 If there is already a link at point, this command will allow you to edit link
9189 and description parts.
9191 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9192 be selected using completion. The path to the file will be relative to the
9193 current directory if the file is in the current directory or a subdirectory.
9194 Otherwise, the link will be the absolute path as completed in the minibuffer
9195 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9196 option `org-link-file-path-type'.
9198 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9199 the current directory or below.
9201 With three \\[universal-argument] prefixes, negate the meaning of
9202 `org-keep-stored-link-after-insertion'.
9204 If `org-make-link-description-function' is non-nil, this function will be
9205 called with the link target, and the result will be the default
9206 link description.
9208 If the LINK-LOCATION parameter is non-nil, this value will be
9209 used as the link location instead of reading one interactively.
9211 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9212 be used as the default description."
9213 (interactive "P")
9214 (let* ((wcf (current-window-configuration))
9215 (region (if (org-region-active-p)
9216 (buffer-substring (region-beginning) (region-end))))
9217 (remove (and region (list (region-beginning) (region-end))))
9218 (desc region)
9219 tmphist ; byte-compile incorrectly complains about this
9220 (link link-location)
9221 (abbrevs org-link-abbrev-alist-local)
9222 entry file all-prefixes auto-desc)
9223 (cond
9224 (link-location) ; specified by arg, just use it.
9225 ((org-in-regexp org-bracket-link-regexp 1)
9226 ;; We do have a link at point, and we are going to edit it.
9227 (setq remove (list (match-beginning 0) (match-end 0)))
9228 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9229 (setq link (read-string "Link: "
9230 (org-link-unescape
9231 (org-match-string-no-properties 1)))))
9232 ((or (org-in-regexp org-angle-link-re)
9233 (org-in-regexp org-plain-link-re))
9234 ;; Convert to bracket link
9235 (setq remove (list (match-beginning 0) (match-end 0))
9236 link (read-string "Link: "
9237 (org-remove-angle-brackets (match-string 0)))))
9238 ((member complete-file '((4) (16)))
9239 ;; Completing read for file names.
9240 (setq link (org-file-complete-link complete-file)))
9242 ;; Read link, with completion for stored links.
9243 (org-link-fontify-links-to-this-file)
9244 (org-switch-to-buffer-other-window "*Org Links*")
9245 (with-current-buffer "*Org Links*"
9246 (erase-buffer)
9247 (insert "Insert a link.
9248 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9249 (when org-stored-links
9250 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9251 (insert (mapconcat 'org-link-prettify
9252 (reverse org-stored-links) "\n")))
9253 (goto-char (point-min)))
9254 (let ((cw (selected-window)))
9255 (select-window (get-buffer-window "*Org Links*" 'visible))
9256 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9257 (unless (pos-visible-in-window-p (point-max))
9258 (org-fit-window-to-buffer))
9259 (and (window-live-p cw) (select-window cw)))
9260 ;; Fake a link history, containing the stored links.
9261 (setq tmphist (append (mapcar 'car org-stored-links)
9262 org-insert-link-history))
9263 (setq all-prefixes (append (mapcar 'car abbrevs)
9264 (mapcar 'car org-link-abbrev-alist)
9265 org-link-types))
9266 (unwind-protect
9267 (progn
9268 (setq link
9269 (let ((org-completion-use-ido nil)
9270 (org-completion-use-iswitchb nil))
9271 (org-completing-read
9272 "Link: "
9273 (append
9274 (mapcar (lambda (x) (list (concat x ":")))
9275 all-prefixes)
9276 (mapcar 'car org-stored-links)
9277 (mapcar 'cadr org-stored-links))
9278 nil nil nil
9279 'tmphist
9280 (caar org-stored-links))))
9281 (if (not (string-match "\\S-" link))
9282 (error "No link selected"))
9283 (mapc (lambda(l)
9284 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9285 org-stored-links)
9286 (if (or (member link all-prefixes)
9287 (and (equal ":" (substring link -1))
9288 (member (substring link 0 -1) all-prefixes)
9289 (setq link (substring link 0 -1))))
9290 (setq link (org-link-try-special-completion link))))
9291 (set-window-configuration wcf)
9292 (kill-buffer "*Org Links*"))
9293 (setq entry (assoc link org-stored-links))
9294 (or entry (push link org-insert-link-history))
9295 (setq desc (or desc (nth 1 entry)))))
9297 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9298 (not org-keep-stored-link-after-insertion))
9299 (setq org-stored-links (delq (assoc link org-stored-links)
9300 org-stored-links)))
9302 (if (string-match org-plain-link-re link)
9303 ;; URL-like link, normalize the use of angular brackets.
9304 (setq link (org-remove-angle-brackets link)))
9306 ;; Check if we are linking to the current file with a search option
9307 ;; If yes, simplify the link by using only the search option.
9308 (when (and buffer-file-name
9309 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9310 (let* ((path (match-string 1 link))
9311 (case-fold-search nil)
9312 (search (match-string 2 link)))
9313 (save-match-data
9314 (if (equal (file-truename buffer-file-name) (file-truename path))
9315 ;; We are linking to this same file, with a search option
9316 (setq link search)))))
9318 ;; Check if we can/should use a relative path. If yes, simplify the link
9319 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9320 (let* ((type (match-string 1 link))
9321 (path (match-string 2 link))
9322 (origpath path)
9323 (case-fold-search nil))
9324 (cond
9325 ((or (eq org-link-file-path-type 'absolute)
9326 (equal complete-file '(16)))
9327 (setq path (abbreviate-file-name (expand-file-name path))))
9328 ((eq org-link-file-path-type 'noabbrev)
9329 (setq path (expand-file-name path)))
9330 ((eq org-link-file-path-type 'relative)
9331 (setq path (file-relative-name path)))
9333 (save-match-data
9334 (if (string-match (concat "^" (regexp-quote
9335 (expand-file-name
9336 (file-name-as-directory
9337 default-directory))))
9338 (expand-file-name path))
9339 ;; We are linking a file with relative path name.
9340 (setq path (substring (expand-file-name path)
9341 (match-end 0)))
9342 (setq path (abbreviate-file-name (expand-file-name path)))))))
9343 (setq link (concat type path))
9344 (if (equal desc origpath)
9345 (setq desc path))))
9347 (if org-make-link-description-function
9348 (setq desc
9349 (or (condition-case nil
9350 (funcall org-make-link-description-function link desc)
9351 (error (progn (message "Can't get link description from `%s'"
9352 (symbol-name org-make-link-description-function))
9353 (sit-for 2) nil)))
9354 (read-string "Description: " default-description)))
9355 (if default-description (setq desc default-description)
9356 (setq desc (or (and auto-desc desc)
9357 (read-string "Description: " desc)))))
9359 (unless (string-match "\\S-" desc) (setq desc nil))
9360 (if remove (apply 'delete-region remove))
9361 (insert (org-make-link-string link desc))))
9363 (defun org-link-try-special-completion (type)
9364 "If there is completion support for link type TYPE, offer it."
9365 (let ((fun (intern (concat "org-" type "-complete-link"))))
9366 (if (functionp fun)
9367 (funcall fun)
9368 (read-string "Link (no completion support): " (concat type ":")))))
9370 (defun org-file-complete-link (&optional arg)
9371 "Create a file link using completion."
9372 (let (file link)
9373 (setq file (read-file-name "File: "))
9374 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9375 (pwd1 (file-name-as-directory (abbreviate-file-name
9376 (expand-file-name ".")))))
9377 (cond
9378 ((equal arg '(16))
9379 (setq link (concat
9380 "file:"
9381 (abbreviate-file-name (expand-file-name file)))))
9382 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9383 (setq link (concat "file:" (match-string 1 file))))
9384 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9385 (expand-file-name file))
9386 (setq link (concat
9387 "file:" (match-string 1 (expand-file-name file)))))
9388 (t (setq link (concat "file:" file)))))
9389 link))
9391 (defun org-completing-read (&rest args)
9392 "Completing-read with SPACE being a normal character."
9393 (let ((enable-recursive-minibuffers t)
9394 (minibuffer-local-completion-map
9395 (copy-keymap minibuffer-local-completion-map)))
9396 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9397 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9398 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9399 (apply 'org-icompleting-read args)))
9401 (defun org-completing-read-no-i (&rest args)
9402 (let (org-completion-use-ido org-completion-use-iswitchb)
9403 (apply 'org-completing-read args)))
9405 (defun org-iswitchb-completing-read (prompt choices &rest args)
9406 "Use iswitch as a completing-read replacement to choose from choices.
9407 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9408 from."
9409 (let* ((iswitchb-use-virtual-buffers nil)
9410 (iswitchb-make-buflist-hook
9411 (lambda ()
9412 (setq iswitchb-temp-buflist choices))))
9413 (iswitchb-read-buffer prompt)))
9415 (defun org-icompleting-read (&rest args)
9416 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9417 (org-without-partial-completion
9418 (if (and org-completion-use-ido
9419 (fboundp 'ido-completing-read)
9420 (boundp 'ido-mode) ido-mode
9421 (listp (second args)))
9422 (let ((ido-enter-matching-directory nil))
9423 (apply 'ido-completing-read (concat (car args))
9424 (if (consp (car (nth 1 args)))
9425 (mapcar 'car (nth 1 args))
9426 (nth 1 args))
9427 (cddr args)))
9428 (if (and org-completion-use-iswitchb
9429 (boundp 'iswitchb-mode) iswitchb-mode
9430 (listp (second args)))
9431 (apply 'org-iswitchb-completing-read (concat (car args))
9432 (if (consp (car (nth 1 args)))
9433 (mapcar 'car (nth 1 args))
9434 (nth 1 args))
9435 (cddr args))
9436 (apply 'completing-read args)))))
9438 (defun org-extract-attributes (s)
9439 "Extract the attributes cookie from a string and set as text property."
9440 (let (a attr (start 0) key value)
9441 (save-match-data
9442 (when (string-match "{{\\([^}]+\\)}}$" s)
9443 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9444 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9445 (setq key (match-string 1 a) value (match-string 2 a)
9446 start (match-end 0)
9447 attr (plist-put attr (intern key) value))))
9448 (org-add-props s nil 'org-attr attr))
9451 (defun org-extract-attributes-from-string (tag)
9452 (let (key value attr)
9453 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9454 (setq key (match-string 1 tag) value (match-string 2 tag)
9455 tag (replace-match "" t t tag)
9456 attr (plist-put attr (intern key) value)))
9457 (cons tag attr)))
9459 (defun org-attributes-to-string (plist)
9460 "Format a property list into an HTML attribute list."
9461 (let ((s "") key value)
9462 (while plist
9463 (setq key (pop plist) value (pop plist))
9464 (and value
9465 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9468 ;;; Opening/following a link
9470 (defvar org-link-search-failed nil)
9472 (defvar org-open-link-functions nil
9473 "Hook for functions finding a plain text link.
9474 These functions must take a single argument, the link content.
9475 They will be called for links that look like [[link text][description]]
9476 when LINK TEXT does not have a protocol like \"http:\" and does not look
9477 like a filename (e.g. \"./blue.png\").
9479 These functions will be called *before* Org attempts to resolve the
9480 link by doing text searches in the current buffer - so if you want a
9481 link \"[[target]]\" to still find \"<<target>>\", your function should
9482 handle this as a special case.
9484 When the function does handle the link, it must return a non-nil value.
9485 If it decides that it is not responsible for this link, it must return
9486 nil to indicate that that Org-mode can continue with other options
9487 like exact and fuzzy text search.")
9489 (defun org-next-link ()
9490 "Move forward to the next link.
9491 If the link is in hidden text, expose it."
9492 (interactive)
9493 (when (and org-link-search-failed (eq this-command last-command))
9494 (goto-char (point-min))
9495 (message "Link search wrapped back to beginning of buffer"))
9496 (setq org-link-search-failed nil)
9497 (let* ((pos (point))
9498 (ct (org-context))
9499 (a (assoc :link ct)))
9500 (if a (goto-char (nth 2 a)))
9501 (if (re-search-forward org-any-link-re nil t)
9502 (progn
9503 (goto-char (match-beginning 0))
9504 (if (outline-invisible-p) (org-show-context)))
9505 (goto-char pos)
9506 (setq org-link-search-failed t)
9507 (error "No further link found"))))
9509 (defun org-previous-link ()
9510 "Move backward to the previous link.
9511 If the link is in hidden text, expose it."
9512 (interactive)
9513 (when (and org-link-search-failed (eq this-command last-command))
9514 (goto-char (point-max))
9515 (message "Link search wrapped back to end of buffer"))
9516 (setq org-link-search-failed nil)
9517 (let* ((pos (point))
9518 (ct (org-context))
9519 (a (assoc :link ct)))
9520 (if a (goto-char (nth 1 a)))
9521 (if (re-search-backward org-any-link-re nil t)
9522 (progn
9523 (goto-char (match-beginning 0))
9524 (if (outline-invisible-p) (org-show-context)))
9525 (goto-char pos)
9526 (setq org-link-search-failed t)
9527 (error "No further link found"))))
9529 (defun org-translate-link (s)
9530 "Translate a link string if a translation function has been defined."
9531 (if (and org-link-translation-function
9532 (fboundp org-link-translation-function)
9533 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9534 (progn
9535 (setq s (funcall org-link-translation-function
9536 (match-string 1 s) (match-string 2 s)))
9537 (concat (car s) ":" (cdr s)))
9540 (defun org-translate-link-from-planner (type path)
9541 "Translate a link from Emacs Planner syntax so that Org can follow it.
9542 This is still an experimental function, your mileage may vary."
9543 (cond
9544 ((member type '("http" "https" "news" "ftp"))
9545 ;; standard Internet links are the same.
9546 nil)
9547 ((and (equal type "irc") (string-match "^//" path))
9548 ;; Planner has two / at the beginning of an irc link, we have 1.
9549 ;; We should have zero, actually....
9550 (setq path (substring path 1)))
9551 ((and (equal type "lisp") (string-match "^/" path))
9552 ;; Planner has a slash, we do not.
9553 (setq type "elisp" path (substring path 1)))
9554 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9555 ;; A typical message link. Planner has the id after the final slash,
9556 ;; we separate it with a hash mark
9557 (setq path (concat (match-string 1 path) "#"
9558 (org-remove-angle-brackets (match-string 2 path)))))
9560 (cons type path))
9562 (defun org-find-file-at-mouse (ev)
9563 "Open file link or URL at mouse."
9564 (interactive "e")
9565 (mouse-set-point ev)
9566 (org-open-at-point 'in-emacs))
9568 (defun org-open-at-mouse (ev)
9569 "Open file link or URL at mouse.
9570 See the docstring of `org-open-file' for details."
9571 (interactive "e")
9572 (mouse-set-point ev)
9573 (if (eq major-mode 'org-agenda-mode)
9574 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9575 (org-open-at-point))
9577 (defvar org-window-config-before-follow-link nil
9578 "The window configuration before following a link.
9579 This is saved in case the need arises to restore it.")
9581 (defvar org-open-link-marker (make-marker)
9582 "Marker pointing to the location where `org-open-at-point; was called.")
9584 ;;;###autoload
9585 (defun org-open-at-point-global ()
9586 "Follow a link like Org-mode does.
9587 This command can be called in any mode to follow a link that has
9588 Org-mode syntax."
9589 (interactive)
9590 (org-run-like-in-org-mode 'org-open-at-point))
9592 ;;;###autoload
9593 (defun org-open-link-from-string (s &optional arg reference-buffer)
9594 "Open a link in the string S, as if it was in Org-mode."
9595 (interactive "sLink: \nP")
9596 (let ((reference-buffer (or reference-buffer (current-buffer))))
9597 (with-temp-buffer
9598 (let ((org-inhibit-startup (not reference-buffer)))
9599 (org-mode)
9600 (insert s)
9601 (goto-char (point-min))
9602 (when reference-buffer
9603 (setq org-link-abbrev-alist-local
9604 (with-current-buffer reference-buffer
9605 org-link-abbrev-alist-local)))
9606 (org-open-at-point arg reference-buffer)))))
9608 (defvar org-open-at-point-functions nil
9609 "Hook that is run when following a link at point.
9611 Functions in this hook must return t if they identify and follow
9612 a link at point. If they don't find anything interesting at point,
9613 they must return nil.")
9615 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9616 (defun org-open-at-point (&optional arg reference-buffer)
9617 "Open link at or after point.
9618 If there is no link at point, this function will search forward up to
9619 the end of the current line.
9620 Normally, files will be opened by an appropriate application. If the
9621 optional prefix argument ARG is non-nil, Emacs will visit the file.
9622 With a double prefix argument, try to open outside of Emacs, in the
9623 application the system uses for this file type."
9624 (interactive "P")
9625 ;; if in a code block, then open the block's results
9626 (unless (call-interactively #'org-babel-open-src-block-result)
9627 (org-load-modules-maybe)
9628 (move-marker org-open-link-marker (point))
9629 (setq org-window-config-before-follow-link (current-window-configuration))
9630 (org-remove-occur-highlights nil nil t)
9631 (cond
9632 ((and (org-at-heading-p)
9633 (not (org-at-timestamp-p t))
9634 (not (org-in-regexp
9635 (concat org-plain-link-re "\\|"
9636 org-bracket-link-regexp "\\|"
9637 org-angle-link-re "\\|"
9638 "[ \t]:[^ \t\n]+:[ \t]*$")))
9639 (not (get-text-property (point) 'org-linked-text)))
9640 (or (org-offer-links-in-entry arg)
9641 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9642 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9643 ((and (org-at-timestamp-p t)
9644 (not (org-in-regexp org-bracket-link-regexp)))
9645 (org-follow-timestamp-link))
9646 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9647 (not (org-in-regexp org-bracket-link-regexp)))
9648 (org-footnote-action))
9650 (let (type path link line search (pos (point)))
9651 (catch 'match
9652 (save-excursion
9653 (skip-chars-forward "^]\n\r")
9654 (when (org-in-regexp org-bracket-link-regexp 1)
9655 (setq link (org-extract-attributes
9656 (org-link-unescape (org-match-string-no-properties 1))))
9657 (while (string-match " *\n *" link)
9658 (setq link (replace-match " " t t link)))
9659 (setq link (org-link-expand-abbrev link))
9660 (cond
9661 ((or (file-name-absolute-p link)
9662 (string-match "^\\.\\.?/" link))
9663 (setq type "file" path link))
9664 ((string-match org-link-re-with-space3 link)
9665 (setq type (match-string 1 link) path (match-string 2 link)))
9666 ((string-match "^help:+\\(.+\\)" link)
9667 (setq type "help" path (match-string 1 link)))
9668 (t (setq type "thisfile" path link)))
9669 (throw 'match t)))
9671 (when (get-text-property (point) 'org-linked-text)
9672 (setq type "thisfile"
9673 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9674 (1+ (point)) (point))
9675 path (buffer-substring
9676 (or (previous-single-property-change pos 'org-linked-text)
9677 (point-min))
9678 (or (next-single-property-change pos 'org-linked-text)
9679 (point-max))))
9680 (throw 'match t))
9682 (save-excursion
9683 (when (or (org-in-regexp org-angle-link-re)
9684 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9685 (save-match-data (not (looking-back "\\[\\[")))))
9686 (setq type (match-string 1)
9687 path (org-link-unescape (match-string 2)))
9688 (throw 'match t)))
9689 (save-excursion
9690 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9691 (setq type "tags"
9692 path (match-string 1))
9693 (while (string-match ":" path)
9694 (setq path (replace-match "+" t t path)))
9695 (throw 'match t)))
9696 (when (org-in-regexp "<\\([^><\n]+\\)>")
9697 (setq type "tree-match"
9698 path (match-string 1))
9699 (throw 'match t)))
9700 (unless path
9701 (error "No link found"))
9703 ;; switch back to reference buffer
9704 ;; needed when if called in a temporary buffer through
9705 ;; org-open-link-from-string
9706 (with-current-buffer (or reference-buffer (current-buffer))
9708 ;; Remove any trailing spaces in path
9709 (if (string-match " +\\'" path)
9710 (setq path (replace-match "" t t path)))
9711 (if (and org-link-translation-function
9712 (fboundp org-link-translation-function))
9713 ;; Check if we need to translate the link
9714 (let ((tmp (funcall org-link-translation-function type path)))
9715 (setq type (car tmp) path (cdr tmp))))
9717 (cond
9719 ((assoc type org-link-protocols)
9720 (funcall (nth 1 (assoc type org-link-protocols)) path))
9722 ((equal type "help")
9723 (let ((f-or-v (intern path)))
9724 (cond ((fboundp f-or-v)
9725 (describe-function f-or-v))
9726 ((boundp f-or-v)
9727 (describe-variable f-or-v))
9728 (t (error "Not a known function or variable")))))
9730 ((equal type "mailto")
9731 (let ((cmd (car org-link-mailto-program))
9732 (args (cdr org-link-mailto-program)) args1
9733 (address path) (subject "") a)
9734 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9735 (setq address (match-string 1 path)
9736 subject (org-link-escape (match-string 2 path))))
9737 (while args
9738 (cond
9739 ((not (stringp (car args))) (push (pop args) args1))
9740 (t (setq a (pop args))
9741 (if (string-match "%a" a)
9742 (setq a (replace-match address t t a)))
9743 (if (string-match "%s" a)
9744 (setq a (replace-match subject t t a)))
9745 (push a args1))))
9746 (apply cmd (nreverse args1))))
9748 ((member type '("http" "https" "ftp" "news"))
9749 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9750 (org-link-escape
9751 path org-link-escape-chars-browser)
9752 path))))
9754 ((string= type "doi")
9755 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9756 (org-link-escape
9757 path org-link-escape-chars-browser)
9758 path))))
9760 ((member type '("message"))
9761 (browse-url (concat type ":" path)))
9763 ((string= type "tags")
9764 (org-tags-view arg path))
9766 ((string= type "tree-match")
9767 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9769 ((string= type "file")
9770 (if (string-match "::\\([0-9]+\\)\\'" path)
9771 (setq line (string-to-number (match-string 1 path))
9772 path (substring path 0 (match-beginning 0)))
9773 (if (string-match "::\\(.+\\)\\'" path)
9774 (setq search (match-string 1 path)
9775 path (substring path 0 (match-beginning 0)))))
9776 (if (string-match "[*?{]" (file-name-nondirectory path))
9777 (dired path)
9778 (org-open-file path arg line search)))
9780 ((string= type "shell")
9781 (let ((buf (generate-new-buffer "*Org Shell Output"))
9782 (cmd path))
9783 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9784 (string-match org-confirm-shell-link-not-regexp cmd))
9785 (not org-confirm-shell-link-function)
9786 (funcall org-confirm-shell-link-function
9787 (format "Execute \"%s\" in shell? "
9788 (org-add-props cmd nil
9789 'face 'org-warning))))
9790 (progn
9791 (message "Executing %s" cmd)
9792 (shell-command cmd buf)
9793 (if (featurep 'midnight)
9794 (setq clean-buffer-list-kill-buffer-names
9795 (cons buf clean-buffer-list-kill-buffer-names))))
9796 (error "Abort"))))
9798 ((string= type "elisp")
9799 (let ((cmd path))
9800 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9801 (string-match org-confirm-elisp-link-not-regexp cmd))
9802 (not org-confirm-elisp-link-function)
9803 (funcall org-confirm-elisp-link-function
9804 (format "Execute \"%s\" as elisp? "
9805 (org-add-props cmd nil
9806 'face 'org-warning))))
9807 (message "%s => %s" cmd
9808 (if (equal (string-to-char cmd) ?\()
9809 (eval (read cmd))
9810 (call-interactively (read cmd))))
9811 (error "Abort"))))
9813 ((and (string= type "thisfile")
9814 (run-hook-with-args-until-success
9815 'org-open-link-functions path)))
9817 ((string= type "thisfile")
9818 (if arg
9819 (switch-to-buffer-other-window
9820 (org-get-buffer-for-internal-link (current-buffer)))
9821 (org-mark-ring-push))
9822 (let ((cmd `(org-link-search
9823 ,path
9824 ,(cond ((equal arg '(4)) ''occur)
9825 ((equal arg '(16)) ''org-occur))
9826 ,pos)))
9827 (condition-case nil (let ((org-link-search-inhibit-query t))
9828 (eval cmd))
9829 (error (progn (widen) (eval cmd))))))
9831 (t (browse-url-at-point)))))))
9832 (move-marker org-open-link-marker nil)
9833 (run-hook-with-args 'org-follow-link-hook)))
9835 (defun org-offer-links-in-entry (&optional nth zero)
9836 "Offer links in the current entry and follow the selected link.
9837 If there is only one link, follow it immediately as well.
9838 If NTH is an integer, immediately pick the NTH link found.
9839 If ZERO is a string, check also this string for a link, and if
9840 there is one, offer it as link number zero."
9841 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9842 "\\(" org-angle-link-re "\\)\\|"
9843 "\\(" org-plain-link-re "\\)"))
9844 (cnt ?0)
9845 (in-emacs (if (integerp nth) nil nth))
9846 have-zero end links link c)
9847 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9848 (push (match-string 0 zero) links)
9849 (setq cnt (1- cnt) have-zero t))
9850 (save-excursion
9851 (org-back-to-heading t)
9852 (setq end (save-excursion (outline-next-heading) (point)))
9853 (while (re-search-forward re end t)
9854 (push (match-string 0) links))
9855 (setq links (org-uniquify (reverse links))))
9857 (cond
9858 ((null links)
9859 (message "No links"))
9860 ((equal (length links) 1)
9861 (setq link (list (car links))))
9862 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9863 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9864 (t ; we have to select a link
9865 (save-excursion
9866 (save-window-excursion
9867 (delete-other-windows)
9868 (with-output-to-temp-buffer "*Select Link*"
9869 (mapc (lambda (l)
9870 (if (not (string-match org-bracket-link-regexp l))
9871 (princ (format "[%c] %s\n" (incf cnt)
9872 (org-remove-angle-brackets l)))
9873 (if (match-end 3)
9874 (princ (format "[%c] %s (%s)\n" (incf cnt)
9875 (match-string 3 l) (match-string 1 l)))
9876 (princ (format "[%c] %s\n" (incf cnt)
9877 (match-string 1 l))))))
9878 links))
9879 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9880 (message "Select link to open, RET to open all:")
9881 (setq c (read-char-exclusive))
9882 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9883 (when (equal c ?q) (error "Abort"))
9884 (if (equal c ?\C-m)
9885 (setq link links)
9886 (setq nth (- c ?0))
9887 (if have-zero (setq nth (1+ nth)))
9888 (unless (and (integerp nth) (>= (length links) nth))
9889 (error "Invalid link selection"))
9890 (setq link (list (nth (1- nth) links))))))
9891 (if link
9892 (let ((buf (current-buffer)))
9893 (dolist (l link)
9894 (org-open-link-from-string l in-emacs buf))
9896 nil)))
9898 ;; Add special file links that specify the way of opening
9900 (org-add-link-type "file+sys" 'org-open-file-with-system)
9901 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9902 (defun org-open-file-with-system (path)
9903 "Open file at PATH using the system way of opening it."
9904 (org-open-file path 'system))
9905 (defun org-open-file-with-emacs (path)
9906 "Open file at PATH in Emacs."
9907 (org-open-file path 'emacs))
9908 (defun org-remove-file-link-modifiers ()
9909 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9910 (goto-char (point-min))
9911 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9912 (org-if-unprotected
9913 (replace-match "file:" t t))))
9914 (eval-after-load "org-exp"
9915 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9916 'org-remove-file-link-modifiers))
9918 ;;;; Time estimates
9920 (defun org-get-effort (&optional pom)
9921 "Get the effort estimate for the current entry."
9922 (org-entry-get pom org-effort-property))
9924 ;;; File search
9926 (defvar org-create-file-search-functions nil
9927 "List of functions to construct the right search string for a file link.
9928 These functions are called in turn with point at the location to
9929 which the link should point.
9931 A function in the hook should first test if it would like to
9932 handle this file type, for example by checking the `major-mode'
9933 or the file extension. If it decides not to handle this file, it
9934 should just return nil to give other functions a chance. If it
9935 does handle the file, it must return the search string to be used
9936 when following the link. The search string will be part of the
9937 file link, given after a double colon, and `org-open-at-point'
9938 will automatically search for it. If special measures must be
9939 taken to make the search successful, another function should be
9940 added to the companion hook `org-execute-file-search-functions',
9941 which see.
9943 A function in this hook may also use `setq' to set the variable
9944 `description' to provide a suggestion for the descriptive text to
9945 be used for this link when it gets inserted into an Org-mode
9946 buffer with \\[org-insert-link].")
9948 (defvar org-execute-file-search-functions nil
9949 "List of functions to execute a file search triggered by a link.
9951 Functions added to this hook must accept a single argument, the
9952 search string that was part of the file link, the part after the
9953 double colon. The function must first check if it would like to
9954 handle this search, for example by checking the `major-mode' or
9955 the file extension. If it decides not to handle this search, it
9956 should just return nil to give other functions a chance. If it
9957 does handle the search, it must return a non-nil value to keep
9958 other functions from trying.
9960 Each function can access the current prefix argument through the
9961 variable `current-prefix-argument'. Note that a single prefix is
9962 used to force opening a link in Emacs, so it may be good to only
9963 use a numeric or double prefix to guide the search function.
9965 In case this is needed, a function in this hook can also restore
9966 the window configuration before `org-open-at-point' was called using:
9968 (set-window-configuration org-window-config-before-follow-link)")
9970 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9971 (defun org-link-search (s &optional type avoid-pos stealth)
9972 "Search for a link search option.
9973 If S is surrounded by forward slashes, it is interpreted as a
9974 regular expression. In org-mode files, this will create an `org-occur'
9975 sparse tree. In ordinary files, `occur' will be used to list matches.
9976 If the current buffer is in `dired-mode', grep will be used to search
9977 in all files. If AVOID-POS is given, ignore matches near that position.
9979 When optional argument STEALTH is non-nil, do not modify
9980 visibility around point, thus ignoring
9981 `org-show-hierarchy-above', `org-show-following-heading' and
9982 `org-show-siblings' variables."
9983 (let ((case-fold-search t)
9984 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9985 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9986 (append '(("") (" ") ("\t") ("\n"))
9987 org-emphasis-alist)
9988 "\\|") "\\)"))
9989 (pos (point))
9990 (pre nil) (post nil)
9991 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9992 (cond
9993 ;; First check if there are any special search functions
9994 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9995 ;; Now try the builtin stuff
9996 ((and (equal (string-to-char s0) ?#)
9997 (> (length s0) 1)
9998 (save-excursion
9999 (goto-char (point-min))
10000 (and
10001 (re-search-forward
10002 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10003 (setq type 'dedicated
10004 pos (match-beginning 0))))
10005 ;; There is an exact target for this
10006 (goto-char pos)
10007 (org-back-to-heading t)))
10008 ((save-excursion
10009 (goto-char (point-min))
10010 (and
10011 (re-search-forward
10012 (concat "<<" (regexp-quote s0) ">>") nil t)
10013 (setq type 'dedicated
10014 pos (match-beginning 0))))
10015 ;; There is an exact target for this
10016 (goto-char pos))
10017 ((save-excursion
10018 (goto-char (point-min))
10019 (and
10020 (re-search-forward
10021 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10022 (setq type 'dedicated pos (match-beginning 0))))
10023 ;; Found an invisible target.
10024 (goto-char pos))
10025 ((save-excursion
10026 (goto-char (point-min))
10027 (and
10028 (re-search-forward
10029 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10030 (setq type 'dedicated pos (match-beginning 0))))
10031 ;; Found an element with a matching #+name affiliated keyword.
10032 (goto-char pos))
10033 ((and (string-match "^(\\(.*\\))$" s0)
10034 (save-excursion
10035 (goto-char (point-min))
10036 (and
10037 (re-search-forward
10038 (concat "[^[]" (regexp-quote
10039 (format org-coderef-label-format
10040 (match-string 1 s0))))
10041 nil t)
10042 (setq type 'dedicated
10043 pos (1+ (match-beginning 0))))))
10044 ;; There is a coderef target for this
10045 (goto-char pos))
10046 ((string-match "^/\\(.*\\)/$" s)
10047 ;; A regular expression
10048 (cond
10049 ((derived-mode-p 'org-mode)
10050 (org-occur (match-string 1 s)))
10051 ;;((eq major-mode 'dired-mode)
10052 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10053 (t (org-do-occur (match-string 1 s)))))
10054 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10055 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10056 (goto-char (point-min))
10057 (cond
10058 ((let (case-fold-search)
10059 (re-search-forward (format org-complex-heading-regexp-format
10060 (regexp-quote s))
10061 nil t))
10062 ;; OK, found a match
10063 (setq type 'dedicated)
10064 (goto-char (match-beginning 0)))
10065 ((and (not org-link-search-inhibit-query)
10066 (eq org-link-search-must-match-exact-headline 'query-to-create)
10067 (y-or-n-p "No match - create this as a new heading? "))
10068 (goto-char (point-max))
10069 (or (bolp) (newline))
10070 (insert "* " s "\n")
10071 (beginning-of-line 0))
10073 (goto-char pos)
10074 (error "No match"))))
10076 ;; A normal search string
10077 (when (equal (string-to-char s) ?*)
10078 ;; Anchor on headlines, post may include tags.
10079 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10080 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10081 s (substring s 1)))
10082 (remove-text-properties
10083 0 (length s)
10084 '(face nil mouse-face nil keymap nil fontified nil) s)
10085 ;; Make a series of regular expressions to find a match
10086 (setq words (org-split-string s "[ \n\r\t]+")
10088 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10089 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10090 "\\)" markers)
10091 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10092 re2a (concat "[ \t\r\n]" re2a_)
10093 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10094 re4 (concat "[^a-zA-Z_]" re4_)
10096 re1 (concat pre re2 post)
10097 re3 (concat pre (if pre re4_ re4) post)
10098 re5 (concat pre ".*" re4)
10099 re2 (concat pre re2)
10100 re2a (concat pre (if pre re2a_ re2a))
10101 re4 (concat pre (if pre re4_ re4))
10102 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10103 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10104 re5 "\\)"
10106 (cond
10107 ((eq type 'org-occur) (org-occur reall))
10108 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10109 (t (goto-char (point-min))
10110 (setq type 'fuzzy)
10111 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10112 (org-search-not-self 1 re1 nil t)
10113 (org-search-not-self 1 re2 nil t)
10114 (org-search-not-self 1 re2a nil t)
10115 (org-search-not-self 1 re3 nil t)
10116 (org-search-not-self 1 re4 nil t)
10117 (org-search-not-self 1 re5 nil t)
10119 (goto-char (match-beginning 1))
10120 (goto-char pos)
10121 (error "No match"))))))
10122 (and (derived-mode-p 'org-mode)
10123 (not stealth)
10124 (org-show-context 'link-search))
10125 type))
10127 (defun org-search-not-self (group &rest args)
10128 "Execute `re-search-forward', but only accept matches that do not
10129 enclose the position of `org-open-link-marker'."
10130 (let ((m org-open-link-marker))
10131 (catch 'exit
10132 (while (apply 're-search-forward args)
10133 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10134 (goto-char (match-end group))
10135 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10136 (> (match-beginning 0) (marker-position m))
10137 (< (match-end 0) (marker-position m)))
10138 (save-match-data
10139 (or (not (org-in-regexp
10140 org-bracket-link-analytic-regexp 1))
10141 (not (match-end 4)) ; no description
10142 (and (<= (match-beginning 4) (point))
10143 (>= (match-end 4) (point))))))
10144 (throw 'exit (point))))))))
10146 (defun org-get-buffer-for-internal-link (buffer)
10147 "Return a buffer to be used for displaying the link target of internal links."
10148 (cond
10149 ((not org-display-internal-link-with-indirect-buffer)
10150 buffer)
10151 ((string-match "(Clone)$" (buffer-name buffer))
10152 (message "Buffer is already a clone, not making another one")
10153 ;; we also do not modify visibility in this case
10154 buffer)
10155 (t ; make a new indirect buffer for displaying the link
10156 (let* ((bn (buffer-name buffer))
10157 (ibn (concat bn "(Clone)"))
10158 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10159 (with-current-buffer ib (org-overview))
10160 ib))))
10162 (defun org-do-occur (regexp &optional cleanup)
10163 "Call the Emacs command `occur'.
10164 If CLEANUP is non-nil, remove the printout of the regular expression
10165 in the *Occur* buffer. This is useful if the regex is long and not useful
10166 to read."
10167 (occur regexp)
10168 (when cleanup
10169 (let ((cwin (selected-window)) win beg end)
10170 (when (setq win (get-buffer-window "*Occur*"))
10171 (select-window win))
10172 (goto-char (point-min))
10173 (when (re-search-forward "match[a-z]+" nil t)
10174 (setq beg (match-end 0))
10175 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10176 (setq end (1- (match-beginning 0)))))
10177 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10178 (goto-char (point-min))
10179 (select-window cwin))))
10181 ;;; The mark ring for links jumps
10183 (defvar org-mark-ring nil
10184 "Mark ring for positions before jumps in Org-mode.")
10185 (defvar org-mark-ring-last-goto nil
10186 "Last position in the mark ring used to go back.")
10187 ;; Fill and close the ring
10188 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10189 (loop for i from 1 to org-mark-ring-length do
10190 (push (make-marker) org-mark-ring))
10191 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10192 org-mark-ring)
10194 (defun org-mark-ring-push (&optional pos buffer)
10195 "Put the current position or POS into the mark ring and rotate it."
10196 (interactive)
10197 (setq pos (or pos (point)))
10198 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10199 (move-marker (car org-mark-ring)
10200 (or pos (point))
10201 (or buffer (current-buffer)))
10202 (message "%s"
10203 (substitute-command-keys
10204 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10206 (defun org-mark-ring-goto (&optional n)
10207 "Jump to the previous position in the mark ring.
10208 With prefix arg N, jump back that many stored positions. When
10209 called several times in succession, walk through the entire ring.
10210 Org-mode commands jumping to a different position in the current file,
10211 or to another Org-mode file, automatically push the old position
10212 onto the ring."
10213 (interactive "p")
10214 (let (p m)
10215 (if (eq last-command this-command)
10216 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10217 (setq p org-mark-ring))
10218 (setq org-mark-ring-last-goto p)
10219 (setq m (car p))
10220 (org-pop-to-buffer-same-window (marker-buffer m))
10221 (goto-char m)
10222 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10224 (defun org-remove-angle-brackets (s)
10225 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10226 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10228 (defun org-add-angle-brackets (s)
10229 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10230 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10232 (defun org-remove-double-quotes (s)
10233 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10234 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10237 ;;; Following specific links
10239 (defun org-follow-timestamp-link ()
10240 "Open an agenda view for the time-stamp date/range at point."
10241 (cond
10242 ((org-at-date-range-p t)
10243 (let ((org-agenda-start-on-weekday)
10244 (t1 (match-string 1))
10245 (t2 (match-string 2)) tt1 tt2)
10246 (setq tt1 (time-to-days (org-time-string-to-time t1))
10247 tt2 (time-to-days (org-time-string-to-time t2)))
10248 (let ((org-agenda-buffer-tmp-name
10249 (format "*Org Agenda(a:%s)"
10250 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10251 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10252 ((org-at-timestamp-p t)
10253 (let ((org-agenda-buffer-tmp-name
10254 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10255 (org-agenda-list nil (time-to-days (org-time-string-to-time
10256 (substring (match-string 1) 0 10)))
10257 1)))
10258 (t (error "This should not happen"))))
10261 ;;; Following file links
10262 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10263 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10264 (declare-function mailcap-mime-info
10265 "mailcap" (string &optional request no-decode))
10266 (defvar org-wait nil)
10267 (defun org-open-file (path &optional in-emacs line search)
10268 "Open the file at PATH.
10269 First, this expands any special file name abbreviations. Then the
10270 configuration variable `org-file-apps' is checked if it contains an
10271 entry for this file type, and if yes, the corresponding command is launched.
10273 If no application is found, Emacs simply visits the file.
10275 With optional prefix argument IN-EMACS, Emacs will visit the file.
10276 With a double \\[universal-argument] \\[universal-argument] \
10277 prefix arg, Org tries to avoid opening in Emacs
10278 and to use an external application to visit the file.
10280 Optional LINE specifies a line to go to, optional SEARCH a string
10281 to search for. If LINE or SEARCH is given, the file will be
10282 opened in Emacs, unless an entry from org-file-apps that makes
10283 use of groups in a regexp matches.
10285 If you want to change the way frames are used when following a
10286 link, please customize `org-link-frame-setup'.
10288 If the file does not exist, an error is thrown."
10289 (let* ((file (if (equal path "")
10290 buffer-file-name
10291 (substitute-in-file-name (expand-file-name path))))
10292 (file-apps (append org-file-apps (org-default-apps)))
10293 (apps (org-remove-if
10294 'org-file-apps-entry-match-against-dlink-p file-apps))
10295 (apps-dlink (org-remove-if-not
10296 'org-file-apps-entry-match-against-dlink-p file-apps))
10297 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10298 (dirp (if remp nil (file-directory-p file)))
10299 (file (if (and dirp org-open-directory-means-index-dot-org)
10300 (concat (file-name-as-directory file) "index.org")
10301 file))
10302 (a-m-a-p (assq 'auto-mode apps))
10303 (dfile (downcase file))
10304 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10305 (link (cond ((and (eq line nil)
10306 (eq search nil))
10307 file)
10308 (line
10309 (concat file "::" (number-to-string line)))
10310 (search
10311 (concat file "::" search))))
10312 (dlink (downcase link))
10313 (old-buffer (current-buffer))
10314 (old-pos (point))
10315 (old-mode major-mode)
10316 ext cmd link-match-data)
10317 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10318 (setq ext (match-string 1 dfile))
10319 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10320 (setq ext (match-string 1 dfile))))
10321 (cond
10322 ((member in-emacs '((16) system))
10323 (setq cmd (cdr (assoc 'system apps))))
10324 (in-emacs (setq cmd 'emacs))
10326 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10327 (and dirp (cdr (assoc 'directory apps)))
10328 ; first, try matching against apps-dlink
10329 ; if we get a match here, store the match data for later
10330 (let ((match (assoc-default dlink apps-dlink
10331 'string-match)))
10332 (if match
10333 (progn (setq link-match-data (match-data))
10334 match)
10335 (progn (setq in-emacs (or in-emacs line search))
10336 nil))) ; if we have no match in apps-dlink,
10337 ; always open the file in emacs if line or search
10338 ; is given (for backwards compatibility)
10339 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10340 'string-match)
10341 (cdr (assoc ext apps))
10342 (cdr (assoc t apps))))))
10343 (when (eq cmd 'system)
10344 (setq cmd (cdr (assoc 'system apps))))
10345 (when (eq cmd 'default)
10346 (setq cmd (cdr (assoc t apps))))
10347 (when (eq cmd 'mailcap)
10348 (require 'mailcap)
10349 (mailcap-parse-mailcaps)
10350 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10351 (command (mailcap-mime-info mime-type)))
10352 (if (stringp command)
10353 (setq cmd command)
10354 (setq cmd 'emacs))))
10355 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10356 (not (file-exists-p file))
10357 (not org-open-non-existing-files))
10358 (error "No such file: %s" file))
10359 (cond
10360 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10361 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10362 (while (string-match "['\"]%s['\"]" cmd)
10363 (setq cmd (replace-match "%s" t t cmd)))
10364 (while (string-match "%s" cmd)
10365 (setq cmd (replace-match
10366 (save-match-data
10367 (shell-quote-argument
10368 (convert-standard-filename file)))
10369 t t cmd)))
10371 ;; Replace "%1", "%2" etc. in command with group matches from regex
10372 (save-match-data
10373 (let ((match-index 1)
10374 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10375 (set-match-data link-match-data)
10376 (while (<= match-index number-of-groups)
10377 (let ((regex (concat "%" (number-to-string match-index)))
10378 (replace-with (match-string match-index dlink)))
10379 (while (string-match regex cmd)
10380 (setq cmd (replace-match replace-with t t cmd))))
10381 (setq match-index (+ match-index 1)))))
10383 (save-window-excursion
10384 (start-process-shell-command cmd nil cmd)
10385 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10387 ((or (stringp cmd)
10388 (eq cmd 'emacs))
10389 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10390 (widen)
10391 (if line (org-goto-line line)
10392 (if search (org-link-search search))))
10393 ((consp cmd)
10394 (let ((file (convert-standard-filename file)))
10395 (save-match-data
10396 (set-match-data link-match-data)
10397 (eval cmd))))
10398 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10399 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10400 (or (not (equal old-buffer (current-buffer)))
10401 (not (equal old-pos (point))))
10402 (org-mark-ring-push old-pos old-buffer))))
10404 (defun org-file-apps-entry-match-against-dlink-p (entry)
10405 "This function returns non-nil if `entry' uses a regular
10406 expression which should be matched against the whole link by
10407 org-open-file.
10409 It assumes that is the case when the entry uses a regular
10410 expression which has at least one grouping construct and the
10411 action is either a lisp form or a command string containing
10412 '%1', i.e. using at least one subexpression match as a
10413 parameter."
10414 (let ((selector (car entry))
10415 (action (cdr entry)))
10416 (if (stringp selector)
10417 (and (> (regexp-opt-depth selector) 0)
10418 (or (and (stringp action)
10419 (string-match "%[0-9]" action))
10420 (consp action)))
10421 nil)))
10423 (defun org-default-apps ()
10424 "Return the default applications for this operating system."
10425 (cond
10426 ((eq system-type 'darwin)
10427 org-file-apps-defaults-macosx)
10428 ((eq system-type 'windows-nt)
10429 org-file-apps-defaults-windowsnt)
10430 (t org-file-apps-defaults-gnu)))
10432 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10433 "Convert extensions to regular expressions in the cars of LIST.
10434 Also, weed out any non-string entries, because the return value is used
10435 only for regexp matching.
10436 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10437 point to the symbol `emacs', indicating that the file should
10438 be opened in Emacs."
10439 (append
10440 (delq nil
10441 (mapcar (lambda (x)
10442 (if (not (stringp (car x)))
10444 (if (string-match "\\W" (car x))
10446 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10447 list))
10448 (if add-auto-mode
10449 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10451 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10452 (defun org-file-remote-p (file)
10453 "Test whether FILE specifies a location on a remote system.
10454 Return non-nil if the location is indeed remote.
10456 For example, the filename \"/user@host:/foo\" specifies a location
10457 on the system \"/user@host:\"."
10458 (cond ((fboundp 'file-remote-p)
10459 (file-remote-p file))
10460 ((fboundp 'tramp-handle-file-remote-p)
10461 (tramp-handle-file-remote-p file))
10462 ((and (boundp 'ange-ftp-name-format)
10463 (string-match (car ange-ftp-name-format) file))
10464 t)))
10467 ;;;; Refiling
10469 (defun org-get-org-file ()
10470 "Read a filename, with default directory `org-directory'."
10471 (let ((default (or org-default-notes-file remember-data-file)))
10472 (read-file-name (format "File name [%s]: " default)
10473 (file-name-as-directory org-directory)
10474 default)))
10476 (defun org-notes-order-reversed-p ()
10477 "Check if the current file should receive notes in reversed order."
10478 (cond
10479 ((not org-reverse-note-order) nil)
10480 ((eq t org-reverse-note-order) t)
10481 ((not (listp org-reverse-note-order)) nil)
10482 (t (catch 'exit
10483 (let ((all org-reverse-note-order)
10484 entry)
10485 (while (setq entry (pop all))
10486 (if (string-match (car entry) buffer-file-name)
10487 (throw 'exit (cdr entry))))
10488 nil)))))
10490 (defvar org-refile-target-table nil
10491 "The list of refile targets, created by `org-refile'.")
10493 (defvar org-agenda-new-buffers nil
10494 "Buffers created to visit agenda files.")
10496 (defvar org-refile-cache nil
10497 "Cache for refile targets.")
10499 (defvar org-refile-markers nil
10500 "All the markers used for caching refile locations.")
10502 (defun org-refile-marker (pos)
10503 "Get a new refile marker, but only if caching is in use."
10504 (if (not org-refile-use-cache)
10506 (let ((m (make-marker)))
10507 (move-marker m pos)
10508 (push m org-refile-markers)
10509 m)))
10511 (defun org-refile-cache-clear ()
10512 "Clear the refile cache and disable all the markers."
10513 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10514 (setq org-refile-markers nil)
10515 (setq org-refile-cache nil)
10516 (message "Refile cache has been cleared"))
10518 (defun org-refile-cache-check-set (set)
10519 "Check if all the markers in the cache still have live buffers."
10520 (let (marker)
10521 (catch 'exit
10522 (while (and set (setq marker (nth 3 (pop set))))
10523 ;; if org-refile-use-outline-path is 'file, marker may be nil
10524 (when (and marker (null (marker-buffer marker)))
10525 (message "not found") (sit-for 3)
10526 (throw 'exit nil)))
10527 t)))
10529 (defun org-refile-cache-put (set &rest identifiers)
10530 "Push the refile targets SET into the cache, under IDENTIFIERS."
10531 (let* ((key (sha1 (prin1-to-string identifiers)))
10532 (entry (assoc key org-refile-cache)))
10533 (if entry
10534 (setcdr entry set)
10535 (push (cons key set) org-refile-cache))))
10537 (defun org-refile-cache-get (&rest identifiers)
10538 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10539 (cond
10540 ((not org-refile-cache) nil)
10541 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10543 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10544 org-refile-cache))))
10545 (and set (org-refile-cache-check-set set) set)))))
10547 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10548 "Produce a table with refile targets."
10549 (let ((case-fold-search nil)
10550 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10551 (entries (or org-refile-targets '((nil . (:level . 1)))))
10552 targets tgs txt re files f desc descre fast-path-p level pos0)
10553 (message "Getting targets...")
10554 (with-current-buffer (or default-buffer (current-buffer))
10555 (while (setq entry (pop entries))
10556 (setq files (car entry) desc (cdr entry))
10557 (setq fast-path-p nil)
10558 (cond
10559 ((null files) (setq files (list (current-buffer))))
10560 ((eq files 'org-agenda-files)
10561 (setq files (org-agenda-files 'unrestricted)))
10562 ((and (symbolp files) (fboundp files))
10563 (setq files (funcall files)))
10564 ((and (symbolp files) (boundp files))
10565 (setq files (symbol-value files))))
10566 (if (stringp files) (setq files (list files)))
10567 (cond
10568 ((eq (car desc) :tag)
10569 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10570 ((eq (car desc) :todo)
10571 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10572 ((eq (car desc) :regexp)
10573 (setq descre (cdr desc)))
10574 ((eq (car desc) :level)
10575 (setq descre (concat "^\\*\\{" (number-to-string
10576 (if org-odd-levels-only
10577 (1- (* 2 (cdr desc)))
10578 (cdr desc)))
10579 "\\}[ \t]")))
10580 ((eq (car desc) :maxlevel)
10581 (setq fast-path-p t)
10582 (setq descre (concat "^\\*\\{1," (number-to-string
10583 (if org-odd-levels-only
10584 (1- (* 2 (cdr desc)))
10585 (cdr desc)))
10586 "\\}[ \t]")))
10587 (t (error "Bad refiling target description %s" desc)))
10588 (while (setq f (pop files))
10589 (with-current-buffer
10590 (if (bufferp f) f (org-get-agenda-file-buffer f))
10592 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10593 (progn
10594 (if (bufferp f) (setq f (buffer-file-name
10595 (buffer-base-buffer f))))
10596 (setq f (and f (expand-file-name f)))
10597 (if (eq org-refile-use-outline-path 'file)
10598 (push (list (file-name-nondirectory f) f nil nil) tgs))
10599 (save-excursion
10600 (save-restriction
10601 (widen)
10602 (goto-char (point-min))
10603 (while (re-search-forward descre nil t)
10604 (goto-char (setq pos0 (point-at-bol)))
10605 (catch 'next
10606 (when org-refile-target-verify-function
10607 (save-match-data
10608 (or (funcall org-refile-target-verify-function)
10609 (throw 'next t))))
10610 (when (and (looking-at org-complex-heading-regexp)
10611 (not (member (match-string 4) excluded-entries))
10612 (match-string 4))
10613 (setq level (org-reduced-level
10614 (- (match-end 1) (match-beginning 1)))
10615 txt (org-link-display-format (match-string 4))
10616 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10617 re (format org-complex-heading-regexp-format
10618 (regexp-quote (match-string 4))))
10619 (when org-refile-use-outline-path
10620 (setq txt (mapconcat
10621 'org-protect-slash
10622 (append
10623 (if (eq org-refile-use-outline-path
10624 'file)
10625 (list (file-name-nondirectory
10626 (buffer-file-name
10627 (buffer-base-buffer))))
10628 (if (eq org-refile-use-outline-path
10629 'full-file-path)
10630 (list (buffer-file-name
10631 (buffer-base-buffer)))))
10632 (org-get-outline-path fast-path-p
10633 level txt)
10634 (list txt))
10635 "/")))
10636 (push (list txt f re (org-refile-marker (point)))
10637 tgs)))
10638 (when (= (point) pos0)
10639 ;; verification function has not moved point
10640 (goto-char (point-at-eol))))))))
10641 (when org-refile-use-cache
10642 (org-refile-cache-put tgs (buffer-file-name) descre))
10643 (setq targets (append tgs targets))
10644 ))))
10645 (message "Getting targets...done")
10646 (nreverse targets)))
10648 (defun org-protect-slash (s)
10649 (while (string-match "/" s)
10650 (setq s (replace-match "\\" t t s)))
10653 (defvar org-olpa (make-vector 20 nil))
10655 (defun org-get-outline-path (&optional fastp level heading)
10656 "Return the outline path to the current entry, as a list.
10658 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10659 routine which makes outline path derivations for an entire file,
10660 avoiding backtracing. Refile target collection makes use of that."
10661 (if fastp
10662 (progn
10663 (if (> level 19)
10664 (error "Outline path failure, more than 19 levels"))
10665 (loop for i from level upto 19 do
10666 (aset org-olpa i nil))
10667 (prog1
10668 (delq nil (append org-olpa nil))
10669 (aset org-olpa level heading)))
10670 (let (rtn case-fold-search)
10671 (save-excursion
10672 (save-restriction
10673 (widen)
10674 (while (org-up-heading-safe)
10675 (when (looking-at org-complex-heading-regexp)
10676 (push (org-match-string-no-properties 4) rtn)))
10677 rtn)))))
10679 (defun org-format-outline-path (path &optional width prefix)
10680 "Format the outline path PATH for display.
10681 Width is the maximum number of characters that is available.
10682 Prefix is a prefix to be included in the returned string,
10683 such as the file name."
10684 (setq width (or width 79))
10685 (if prefix (setq width (- width (length prefix))))
10686 (if (not path)
10687 (or prefix "")
10688 (let* ((nsteps (length path))
10689 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10690 (maxwidth (if (<= total-width width)
10691 10000 ;; everything fits
10692 ;; we need to shorten the level headings
10693 (/ (- width nsteps) nsteps)))
10694 (org-odd-levels-only nil)
10695 (n 0)
10696 (total (1+ (length prefix))))
10697 (setq maxwidth (max maxwidth 10))
10698 (concat prefix
10699 (mapconcat
10700 (lambda (h)
10701 (setq n (1+ n))
10702 (if (and (= n nsteps) (< maxwidth 10000))
10703 (setq maxwidth (- total-width total)))
10704 (if (< (length h) maxwidth)
10705 (progn (setq total (+ total (length h) 1)) h)
10706 (setq h (substring h 0 (- maxwidth 2))
10707 total (+ total maxwidth 1))
10708 (if (string-match "[ \t]+\\'" h)
10709 (setq h (substring h 0 (match-beginning 0))))
10710 (setq h (concat h "..")))
10711 (org-add-props h nil 'face
10712 (nth (% (1- n) org-n-level-faces)
10713 org-level-faces))
10715 path "/")))))
10717 (defun org-display-outline-path (&optional file current)
10718 "Display the current outline path in the echo area."
10719 (interactive "P")
10720 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10721 (case-fold-search nil)
10722 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10723 (if current (setq path (append path
10724 (save-excursion
10725 (org-back-to-heading t)
10726 (if (looking-at org-complex-heading-regexp)
10727 (list (match-string 4)))))))
10728 (message "%s"
10729 (org-format-outline-path
10730 path
10731 (1- (frame-width))
10732 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10734 (defvar org-refile-history nil
10735 "History for refiling operations.")
10737 (defvar org-after-refile-insert-hook nil
10738 "Hook run after `org-refile' has inserted its stuff at the new location.
10739 Note that this is still *before* the stuff will be removed from
10740 the *old* location.")
10742 (defvar org-capture-last-stored-marker)
10743 (defun org-refile (&optional goto default-buffer rfloc)
10744 "Move the entry or entries at point to another heading.
10745 The list of target headings is compiled using the information in
10746 `org-refile-targets', which see.
10748 At the target location, the entry is filed as a subitem of the target
10749 heading. Depending on `org-reverse-note-order', the new subitem will
10750 either be the first or the last subitem.
10752 If there is an active region, all entries in that region will be moved.
10753 However, the region must fulfill the requirement that the first heading
10754 is the first one sets the top-level of the moved text - at most siblings
10755 below it are allowed.
10757 With prefix arg GOTO, the command will only visit the target location
10758 and not actually move anything.
10760 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10761 go to the location where the last refiling operation has put the subtree.
10762 With a prefix argument of `2', refile to the running clock.
10764 RFLOC can be a refile location obtained in a different way.
10766 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10768 If you are using target caching (see `org-refile-use-cache'),
10769 you have to clear the target cache in order to find new targets.
10770 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10771 prefix argument (`C-u C-u C-u C-c C-w')."
10773 (interactive "P")
10774 (if (member goto '(0 (64)))
10775 (org-refile-cache-clear)
10776 (let* ((cbuf (current-buffer))
10777 (regionp (org-region-active-p))
10778 (region-start (and regionp (region-beginning)))
10779 (region-end (and regionp (region-end)))
10780 (region-length (and regionp (- region-end region-start)))
10781 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10782 pos it nbuf file re level reversed)
10783 (setq last-command nil)
10784 (when regionp
10785 (goto-char region-start)
10786 (or (bolp) (goto-char (point-at-bol)))
10787 (setq region-start (point))
10788 (unless (or (org-kill-is-subtree-p
10789 (buffer-substring region-start region-end))
10790 (prog1 org-refile-active-region-within-subtree
10791 (org-toggle-heading)))
10792 (error "The region is not a (sequence of) subtree(s)")))
10793 (if (equal goto '(16))
10794 (org-refile-goto-last-stored)
10795 (when (or
10796 (and (equal goto 2)
10797 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10798 (prog1
10799 (setq it (list (or org-clock-heading "running clock")
10800 (buffer-file-name
10801 (marker-buffer org-clock-hd-marker))
10803 (marker-position org-clock-hd-marker)))
10804 (setq goto nil)))
10805 (setq it (or rfloc
10806 (let (heading-text)
10807 (save-excursion
10808 (unless goto
10809 (org-back-to-heading t)
10810 (setq heading-text
10811 (nth 4 (org-heading-components))))
10812 (org-refile-get-location
10813 (cond (goto "Goto")
10814 (regionp "Refile region to")
10815 (t (concat "Refile subtree \""
10816 heading-text "\" to")))
10817 default-buffer
10818 (and (not (equal '(4) goto))
10819 org-refile-allow-creating-parent-nodes)
10820 goto))))))
10821 (setq file (nth 1 it)
10822 re (nth 2 it)
10823 pos (nth 3 it))
10824 (if (and (not goto)
10826 (equal (buffer-file-name) file)
10827 (if regionp
10828 (and (>= pos region-start)
10829 (<= pos region-end))
10830 (and (>= pos (point))
10831 (< pos (save-excursion
10832 (org-end-of-subtree t t))))))
10833 (error "Cannot refile to position inside the tree or region"))
10835 (setq nbuf (or (find-buffer-visiting file)
10836 (find-file-noselect file)))
10837 (if goto
10838 (progn
10839 (org-pop-to-buffer-same-window nbuf)
10840 (goto-char pos)
10841 (org-show-context 'org-goto))
10842 (if regionp
10843 (progn
10844 (org-kill-new (buffer-substring region-start region-end))
10845 (org-save-markers-in-region region-start region-end))
10846 (org-copy-subtree 1 nil t))
10847 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10848 (find-file-noselect file)))
10849 (setq reversed (org-notes-order-reversed-p))
10850 (save-excursion
10851 (save-restriction
10852 (widen)
10853 (if pos
10854 (progn
10855 (goto-char pos)
10856 (looking-at org-outline-regexp)
10857 (setq level (org-get-valid-level (funcall outline-level) 1))
10858 (goto-char
10859 (if reversed
10860 (or (outline-next-heading) (point-max))
10861 (or (save-excursion (org-get-next-sibling))
10862 (org-end-of-subtree t t)
10863 (point-max)))))
10864 (setq level 1)
10865 (if (not reversed)
10866 (goto-char (point-max))
10867 (goto-char (point-min))
10868 (or (outline-next-heading) (goto-char (point-max)))))
10869 (if (not (bolp)) (newline))
10870 (org-paste-subtree level)
10871 (when org-log-refile
10872 (org-add-log-setup 'refile nil nil 'findpos
10873 org-log-refile)
10874 (unless (eq org-log-refile 'note)
10875 (save-excursion (org-add-log-note))))
10876 (and org-auto-align-tags
10877 (let ((org-loop-over-headlines-in-active-region nil))
10878 (org-set-tags nil t)))
10879 (with-demoted-errors
10880 (bookmark-set "org-refile-last-stored"))
10881 ;; If we are refiling for capture, make sure that the
10882 ;; last-capture pointers point here
10883 (when (org-bound-and-true-p org-refile-for-capture)
10884 (with-demoted-errors
10885 (bookmark-set "org-capture-last-stored-marker"))
10886 (move-marker org-capture-last-stored-marker (point)))
10887 (if (fboundp 'deactivate-mark) (deactivate-mark))
10888 (run-hooks 'org-after-refile-insert-hook))))
10889 (if regionp
10890 (delete-region (point) (+ (point) region-length))
10891 (org-cut-subtree))
10892 (when (featurep 'org-inlinetask)
10893 (org-inlinetask-remove-END-maybe))
10894 (setq org-markers-to-move nil)
10895 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10897 (defun org-refile-goto-last-stored ()
10898 "Go to the location where the last refile was stored."
10899 (interactive)
10900 (bookmark-jump "org-refile-last-stored")
10901 (message "This is the location of the last refile"))
10903 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10904 no-exclude)
10905 "Prompt the user for a refile location, using PROMPT.
10906 PROMPT should not be suffixed with a colon and a space, because
10907 this function appends the default value from
10908 `org-refile-history' automatically, if that is not empty.
10909 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10910 this is used for the GOTO interface."
10911 (let ((org-refile-targets org-refile-targets)
10912 (org-refile-use-outline-path org-refile-use-outline-path)
10913 excluded-entries)
10914 (when (and (derived-mode-p 'org-mode)
10915 (not org-refile-use-cache)
10916 (not no-exclude))
10917 (org-map-tree
10918 (lambda()
10919 (setq excluded-entries
10920 (append excluded-entries (list (org-get-heading t t)))))))
10921 (setq org-refile-target-table
10922 (org-refile-get-targets default-buffer excluded-entries)))
10923 (unless org-refile-target-table
10924 (error "No refile targets"))
10925 (let* ((prompt (concat prompt
10926 (and (car org-refile-history)
10927 (concat " (default " (car org-refile-history) ")"))
10928 ": "))
10929 (cbuf (current-buffer))
10930 (partial-completion-mode nil)
10931 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10932 (cfunc (if (and org-refile-use-outline-path
10933 org-outline-path-complete-in-steps)
10934 'org-olpath-completing-read
10935 'org-icompleting-read))
10936 (extra (if org-refile-use-outline-path "/" ""))
10937 (filename (and cfn (expand-file-name cfn)))
10938 (tbl (mapcar
10939 (lambda (x)
10940 (if (and (not (member org-refile-use-outline-path
10941 '(file full-file-path)))
10942 (not (equal filename (nth 1 x))))
10943 (cons (concat (car x) extra " ("
10944 (file-name-nondirectory (nth 1 x)) ")")
10945 (cdr x))
10946 (cons (concat (car x) extra) (cdr x))))
10947 org-refile-target-table))
10948 (completion-ignore-case t)
10949 pa answ parent-target child parent old-hist)
10950 (setq old-hist org-refile-history)
10951 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10952 nil 'org-refile-history (car org-refile-history)))
10953 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10954 (org-refile-check-position pa)
10955 (if pa
10956 (progn
10957 (when (or (not org-refile-history)
10958 (not (eq old-hist org-refile-history))
10959 (not (equal (car pa) (car org-refile-history))))
10960 (setq org-refile-history
10961 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10962 org-refile-history
10963 (cdr org-refile-history))))
10964 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10965 (pop org-refile-history)))
10967 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10968 (progn
10969 (setq parent (match-string 1 answ)
10970 child (match-string 2 answ))
10971 (setq parent-target (or (assoc parent tbl)
10972 (assoc (concat parent "/") tbl)))
10973 (when (and parent-target
10974 (or (eq new-nodes t)
10975 (and (eq new-nodes 'confirm)
10976 (y-or-n-p (format "Create new node \"%s\"? "
10977 child)))))
10978 (org-refile-new-child parent-target child)))
10979 (error "Invalid target location")))))
10981 (declare-function org-string-nw-p "org-macs" (s))
10982 (defun org-refile-check-position (refile-pointer)
10983 "Check if the refile pointer matches the headline to which it points."
10984 (let* ((file (nth 1 refile-pointer))
10985 (re (nth 2 refile-pointer))
10986 (pos (nth 3 refile-pointer))
10987 buffer)
10988 (if (and (not (markerp pos)) (not file))
10989 (error "Please save the buffer to a file before refiling")
10990 (when (org-string-nw-p re)
10991 (setq buffer (if (markerp pos)
10992 (marker-buffer pos)
10993 (or (find-buffer-visiting file)
10994 (find-file-noselect file))))
10995 (with-current-buffer buffer
10996 (save-excursion
10997 (save-restriction
10998 (widen)
10999 (goto-char pos)
11000 (beginning-of-line 1)
11001 (unless (org-looking-at-p re)
11002 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11004 (defun org-refile-new-child (parent-target child)
11005 "Use refile target PARENT-TARGET to add new CHILD below it."
11006 (unless parent-target
11007 (error "Cannot find parent for new node"))
11008 (let ((file (nth 1 parent-target))
11009 (pos (nth 3 parent-target))
11010 level)
11011 (with-current-buffer (or (find-buffer-visiting file)
11012 (find-file-noselect file))
11013 (save-excursion
11014 (save-restriction
11015 (widen)
11016 (if pos
11017 (goto-char pos)
11018 (goto-char (point-max))
11019 (if (not (bolp)) (newline)))
11020 (when (looking-at org-outline-regexp)
11021 (setq level (funcall outline-level))
11022 (org-end-of-subtree t t))
11023 (org-back-over-empty-lines)
11024 (insert "\n" (make-string
11025 (if pos (org-get-valid-level level 1) 1) ?*)
11026 " " child "\n")
11027 (beginning-of-line 0)
11028 (list (concat (car parent-target) "/" child) file "" (point)))))))
11030 (defun org-olpath-completing-read (prompt collection &rest args)
11031 "Read an outline path like a file name."
11032 (let ((thetable collection)
11033 (org-completion-use-ido nil) ; does not work with ido.
11034 (org-completion-use-iswitchb nil)) ; or iswitchb
11035 (apply
11036 'org-icompleting-read prompt
11037 (lambda (string predicate &optional flag)
11038 (let (rtn r f (l (length string)))
11039 (cond
11040 ((eq flag nil)
11041 ;; try completion
11042 (try-completion string thetable))
11043 ((eq flag t)
11044 ;; all-completions
11045 (setq rtn (all-completions string thetable predicate))
11046 (mapcar
11047 (lambda (x)
11048 (setq r (substring x l))
11049 (if (string-match " ([^)]*)$" x)
11050 (setq f (match-string 0 x))
11051 (setq f ""))
11052 (if (string-match "/" r)
11053 (concat string (substring r 0 (match-end 0)) f)
11055 rtn))
11056 ((eq flag 'lambda)
11057 ;; exact match?
11058 (assoc string thetable)))))
11059 args)))
11061 ;;;; Dynamic blocks
11063 (defun org-find-dblock (name)
11064 "Find the first dynamic block with name NAME in the buffer.
11065 If not found, stay at current position and return nil."
11066 (let ((case-fold-search t) pos)
11067 (save-excursion
11068 (goto-char (point-min))
11069 (setq pos (and (re-search-forward
11070 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11071 (match-beginning 0))))
11072 (if pos (goto-char pos))
11073 pos))
11075 (defconst org-dblock-start-re
11076 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11077 "Matches the start line of a dynamic block, with parameters.")
11079 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11080 "Matches the end of a dynamic block.")
11082 (defun org-create-dblock (plist)
11083 "Create a dynamic block section, with parameters taken from PLIST.
11084 PLIST must contain a :name entry which is used as name of the block."
11085 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11086 (end-of-line 1)
11087 (newline))
11088 (let ((col (current-column))
11089 (name (plist-get plist :name)))
11090 (insert "#+BEGIN: " name)
11091 (while plist
11092 (if (eq (car plist) :name)
11093 (setq plist (cddr plist))
11094 (insert " " (prin1-to-string (pop plist)))))
11095 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11096 (beginning-of-line -2)))
11098 (defun org-prepare-dblock ()
11099 "Prepare dynamic block for refresh.
11100 This empties the block, puts the cursor at the insert position and returns
11101 the property list including an extra property :name with the block name."
11102 (unless (looking-at org-dblock-start-re)
11103 (error "Not at a dynamic block"))
11104 (let* ((begdel (1+ (match-end 0)))
11105 (name (org-no-properties (match-string 1)))
11106 (params (append (list :name name)
11107 (read (concat "(" (match-string 3) ")")))))
11108 (save-excursion
11109 (beginning-of-line 1)
11110 (skip-chars-forward " \t")
11111 (setq params (plist-put params :indentation-column (current-column))))
11112 (unless (re-search-forward org-dblock-end-re nil t)
11113 (error "Dynamic block not terminated"))
11114 (setq params
11115 (append params
11116 (list :content (buffer-substring
11117 begdel (match-beginning 0)))))
11118 (delete-region begdel (match-beginning 0))
11119 (goto-char begdel)
11120 (open-line 1)
11121 params))
11123 (defun org-map-dblocks (&optional command)
11124 "Apply COMMAND to all dynamic blocks in the current buffer.
11125 If COMMAND is not given, use `org-update-dblock'."
11126 (let ((cmd (or command 'org-update-dblock)))
11127 (save-excursion
11128 (goto-char (point-min))
11129 (while (re-search-forward org-dblock-start-re nil t)
11130 (goto-char (match-beginning 0))
11131 (save-excursion
11132 (condition-case nil
11133 (funcall cmd)
11134 (error (message "Error during update of dynamic block"))))
11135 (unless (re-search-forward org-dblock-end-re nil t)
11136 (error "Dynamic block not terminated"))))))
11138 (defun org-dblock-update (&optional arg)
11139 "User command for updating dynamic blocks.
11140 Update the dynamic block at point. With prefix ARG, update all dynamic
11141 blocks in the buffer."
11142 (interactive "P")
11143 (if arg
11144 (org-update-all-dblocks)
11145 (or (looking-at org-dblock-start-re)
11146 (org-beginning-of-dblock))
11147 (org-update-dblock)))
11149 (defun org-update-dblock ()
11150 "Update the dynamic block at point.
11151 This means to empty the block, parse for parameters and then call
11152 the correct writing function."
11153 (interactive)
11154 (save-window-excursion
11155 (let* ((pos (point))
11156 (line (org-current-line))
11157 (params (org-prepare-dblock))
11158 (name (plist-get params :name))
11159 (indent (plist-get params :indentation-column))
11160 (cmd (intern (concat "org-dblock-write:" name))))
11161 (message "Updating dynamic block `%s' at line %d..." name line)
11162 (funcall cmd params)
11163 (message "Updating dynamic block `%s' at line %d...done" name line)
11164 (goto-char pos)
11165 (when (and indent (> indent 0))
11166 (setq indent (make-string indent ?\ ))
11167 (save-excursion
11168 (org-beginning-of-dblock)
11169 (forward-line 1)
11170 (while (not (looking-at org-dblock-end-re))
11171 (insert indent)
11172 (beginning-of-line 2))
11173 (when (looking-at org-dblock-end-re)
11174 (and (looking-at "[ \t]+")
11175 (replace-match ""))
11176 (insert indent)))))))
11178 (defun org-beginning-of-dblock ()
11179 "Find the beginning of the dynamic block at point.
11180 Error if there is no such block at point."
11181 (let ((pos (point))
11182 beg)
11183 (end-of-line 1)
11184 (if (and (re-search-backward org-dblock-start-re nil t)
11185 (setq beg (match-beginning 0))
11186 (re-search-forward org-dblock-end-re nil t)
11187 (> (match-end 0) pos))
11188 (goto-char beg)
11189 (goto-char pos)
11190 (error "Not in a dynamic block"))))
11192 (defun org-update-all-dblocks ()
11193 "Update all dynamic blocks in the buffer.
11194 This function can be used in a hook."
11195 (interactive)
11196 (when (derived-mode-p 'org-mode)
11197 (org-map-dblocks 'org-update-dblock)))
11200 ;;;; Completion
11202 (defconst org-additional-option-like-keywords
11203 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11204 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11205 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11206 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11207 "BEGIN:" "END:"
11208 "ORGTBL" "TBLFM:" "TBLNAME:"
11209 "BEGIN_EXAMPLE" "END_EXAMPLE"
11210 "BEGIN_VERBATIM" "END_VERBATIM"
11211 "BEGIN_QUOTE" "END_QUOTE"
11212 "BEGIN_VERSE" "END_VERSE"
11213 "BEGIN_CENTER" "END_CENTER"
11214 "BEGIN_SRC" "END_SRC"
11215 "BEGIN_RESULT" "END_RESULT"
11216 "BEGIN_lstlisting" "END_lstlisting"
11217 "NAME:" "RESULTS:"
11218 "HEADER:" "HEADERS:"
11219 "COLUMNS:" "PROPERTY:"
11220 "CAPTION:" "LABEL:"
11221 "SETUPFILE:"
11222 "INCLUDE:"
11223 "BIND:"
11224 "MACRO:"))
11226 (defconst org-options-keywords
11227 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11228 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11229 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11230 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11231 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11232 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11233 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11235 (defconst org-additional-option-like-keywords-for-flyspell
11236 (delete-dups
11237 (split-string
11238 (mapconcat (lambda(k)
11239 (replace-regexp-in-string
11240 "_\\|:" " "
11241 (concat k " " (downcase k) " " (upcase k))))
11242 (append org-options-keywords org-additional-option-like-keywords)
11243 " ")
11244 " +" t)))
11246 (defcustom org-structure-template-alist
11248 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11249 "<src lang=\"?\">\n\n</src>")
11250 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11251 "<example>\n?\n</example>")
11252 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11253 "<quote>\n?\n</quote>")
11254 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11255 "<verse>\n?\n</verse>")
11256 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11257 "<center>\n?\n</center>")
11258 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11259 "<literal style=\"latex\">\n?\n</literal>")
11260 ("L" "#+LaTeX: "
11261 "<literal style=\"latex\">?</literal>")
11262 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11263 "<literal style=\"html\">\n?\n</literal>")
11264 ("H" "#+HTML: "
11265 "<literal style=\"html\">?</literal>")
11266 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11267 ("A" "#+ASCII: ")
11268 ("i" "#+INDEX: ?"
11269 "#+INDEX: ?")
11270 ("I" "#+INCLUDE: %file ?"
11271 "<include file=%file markup=\"?\">")
11273 "Structure completion elements.
11274 This is a list of abbreviation keys and values. The value gets inserted
11275 if you type `<' followed by the key and then press the completion key,
11276 usually `M-TAB'. %file will be replaced by a file name after prompting
11277 for the file using completion. The cursor will be placed at the position
11278 of the `?` in the template.
11279 There are two templates for each key, the first uses the original Org syntax,
11280 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11281 the default when the /org-mtags.el/ module has been loaded. See also the
11282 variable `org-mtags-prefer-muse-templates'."
11283 :group 'org-completion
11284 :type '(repeat
11285 (string :tag "Key")
11286 (string :tag "Template")
11287 (string :tag "Muse Template")))
11289 (defun org-try-structure-completion ()
11290 "Try to complete a structure template before point.
11291 This looks for strings like \"<e\" on an otherwise empty line and
11292 expands them."
11293 (let ((l (buffer-substring (point-at-bol) (point)))
11295 (when (and (looking-at "[ \t]*$")
11296 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11297 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11298 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11299 (match-beginning 1)) a)
11300 t)))
11302 (defun org-complete-expand-structure-template (start cell)
11303 "Expand a structure template."
11304 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11305 (rpl (nth (if musep 2 1) cell))
11306 (ind ""))
11307 (delete-region start (point))
11308 (when (string-match "\\`#\\+" rpl)
11309 (cond
11310 ((bolp))
11311 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11312 (setq ind (buffer-substring (point-at-bol) (point))))
11313 (t (newline))))
11314 (setq start (point))
11315 (if (string-match "%file" rpl)
11316 (setq rpl (replace-match
11317 (concat
11318 "\""
11319 (save-match-data
11320 (abbreviate-file-name (read-file-name "Include file: ")))
11321 "\"")
11322 t t rpl)))
11323 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11324 (concat "\n" ind)))
11325 (insert rpl)
11326 (if (re-search-backward "\\?" start t) (delete-char 1))))
11328 ;;;; TODO, DEADLINE, Comments
11330 (defun org-toggle-comment ()
11331 "Change the COMMENT state of an entry."
11332 (interactive)
11333 (save-excursion
11334 (org-back-to-heading)
11335 (let (case-fold-search)
11336 (cond
11337 ((looking-at (format org-heading-keyword-regexp-format
11338 org-comment-string))
11339 (goto-char (match-end 1))
11340 (looking-at (concat " +" org-comment-string))
11341 (replace-match "" t t)
11342 (when (eolp) (insert " ")))
11343 ((looking-at org-outline-regexp)
11344 (goto-char (match-end 0))
11345 (insert org-comment-string " "))))))
11347 (defvar org-last-todo-state-is-todo nil
11348 "This is non-nil when the last TODO state change led to a TODO state.
11349 If the last change removed the TODO tag or switched to DONE, then
11350 this is nil.")
11352 (defvar org-setting-tags nil) ; dynamically skipped
11354 (defvar org-todo-setup-filter-hook nil
11355 "Hook for functions that pre-filter todo specs.
11356 Each function takes a todo spec and returns either nil or the spec
11357 transformed into canonical form." )
11359 (defvar org-todo-get-default-hook nil
11360 "Hook for functions that get a default item for todo.
11361 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11362 nil or a string to be used for the todo mark." )
11364 (defvar org-agenda-headline-snapshot-before-repeat)
11366 (defun org-current-effective-time ()
11367 "Return current time adjusted for `org-extend-today-until' variable."
11368 (let* ((ct (org-current-time))
11369 (dct (decode-time ct))
11370 (ct1
11371 (if (and org-use-effective-time
11372 (< (nth 2 dct) org-extend-today-until))
11373 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11374 ct)))
11375 ct1))
11377 (defun org-todo-yesterday (&optional arg)
11378 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11379 (interactive "P")
11380 (if (eq major-mode 'org-agenda-mode)
11381 (apply 'org-agenda-todo-yesterday arg)
11382 (let* ((hour (third (decode-time
11383 (org-current-time))))
11384 (org-extend-today-until (1+ hour)))
11385 (org-todo arg))))
11387 (defun org-todo (&optional arg)
11388 "Change the TODO state of an item.
11389 The state of an item is given by a keyword at the start of the heading,
11390 like
11391 *** TODO Write paper
11392 *** DONE Call mom
11394 The different keywords are specified in the variable `org-todo-keywords'.
11395 By default the available states are \"TODO\" and \"DONE\".
11396 So for this example: when the item starts with TODO, it is changed to DONE.
11397 When it starts with DONE, the DONE is removed. And when neither TODO nor
11398 DONE are present, add TODO at the beginning of the heading.
11400 With \\[universal-argument] prefix arg, use completion to determine the new \
11401 state.
11402 With numeric prefix arg, switch to that state.
11403 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11404 keywords (nextset).
11405 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11406 With a numeric prefix arg of 0, inhibit note taking for the change.
11408 For calling through lisp, arg is also interpreted in the following way:
11409 'none -> empty state
11410 \"\"(empty string) -> switch to empty state
11411 'done -> switch to DONE
11412 'nextset -> switch to the next set of keywords
11413 'previousset -> switch to the previous set of keywords
11414 \"WAITING\" -> switch to the specified keyword, but only if it
11415 really is a member of `org-todo-keywords'."
11416 (interactive "P")
11417 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11418 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11419 'region-start-level 'region))
11420 org-loop-over-headlines-in-active-region)
11421 (org-map-entries
11422 `(org-todo ,arg)
11423 org-loop-over-headlines-in-active-region
11424 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11425 (if (equal arg '(16)) (setq arg 'nextset))
11426 (let ((org-blocker-hook org-blocker-hook)
11427 (case-fold-search nil))
11428 (when (equal arg '(64))
11429 (setq arg nil org-blocker-hook nil))
11430 (when (and org-blocker-hook
11431 (or org-inhibit-blocking
11432 (org-entry-get nil "NOBLOCKING")))
11433 (setq org-blocker-hook nil))
11434 (save-excursion
11435 (catch 'exit
11436 (org-back-to-heading t)
11437 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11438 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11439 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11440 (let* ((match-data (match-data))
11441 (startpos (point-at-bol))
11442 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11443 (org-log-done org-log-done)
11444 (org-log-repeat org-log-repeat)
11445 (org-todo-log-states org-todo-log-states)
11446 (org-inhibit-logging
11447 (if (equal arg 0)
11448 (progn (setq arg nil) 'note) org-inhibit-logging))
11449 (this (match-string 1))
11450 (hl-pos (match-beginning 0))
11451 (head (org-get-todo-sequence-head this))
11452 (ass (assoc head org-todo-kwd-alist))
11453 (interpret (nth 1 ass))
11454 (done-word (nth 3 ass))
11455 (final-done-word (nth 4 ass))
11456 (org-last-state (or this ""))
11457 (completion-ignore-case t)
11458 (member (member this org-todo-keywords-1))
11459 (tail (cdr member))
11460 (org-state (cond
11461 ((and org-todo-key-trigger
11462 (or (and (equal arg '(4))
11463 (eq org-use-fast-todo-selection 'prefix))
11464 (and (not arg) org-use-fast-todo-selection
11465 (not (eq org-use-fast-todo-selection
11466 'prefix)))))
11467 ;; Use fast selection
11468 (org-fast-todo-selection))
11469 ((and (equal arg '(4))
11470 (or (not org-use-fast-todo-selection)
11471 (not org-todo-key-trigger)))
11472 ;; Read a state with completion
11473 (org-icompleting-read
11474 "State: " (mapcar (lambda(x) (list x))
11475 org-todo-keywords-1)
11476 nil t))
11477 ((eq arg 'right)
11478 (if this
11479 (if tail (car tail) nil)
11480 (car org-todo-keywords-1)))
11481 ((eq arg 'left)
11482 (if (equal member org-todo-keywords-1)
11484 (if this
11485 (nth (- (length org-todo-keywords-1)
11486 (length tail) 2)
11487 org-todo-keywords-1)
11488 (org-last org-todo-keywords-1))))
11489 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11490 (setq arg nil))) ; hack to fall back to cycling
11491 (arg
11492 ;; user or caller requests a specific state
11493 (cond
11494 ((equal arg "") nil)
11495 ((eq arg 'none) nil)
11496 ((eq arg 'done) (or done-word (car org-done-keywords)))
11497 ((eq arg 'nextset)
11498 (or (car (cdr (member head org-todo-heads)))
11499 (car org-todo-heads)))
11500 ((eq arg 'previousset)
11501 (let ((org-todo-heads (reverse org-todo-heads)))
11502 (or (car (cdr (member head org-todo-heads)))
11503 (car org-todo-heads))))
11504 ((car (member arg org-todo-keywords-1)))
11505 ((stringp arg)
11506 (error "State `%s' not valid in this file" arg))
11507 ((nth (1- (prefix-numeric-value arg))
11508 org-todo-keywords-1))))
11509 ((null member) (or head (car org-todo-keywords-1)))
11510 ((equal this final-done-word) nil) ;; -> make empty
11511 ((null tail) nil) ;; -> first entry
11512 ((memq interpret '(type priority))
11513 (if (eq this-command last-command)
11514 (car tail)
11515 (if (> (length tail) 0)
11516 (or done-word (car org-done-keywords))
11517 nil)))
11519 (car tail))))
11520 (org-state (or
11521 (run-hook-with-args-until-success
11522 'org-todo-get-default-hook org-state org-last-state)
11523 org-state))
11524 (next (if org-state (concat " " org-state " ") " "))
11525 (change-plist (list :type 'todo-state-change :from this :to org-state
11526 :position startpos))
11527 dolog now-done-p)
11528 (when org-blocker-hook
11529 (setq org-last-todo-state-is-todo
11530 (not (member this org-done-keywords)))
11531 (unless (save-excursion
11532 (save-match-data
11533 (org-with-wide-buffer
11534 (run-hook-with-args-until-failure
11535 'org-blocker-hook change-plist))))
11536 (if (org-called-interactively-p 'interactive)
11537 (error "TODO state change from %s to %s blocked" this org-state)
11538 ;; fail silently
11539 (message "TODO state change from %s to %s blocked" this org-state)
11540 (throw 'exit nil))))
11541 (store-match-data match-data)
11542 (replace-match next t t)
11543 (unless (pos-visible-in-window-p hl-pos)
11544 (message "TODO state changed to %s" (org-trim next)))
11545 (unless head
11546 (setq head (org-get-todo-sequence-head org-state)
11547 ass (assoc head org-todo-kwd-alist)
11548 interpret (nth 1 ass)
11549 done-word (nth 3 ass)
11550 final-done-word (nth 4 ass)))
11551 (when (memq arg '(nextset previousset))
11552 (message "Keyword-Set %d/%d: %s"
11553 (- (length org-todo-sets) -1
11554 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11555 (length org-todo-sets)
11556 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11557 (setq org-last-todo-state-is-todo
11558 (not (member org-state org-done-keywords)))
11559 (setq now-done-p (and (member org-state org-done-keywords)
11560 (not (member this org-done-keywords))))
11561 (and logging (org-local-logging logging))
11562 (when (and (or org-todo-log-states org-log-done)
11563 (not (eq org-inhibit-logging t))
11564 (not (memq arg '(nextset previousset))))
11565 ;; we need to look at recording a time and note
11566 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11567 (nth 2 (assoc this org-todo-log-states))))
11568 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11569 (setq dolog 'time))
11570 (when (and org-state
11571 (member org-state org-not-done-keywords)
11572 (not (member this org-not-done-keywords)))
11573 ;; This is now a todo state and was not one before
11574 ;; If there was a CLOSED time stamp, get rid of it.
11575 (org-add-planning-info nil nil 'closed))
11576 (when (and now-done-p org-log-done)
11577 ;; It is now done, and it was not done before
11578 (org-add-planning-info 'closed (org-current-effective-time))
11579 (if (and (not dolog) (eq 'note org-log-done))
11580 (org-add-log-setup 'done org-state this 'findpos 'note)))
11581 (when (and org-state dolog)
11582 ;; This is a non-nil state, and we need to log it
11583 (org-add-log-setup 'state org-state this 'findpos dolog)))
11584 ;; Fixup tag positioning
11585 (org-todo-trigger-tag-changes org-state)
11586 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11587 (when org-provide-todo-statistics
11588 (org-update-parent-todo-statistics))
11589 (run-hooks 'org-after-todo-state-change-hook)
11590 (if (and arg (not (member org-state org-done-keywords)))
11591 (setq head (org-get-todo-sequence-head org-state)))
11592 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11593 ;; Do we need to trigger a repeat?
11594 (when now-done-p
11595 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11596 ;; This is for the agenda, take a snapshot of the headline.
11597 (save-match-data
11598 (setq org-agenda-headline-snapshot-before-repeat
11599 (org-get-heading))))
11600 (org-auto-repeat-maybe org-state))
11601 ;; Fixup cursor location if close to the keyword
11602 (if (and (outline-on-heading-p)
11603 (not (bolp))
11604 (save-excursion (beginning-of-line 1)
11605 (looking-at org-todo-line-regexp))
11606 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11607 (progn
11608 (goto-char (or (match-end 2) (match-end 1)))
11609 (and (looking-at " ") (just-one-space))))
11610 (when org-trigger-hook
11611 (save-excursion
11612 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11614 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11615 "Block turning an entry into a TODO, using the hierarchy.
11616 This checks whether the current task should be blocked from state
11617 changes. Such blocking occurs when:
11619 1. The task has children which are not all in a completed state.
11621 2. A task has a parent with the property :ORDERED:, and there
11622 are siblings prior to the current task with incomplete
11623 status.
11625 3. The parent of the task is blocked because it has siblings that should
11626 be done first, or is child of a block grandparent TODO entry."
11628 (if (not org-enforce-todo-dependencies)
11629 t ; if locally turned off don't block
11630 (catch 'dont-block
11631 ;; If this is not a todo state change, or if this entry is already DONE,
11632 ;; do not block
11633 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11634 (member (plist-get change-plist :from)
11635 (cons 'done org-done-keywords))
11636 (member (plist-get change-plist :to)
11637 (cons 'todo org-not-done-keywords))
11638 (not (plist-get change-plist :to)))
11639 (throw 'dont-block t))
11640 ;; If this task has children, and any are undone, it's blocked
11641 (save-excursion
11642 (org-back-to-heading t)
11643 (let ((this-level (funcall outline-level)))
11644 (outline-next-heading)
11645 (let ((child-level (funcall outline-level)))
11646 (while (and (not (eobp))
11647 (> child-level this-level))
11648 ;; this todo has children, check whether they are all
11649 ;; completed
11650 (if (and (not (org-entry-is-done-p))
11651 (org-entry-is-todo-p))
11652 (throw 'dont-block nil))
11653 (outline-next-heading)
11654 (setq child-level (funcall outline-level))))))
11655 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11656 ;; any previous siblings are undone, it's blocked
11657 (save-excursion
11658 (org-back-to-heading t)
11659 (let* ((pos (point))
11660 (parent-pos (and (org-up-heading-safe) (point))))
11661 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11662 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11663 (forward-line 1)
11664 (re-search-forward org-not-done-heading-regexp pos t))
11665 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11666 ;; Search further up the hierarchy, to see if an ancestor is blocked
11667 (while t
11668 (goto-char parent-pos)
11669 (if (not (looking-at org-not-done-heading-regexp))
11670 (throw 'dont-block t)) ; do not block, parent is not a TODO
11671 (setq pos (point))
11672 (setq parent-pos (and (org-up-heading-safe) (point)))
11673 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11674 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11675 (forward-line 1)
11676 (re-search-forward org-not-done-heading-regexp pos t))
11677 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11679 (defcustom org-track-ordered-property-with-tag nil
11680 "Should the ORDERED property also be shown as a tag?
11681 The ORDERED property decides if an entry should require subtasks to be
11682 completed in sequence. Since a property is not very visible, setting
11683 this option means that toggling the ORDERED property with the command
11684 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11685 not relevant for the behavior, but it makes things more visible.
11687 Note that toggling the tag with tags commands will not change the property
11688 and therefore not influence behavior!
11690 This can be t, meaning the tag ORDERED should be used, It can also be a
11691 string to select a different tag for this task."
11692 :group 'org-todo
11693 :type '(choice
11694 (const :tag "No tracking" nil)
11695 (const :tag "Track with ORDERED tag" t)
11696 (string :tag "Use other tag")))
11698 (defun org-toggle-ordered-property ()
11699 "Toggle the ORDERED property of the current entry.
11700 For better visibility, you can track the value of this property with a tag.
11701 See variable `org-track-ordered-property-with-tag'."
11702 (interactive)
11703 (let* ((t1 org-track-ordered-property-with-tag)
11704 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11705 (save-excursion
11706 (org-back-to-heading)
11707 (if (org-entry-get nil "ORDERED")
11708 (progn
11709 (org-delete-property "ORDERED")
11710 (and tag (org-toggle-tag tag 'off))
11711 (message "Subtasks can be completed in arbitrary order"))
11712 (org-entry-put nil "ORDERED" "t")
11713 (and tag (org-toggle-tag tag 'on))
11714 (message "Subtasks must be completed in sequence")))))
11716 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11717 (defun org-block-todo-from-checkboxes (change-plist)
11718 "Block turning an entry into a TODO, using checkboxes.
11719 This checks whether the current task should be blocked from state
11720 changes because there are unchecked boxes in this entry."
11721 (if (not org-enforce-todo-checkbox-dependencies)
11722 t ; if locally turned off don't block
11723 (catch 'dont-block
11724 ;; If this is not a todo state change, or if this entry is already DONE,
11725 ;; do not block
11726 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11727 (member (plist-get change-plist :from)
11728 (cons 'done org-done-keywords))
11729 (member (plist-get change-plist :to)
11730 (cons 'todo org-not-done-keywords))
11731 (not (plist-get change-plist :to)))
11732 (throw 'dont-block t))
11733 ;; If this task has checkboxes that are not checked, it's blocked
11734 (save-excursion
11735 (org-back-to-heading t)
11736 (let ((beg (point)) end)
11737 (outline-next-heading)
11738 (setq end (point))
11739 (goto-char beg)
11740 (if (org-list-search-forward
11741 (concat (org-item-beginning-re)
11742 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11743 "\\[[- ]\\]")
11744 end t)
11745 (progn
11746 (if (boundp 'org-blocked-by-checkboxes)
11747 (setq org-blocked-by-checkboxes t))
11748 (throw 'dont-block nil)))))
11749 t))) ; do not block
11751 (defun org-entry-blocked-p ()
11752 "Is the current entry blocked?"
11753 (if (org-entry-get nil "NOBLOCKING")
11754 nil ;; Never block this entry
11755 (not
11756 (run-hook-with-args-until-failure
11757 'org-blocker-hook
11758 (list :type 'todo-state-change
11759 :position (point)
11760 :from 'todo
11761 :to 'done)))))
11763 (defun org-update-statistics-cookies (all)
11764 "Update the statistics cookie, either from TODO or from checkboxes.
11765 This should be called with the cursor in a line with a statistics cookie."
11766 (interactive "P")
11767 (if all
11768 (progn
11769 (org-update-checkbox-count 'all)
11770 (org-map-entries 'org-update-parent-todo-statistics))
11771 (if (not (org-at-heading-p))
11772 (org-update-checkbox-count)
11773 (let ((pos (move-marker (make-marker) (point)))
11774 end l1 l2)
11775 (ignore-errors (org-back-to-heading t))
11776 (if (not (org-at-heading-p))
11777 (org-update-checkbox-count)
11778 (setq l1 (org-outline-level))
11779 (setq end (save-excursion
11780 (outline-next-heading)
11781 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11782 (point)))
11783 (if (and (save-excursion
11784 (re-search-forward
11785 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11786 (not (save-excursion (re-search-forward
11787 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11788 (org-update-checkbox-count)
11789 (if (and l2 (> l2 l1))
11790 (progn
11791 (goto-char end)
11792 (org-update-parent-todo-statistics))
11793 (goto-char pos)
11794 (beginning-of-line 1)
11795 (while (re-search-forward
11796 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11797 (point-at-eol) t)
11798 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11799 (goto-char pos)
11800 (move-marker pos nil)))))
11802 (defvar org-entry-property-inherited-from) ;; defined below
11803 (defun org-update-parent-todo-statistics ()
11804 "Update any statistics cookie in the parent of the current headline.
11805 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11806 the entire subtree and this will travel up the hierarchy and update
11807 statistics everywhere."
11808 (let* ((prop (save-excursion (org-up-heading-safe)
11809 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11810 (recursive (or (not org-hierarchical-todo-statistics)
11811 (and prop (string-match "\\<recursive\\>" prop))))
11812 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11814 (first t)
11815 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11816 level ltoggle l1 new ndel
11817 (cnt-all 0) (cnt-done 0) is-percent kwd
11818 checkbox-beg ov ovs ove cookie-present)
11819 (catch 'exit
11820 (save-excursion
11821 (beginning-of-line 1)
11822 (setq ltoggle (funcall outline-level))
11823 ;; Three situations are to consider:
11825 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11826 ;; to the top-level ancestor on the headline;
11828 ;; 2. If parent has "recursive" property, repeat up to the
11829 ;; headline setting that property, taking inheritance into
11830 ;; account;
11832 ;; 3. Else, move up to direct parent and proceed only once.
11833 (while (and (setq level (org-up-heading-safe))
11834 (or recursive first)
11835 (>= (point) lim))
11836 (setq first nil cookie-present nil)
11837 (unless (and level
11838 (not (string-match
11839 "\\<checkbox\\>"
11840 (downcase (or (org-entry-get nil "COOKIE_DATA")
11841 "")))))
11842 (throw 'exit nil))
11843 (while (re-search-forward box-re (point-at-eol) t)
11844 (setq cnt-all 0 cnt-done 0 cookie-present t)
11845 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11846 (save-match-data
11847 (unless (outline-next-heading) (throw 'exit nil))
11848 (while (and (looking-at org-complex-heading-regexp)
11849 (> (setq l1 (length (match-string 1))) level))
11850 (setq kwd (and (or recursive (= l1 ltoggle))
11851 (match-string 2)))
11852 (if (or (eq org-provide-todo-statistics 'all-headlines)
11853 (and (listp org-provide-todo-statistics)
11854 (or (member kwd org-provide-todo-statistics)
11855 (member kwd org-done-keywords))))
11856 (setq cnt-all (1+ cnt-all))
11857 (if (eq org-provide-todo-statistics t)
11858 (and kwd (setq cnt-all (1+ cnt-all)))))
11859 (and (member kwd org-done-keywords)
11860 (setq cnt-done (1+ cnt-done)))
11861 (outline-next-heading)))
11862 (setq new
11863 (if is-percent
11864 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11865 (format "[%d/%d]" cnt-done cnt-all))
11866 ndel (- (match-end 0) checkbox-beg))
11867 ;; handle overlays when updating cookie from column view
11868 (when (setq ov (car (overlays-at checkbox-beg)))
11869 (setq ovs (overlay-start ov) ove (overlay-end ov))
11870 (delete-overlay ov))
11871 (goto-char checkbox-beg)
11872 (insert new)
11873 (delete-region (point) (+ (point) ndel))
11874 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11875 (when ov (move-overlay ov ovs ove)))
11876 (when cookie-present
11877 (run-hook-with-args 'org-after-todo-statistics-hook
11878 cnt-done (- cnt-all cnt-done))))))
11879 (run-hooks 'org-todo-statistics-hook)))
11881 (defvar org-after-todo-statistics-hook nil
11882 "Hook that is called after a TODO statistics cookie has been updated.
11883 Each function is called with two arguments: the number of not-done entries
11884 and the number of done entries.
11886 For example, the following function, when added to this hook, will switch
11887 an entry to DONE when all children are done, and back to TODO when new
11888 entries are set to a TODO status. Note that this hook is only called
11889 when there is a statistics cookie in the headline!
11891 (defun org-summary-todo (n-done n-not-done)
11892 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11893 (let (org-log-done org-log-states) ; turn off logging
11894 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11897 (defvar org-todo-statistics-hook nil
11898 "Hook that is run whenever Org thinks TODO statistics should be updated.
11899 This hook runs even if there is no statistics cookie present, in which case
11900 `org-after-todo-statistics-hook' would not run.")
11902 (defun org-todo-trigger-tag-changes (state)
11903 "Apply the changes defined in `org-todo-state-tags-triggers'."
11904 (let ((l org-todo-state-tags-triggers)
11905 changes)
11906 (when (or (not state) (equal state ""))
11907 (setq changes (append changes (cdr (assoc "" l)))))
11908 (when (and (stringp state) (> (length state) 0))
11909 (setq changes (append changes (cdr (assoc state l)))))
11910 (when (member state org-not-done-keywords)
11911 (setq changes (append changes (cdr (assoc 'todo l)))))
11912 (when (member state org-done-keywords)
11913 (setq changes (append changes (cdr (assoc 'done l)))))
11914 (dolist (c changes)
11915 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11917 (defun org-local-logging (value)
11918 "Get logging settings from a property VALUE."
11919 (let* (words w a)
11920 ;; directly set the variables, they are already local.
11921 (setq org-log-done nil
11922 org-log-repeat nil
11923 org-todo-log-states nil)
11924 (setq words (org-split-string value))
11925 (while (setq w (pop words))
11926 (cond
11927 ((setq a (assoc w org-startup-options))
11928 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11929 (set (nth 1 a) (nth 2 a))))
11930 ((setq a (org-extract-log-state-settings w))
11931 (and (member (car a) org-todo-keywords-1)
11932 (push a org-todo-log-states)))))))
11934 (defun org-get-todo-sequence-head (kwd)
11935 "Return the head of the TODO sequence to which KWD belongs.
11936 If KWD is not set, check if there is a text property remembering the
11937 right sequence."
11938 (let (p)
11939 (cond
11940 ((not kwd)
11941 (or (get-text-property (point-at-bol) 'org-todo-head)
11942 (progn
11943 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11944 nil (point-at-eol)))
11945 (get-text-property p 'org-todo-head))))
11946 ((not (member kwd org-todo-keywords-1))
11947 (car org-todo-keywords-1))
11948 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11950 (defun org-fast-todo-selection ()
11951 "Fast TODO keyword selection with single keys.
11952 Returns the new TODO keyword, or nil if no state change should occur."
11953 (let* ((fulltable org-todo-key-alist)
11954 (done-keywords org-done-keywords) ;; needed for the faces.
11955 (maxlen (apply 'max (mapcar
11956 (lambda (x)
11957 (if (stringp (car x)) (string-width (car x)) 0))
11958 fulltable)))
11959 (expert nil)
11960 (fwidth (+ maxlen 3 1 3))
11961 (ncol (/ (- (window-width) 4) fwidth))
11962 tg cnt e c tbl
11963 groups ingroup)
11964 (save-excursion
11965 (save-window-excursion
11966 (if expert
11967 (set-buffer (get-buffer-create " *Org todo*"))
11968 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11969 (erase-buffer)
11970 (org-set-local 'org-done-keywords done-keywords)
11971 (setq tbl fulltable cnt 0)
11972 (while (setq e (pop tbl))
11973 (cond
11974 ((equal e '(:startgroup))
11975 (push '() groups) (setq ingroup t)
11976 (when (not (= cnt 0))
11977 (setq cnt 0)
11978 (insert "\n"))
11979 (insert "{ "))
11980 ((equal e '(:endgroup))
11981 (setq ingroup nil cnt 0)
11982 (insert "}\n"))
11983 ((equal e '(:newline))
11984 (when (not (= cnt 0))
11985 (setq cnt 0)
11986 (insert "\n")
11987 (setq e (car tbl))
11988 (while (equal (car tbl) '(:newline))
11989 (insert "\n")
11990 (setq tbl (cdr tbl)))))
11992 (setq tg (car e) c (cdr e))
11993 (if ingroup (push tg (car groups)))
11994 (setq tg (org-add-props tg nil 'face
11995 (org-get-todo-face tg)))
11996 (if (and (= cnt 0) (not ingroup)) (insert " "))
11997 (insert "[" c "] " tg (make-string
11998 (- fwidth 4 (length tg)) ?\ ))
11999 (when (= (setq cnt (1+ cnt)) ncol)
12000 (insert "\n")
12001 (if ingroup (insert " "))
12002 (setq cnt 0)))))
12003 (insert "\n")
12004 (goto-char (point-min))
12005 (if (not expert) (org-fit-window-to-buffer))
12006 (message "[a-z..]:Set [SPC]:clear")
12007 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12008 (cond
12009 ((or (= c ?\C-g)
12010 (and (= c ?q) (not (rassoc c fulltable))))
12011 (setq quit-flag t))
12012 ((= c ?\ ) nil)
12013 ((setq e (rassoc c fulltable) tg (car e))
12015 (t (setq quit-flag t)))))))
12017 (defun org-entry-is-todo-p ()
12018 (member (org-get-todo-state) org-not-done-keywords))
12020 (defun org-entry-is-done-p ()
12021 (member (org-get-todo-state) org-done-keywords))
12023 (defun org-get-todo-state ()
12024 (save-excursion
12025 (org-back-to-heading t)
12026 (and (looking-at org-todo-line-regexp)
12027 (match-end 2)
12028 (match-string 2))))
12030 (defun org-at-date-range-p (&optional inactive-ok)
12031 "Is the cursor inside a date range?"
12032 (interactive)
12033 (save-excursion
12034 (catch 'exit
12035 (let ((pos (point)))
12036 (skip-chars-backward "^[<\r\n")
12037 (skip-chars-backward "<[")
12038 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12039 (>= (match-end 0) pos)
12040 (throw 'exit t))
12041 (skip-chars-backward "^<[\r\n")
12042 (skip-chars-backward "<[")
12043 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12044 (>= (match-end 0) pos)
12045 (throw 'exit t)))
12046 nil)))
12048 (defun org-get-repeat (&optional tagline)
12049 "Check if there is a deadline/schedule with repeater in this entry."
12050 (save-match-data
12051 (save-excursion
12052 (org-back-to-heading t)
12053 (and (re-search-forward (if tagline
12054 (concat tagline "\\s-*" org-repeat-re)
12055 org-repeat-re)
12056 (org-entry-end-position) t)
12057 (match-string-no-properties 1)))))
12059 (defvar org-last-changed-timestamp)
12060 (defvar org-last-inserted-timestamp)
12061 (defvar org-log-post-message)
12062 (defvar org-log-note-purpose)
12063 (defvar org-log-note-how)
12064 (defvar org-log-note-extra)
12065 (defun org-auto-repeat-maybe (done-word)
12066 "Check if the current headline contains a repeated deadline/schedule.
12067 If yes, set TODO state back to what it was and change the base date
12068 of repeating deadline/scheduled time stamps to new date.
12069 This function is run automatically after each state change to a DONE state."
12070 ;; last-state is dynamically scoped into this function
12071 (let* ((repeat (org-get-repeat))
12072 (aa (assoc org-last-state org-todo-kwd-alist))
12073 (interpret (nth 1 aa))
12074 (head (nth 2 aa))
12075 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12076 (msg "Entry repeats: ")
12077 (org-log-done nil)
12078 (org-todo-log-states nil)
12079 re type n what ts time to-state)
12080 (when repeat
12081 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12082 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12083 org-todo-repeat-to-state))
12084 (unless (and to-state (member to-state org-todo-keywords-1))
12085 (setq to-state (if (eq interpret 'type) org-last-state head)))
12086 (org-todo to-state)
12087 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12088 (org-entry-put nil "LAST_REPEAT" (format-time-string
12089 (org-time-stamp-format t t))))
12090 (when org-log-repeat
12091 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12092 (memq 'org-add-log-note post-command-hook))
12093 ;; OK, we are already setup for some record
12094 (if (eq org-log-repeat 'note)
12095 ;; make sure we take a note, not only a time stamp
12096 (setq org-log-note-how 'note))
12097 ;; Set up for taking a record
12098 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12099 org-last-state
12100 'findpos org-log-repeat)))
12101 (org-back-to-heading t)
12102 (org-add-planning-info nil nil 'closed)
12103 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12104 org-deadline-time-regexp "\\)\\|\\("
12105 org-ts-regexp "\\)"))
12106 (while (re-search-forward
12107 re (save-excursion (outline-next-heading) (point)) t)
12108 (setq type (if (match-end 1) org-scheduled-string
12109 (if (match-end 3) org-deadline-string "Plain:"))
12110 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12111 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12112 (setq n (string-to-number (match-string 2 ts))
12113 what (match-string 3 ts))
12114 (if (equal what "w") (setq n (* n 7) what "d"))
12115 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12116 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12117 ;; Preparation, see if we need to modify the start date for the change
12118 (when (match-end 1)
12119 (setq time (save-match-data (org-time-string-to-time ts)))
12120 (cond
12121 ((equal (match-string 1 ts) ".")
12122 ;; Shift starting date to today
12123 (org-timestamp-change
12124 (- (org-today) (time-to-days time))
12125 'day))
12126 ((equal (match-string 1 ts) "+")
12127 (let ((nshiftmax 10) (nshift 0))
12128 (while (or (= nshift 0)
12129 (<= (time-to-days time)
12130 (time-to-days (current-time))))
12131 (when (= (incf nshift) nshiftmax)
12132 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12133 (error "Abort")))
12134 (org-timestamp-change n (cdr (assoc what whata)))
12135 (org-at-timestamp-p t)
12136 (setq ts (match-string 1))
12137 (setq time (save-match-data (org-time-string-to-time ts)))))
12138 (org-timestamp-change (- n) (cdr (assoc what whata)))
12139 ;; rematch, so that we have everything in place for the real shift
12140 (org-at-timestamp-p t)
12141 (setq ts (match-string 1))
12142 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12143 (org-timestamp-change n (cdr (assoc what whata)))
12144 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12145 (setq org-log-post-message msg)
12146 (message "%s" msg))))
12148 (defun org-show-todo-tree (arg)
12149 "Make a compact tree which shows all headlines marked with TODO.
12150 The tree will show the lines where the regexp matches, and all higher
12151 headlines above the match.
12152 With a \\[universal-argument] prefix, prompt for a regexp to match.
12153 With a numeric prefix N, construct a sparse tree for the Nth element
12154 of `org-todo-keywords-1'."
12155 (interactive "P")
12156 (let ((case-fold-search nil)
12157 (kwd-re
12158 (cond ((null arg) org-not-done-regexp)
12159 ((equal arg '(4))
12160 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12161 (mapcar 'list org-todo-keywords-1))))
12162 (concat "\\("
12163 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12164 "\\)\\>")))
12165 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12166 (regexp-quote (nth (1- (prefix-numeric-value arg))
12167 org-todo-keywords-1)))
12168 (t (error "Invalid prefix argument: %s" arg)))))
12169 (message "%d TODO entries found"
12170 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12172 (defun org-deadline (&optional remove time)
12173 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12174 With argument REMOVE, remove any deadline from the item.
12175 With argument TIME, set the deadline at the corresponding date. TIME
12176 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12177 (interactive "P")
12178 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12179 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12180 'region-start-level 'region))
12181 org-loop-over-headlines-in-active-region)
12182 (org-map-entries
12183 `(org-deadline ',remove ,time)
12184 org-loop-over-headlines-in-active-region
12185 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12186 (let* ((old-date (org-entry-get nil "DEADLINE"))
12187 (repeater (and old-date
12188 (string-match
12189 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12190 old-date)
12191 (match-string 1 old-date))))
12192 (if remove
12193 (progn
12194 (when (and old-date org-log-redeadline)
12195 (org-add-log-setup 'deldeadline nil old-date 'findpos
12196 org-log-redeadline))
12197 (org-remove-timestamp-with-keyword org-deadline-string)
12198 (message "Item no longer has a deadline."))
12199 (org-add-planning-info 'deadline time 'closed)
12200 (when (and old-date org-log-redeadline
12201 (not (equal old-date
12202 (substring org-last-inserted-timestamp 1 -1))))
12203 (org-add-log-setup 'redeadline nil old-date 'findpos
12204 org-log-redeadline))
12205 (when repeater
12206 (save-excursion
12207 (org-back-to-heading t)
12208 (when (re-search-forward (concat org-deadline-string " "
12209 org-last-inserted-timestamp)
12210 (save-excursion
12211 (outline-next-heading) (point)) t)
12212 (goto-char (1- (match-end 0)))
12213 (insert " " repeater)
12214 (setq org-last-inserted-timestamp
12215 (concat (substring org-last-inserted-timestamp 0 -1)
12216 " " repeater
12217 (substring org-last-inserted-timestamp -1))))))
12218 (message "Deadline on %s" org-last-inserted-timestamp)))))
12220 (defun org-schedule (&optional remove time)
12221 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12222 With argument REMOVE, remove any scheduling date from the item.
12223 With argument TIME, scheduled at the corresponding date. TIME can
12224 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12225 (interactive "P")
12226 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12227 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12228 'region-start-level 'region))
12229 org-loop-over-headlines-in-active-region)
12230 (org-map-entries
12231 `(org-schedule ',remove ,time)
12232 org-loop-over-headlines-in-active-region
12233 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12234 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12235 (repeater (and old-date
12236 (string-match
12237 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12238 old-date)
12239 (match-string 1 old-date))))
12240 (if remove
12241 (progn
12242 (when (and old-date org-log-reschedule)
12243 (org-add-log-setup 'delschedule nil old-date 'findpos
12244 org-log-reschedule))
12245 (org-remove-timestamp-with-keyword org-scheduled-string)
12246 (message "Item is no longer scheduled."))
12247 (org-add-planning-info 'scheduled time 'closed)
12248 (when (and old-date org-log-reschedule
12249 (not (equal old-date
12250 (substring org-last-inserted-timestamp 1 -1))))
12251 (org-add-log-setup 'reschedule nil old-date 'findpos
12252 org-log-reschedule))
12253 (when repeater
12254 (save-excursion
12255 (org-back-to-heading t)
12256 (when (re-search-forward (concat org-scheduled-string " "
12257 org-last-inserted-timestamp)
12258 (save-excursion
12259 (outline-next-heading) (point)) t)
12260 (goto-char (1- (match-end 0)))
12261 (insert " " repeater)
12262 (setq org-last-inserted-timestamp
12263 (concat (substring org-last-inserted-timestamp 0 -1)
12264 " " repeater
12265 (substring org-last-inserted-timestamp -1))))))
12266 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12268 (defun org-get-scheduled-time (pom &optional inherit)
12269 "Get the scheduled time as a time tuple, of a format suitable
12270 for calling org-schedule with, or if there is no scheduling,
12271 returns nil."
12272 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12273 (when time
12274 (apply 'encode-time (org-parse-time-string time)))))
12276 (defun org-get-deadline-time (pom &optional inherit)
12277 "Get the deadline as a time tuple, of a format suitable for
12278 calling org-deadline with, or if there is no scheduling, returns
12279 nil."
12280 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12281 (when time
12282 (apply 'encode-time (org-parse-time-string time)))))
12284 (defun org-remove-timestamp-with-keyword (keyword)
12285 "Remove all time stamps with KEYWORD in the current entry."
12286 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12287 beg)
12288 (save-excursion
12289 (org-back-to-heading t)
12290 (setq beg (point))
12291 (outline-next-heading)
12292 (while (re-search-backward re beg t)
12293 (replace-match "")
12294 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12295 (equal (char-before) ?\ ))
12296 (backward-delete-char 1)
12297 (if (string-match "^[ \t]*$" (buffer-substring
12298 (point-at-bol) (point-at-eol)))
12299 (delete-region (point-at-bol)
12300 (min (point-max) (1+ (point-at-eol))))))))))
12302 (defun org-add-planning-info (what &optional time &rest remove)
12303 "Insert new timestamp with keyword in the line directly after the headline.
12304 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12305 If non is given, the user is prompted for a date.
12306 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12307 be removed."
12308 (interactive)
12309 (let (org-time-was-given org-end-time-was-given ts
12310 end default-time default-input)
12312 (catch 'exit
12313 (when (and (memq what '(scheduled deadline))
12314 (or (not time)
12315 (and (stringp time)
12316 (string-match "^[-+]+[0-9]" time))))
12317 ;; Try to get a default date/time from existing timestamp
12318 (save-excursion
12319 (org-back-to-heading t)
12320 (setq end (save-excursion (outline-next-heading) (point)))
12321 (when (re-search-forward (if (eq what 'scheduled)
12322 org-scheduled-time-regexp
12323 org-deadline-time-regexp)
12324 end t)
12325 (setq ts (match-string 1)
12326 default-time
12327 (apply 'encode-time (org-parse-time-string ts))
12328 default-input (and ts (org-get-compact-tod ts))))))
12329 (when what
12330 (setq time
12331 (if (stringp time)
12332 ;; This is a string (relative or absolute), set proper date
12333 (apply 'encode-time
12334 (org-read-date-analyze
12335 time default-time (decode-time default-time)))
12336 ;; If necessary, get the time from the user
12337 (or time (org-read-date nil 'to-time nil nil
12338 default-time default-input)))))
12340 (when (and org-insert-labeled-timestamps-at-point
12341 (member what '(scheduled deadline)))
12342 (insert
12343 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12344 (org-insert-time-stamp time org-time-was-given
12345 nil nil nil (list org-end-time-was-given))
12346 (setq what nil))
12347 (save-excursion
12348 (save-restriction
12349 (let (col list elt ts buffer-invisibility-spec)
12350 (org-back-to-heading t)
12351 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12352 (goto-char (match-end 1))
12353 (setq col (current-column))
12354 (goto-char (match-end 0))
12355 (if (eobp) (insert "\n") (forward-char 1))
12356 (when (and (not what)
12357 (not (looking-at
12358 (concat "[ \t]*"
12359 org-keyword-time-not-clock-regexp))))
12360 ;; Nothing to add, nothing to remove...... :-)
12361 (throw 'exit nil))
12362 (if (and (not (looking-at org-outline-regexp))
12363 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12364 "[^\r\n]*"))
12365 (not (equal (match-string 1) org-clock-string)))
12366 (narrow-to-region (match-beginning 0) (match-end 0))
12367 (insert-before-markers "\n")
12368 (backward-char 1)
12369 (narrow-to-region (point) (point))
12370 (and org-adapt-indentation (org-indent-to-column col)))
12371 ;; Check if we have to remove something.
12372 (setq list (cons what remove))
12373 (while list
12374 (setq elt (pop list))
12375 (when (or (and (eq elt 'scheduled)
12376 (re-search-forward org-scheduled-time-regexp nil t))
12377 (and (eq elt 'deadline)
12378 (re-search-forward org-deadline-time-regexp nil t))
12379 (and (eq elt 'closed)
12380 (re-search-forward org-closed-time-regexp nil t)))
12381 (replace-match "")
12382 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12383 (and (looking-at "[ \t]+") (replace-match ""))
12384 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12385 (when what
12386 (insert
12387 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12388 (cond ((eq what 'scheduled) org-scheduled-string)
12389 ((eq what 'deadline) org-deadline-string)
12390 ((eq what 'closed) org-closed-string))
12391 " ")
12392 (setq ts (org-insert-time-stamp
12393 time
12394 (or org-time-was-given
12395 (and (eq what 'closed) org-log-done-with-time))
12396 (eq what 'closed)
12397 nil nil (list org-end-time-was-given)))
12398 (insert
12399 (if (not (or (bolp) (eq (char-before) ?\ )
12400 (memq (char-after) '(32 10))
12401 (eobp))) " " ""))
12402 (end-of-line 1))
12403 (goto-char (point-min))
12404 (widen)
12405 (if (and (looking-at "[ \t]*\n")
12406 (equal (char-before) ?\n))
12407 (delete-region (1- (point)) (point-at-eol)))
12408 ts))))))
12410 (defvar org-log-note-marker (make-marker))
12411 (defvar org-log-note-purpose nil)
12412 (defvar org-log-note-state nil)
12413 (defvar org-log-note-previous-state nil)
12414 (defvar org-log-note-how nil)
12415 (defvar org-log-note-extra nil)
12416 (defvar org-log-note-window-configuration nil)
12417 (defvar org-log-note-return-to (make-marker))
12418 (defvar org-log-note-effective-time nil
12419 "Remembered current time so that dynamically scoped
12420 `org-extend-today-until' affects tha timestamps in state change
12421 log")
12423 (defvar org-log-post-message nil
12424 "Message to be displayed after a log note has been stored.
12425 The auto-repeater uses this.")
12427 (defun org-add-note ()
12428 "Add a note to the current entry.
12429 This is done in the same way as adding a state change note."
12430 (interactive)
12431 (org-add-log-setup 'note nil nil 'findpos nil))
12433 (defvar org-property-end-re)
12434 (defun org-add-log-setup (&optional purpose state prev-state
12435 findpos how extra)
12436 "Set up the post command hook to take a note.
12437 If this is about to TODO state change, the new state is expected in STATE.
12438 When FINDPOS is non-nil, find the correct position for the note in
12439 the current entry. If not, assume that it can be inserted at point.
12440 HOW is an indicator what kind of note should be created.
12441 EXTRA is additional text that will be inserted into the notes buffer."
12442 (let* ((org-log-into-drawer (org-log-into-drawer))
12443 (drawer (cond ((stringp org-log-into-drawer)
12444 org-log-into-drawer)
12445 (org-log-into-drawer "LOGBOOK"))))
12446 (save-restriction
12447 (save-excursion
12448 (when findpos
12449 (org-back-to-heading t)
12450 (narrow-to-region (point) (save-excursion
12451 (outline-next-heading) (point)))
12452 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12453 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12454 "[^\r\n]*\\)?"))
12455 (goto-char (match-end 0))
12456 (cond
12457 (drawer
12458 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12459 nil t)
12460 (progn
12461 (goto-char (match-end 0))
12462 (or org-log-states-order-reversed
12463 (and (re-search-forward org-property-end-re nil t)
12464 (goto-char (1- (match-beginning 0))))))
12465 (insert "\n:" drawer ":\n:END:")
12466 (beginning-of-line 0)
12467 (org-indent-line)
12468 (beginning-of-line 2)
12469 (org-indent-line)
12470 (end-of-line 0)))
12471 ((and org-log-state-notes-insert-after-drawers
12472 (save-excursion
12473 (forward-line) (looking-at org-drawer-regexp)))
12474 (forward-line)
12475 (while (looking-at org-drawer-regexp)
12476 (goto-char (match-end 0))
12477 (re-search-forward org-property-end-re (point-max) t)
12478 (forward-line))
12479 (forward-line -1)))
12480 (unless org-log-states-order-reversed
12481 (and (= (char-after) ?\n) (forward-char 1))
12482 (org-skip-over-state-notes)
12483 (skip-chars-backward " \t\n\r")))
12484 (move-marker org-log-note-marker (point))
12485 (setq org-log-note-purpose purpose
12486 org-log-note-state state
12487 org-log-note-previous-state prev-state
12488 org-log-note-how how
12489 org-log-note-extra extra
12490 org-log-note-effective-time (org-current-effective-time))
12491 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12493 (defun org-skip-over-state-notes ()
12494 "Skip past the list of State notes in an entry."
12495 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12496 (when (ignore-errors (goto-char (org-in-item-p)))
12497 (let* ((struct (org-list-struct))
12498 (prevs (org-list-prevs-alist struct)))
12499 (while (looking-at "[ \t]*- State")
12500 (goto-char (or (org-list-get-next-item (point) struct prevs)
12501 (org-list-get-item-end (point) struct)))))))
12503 (defun org-add-log-note (&optional purpose)
12504 "Pop up a window for taking a note, and add this note later at point."
12505 (remove-hook 'post-command-hook 'org-add-log-note)
12506 (setq org-log-note-window-configuration (current-window-configuration))
12507 (delete-other-windows)
12508 (move-marker org-log-note-return-to (point))
12509 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12510 (goto-char org-log-note-marker)
12511 (org-switch-to-buffer-other-window "*Org Note*")
12512 (erase-buffer)
12513 (if (memq org-log-note-how '(time state))
12514 (let (current-prefix-arg) (org-store-log-note))
12515 (let ((org-inhibit-startup t)) (org-mode))
12516 (insert (format "# Insert note for %s.
12517 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12518 (cond
12519 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12520 ((eq org-log-note-purpose 'done) "closed todo item")
12521 ((eq org-log-note-purpose 'state)
12522 (format "state change from \"%s\" to \"%s\""
12523 (or org-log-note-previous-state "")
12524 (or org-log-note-state "")))
12525 ((eq org-log-note-purpose 'reschedule)
12526 "rescheduling")
12527 ((eq org-log-note-purpose 'delschedule)
12528 "no longer scheduled")
12529 ((eq org-log-note-purpose 'redeadline)
12530 "changing deadline")
12531 ((eq org-log-note-purpose 'deldeadline)
12532 "removing deadline")
12533 ((eq org-log-note-purpose 'refile)
12534 "refiling")
12535 ((eq org-log-note-purpose 'note)
12536 "this entry")
12537 (t (error "This should not happen")))))
12538 (if org-log-note-extra (insert org-log-note-extra))
12539 (org-set-local 'org-finish-function 'org-store-log-note)
12540 (run-hooks 'org-log-buffer-setup-hook)))
12542 (defvar org-note-abort nil) ; dynamically scoped
12543 (defun org-store-log-note ()
12544 "Finish taking a log note, and insert it to where it belongs."
12545 (let ((txt (buffer-string))
12546 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12547 lines ind bul)
12548 (kill-buffer (current-buffer))
12549 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12550 (setq txt (replace-match "" t t txt)))
12551 (if (string-match "\\s-+\\'" txt)
12552 (setq txt (replace-match "" t t txt)))
12553 (setq lines (org-split-string txt "\n"))
12554 (when (and note (string-match "\\S-" note))
12555 (setq note
12556 (org-replace-escapes
12557 note
12558 (list (cons "%u" (user-login-name))
12559 (cons "%U" user-full-name)
12560 (cons "%t" (format-time-string
12561 (org-time-stamp-format 'long 'inactive)
12562 org-log-note-effective-time))
12563 (cons "%T" (format-time-string
12564 (org-time-stamp-format 'long nil)
12565 org-log-note-effective-time))
12566 (cons "%d" (format-time-string
12567 (org-time-stamp-format nil 'inactive)
12568 org-log-note-effective-time))
12569 (cons "%D" (format-time-string
12570 (org-time-stamp-format nil nil)
12571 org-log-note-effective-time))
12572 (cons "%s" (if org-log-note-state
12573 (concat "\"" org-log-note-state "\"")
12574 ""))
12575 (cons "%S" (if org-log-note-previous-state
12576 (concat "\"" org-log-note-previous-state "\"")
12577 "\"\"")))))
12578 (if lines (setq note (concat note " \\\\")))
12579 (push note lines))
12580 (when (or current-prefix-arg org-note-abort)
12581 (when org-log-into-drawer
12582 (org-remove-empty-drawer-at
12583 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12584 org-log-note-marker))
12585 (setq lines nil))
12586 (when lines
12587 (with-current-buffer (marker-buffer org-log-note-marker)
12588 (save-excursion
12589 (goto-char org-log-note-marker)
12590 (move-marker org-log-note-marker nil)
12591 (end-of-line 1)
12592 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12593 (setq ind (save-excursion
12594 (if (ignore-errors (goto-char (org-in-item-p)))
12595 (let ((struct (org-list-struct)))
12596 (org-list-get-ind
12597 (org-list-get-top-point struct) struct))
12598 (skip-chars-backward " \r\t\n")
12599 (cond
12600 ((and (org-at-heading-p)
12601 org-adapt-indentation)
12602 (1+ (org-current-level)))
12603 ((org-at-heading-p) 0)
12604 (t (org-get-indentation))))))
12605 (setq bul (org-list-bullet-string "-"))
12606 (org-indent-line-to ind)
12607 (insert bul (pop lines))
12608 (let ((ind-body (+ (length bul) ind)))
12609 (while lines
12610 (insert "\n")
12611 (org-indent-line-to ind-body)
12612 (insert (pop lines))))
12613 (message "Note stored")
12614 (org-back-to-heading t)
12615 (org-cycle-hide-drawers 'children)))))
12616 (set-window-configuration org-log-note-window-configuration)
12617 (with-current-buffer (marker-buffer org-log-note-return-to)
12618 (goto-char org-log-note-return-to))
12619 (move-marker org-log-note-return-to nil)
12620 (and org-log-post-message (message "%s" org-log-post-message)))
12622 (defun org-remove-empty-drawer-at (drawer pos)
12623 "Remove an empty drawer DRAWER at position POS.
12624 POS may also be a marker."
12625 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12626 (save-excursion
12627 (save-restriction
12628 (widen)
12629 (goto-char pos)
12630 (if (org-in-regexp
12631 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12632 (replace-match ""))))))
12634 (defvar org-ts-type nil)
12635 (defun org-sparse-tree (&optional arg type)
12636 "Create a sparse tree, prompt for the details.
12637 This command can create sparse trees. You first need to select the type
12638 of match used to create the tree:
12640 t Show all TODO entries.
12641 T Show entries with a specific TODO keyword.
12642 m Show entries selected by a tags/property match.
12643 p Enter a property name and its value (both with completion on existing
12644 names/values) and show entries with that property.
12645 r Show entries matching a regular expression (`/' can be used as well).
12646 b Show deadlines and scheduled items before a date.
12647 a Show deadlines and scheduled items after a date.
12648 d Show deadlines due within `org-deadline-warning-days'.
12649 D Show deadlines and scheduled items between a date range."
12650 (interactive "P")
12651 (let (ans kwd value ts-type)
12652 (setq type (or type org-sparse-tree-default-date-type))
12653 (setq org-ts-type type)
12654 (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"
12655 (cond ((eq type 'all) "all timestamps")
12656 ((eq type 'scheduled) "only scheduled")
12657 ((eq type 'deadline) "only deadline")
12658 ((eq type 'active) "only active timestamps")
12659 ((eq type 'inactive) "only inactive timestamps")
12660 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12661 (t "scheduled/deadline")))
12662 (setq ans (read-char-exclusive))
12663 (cond
12664 ((equal ans ?c)
12665 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12666 ((equal ans ?d)
12667 (call-interactively 'org-check-deadlines))
12668 ((equal ans ?b)
12669 (call-interactively 'org-check-before-date))
12670 ((equal ans ?a)
12671 (call-interactively 'org-check-after-date))
12672 ((equal ans ?D)
12673 (call-interactively 'org-check-dates-range))
12674 ((equal ans ?t)
12675 (call-interactively 'org-show-todo-tree))
12676 ((equal ans ?T)
12677 (org-show-todo-tree '(4)))
12678 ((member ans '(?T ?m))
12679 (call-interactively 'org-match-sparse-tree))
12680 ((member ans '(?p ?P))
12681 (setq kwd (org-icompleting-read "Property: "
12682 (mapcar 'list (org-buffer-property-keys))))
12683 (setq value (org-icompleting-read "Value: "
12684 (mapcar 'list (org-property-values kwd))))
12685 (unless (string-match "\\`{.*}\\'" value)
12686 (setq value (concat "\"" value "\"")))
12687 (org-match-sparse-tree arg (concat kwd "=" value)))
12688 ((member ans '(?r ?R ?/))
12689 (call-interactively 'org-occur))
12690 (t (error "No such sparse tree command \"%c\"" ans)))))
12692 (defvar org-occur-highlights nil
12693 "List of overlays used for occur matches.")
12694 (make-variable-buffer-local 'org-occur-highlights)
12695 (defvar org-occur-parameters nil
12696 "Parameters of the active org-occur calls.
12697 This is a list, each call to org-occur pushes as cons cell,
12698 containing the regular expression and the callback, onto the list.
12699 The list can contain several entries if `org-occur' has been called
12700 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12701 will only contain one set of parameters. When the highlights are
12702 removed (for example with `C-c C-c', or with the next edit (depending
12703 on `org-remove-highlights-with-change'), this variable is emptied
12704 as well.")
12705 (make-variable-buffer-local 'org-occur-parameters)
12707 (defun org-occur (regexp &optional keep-previous callback)
12708 "Make a compact tree which shows all matches of REGEXP.
12709 The tree will show the lines where the regexp matches, and all higher
12710 headlines above the match. It will also show the heading after the match,
12711 to make sure editing the matching entry is easy.
12712 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12713 call to `org-occur' will be kept, to allow stacking of calls to this
12714 command.
12715 If CALLBACK is non-nil, it is a function which is called to confirm
12716 that the match should indeed be shown."
12717 (interactive "sRegexp: \nP")
12718 (when (equal regexp "")
12719 (error "Regexp cannot be empty"))
12720 (unless keep-previous
12721 (org-remove-occur-highlights nil nil t))
12722 (push (cons regexp callback) org-occur-parameters)
12723 (let ((cnt 0))
12724 (save-excursion
12725 (goto-char (point-min))
12726 (if (or (not keep-previous) ; do not want to keep
12727 (not org-occur-highlights)) ; no previous matches
12728 ;; hide everything
12729 (org-overview))
12730 (while (re-search-forward regexp nil t)
12731 (when (or (not callback)
12732 (save-match-data (funcall callback)))
12733 (setq cnt (1+ cnt))
12734 (when org-highlight-sparse-tree-matches
12735 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12736 (org-show-context 'occur-tree))))
12737 (when org-remove-highlights-with-change
12738 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12739 nil 'local))
12740 (unless org-sparse-tree-open-archived-trees
12741 (org-hide-archived-subtrees (point-min) (point-max)))
12742 (run-hooks 'org-occur-hook)
12743 (if (org-called-interactively-p 'interactive)
12744 (message "%d match(es) for regexp %s" cnt regexp))
12745 cnt))
12747 (defun org-occur-next-match (&optional n reset)
12748 "Function for `next-error-function' to find sparse tree matches.
12749 N is the number of matches to move, when negative move backwards.
12750 RESET is entirely ignored - this function always goes back to the
12751 starting point when no match is found."
12752 (let* ((limit (if (< n 0) (point-min) (point-max)))
12753 (search-func (if (< n 0)
12754 'previous-single-char-property-change
12755 'next-single-char-property-change))
12756 (n (abs n))
12757 (pos (point))
12759 (catch 'exit
12760 (while (setq p1 (funcall search-func (point) 'org-type))
12761 (when (equal p1 limit)
12762 (goto-char pos)
12763 (error "No more matches"))
12764 (when (equal (get-char-property p1 'org-type) 'org-occur)
12765 (setq n (1- n))
12766 (when (= n 0)
12767 (goto-char p1)
12768 (throw 'exit (point))))
12769 (goto-char p1))
12770 (goto-char p1)
12771 (error "No more matches"))))
12773 (defun org-show-context (&optional key)
12774 "Make sure point and context are visible.
12775 How much context is shown depends upon the variables
12776 `org-show-hierarchy-above', `org-show-following-heading',
12777 `org-show-entry-below' and `org-show-siblings'."
12778 (let ((heading-p (org-at-heading-p t))
12779 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12780 (following-p (org-get-alist-option org-show-following-heading key))
12781 (entry-p (org-get-alist-option org-show-entry-below key))
12782 (siblings-p (org-get-alist-option org-show-siblings key)))
12783 (catch 'exit
12784 ;; Show heading or entry text
12785 (if (and heading-p (not entry-p))
12786 (org-flag-heading nil) ; only show the heading
12787 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12788 (org-show-hidden-entry))) ; show entire entry
12789 (when following-p
12790 ;; Show next sibling, or heading below text
12791 (save-excursion
12792 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12793 (org-flag-heading nil))))
12794 (when siblings-p (org-show-siblings))
12795 (when hierarchy-p
12796 ;; show all higher headings, possibly with siblings
12797 (save-excursion
12798 (while (and (condition-case nil
12799 (progn (org-up-heading-all 1) t)
12800 (error nil))
12801 (not (bobp)))
12802 (org-flag-heading nil)
12803 (when siblings-p (org-show-siblings))))))))
12805 (defvar org-reveal-start-hook nil
12806 "Hook run before revealing a location.")
12808 (defun org-reveal (&optional siblings)
12809 "Show current entry, hierarchy above it, and the following headline.
12810 This can be used to show a consistent set of context around locations
12811 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12812 not t for the search context.
12814 With optional argument SIBLINGS, on each level of the hierarchy all
12815 siblings are shown. This repairs the tree structure to what it would
12816 look like when opened with hierarchical calls to `org-cycle'.
12817 With double optional argument \\[universal-argument] \\[universal-argument], \
12818 go to the parent and show the
12819 entire tree."
12820 (interactive "P")
12821 (run-hooks 'org-reveal-start-hook)
12822 (let ((org-show-hierarchy-above t)
12823 (org-show-following-heading t)
12824 (org-show-siblings (if siblings t org-show-siblings)))
12825 (org-show-context nil))
12826 (when (equal siblings '(16))
12827 (save-excursion
12828 (when (org-up-heading-safe)
12829 (org-show-subtree)
12830 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12832 (defun org-highlight-new-match (beg end)
12833 "Highlight from BEG to END and mark the highlight is an occur headline."
12834 (let ((ov (make-overlay beg end)))
12835 (overlay-put ov 'face 'secondary-selection)
12836 (overlay-put ov 'org-type 'org-occur)
12837 (push ov org-occur-highlights)))
12839 (defun org-remove-occur-highlights (&optional beg end noremove)
12840 "Remove the occur highlights from the buffer.
12841 BEG and END are ignored. If NOREMOVE is nil, remove this function
12842 from the `before-change-functions' in the current buffer."
12843 (interactive)
12844 (unless org-inhibit-highlight-removal
12845 (mapc 'delete-overlay org-occur-highlights)
12846 (setq org-occur-highlights nil)
12847 (setq org-occur-parameters nil)
12848 (unless noremove
12849 (remove-hook 'before-change-functions
12850 'org-remove-occur-highlights 'local))))
12852 ;;;; Priorities
12854 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12855 "Regular expression matching the priority indicator.")
12857 (defvar org-remove-priority-next-time nil)
12859 (defun org-priority-up ()
12860 "Increase the priority of the current item."
12861 (interactive)
12862 (org-priority 'up))
12864 (defun org-priority-down ()
12865 "Decrease the priority of the current item."
12866 (interactive)
12867 (org-priority 'down))
12869 (defun org-priority (&optional action show)
12870 "Change the priority of an item.
12871 ACTION can be `set', `up', `down', or a character."
12872 (interactive "P")
12873 (if (equal action '(4))
12874 (org-show-priority)
12875 (unless org-enable-priority-commands
12876 (error "Priority commands are disabled"))
12877 (setq action (or action 'set))
12878 (let (current new news have remove)
12879 (save-excursion
12880 (org-back-to-heading t)
12881 (if (looking-at org-priority-regexp)
12882 (setq current (string-to-char (match-string 2))
12883 have t))
12884 (cond
12885 ((eq action 'remove)
12886 (setq remove t new ?\ ))
12887 ((or (eq action 'set)
12888 (if (featurep 'xemacs) (characterp action) (integerp action)))
12889 (if (not (eq action 'set))
12890 (setq new action)
12891 (message "Priority %c-%c, SPC to remove: "
12892 org-highest-priority org-lowest-priority)
12893 (save-match-data
12894 (setq new (read-char-exclusive))))
12895 (if (and (= (upcase org-highest-priority) org-highest-priority)
12896 (= (upcase org-lowest-priority) org-lowest-priority))
12897 (setq new (upcase new)))
12898 (cond ((equal new ?\ ) (setq remove t))
12899 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12900 (error "Priority must be between `%c' and `%c'"
12901 org-highest-priority org-lowest-priority))))
12902 ((eq action 'up)
12903 (setq new (if have
12904 (1- current) ; normal cycling
12905 ;; last priority was empty
12906 (if (eq last-command this-command)
12907 org-lowest-priority ; wrap around empty to lowest
12908 ;; default
12909 (if org-priority-start-cycle-with-default
12910 org-default-priority
12911 (1- org-default-priority))))))
12912 ((eq action 'down)
12913 (setq new (if have
12914 (1+ current) ; normal cycling
12915 ;; last priority was empty
12916 (if (eq last-command this-command)
12917 org-highest-priority ; wrap around empty to highest
12918 ;; default
12919 (if org-priority-start-cycle-with-default
12920 org-default-priority
12921 (1+ org-default-priority))))))
12922 (t (error "Invalid action")))
12923 (if (or (< (upcase new) org-highest-priority)
12924 (> (upcase new) org-lowest-priority))
12925 (if (and (memq action '(up down))
12926 (not have) (not (eq last-command this-command)))
12927 ;; `new' is from default priority
12928 (error
12929 "The default can not be set, see `org-default-priority' why")
12930 ;; normal cycling: `new' is beyond highest/lowest priority
12931 ;; and is wrapped around to the empty priority
12932 (setq remove t)))
12933 (setq news (format "%c" new))
12934 (if have
12935 (if remove
12936 (replace-match "" t t nil 1)
12937 (replace-match news t t nil 2))
12938 (if remove
12939 (error "No priority cookie found in line")
12940 (let ((case-fold-search nil))
12941 (looking-at org-todo-line-regexp))
12942 (if (match-end 2)
12943 (progn
12944 (goto-char (match-end 2))
12945 (insert " [#" news "]"))
12946 (goto-char (match-beginning 3))
12947 (insert "[#" news "] "))))
12948 (org-preserve-lc (org-set-tags nil 'align)))
12949 (if remove
12950 (message "Priority removed")
12951 (message "Priority of current item set to %s" news)))))
12953 (defun org-show-priority ()
12954 "Show the priority of the current item.
12955 This priority is composed of the main priority given with the [#A] cookies,
12956 and by additional input from the age of a schedules or deadline entry."
12957 (interactive)
12958 (let ((pri (if (eq major-mode 'org-agenda-mode)
12959 (org-get-at-bol 'priority)
12960 (save-excursion
12961 (save-match-data
12962 (beginning-of-line)
12963 (and (looking-at org-heading-regexp)
12964 (org-get-priority (match-string 0))))))))
12965 (message "Priority is %d" (if pri pri -1000))))
12967 (defun org-get-priority (s)
12968 "Find priority cookie and return priority."
12969 (if (functionp org-get-priority-function)
12970 (funcall org-get-priority-function)
12971 (save-match-data
12972 (if (not (string-match org-priority-regexp s))
12973 (* 1000 (- org-lowest-priority org-default-priority))
12974 (* 1000 (- org-lowest-priority
12975 (string-to-char (match-string 2 s))))))))
12977 ;;;; Tags
12979 (defvar org-agenda-archives-mode)
12980 (defvar org-map-continue-from nil
12981 "Position from where mapping should continue.
12982 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12984 (defvar org-scanner-tags nil
12985 "The current tag list while the tags scanner is running.")
12986 (defvar org-trust-scanner-tags nil
12987 "Should `org-get-tags-at' use the tags for the scanner.
12988 This is for internal dynamical scoping only.
12989 When this is non-nil, the function `org-get-tags-at' will return the value
12990 of `org-scanner-tags' instead of building the list by itself. This
12991 can lead to large speed-ups when the tags scanner is used in a file with
12992 many entries, and when the list of tags is retrieved, for example to
12993 obtain a list of properties. Building the tags list for each entry in such
12994 a file becomes an N^2 operation - but with this variable set, it scales
12995 as N.")
12997 (defun org-scan-tags (action matcher todo-only &optional start-level)
12998 "Scan headline tags with inheritance and produce output ACTION.
13000 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13001 or `agenda' to produce an entry list for an agenda view. It can also be
13002 a Lisp form or a function that should be called at each matched headline, in
13003 this case the return value is a list of all return values from these calls.
13005 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13006 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13007 only lines with a not-done TODO keyword are included in the output.
13008 This should be the same variable that was scoped into
13009 and set by `org-make-tags-matcher' when it constructed MATCHER.
13011 START-LEVEL can be a string with asterisks, reducing the scope to
13012 headlines matching this string."
13013 (require 'org-agenda)
13014 (let* ((re (concat "^"
13015 (if start-level
13016 ;; Get the correct level to match
13017 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13018 org-outline-regexp)
13019 " *\\(\\<\\("
13020 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13021 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13022 (props (list 'face 'default
13023 'done-face 'org-agenda-done
13024 'undone-face 'default
13025 'mouse-face 'highlight
13026 'org-not-done-regexp org-not-done-regexp
13027 'org-todo-regexp org-todo-regexp
13028 'org-complex-heading-regexp org-complex-heading-regexp
13029 'help-echo
13030 (format "mouse-2 or RET jump to org file %s"
13031 (abbreviate-file-name
13032 (or (buffer-file-name (buffer-base-buffer))
13033 (buffer-name (buffer-base-buffer)))))))
13034 (case-fold-search nil)
13035 (org-map-continue-from nil)
13036 lspos tags tags-list
13037 (tags-alist (list (cons 0 org-file-tags)))
13038 (llast 0) rtn rtn1 level category i txt
13039 todo marker entry priority)
13040 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13041 (setq action (list 'lambda nil action)))
13042 (save-excursion
13043 (goto-char (point-min))
13044 (when (eq action 'sparse-tree)
13045 (org-overview)
13046 (org-remove-occur-highlights))
13047 (while (re-search-forward re nil t)
13048 (setq org-map-continue-from nil)
13049 (catch :skip
13050 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13051 tags (if (match-end 4) (org-match-string-no-properties 4)))
13052 (goto-char (setq lspos (match-beginning 0)))
13053 (setq level (org-reduced-level (funcall outline-level))
13054 category (org-get-category))
13055 (setq i llast llast level)
13056 ;; remove tag lists from same and sublevels
13057 (while (>= i level)
13058 (when (setq entry (assoc i tags-alist))
13059 (setq tags-alist (delete entry tags-alist)))
13060 (setq i (1- i)))
13061 ;; add the next tags
13062 (when tags
13063 (setq tags (org-split-string tags ":")
13064 tags-alist
13065 (cons (cons level tags) tags-alist)))
13066 ;; compile tags for current headline
13067 (setq tags-list
13068 (if org-use-tag-inheritance
13069 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13070 tags)
13071 org-scanner-tags tags-list)
13072 (when org-use-tag-inheritance
13073 (setcdr (car tags-alist)
13074 (mapcar (lambda (x)
13075 (setq x (copy-sequence x))
13076 (org-add-prop-inherited x))
13077 (cdar tags-alist))))
13078 (when (and tags org-use-tag-inheritance
13079 (or (not (eq t org-use-tag-inheritance))
13080 org-tags-exclude-from-inheritance))
13081 ;; selective inheritance, remove uninherited ones
13082 (setcdr (car tags-alist)
13083 (org-remove-uninherited-tags (cdar tags-alist))))
13084 (when (and
13086 ;; eval matcher only when the todo condition is OK
13087 (and (or (not todo-only) (member todo org-not-done-keywords))
13088 (let ((case-fold-search t) (org-trust-scanner-tags t))
13089 (eval matcher)))
13091 ;; Call the skipper, but return t if it does not skip,
13092 ;; so that the `and' form continues evaluating
13093 (progn
13094 (unless (eq action 'sparse-tree) (org-agenda-skip))
13097 ;; Check if timestamps are deselecting this entry
13098 (or (not todo-only)
13099 (and (member todo org-not-done-keywords)
13100 (or (not org-agenda-tags-todo-honor-ignore-options)
13101 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13103 ;; Extra check for the archive tag
13104 ;; FIXME: Does the skipper already do this????
13106 (not (member org-archive-tag tags-list))
13107 ;; we have an archive tag, should we use this anyway?
13108 (or (not org-agenda-skip-archived-trees)
13109 (and (eq action 'agenda) org-agenda-archives-mode))))
13111 ;; select this headline
13113 (cond
13114 ((eq action 'sparse-tree)
13115 (and org-highlight-sparse-tree-matches
13116 (org-get-heading) (match-end 0)
13117 (org-highlight-new-match
13118 (match-beginning 1) (match-end 1)))
13119 (org-show-context 'tags-tree))
13120 ((eq action 'agenda)
13121 (setq txt (org-agenda-format-item
13123 (concat
13124 (if (eq org-tags-match-list-sublevels 'indented)
13125 (make-string (1- level) ?.) "")
13126 (org-get-heading))
13127 category
13128 tags-list)
13129 priority (org-get-priority txt))
13130 (goto-char lspos)
13131 (setq marker (org-agenda-new-marker))
13132 (org-add-props txt props
13133 'org-marker marker 'org-hd-marker marker 'org-category category
13134 'todo-state todo
13135 'priority priority 'type "tagsmatch")
13136 (push txt rtn))
13137 ((functionp action)
13138 (setq org-map-continue-from nil)
13139 (save-excursion
13140 (setq rtn1 (funcall action))
13141 (push rtn1 rtn)))
13142 (t (error "Invalid action")))
13144 ;; if we are to skip sublevels, jump to end of subtree
13145 (unless org-tags-match-list-sublevels
13146 (org-end-of-subtree t)
13147 (backward-char 1))))
13148 ;; Get the correct position from where to continue
13149 (if org-map-continue-from
13150 (goto-char org-map-continue-from)
13151 (and (= (point) lspos) (end-of-line 1)))))
13152 (when (and (eq action 'sparse-tree)
13153 (not org-sparse-tree-open-archived-trees))
13154 (org-hide-archived-subtrees (point-min) (point-max)))
13155 (nreverse rtn)))
13157 (defun org-remove-uninherited-tags (tags)
13158 "Remove all tags that are not inherited from the list TAGS."
13159 (cond
13160 ((eq org-use-tag-inheritance t)
13161 (if org-tags-exclude-from-inheritance
13162 (org-delete-all org-tags-exclude-from-inheritance tags)
13163 tags))
13164 ((not org-use-tag-inheritance) nil)
13165 ((stringp org-use-tag-inheritance)
13166 (delq nil (mapcar
13167 (lambda (x)
13168 (if (and (string-match org-use-tag-inheritance x)
13169 (not (member x org-tags-exclude-from-inheritance)))
13170 x nil))
13171 tags)))
13172 ((listp org-use-tag-inheritance)
13173 (delq nil (mapcar
13174 (lambda (x)
13175 (if (member x org-use-tag-inheritance) x nil))
13176 tags)))))
13178 (defun org-match-sparse-tree (&optional todo-only match)
13179 "Create a sparse tree according to tags string MATCH.
13180 MATCH can contain positive and negative selection of tags, like
13181 \"+WORK+URGENT-WITHBOSS\".
13182 If optional argument TODO-ONLY is non-nil, only select lines that are
13183 also TODO lines."
13184 (interactive "P")
13185 (org-agenda-prepare-buffers (list (current-buffer)))
13186 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13188 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13190 (defvar org-cached-props nil)
13191 (defun org-cached-entry-get (pom property)
13192 (if (or (eq t org-use-property-inheritance)
13193 (and (stringp org-use-property-inheritance)
13194 (string-match org-use-property-inheritance property))
13195 (and (listp org-use-property-inheritance)
13196 (member property org-use-property-inheritance)))
13197 ;; Caching is not possible, check it directly
13198 (org-entry-get pom property 'inherit)
13199 ;; Get all properties, so that we can do complicated checks easily
13200 (cdr (assoc property (or org-cached-props
13201 (setq org-cached-props
13202 (org-entry-properties pom)))))))
13204 (defun org-global-tags-completion-table (&optional files)
13205 "Return the list of all tags in all agenda buffer/files.
13206 Optional FILES argument is a list of files which can be used
13207 instead of the agenda files."
13208 (save-excursion
13209 (org-uniquify
13210 (delq nil
13211 (apply 'append
13212 (mapcar
13213 (lambda (file)
13214 (set-buffer (find-file-noselect file))
13215 (append (org-get-buffer-tags)
13216 (mapcar (lambda (x) (if (stringp (car-safe x))
13217 (list (car-safe x)) nil))
13218 org-tag-alist)))
13219 (if (and files (car files))
13220 files
13221 (org-agenda-files))))))))
13223 (defun org-make-tags-matcher (match)
13224 "Create the TAGS/TODO matcher form for the selection string MATCH.
13226 The variable `todo-only' is scoped dynamically into this function.
13227 It will be set to t if the matcher restricts matching to TODO entries,
13228 otherwise will not be touched.
13230 Returns a cons of the selection string MATCH and the constructed
13231 lisp form implementing the matcher. The matcher is to be evaluated
13232 at an Org entry, with point on the headline, and returns t if the
13233 entry matches the selection string MATCH. The returned lisp form
13234 references two variables with information about the entry, which
13235 must be bound around the form's evaluation: todo, the TODO keyword
13236 at the entry (or nil of none); and tags-list, the list of all tags
13237 at the entry including inherited ones. Additionally, the category
13238 of the entry (if any) must be specified as the text property
13239 'org-category on the headline.
13241 See also `org-scan-tags'.
13243 (declare (special todo-only))
13244 (unless (boundp 'todo-only)
13245 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13246 (unless match
13247 ;; Get a new match request, with completion
13248 (let ((org-last-tags-completion-table
13249 (org-global-tags-completion-table)))
13250 (setq match (org-completing-read-no-i
13251 "Match: " 'org-tags-completion-function nil nil nil
13252 'org-tags-history))))
13254 ;; Parse the string and create a lisp form
13255 (let ((match0 match)
13256 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13257 minus tag mm
13258 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13259 orterms term orlist re-p str-p level-p level-op time-p
13260 prop-p pn pv po gv rest)
13261 (if (string-match "/+" match)
13262 ;; match contains also a todo-matching request
13263 (progn
13264 (setq tagsmatch (substring match 0 (match-beginning 0))
13265 todomatch (substring match (match-end 0)))
13266 (if (string-match "^!" todomatch)
13267 (setq todo-only t todomatch (substring todomatch 1)))
13268 (if (string-match "^\\s-*$" todomatch)
13269 (setq todomatch nil)))
13270 ;; only matching tags
13271 (setq tagsmatch match todomatch nil))
13273 ;; Make the tags matcher
13274 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13275 (setq tagsmatcher t)
13276 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13277 (while (setq term (pop orterms))
13278 (while (and (equal (substring term -1) "\\") orterms)
13279 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13280 (while (string-match re term)
13281 (setq rest (substring term (match-end 0))
13282 minus (and (match-end 1)
13283 (equal (match-string 1 term) "-"))
13284 tag (save-match-data (replace-regexp-in-string
13285 "\\\\-" "-"
13286 (match-string 2 term)))
13287 re-p (equal (string-to-char tag) ?{)
13288 level-p (match-end 4)
13289 prop-p (match-end 5)
13290 mm (cond
13291 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13292 (level-p
13293 (setq level-op (org-op-to-function (match-string 3 term)))
13294 `(,level-op level ,(string-to-number
13295 (match-string 4 term))))
13296 (prop-p
13297 (setq pn (match-string 5 term)
13298 po (match-string 6 term)
13299 pv (match-string 7 term)
13300 re-p (equal (string-to-char pv) ?{)
13301 str-p (equal (string-to-char pv) ?\")
13302 time-p (save-match-data
13303 (string-match "^\"[[<].*[]>]\"$" pv))
13304 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13305 (if time-p (setq pv (org-matcher-time pv)))
13306 (setq po (org-op-to-function po (if time-p 'time str-p)))
13307 (cond
13308 ((equal pn "CATEGORY")
13309 (setq gv '(get-text-property (point) 'org-category)))
13310 ((equal pn "TODO")
13311 (setq gv 'todo))
13313 (setq gv `(org-cached-entry-get nil ,pn))))
13314 (if re-p
13315 (if (eq po 'org<>)
13316 `(not (string-match ,pv (or ,gv "")))
13317 `(string-match ,pv (or ,gv "")))
13318 (if str-p
13319 `(,po (or ,gv "") ,pv)
13320 `(,po (string-to-number (or ,gv ""))
13321 ,(string-to-number pv) ))))
13322 (t `(member ,tag tags-list)))
13323 mm (if minus (list 'not mm) mm)
13324 term rest)
13325 (push mm tagsmatcher))
13326 (push (if (> (length tagsmatcher) 1)
13327 (cons 'and tagsmatcher)
13328 (car tagsmatcher))
13329 orlist)
13330 (setq tagsmatcher nil))
13331 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13332 (setq tagsmatcher
13333 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13334 ;; Make the todo matcher
13335 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13336 (setq todomatcher t)
13337 (setq orterms (org-split-string todomatch "|") orlist nil)
13338 (while (setq term (pop orterms))
13339 (while (string-match re term)
13340 (setq minus (and (match-end 1)
13341 (equal (match-string 1 term) "-"))
13342 kwd (match-string 2 term)
13343 re-p (equal (string-to-char kwd) ?{)
13344 term (substring term (match-end 0))
13345 mm (if re-p
13346 `(string-match ,(substring kwd 1 -1) todo)
13347 (list 'equal 'todo kwd))
13348 mm (if minus (list 'not mm) mm))
13349 (push mm todomatcher))
13350 (push (if (> (length todomatcher) 1)
13351 (cons 'and todomatcher)
13352 (car todomatcher))
13353 orlist)
13354 (setq todomatcher nil))
13355 (setq todomatcher (if (> (length orlist) 1)
13356 (cons 'or orlist) (car orlist))))
13358 ;; Return the string and lisp forms of the matcher
13359 (setq matcher (if todomatcher
13360 (list 'and tagsmatcher todomatcher)
13361 tagsmatcher))
13362 (when todo-only
13363 (setq matcher (list 'and '(member todo org-not-done-keywords)
13364 matcher)))
13365 (cons match0 matcher)))
13367 (defun org-op-to-function (op &optional stringp)
13368 "Turn an operator into the appropriate function."
13369 (setq op
13370 (cond
13371 ((equal op "<" ) '(< string< org-time<))
13372 ((equal op ">" ) '(> org-string> org-time>))
13373 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13374 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13375 ((member op '("=" "==")) '(= string= org-time=))
13376 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13377 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13379 (defun org<> (a b) (not (= a b)))
13380 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13381 (defun org-string>= (a b) (not (string< a b)))
13382 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13383 (defun org-string<> (a b) (not (string= a b)))
13384 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13385 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13386 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13387 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> 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) (org<> a b)))
13390 (defun org-2ft (s)
13391 "Convert S to a floating point time.
13392 If S is already a number, just return it. If it is a string, parse
13393 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13394 (cond
13395 ((numberp s) s)
13396 ((stringp s)
13397 (condition-case nil
13398 (float-time (apply 'encode-time (org-parse-time-string s)))
13399 (error 0.)))
13400 (t 0.)))
13402 (defun org-time-today ()
13403 "Time in seconds today at 0:00.
13404 Returns the float number of seconds since the beginning of the
13405 epoch to the beginning of today (00:00)."
13406 (float-time (apply 'encode-time
13407 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13409 (defun org-matcher-time (s)
13410 "Interpret a time comparison value."
13411 (save-match-data
13412 (cond
13413 ((string= s "<now>") (float-time))
13414 ((string= s "<today>") (org-time-today))
13415 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13416 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13417 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13418 (+ (org-time-today)
13419 (* (string-to-number (match-string 1 s))
13420 (cdr (assoc (match-string 2 s)
13421 '(("d" . 86400.0) ("w" . 604800.0)
13422 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13423 (t (org-2ft s)))))
13425 (defun org-match-any-p (re list)
13426 "Does re match any element of list?"
13427 (setq list (mapcar (lambda (x) (string-match re x)) list))
13428 (delq nil list))
13430 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13431 (defvar org-tags-overlay (make-overlay 1 1))
13432 (org-detach-overlay org-tags-overlay)
13434 (defun org-get-local-tags-at (&optional pos)
13435 "Get a list of tags defined in the current headline."
13436 (org-get-tags-at pos 'local))
13438 (defun org-get-local-tags ()
13439 "Get a list of tags defined in the current headline."
13440 (org-get-tags-at nil 'local))
13442 (defun org-get-tags-at (&optional pos local)
13443 "Get a list of all headline tags applicable at POS.
13444 POS defaults to point. If tags are inherited, the list contains
13445 the targets in the same sequence as the headlines appear, i.e.
13446 the tags of the current headline come last.
13447 When LOCAL is non-nil, only return tags from the current headline,
13448 ignore inherited ones."
13449 (interactive)
13450 (if (and org-trust-scanner-tags
13451 (or (not pos) (equal pos (point)))
13452 (not local))
13453 org-scanner-tags
13454 (let (tags ltags lastpos parent)
13455 (save-excursion
13456 (save-restriction
13457 (widen)
13458 (goto-char (or pos (point)))
13459 (save-match-data
13460 (catch 'done
13461 (condition-case nil
13462 (progn
13463 (org-back-to-heading t)
13464 (while (not (equal lastpos (point)))
13465 (setq lastpos (point))
13466 (when (looking-at
13467 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13468 (setq ltags (org-split-string
13469 (org-match-string-no-properties 1) ":"))
13470 (when parent
13471 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13472 (setq tags (append
13473 (if parent
13474 (org-remove-uninherited-tags ltags)
13475 ltags)
13476 tags)))
13477 (or org-use-tag-inheritance (throw 'done t))
13478 (if local (throw 'done t))
13479 (or (org-up-heading-safe) (error nil))
13480 (setq parent t)))
13481 (error nil)))))
13482 (if local
13483 tags
13484 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13486 (defun org-add-prop-inherited (s)
13487 (add-text-properties 0 (length s) '(inherited t) s)
13490 (defun org-toggle-tag (tag &optional onoff)
13491 "Toggle the tag TAG for the current line.
13492 If ONOFF is `on' or `off', don't toggle but set to this state."
13493 (let (res current)
13494 (save-excursion
13495 (org-back-to-heading t)
13496 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13497 (point-at-eol) t)
13498 (progn
13499 (setq current (match-string 1))
13500 (replace-match ""))
13501 (setq current ""))
13502 (setq current (nreverse (org-split-string current ":")))
13503 (cond
13504 ((eq onoff 'on)
13505 (setq res t)
13506 (or (member tag current) (push tag current)))
13507 ((eq onoff 'off)
13508 (or (not (member tag current)) (setq current (delete tag current))))
13509 (t (if (member tag current)
13510 (setq current (delete tag current))
13511 (setq res t)
13512 (push tag current))))
13513 (end-of-line 1)
13514 (if current
13515 (progn
13516 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13517 (org-set-tags nil t))
13518 (delete-horizontal-space))
13519 (run-hooks 'org-after-tags-change-hook))
13520 res))
13522 (defun org-align-tags-here (to-col)
13523 ;; Assumes that this is a headline
13524 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13525 (beginning-of-line 1)
13526 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13527 (< pos (match-beginning 2)))
13528 (progn
13529 (setq tags-l (- (match-end 2) (match-beginning 2)))
13530 (goto-char (match-beginning 1))
13531 (insert " ")
13532 (delete-region (point) (1+ (match-beginning 2)))
13533 (setq ncol (max (current-column)
13534 (1+ col)
13535 (if (> to-col 0)
13536 to-col
13537 (- (abs to-col) tags-l))))
13538 (setq p (point))
13539 (insert (make-string (- ncol (current-column)) ?\ ))
13540 (setq ncol (current-column))
13541 (when indent-tabs-mode (tabify p (point-at-eol)))
13542 (org-move-to-column (min ncol col) t))
13543 (goto-char pos))))
13545 (defun org-set-tags-command (&optional arg just-align)
13546 "Call the set-tags command for the current entry."
13547 (interactive "P")
13548 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13549 (org-set-tags arg just-align)
13550 (save-excursion
13551 (org-back-to-heading t)
13552 (org-set-tags arg just-align))))
13554 (defun org-set-tags-to (data)
13555 "Set the tags of the current entry to DATA, replacing the current tags.
13556 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13557 If DATA is nil or the empty string, any tags will be removed."
13558 (interactive "sTags: ")
13559 (setq data
13560 (cond
13561 ((eq data nil) "")
13562 ((equal data "") "")
13563 ((stringp data)
13564 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13565 ":"))
13566 ((listp data)
13567 (concat ":" (mapconcat 'identity data ":") ":"))))
13568 (when data
13569 (save-excursion
13570 (org-back-to-heading t)
13571 (when (looking-at org-complex-heading-regexp)
13572 (if (match-end 5)
13573 (progn
13574 (goto-char (match-beginning 5))
13575 (insert data)
13576 (delete-region (point) (point-at-eol))
13577 (org-set-tags nil 'align))
13578 (goto-char (point-at-eol))
13579 (insert " " data)
13580 (org-set-tags nil 'align)))
13581 (beginning-of-line 1)
13582 (if (looking-at ".*?\\([ \t]+\\)$")
13583 (delete-region (match-beginning 1) (match-end 1))))))
13585 (defun org-align-all-tags ()
13586 "Align the tags i all headings."
13587 (interactive)
13588 (save-excursion
13589 (or (ignore-errors (org-back-to-heading t))
13590 (outline-next-heading))
13591 (if (org-at-heading-p)
13592 (org-set-tags t)
13593 (message "No headings"))))
13595 (defvar org-indent-indentation-per-level)
13596 (defun org-set-tags (&optional arg just-align)
13597 "Set the tags for the current headline.
13598 With prefix ARG, realign all tags in headings in the current buffer."
13599 (interactive "P")
13600 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13601 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13602 'region-start-level 'region))
13603 org-loop-over-headlines-in-active-region)
13604 (org-map-entries
13605 ;; We don't use ARG and JUST-ALIGN here these args are not
13606 ;; useful when looping over headlines
13607 `(org-set-tags)
13608 org-loop-over-headlines-in-active-region
13609 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13610 (let* ((re org-outline-regexp-bol)
13611 (current (unless arg (org-get-tags-string)))
13612 (col (current-column))
13613 (org-setting-tags t)
13614 table current-tags inherited-tags ; computed below when needed
13615 tags p0 c0 c1 rpl di tc level)
13616 (if arg
13617 (save-excursion
13618 (goto-char (point-min))
13619 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13620 (while (re-search-forward re nil t)
13621 (org-set-tags nil t)
13622 (end-of-line 1)))
13623 (message "All tags realigned to column %d" org-tags-column))
13624 (if just-align
13625 (setq tags current)
13626 ;; Get a new set of tags from the user
13627 (save-excursion
13628 (setq table (append org-tag-persistent-alist
13629 (or org-tag-alist (org-get-buffer-tags))
13630 (and
13631 org-complete-tags-always-offer-all-agenda-tags
13632 (org-global-tags-completion-table
13633 (org-agenda-files))))
13634 org-last-tags-completion-table table
13635 current-tags (org-split-string current ":")
13636 inherited-tags (nreverse
13637 (nthcdr (length current-tags)
13638 (nreverse (org-get-tags-at))))
13639 tags
13640 (if (or (eq t org-use-fast-tag-selection)
13641 (and org-use-fast-tag-selection
13642 (delq nil (mapcar 'cdr table))))
13643 (org-fast-tag-selection
13644 current-tags inherited-tags table
13645 (if org-fast-tag-selection-include-todo
13646 org-todo-key-alist))
13647 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13648 (org-trim
13649 (org-icompleting-read "Tags: "
13650 'org-tags-completion-function
13651 nil nil current 'org-tags-history))))))
13652 (while (string-match "[-+&]+" tags)
13653 ;; No boolean logic, just a list
13654 (setq tags (replace-match ":" t t tags))))
13656 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13658 (if org-tags-sort-function
13659 (setq tags (mapconcat 'identity
13660 (sort (org-split-string
13661 tags (org-re "[^[:alnum:]_@#%]+"))
13662 org-tags-sort-function) ":")))
13664 (if (string-match "\\`[\t ]*\\'" tags)
13665 (setq tags "")
13666 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13667 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13669 ;; Insert new tags at the correct column
13670 (beginning-of-line 1)
13671 (setq level (or (and (looking-at org-outline-regexp)
13672 (- (match-end 0) (point) 1))
13674 (cond
13675 ((and (equal current "") (equal tags "")))
13676 ((re-search-forward
13677 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13678 (point-at-eol) t)
13679 (if (equal tags "")
13680 (setq rpl "")
13681 (goto-char (match-beginning 0))
13682 (setq c0 (current-column)
13683 ;; compute offset for the case of org-indent-mode active
13684 di (if org-indent-mode
13685 (* (1- org-indent-indentation-per-level) (1- level))
13687 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13688 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13689 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13690 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13691 (replace-match rpl t t)
13692 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13693 tags)
13694 (t (error "Tags alignment failed")))
13695 (org-move-to-column col)
13696 (unless just-align
13697 (run-hooks 'org-after-tags-change-hook))))))
13699 (defun org-change-tag-in-region (beg end tag off)
13700 "Add or remove TAG for each entry in the region.
13701 This works in the agenda, and also in an org-mode buffer."
13702 (interactive
13703 (list (region-beginning) (region-end)
13704 (let ((org-last-tags-completion-table
13705 (if (derived-mode-p 'org-mode)
13706 (org-get-buffer-tags)
13707 (org-global-tags-completion-table))))
13708 (org-icompleting-read
13709 "Tag: " 'org-tags-completion-function nil nil nil
13710 'org-tags-history))
13711 (progn
13712 (message "[s]et or [r]emove? ")
13713 (equal (read-char-exclusive) ?r))))
13714 (if (fboundp 'deactivate-mark) (deactivate-mark))
13715 (let ((agendap (equal major-mode 'org-agenda-mode))
13716 l1 l2 m buf pos newhead (cnt 0))
13717 (goto-char end)
13718 (setq l2 (1- (org-current-line)))
13719 (goto-char beg)
13720 (setq l1 (org-current-line))
13721 (loop for l from l1 to l2 do
13722 (org-goto-line l)
13723 (setq m (get-text-property (point) 'org-hd-marker))
13724 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13725 (and agendap m))
13726 (setq buf (if agendap (marker-buffer m) (current-buffer))
13727 pos (if agendap m (point)))
13728 (with-current-buffer buf
13729 (save-excursion
13730 (save-restriction
13731 (goto-char pos)
13732 (setq cnt (1+ cnt))
13733 (org-toggle-tag tag (if off 'off 'on))
13734 (setq newhead (org-get-heading)))))
13735 (and agendap (org-agenda-change-all-lines newhead m))))
13736 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13738 (defun org-tags-completion-function (string predicate &optional flag)
13739 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13740 (confirm (lambda (x) (stringp (car x)))))
13741 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13742 (setq s1 (match-string 1 string)
13743 s2 (match-string 2 string))
13744 (setq s1 "" s2 string))
13745 (cond
13746 ((eq flag nil)
13747 ;; try completion
13748 (setq rtn (try-completion s2 ctable confirm))
13749 (if (stringp rtn)
13750 (setq rtn
13751 (concat s1 s2 (substring rtn (length s2))
13752 (if (and org-add-colon-after-tag-completion
13753 (assoc rtn ctable))
13754 ":" ""))))
13755 rtn)
13756 ((eq flag t)
13757 ;; all-completions
13758 (all-completions s2 ctable confirm)
13760 ((eq flag 'lambda)
13761 ;; exact match?
13762 (assoc s2 ctable)))
13765 (defun org-fast-tag-insert (kwd tags face &optional end)
13766 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13767 (insert (format "%-12s" (concat kwd ":"))
13768 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13769 (or end "")))
13771 (defun org-fast-tag-show-exit (flag)
13772 (save-excursion
13773 (org-goto-line 3)
13774 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13775 (replace-match ""))
13776 (when flag
13777 (end-of-line 1)
13778 (org-move-to-column (- (window-width) 19) t)
13779 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13781 (defun org-set-current-tags-overlay (current prefix)
13782 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13783 (if (featurep 'xemacs)
13784 (org-overlay-display org-tags-overlay (concat prefix s)
13785 'secondary-selection)
13786 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13787 (org-overlay-display org-tags-overlay (concat prefix s)))))
13789 (defvar org-last-tag-selection-key nil)
13790 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13791 "Fast tag selection with single keys.
13792 CURRENT is the current list of tags in the headline, INHERITED is the
13793 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13794 possibly with grouping information. TODO-TABLE is a similar table with
13795 TODO keywords, should these have keys assigned to them.
13796 If the keys are nil, a-z are automatically assigned.
13797 Returns the new tags string, or nil to not change the current settings."
13798 (let* ((fulltable (append table todo-table))
13799 (maxlen (apply 'max (mapcar
13800 (lambda (x)
13801 (if (stringp (car x)) (string-width (car x)) 0))
13802 fulltable)))
13803 (buf (current-buffer))
13804 (expert (eq org-fast-tag-selection-single-key 'expert))
13805 (buffer-tags nil)
13806 (fwidth (+ maxlen 3 1 3))
13807 (ncol (/ (- (window-width) 4) fwidth))
13808 (i-face 'org-done)
13809 (c-face 'org-todo)
13810 tg cnt e c char c1 c2 ntable tbl rtn
13811 ov-start ov-end ov-prefix
13812 (exit-after-next org-fast-tag-selection-single-key)
13813 (done-keywords org-done-keywords)
13814 groups ingroup)
13815 (save-excursion
13816 (beginning-of-line 1)
13817 (if (looking-at
13818 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13819 (setq ov-start (match-beginning 1)
13820 ov-end (match-end 1)
13821 ov-prefix "")
13822 (setq ov-start (1- (point-at-eol))
13823 ov-end (1+ ov-start))
13824 (skip-chars-forward "^\n\r")
13825 (setq ov-prefix
13826 (concat
13827 (buffer-substring (1- (point)) (point))
13828 (if (> (current-column) org-tags-column)
13830 (make-string (- org-tags-column (current-column)) ?\ ))))))
13831 (move-overlay org-tags-overlay ov-start ov-end)
13832 (save-window-excursion
13833 (if expert
13834 (set-buffer (get-buffer-create " *Org tags*"))
13835 (delete-other-windows)
13836 (split-window-vertically)
13837 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13838 (erase-buffer)
13839 (org-set-local 'org-done-keywords done-keywords)
13840 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13841 (org-fast-tag-insert "Current" current c-face "\n\n")
13842 (org-fast-tag-show-exit exit-after-next)
13843 (org-set-current-tags-overlay current ov-prefix)
13844 (setq tbl fulltable char ?a cnt 0)
13845 (while (setq e (pop tbl))
13846 (cond
13847 ((equal (car e) :startgroup)
13848 (push '() groups) (setq ingroup t)
13849 (when (not (= cnt 0))
13850 (setq cnt 0)
13851 (insert "\n"))
13852 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13853 ((equal (car e) :endgroup)
13854 (setq ingroup nil cnt 0)
13855 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13856 ((equal e '(:newline))
13857 (when (not (= cnt 0))
13858 (setq cnt 0)
13859 (insert "\n")
13860 (setq e (car tbl))
13861 (while (equal (car tbl) '(:newline))
13862 (insert "\n")
13863 (setq tbl (cdr tbl)))))
13865 (setq tg (copy-sequence (car e)) c2 nil)
13866 (if (cdr e)
13867 (setq c (cdr e))
13868 ;; automatically assign a character.
13869 (setq c1 (string-to-char
13870 (downcase (substring
13871 tg (if (= (string-to-char tg) ?@) 1 0)))))
13872 (if (or (rassoc c1 ntable) (rassoc c1 table))
13873 (while (or (rassoc char ntable) (rassoc char table))
13874 (setq char (1+ char)))
13875 (setq c2 c1))
13876 (setq c (or c2 char)))
13877 (if ingroup (push tg (car groups)))
13878 (setq tg (org-add-props tg nil 'face
13879 (cond
13880 ((not (assoc tg table))
13881 (org-get-todo-face tg))
13882 ((member tg current) c-face)
13883 ((member tg inherited) i-face))))
13884 (if (and (= cnt 0) (not ingroup)) (insert " "))
13885 (insert "[" c "] " tg (make-string
13886 (- fwidth 4 (length tg)) ?\ ))
13887 (push (cons tg c) ntable)
13888 (when (= (setq cnt (1+ cnt)) ncol)
13889 (insert "\n")
13890 (if ingroup (insert " "))
13891 (setq cnt 0)))))
13892 (setq ntable (nreverse ntable))
13893 (insert "\n")
13894 (goto-char (point-min))
13895 (if (not expert) (org-fit-window-to-buffer))
13896 (setq rtn
13897 (catch 'exit
13898 (while t
13899 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13900 (if (not groups) "no " "")
13901 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13902 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13903 (setq org-last-tag-selection-key c)
13904 (cond
13905 ((= c ?\r) (throw 'exit t))
13906 ((= c ?!)
13907 (setq groups (not groups))
13908 (goto-char (point-min))
13909 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13910 ((= c ?\C-c)
13911 (if (not expert)
13912 (org-fast-tag-show-exit
13913 (setq exit-after-next (not exit-after-next)))
13914 (setq expert nil)
13915 (delete-other-windows)
13916 (set-window-buffer (split-window-vertically) " *Org tags*")
13917 (org-switch-to-buffer-other-window " *Org tags*")
13918 (org-fit-window-to-buffer)))
13919 ((or (= c ?\C-g)
13920 (and (= c ?q) (not (rassoc c ntable))))
13921 (org-detach-overlay org-tags-overlay)
13922 (setq quit-flag t))
13923 ((= c ?\ )
13924 (setq current nil)
13925 (if exit-after-next (setq exit-after-next 'now)))
13926 ((= c ?\t)
13927 (condition-case nil
13928 (setq tg (org-icompleting-read
13929 "Tag: "
13930 (or buffer-tags
13931 (with-current-buffer buf
13932 (org-get-buffer-tags)))))
13933 (quit (setq tg "")))
13934 (when (string-match "\\S-" tg)
13935 (add-to-list 'buffer-tags (list tg))
13936 (if (member tg current)
13937 (setq current (delete tg current))
13938 (push tg current)))
13939 (if exit-after-next (setq exit-after-next 'now)))
13940 ((setq e (rassoc c todo-table) tg (car e))
13941 (with-current-buffer buf
13942 (save-excursion (org-todo tg)))
13943 (if exit-after-next (setq exit-after-next 'now)))
13944 ((setq e (rassoc c ntable) tg (car e))
13945 (if (member tg current)
13946 (setq current (delete tg current))
13947 (loop for g in groups do
13948 (if (member tg g)
13949 (mapc (lambda (x)
13950 (setq current (delete x current)))
13951 g)))
13952 (push tg current))
13953 (if exit-after-next (setq exit-after-next 'now))))
13955 ;; Create a sorted list
13956 (setq current
13957 (sort current
13958 (lambda (a b)
13959 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13960 (if (eq exit-after-next 'now) (throw 'exit t))
13961 (goto-char (point-min))
13962 (beginning-of-line 2)
13963 (delete-region (point) (point-at-eol))
13964 (org-fast-tag-insert "Current" current c-face)
13965 (org-set-current-tags-overlay current ov-prefix)
13966 (while (re-search-forward
13967 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13968 (setq tg (match-string 1))
13969 (add-text-properties
13970 (match-beginning 1) (match-end 1)
13971 (list 'face
13972 (cond
13973 ((member tg current) c-face)
13974 ((member tg inherited) i-face)
13975 (t (get-text-property (match-beginning 1) 'face))))))
13976 (goto-char (point-min)))))
13977 (org-detach-overlay org-tags-overlay)
13978 (if rtn
13979 (mapconcat 'identity current ":")
13980 nil))))
13982 (defun org-get-tags-string ()
13983 "Get the TAGS string in the current headline."
13984 (unless (org-at-heading-p t)
13985 (error "Not on a heading"))
13986 (save-excursion
13987 (beginning-of-line 1)
13988 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13989 (org-match-string-no-properties 1)
13990 "")))
13992 (defun org-get-tags ()
13993 "Get the list of tags specified in the current headline."
13994 (org-split-string (org-get-tags-string) ":"))
13996 (defun org-get-buffer-tags ()
13997 "Get a table of all tags used in the buffer, for completion."
13998 (let (tags)
13999 (save-excursion
14000 (goto-char (point-min))
14001 (while (re-search-forward
14002 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14003 (when (equal (char-after (point-at-bol 0)) ?*)
14004 (mapc (lambda (x) (add-to-list 'tags x))
14005 (org-split-string (org-match-string-no-properties 1) ":")))))
14006 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14007 (mapcar 'list tags)))
14009 ;;;; The mapping API
14011 (defun org-map-entries (func &optional match scope &rest skip)
14012 "Call FUNC at each headline selected by MATCH in SCOPE.
14014 FUNC is a function or a lisp form. The function will be called without
14015 arguments, with the cursor positioned at the beginning of the headline.
14016 The return values of all calls to the function will be collected and
14017 returned as a list.
14019 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14020 does not need to preserve point. After evaluation, the cursor will be
14021 moved to the end of the line (presumably of the headline of the
14022 processed entry) and search continues from there. Under some
14023 circumstances, this may not produce the wanted results. For example,
14024 if you have removed (e.g. archived) the current (sub)tree it could
14025 mean that the next entry will be skipped entirely. In such cases, you
14026 can specify the position from where search should continue by making
14027 FUNC set the variable `org-map-continue-from' to the desired buffer
14028 position.
14030 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14031 Only headlines that are matched by this query will be considered during
14032 the iteration. When MATCH is nil or t, all headlines will be
14033 visited by the iteration.
14035 SCOPE determines the scope of this command. It can be any of:
14037 nil The current buffer, respecting the restriction if any
14038 tree The subtree started with the entry at point
14039 region The entries within the active region, if any
14040 region-start-level
14041 The entries within the active region, but only those at
14042 the same level than the first one.
14043 file The current buffer, without restriction
14044 file-with-archives
14045 The current buffer, and any archives associated with it
14046 agenda All agenda files
14047 agenda-with-archives
14048 All agenda files with any archive files associated with them
14049 \(file1 file2 ...)
14050 If this is a list, all files in the list will be scanned
14052 The remaining args are treated as settings for the skipping facilities of
14053 the scanner. The following items can be given here:
14055 archive skip trees with the archive tag.
14056 comment skip trees with the COMMENT keyword
14057 function or Emacs Lisp form:
14058 will be used as value for `org-agenda-skip-function', so whenever
14059 the function returns t, FUNC will not be called for that
14060 entry and search will continue from the point where the
14061 function leaves it.
14063 If your function needs to retrieve the tags including inherited tags
14064 at the *current* entry, you can use the value of the variable
14065 `org-scanner-tags' which will be much faster than getting the value
14066 with `org-get-tags-at'. If your function gets properties with
14067 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14068 to t around the call to `org-entry-properties' to get the same speedup.
14069 Note that if your function moves around to retrieve tags and properties at
14070 a *different* entry, you cannot use these techniques."
14071 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14072 (not (org-region-active-p)))
14073 (let* ((org-agenda-archives-mode nil) ; just to make sure
14074 (org-agenda-skip-archived-trees (memq 'archive skip))
14075 (org-agenda-skip-comment-trees (memq 'comment skip))
14076 (org-agenda-skip-function
14077 (car (org-delete-all '(comment archive) skip)))
14078 (org-tags-match-list-sublevels t)
14079 (start-level (eq scope 'region-start-level))
14080 matcher file res
14081 org-todo-keywords-for-agenda
14082 org-done-keywords-for-agenda
14083 org-todo-keyword-alist-for-agenda
14084 org-drawers-for-agenda
14085 org-tag-alist-for-agenda
14086 todo-only)
14088 (cond
14089 ((eq match t) (setq matcher t))
14090 ((eq match nil) (setq matcher t))
14091 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14093 (save-excursion
14094 (save-restriction
14095 (cond ((eq scope 'tree)
14096 (org-back-to-heading t)
14097 (org-narrow-to-subtree)
14098 (setq scope nil))
14099 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14100 (org-region-active-p))
14101 ;; If needed, set start-level to a string like "2"
14102 (when start-level
14103 (save-excursion
14104 (goto-char (region-beginning))
14105 (unless (org-at-heading-p) (outline-next-heading))
14106 (setq start-level (org-current-level))))
14107 (narrow-to-region (region-beginning)
14108 (save-excursion
14109 (goto-char (region-end))
14110 (unless (and (bolp) (org-at-heading-p))
14111 (outline-next-heading))
14112 (point)))
14113 (setq scope nil)))
14115 (if (not scope)
14116 (progn
14117 (org-agenda-prepare-buffers
14118 (list (buffer-file-name (current-buffer))))
14119 (setq res (org-scan-tags func matcher todo-only start-level)))
14120 ;; Get the right scope
14121 (cond
14122 ((and scope (listp scope) (symbolp (car scope)))
14123 (setq scope (eval scope)))
14124 ((eq scope 'agenda)
14125 (setq scope (org-agenda-files t)))
14126 ((eq scope 'agenda-with-archives)
14127 (setq scope (org-agenda-files t))
14128 (setq scope (org-add-archive-files scope)))
14129 ((eq scope 'file)
14130 (setq scope (list (buffer-file-name))))
14131 ((eq scope 'file-with-archives)
14132 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14133 (org-agenda-prepare-buffers scope)
14134 (while (setq file (pop scope))
14135 (with-current-buffer (org-find-base-buffer-visiting file)
14136 (save-excursion
14137 (save-restriction
14138 (widen)
14139 (goto-char (point-min))
14140 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14141 res)))
14143 ;;;; Properties
14145 ;;; Setting and retrieving properties
14147 (defconst org-special-properties
14148 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14149 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14150 "The special properties valid in Org-mode.
14152 These are properties that are not defined in the property drawer,
14153 but in some other way.")
14155 (defconst org-default-properties
14156 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14157 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14158 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14159 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14160 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14161 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14162 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14163 "Some properties that are used by Org-mode for various purposes.
14164 Being in this list makes sure that they are offered for completion.")
14166 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14167 "Regular expression matching the first line of a property drawer.")
14169 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14170 "Regular expression matching the last line of a property drawer.")
14172 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14173 "Regular expression matching the first line of a property drawer.")
14175 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14176 "Regular expression matching the first line of a property drawer.")
14178 (defconst org-property-drawer-re
14179 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14180 org-property-end-re "\\)\n?")
14181 "Matches an entire property drawer.")
14183 (defconst org-clock-drawer-re
14184 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14185 org-property-end-re "\\)\n?")
14186 "Matches an entire clock drawer.")
14188 (defsubst org-re-property (property)
14189 "Return a regexp matching a PROPERTY line.
14190 Match group 1 will be set to the value."
14191 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14193 (defsubst org-re-property-keyword (property)
14194 "Return a regexp matching a PROPERTY line, possibly with no
14195 value for the property."
14196 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14198 (defun org-property-action ()
14199 "Do an action on properties."
14200 (interactive)
14201 (let (c)
14202 (org-at-property-p)
14203 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14204 (setq c (read-char-exclusive))
14205 (cond
14206 ((equal c ?s)
14207 (call-interactively 'org-set-property))
14208 ((equal c ?d)
14209 (call-interactively 'org-delete-property))
14210 ((equal c ?D)
14211 (call-interactively 'org-delete-property-globally))
14212 ((equal c ?c)
14213 (call-interactively 'org-compute-property-at-point))
14214 (t (error "No such property action %c" c)))))
14216 (defun org-inc-effort ()
14217 "Increment the value of the effort property in the current entry."
14218 (interactive)
14219 (org-set-effort nil t))
14221 (defun org-set-effort (&optional value increment)
14222 "Set the effort property of the current entry.
14223 With numerical prefix arg, use the nth allowed value, 0 stands for the
14224 10th allowed value.
14226 When INCREMENT is non-nil, set the property to the next allowed value."
14227 (interactive "P")
14228 (if (equal value 0) (setq value 10))
14229 (let* ((completion-ignore-case t)
14230 (prop org-effort-property)
14231 (cur (org-entry-get nil prop))
14232 (allowed (org-property-get-allowed-values nil prop 'table))
14233 (existing (mapcar 'list (org-property-values prop)))
14235 (val (cond
14236 ((stringp value) value)
14237 ((and allowed (integerp value))
14238 (or (car (nth (1- value) allowed))
14239 (car (org-last allowed))))
14240 ((and allowed increment)
14241 (or (caadr (member (list cur) allowed))
14242 (error "Allowed effort values are not set")))
14243 (allowed
14244 (message "Select 1-9,0, [RET%s]: %s"
14245 (if cur (concat "=" cur) "")
14246 (mapconcat 'car allowed " "))
14247 (setq rpl (read-char-exclusive))
14248 (if (equal rpl ?\r)
14250 (setq rpl (- rpl ?0))
14251 (if (equal rpl 0) (setq rpl 10))
14252 (if (and (> rpl 0) (<= rpl (length allowed)))
14253 (car (nth (1- rpl) allowed))
14254 (org-completing-read "Effort: " allowed nil))))
14256 (let (org-completion-use-ido org-completion-use-iswitchb)
14257 (org-completing-read
14258 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14259 (concat "[" cur "]") "")
14260 ": ")
14261 existing nil nil "" nil cur))))))
14262 (unless (equal (org-entry-get nil prop) val)
14263 (org-entry-put nil prop val))
14264 (message "%s is now %s" prop val)))
14266 (defun org-at-property-p ()
14267 "Is cursor inside a property drawer?"
14268 (save-excursion
14269 (beginning-of-line 1)
14270 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14271 (save-match-data ;; Used by calling procedures
14272 (let ((p (point))
14273 (range (unless (org-before-first-heading-p)
14274 (org-get-property-block))))
14275 (and range (<= (car range) p) (< p (cdr range))))))))
14277 (defun org-get-property-block (&optional beg end force)
14278 "Return the (beg . end) range of the body of the property drawer.
14279 BEG and END are the beginning and end of the current subtree, or of
14280 the part before the first headline. If they are not given, they will
14281 be found. If the drawer does not exist and FORCE is non-nil, create
14282 the drawer."
14283 (catch 'exit
14284 (save-excursion
14285 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14286 (progn (org-back-to-heading t) (point))))
14287 (end (or end (and (not (outline-next-heading)) (point-max))
14288 (point))))
14289 (goto-char beg)
14290 (if (re-search-forward org-property-start-re end t)
14291 (setq beg (1+ (match-end 0)))
14292 (if force
14293 (save-excursion
14294 (org-insert-property-drawer)
14295 (setq end (progn (outline-next-heading) (point))))
14296 (throw 'exit nil))
14297 (goto-char beg)
14298 (if (re-search-forward org-property-start-re end t)
14299 (setq beg (1+ (match-end 0)))))
14300 (if (re-search-forward org-property-end-re end t)
14301 (setq end (match-beginning 0))
14302 (or force (throw 'exit nil))
14303 (goto-char beg)
14304 (setq end beg)
14305 (org-indent-line)
14306 (insert ":END:\n"))
14307 (cons beg end)))))
14309 (defun org-entry-properties (&optional pom which specific)
14310 "Get all properties of the entry at point-or-marker POM.
14311 This includes the TODO keyword, the tags, time strings for deadline,
14312 scheduled, and clocking, and any additional properties defined in the
14313 entry. The return value is an alist, keys may occur multiple times
14314 if the property key was used several times.
14315 POM may also be nil, in which case the current entry is used.
14316 If WHICH is nil or `all', get all properties. If WHICH is
14317 `special' or `standard', only get that subclass. If WHICH
14318 is a string only get exactly this property. SPECIFIC can be a string, the
14319 specific property we are interested in. Specifying it can speed
14320 things up because then unnecessary parsing is avoided."
14321 (setq which (or which 'all))
14322 (org-with-point-at pom
14323 (let ((clockstr (substring org-clock-string 0 -1))
14324 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14325 (case-fold-search nil)
14326 beg end range props sum-props key key1 value string clocksum clocksumt)
14327 (save-excursion
14328 (when (condition-case nil
14329 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14330 (error nil))
14331 (setq beg (point))
14332 (setq sum-props (get-text-property (point) 'org-summaries))
14333 (setq clocksum (get-text-property (point) :org-clock-minutes)
14334 clocksumt (get-text-property (point) :org-clock-minutes-today))
14335 (outline-next-heading)
14336 (setq end (point))
14337 (when (memq which '(all special))
14338 ;; Get the special properties, like TODO and tags
14339 (goto-char beg)
14340 (when (and (or (not specific) (string= specific "TODO"))
14341 (looking-at org-todo-line-regexp) (match-end 2))
14342 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14343 (when (and (or (not specific) (string= specific "PRIORITY"))
14344 (looking-at org-priority-regexp))
14345 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14346 (when (or (not specific) (string= specific "FILE"))
14347 (push (cons "FILE" buffer-file-name) props))
14348 (when (and (or (not specific) (string= specific "TAGS"))
14349 (setq value (org-get-tags-string))
14350 (string-match "\\S-" value))
14351 (push (cons "TAGS" value) props))
14352 (when (and (or (not specific) (string= specific "ALLTAGS"))
14353 (setq value (org-get-tags-at)))
14354 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14355 ":"))
14356 props))
14357 (when (or (not specific) (string= specific "BLOCKED"))
14358 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14359 (when (or (not specific)
14360 (member specific
14361 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14362 "TIMESTAMP" "TIMESTAMP_IA")))
14363 (catch 'match
14364 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14365 (setq key (if (match-end 1)
14366 (substring (org-match-string-no-properties 1)
14367 0 -1))
14368 string (if (equal key clockstr)
14369 (org-trim
14370 (buffer-substring-no-properties
14371 (match-beginning 3) (goto-char
14372 (point-at-eol))))
14373 (substring (org-match-string-no-properties 3)
14374 1 -1)))
14375 ;; Get the correct property name from the key. This is
14376 ;; necessary if the user has configured time keywords.
14377 (setq key1 (concat key ":"))
14378 (cond
14379 ((not key)
14380 (setq key
14381 (if (= (char-after (match-beginning 3)) ?\[)
14382 "TIMESTAMP_IA" "TIMESTAMP")))
14383 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14384 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14385 ((equal key1 org-closed-string) (setq key "CLOSED"))
14386 ((equal key1 org-clock-string) (setq key "CLOCK")))
14387 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14388 (progn
14389 (push (cons key string) props)
14390 ;; no need to search further if match is found
14391 (throw 'match t))
14392 (when (or (equal key "CLOCK") (not (assoc key props)))
14393 (push (cons key string) props)))))))
14395 (when (memq which '(all standard))
14396 ;; Get the standard properties, like :PROP: ...
14397 (setq range (org-get-property-block beg end))
14398 (when range
14399 (goto-char (car range))
14400 (while (re-search-forward
14401 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14402 (cdr range) t)
14403 (setq key (org-match-string-no-properties 1)
14404 value (org-trim (or (org-match-string-no-properties 2) "")))
14405 (unless (member key excluded)
14406 (push (cons key (or value "")) props)))))
14407 (if clocksum
14408 (push (cons "CLOCKSUM"
14409 (org-columns-number-to-string (/ (float clocksum) 60.)
14410 'add_times))
14411 props))
14412 (if clocksumt
14413 (push (cons "CLOCKSUM_T"
14414 (org-columns-number-to-string (/ (float clocksumt) 60.)
14415 'add_times))
14416 props))
14417 (unless (assoc "CATEGORY" props)
14418 (push (cons "CATEGORY" (org-get-category)) props))
14419 (append sum-props (nreverse props)))))))
14421 (defun org-entry-get (pom property &optional inherit literal-nil)
14422 "Get value of PROPERTY for entry or content at point-or-marker POM.
14423 If INHERIT is non-nil and the entry does not have the property,
14424 then also check higher levels of the hierarchy.
14425 If INHERIT is the symbol `selective', use inheritance only if the setting
14426 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14427 If the property is present but empty, the return value is the empty string.
14428 If the property is not present at all, nil is returned.
14430 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14431 do not interpret it as the list atom nil. This is used for inheritance
14432 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14433 (org-with-point-at pom
14434 (if (and inherit (if (eq inherit 'selective)
14435 (org-property-inherit-p property)
14437 (org-entry-get-with-inheritance property literal-nil)
14438 (if (member property org-special-properties)
14439 ;; We need a special property. Use `org-entry-properties' to
14440 ;; retrieve it, but specify the wanted property
14441 (cdr (assoc property (org-entry-properties nil 'special property)))
14442 (let* ((range (org-get-property-block))
14443 (props (list (or (assoc property org-file-properties)
14444 (assoc property org-global-properties)
14445 (assoc property org-global-properties-fixed))))
14446 (ap (lambda (key)
14447 (when (re-search-forward
14448 (org-re-property key) (cdr range) t)
14449 (setq props
14450 (org-update-property-plist
14452 (if (match-end 1)
14453 (org-match-string-no-properties 1) "")
14454 props)))))
14455 val)
14456 (when (and range (goto-char (car range)))
14457 (funcall ap property)
14458 (goto-char (car range))
14459 (while (funcall ap (concat property "+")))
14460 (setq val (cdr (assoc property props)))
14461 (when val (if literal-nil val (org-not-nil val)))))))))
14463 (defun org-property-or-variable-value (var &optional inherit)
14464 "Check if there is a property fixing the value of VAR.
14465 If yes, return this value. If not, return the current value of the variable."
14466 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14467 (if (and prop (stringp prop) (string-match "\\S-" prop))
14468 (read prop)
14469 (symbol-value var))))
14471 (defun org-entry-delete (pom property)
14472 "Delete the property PROPERTY from entry at point-or-marker POM."
14473 (org-with-point-at pom
14474 (if (member property org-special-properties)
14475 nil ; cannot delete these properties.
14476 (let ((range (org-get-property-block)))
14477 (if (and range
14478 (goto-char (car range))
14479 (re-search-forward
14480 (org-re-property property)
14481 (cdr range) t))
14482 (progn
14483 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14485 nil)))))
14487 ;; Multi-values properties are properties that contain multiple values
14488 ;; These values are assumed to be single words, separated by whitespace.
14489 (defun org-entry-add-to-multivalued-property (pom property value)
14490 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14491 (let* ((old (org-entry-get pom property))
14492 (values (and old (org-split-string old "[ \t]"))))
14493 (setq value (org-entry-protect-space value))
14494 (unless (member value values)
14495 (setq values (cons value values))
14496 (org-entry-put pom property
14497 (mapconcat 'identity values " ")))))
14499 (defun org-entry-remove-from-multivalued-property (pom property value)
14500 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14501 (let* ((old (org-entry-get pom property))
14502 (values (and old (org-split-string old "[ \t]"))))
14503 (setq value (org-entry-protect-space value))
14504 (when (member value values)
14505 (setq values (delete value values))
14506 (org-entry-put pom property
14507 (mapconcat 'identity values " ")))))
14509 (defun org-entry-member-in-multivalued-property (pom property value)
14510 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14511 (let* ((old (org-entry-get pom property))
14512 (values (and old (org-split-string old "[ \t]"))))
14513 (setq value (org-entry-protect-space value))
14514 (member value values)))
14516 (defun org-entry-get-multivalued-property (pom property)
14517 "Return a list of values in a multivalued property."
14518 (let* ((value (org-entry-get pom property))
14519 (values (and value (org-split-string value "[ \t]"))))
14520 (mapcar 'org-entry-restore-space values)))
14522 (defun org-entry-put-multivalued-property (pom property &rest values)
14523 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14524 VALUES should be a list of strings. Spaces will be protected."
14525 (org-entry-put pom property
14526 (mapconcat 'org-entry-protect-space values " "))
14527 (let* ((value (org-entry-get pom property))
14528 (values (and value (org-split-string value "[ \t]"))))
14529 (mapcar 'org-entry-restore-space values)))
14531 (defun org-entry-protect-space (s)
14532 "Protect spaces and newline in string S."
14533 (while (string-match " " s)
14534 (setq s (replace-match "%20" t t s)))
14535 (while (string-match "\n" s)
14536 (setq s (replace-match "%0A" t t s)))
14539 (defun org-entry-restore-space (s)
14540 "Restore spaces and newline in string S."
14541 (while (string-match "%20" s)
14542 (setq s (replace-match " " t t s)))
14543 (while (string-match "%0A" s)
14544 (setq s (replace-match "\n" t t s)))
14547 (defvar org-entry-property-inherited-from (make-marker)
14548 "Marker pointing to the entry from where a property was inherited.
14549 Each call to `org-entry-get-with-inheritance' will set this marker to the
14550 location of the entry where the inheritance search matched. If there was
14551 no match, the marker will point nowhere.
14552 Note that also `org-entry-get' calls this function, if the INHERIT flag
14553 is set.")
14555 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14556 "Get PROPERTY of entry or content at point, search higher levels if needed.
14557 The search will stop at the first ancestor which has the property defined.
14558 If the value found is \"nil\", return nil to show that the property
14559 should be considered as undefined (this is the meaning of nil here).
14560 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14561 (move-marker org-entry-property-inherited-from nil)
14562 (let (tmp)
14563 (save-excursion
14564 (save-restriction
14565 (widen)
14566 (catch 'ex
14567 (while t
14568 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14569 (or (ignore-errors (org-back-to-heading t))
14570 (goto-char (point-min)))
14571 (move-marker org-entry-property-inherited-from (point))
14572 (throw 'ex tmp))
14573 (or (ignore-errors (org-up-heading-safe))
14574 (throw 'ex nil))))))
14575 (setq tmp (or tmp
14576 (cdr (assoc property org-file-properties))
14577 (cdr (assoc property org-global-properties))
14578 (cdr (assoc property org-global-properties-fixed))))
14579 (if literal-nil tmp (org-not-nil tmp))))
14581 (defvar org-property-changed-functions nil
14582 "Hook called when the value of a property has changed.
14583 Each hook function should accept two arguments, the name of the property
14584 and the new value.")
14586 (defun org-entry-put (pom property value)
14587 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14588 (org-with-point-at pom
14589 (org-back-to-heading t)
14590 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14591 range)
14592 (cond
14593 ((equal property "TODO")
14594 (when (and (stringp value) (string-match "\\S-" value)
14595 (not (member value org-todo-keywords-1)))
14596 (error "\"%s\" is not a valid TODO state" value))
14597 (if (or (not value)
14598 (not (string-match "\\S-" value)))
14599 (setq value 'none))
14600 (org-todo value)
14601 (org-set-tags nil 'align))
14602 ((equal property "PRIORITY")
14603 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14604 (string-to-char value) ?\ ))
14605 (org-set-tags nil 'align))
14606 ((equal property "SCHEDULED")
14607 (if (re-search-forward org-scheduled-time-regexp end t)
14608 (cond
14609 ((eq value 'earlier) (org-timestamp-change -1 'day))
14610 ((eq value 'later) (org-timestamp-change 1 'day))
14611 (t (call-interactively 'org-schedule)))
14612 (call-interactively 'org-schedule)))
14613 ((equal property "DEADLINE")
14614 (if (re-search-forward org-deadline-time-regexp end t)
14615 (cond
14616 ((eq value 'earlier) (org-timestamp-change -1 'day))
14617 ((eq value 'later) (org-timestamp-change 1 'day))
14618 (t (call-interactively 'org-deadline)))
14619 (call-interactively 'org-deadline)))
14620 ((member property org-special-properties)
14621 (error "The %s property can not yet be set with `org-entry-put'"
14622 property))
14623 (t ; a non-special property
14624 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14625 (setq range (org-get-property-block beg end 'force))
14626 (goto-char (car range))
14627 (if (re-search-forward
14628 (org-re-property-keyword property) (cdr range) t)
14629 (progn
14630 (delete-region (match-beginning 0) (match-end 0))
14631 (goto-char (match-beginning 0)))
14632 (goto-char (cdr range))
14633 (insert "\n")
14634 (backward-char 1)
14635 (org-indent-line))
14636 (insert ":" property ":")
14637 (and value (insert " " value))
14638 (org-indent-line)))))
14639 (run-hook-with-args 'org-property-changed-functions property value)))
14641 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14642 "Get all property keys in the current buffer.
14643 With INCLUDE-SPECIALS, also list the special properties that reflect things
14644 like tags and TODO state.
14645 With INCLUDE-DEFAULTS, also include properties that has special meaning
14646 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14647 and others.
14648 With INCLUDE-COLUMNS, also include property names given in COLUMN
14649 formats in the current buffer."
14650 (let (rtn range cfmt s p)
14651 (save-excursion
14652 (save-restriction
14653 (widen)
14654 (goto-char (point-min))
14655 (while (re-search-forward org-property-start-re nil t)
14656 (setq range (org-get-property-block))
14657 (goto-char (car range))
14658 (while (re-search-forward
14659 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14660 (cdr range) t)
14661 (add-to-list 'rtn (org-match-string-no-properties 1)))
14662 (outline-next-heading))))
14664 (when include-specials
14665 (setq rtn (append org-special-properties rtn)))
14667 (when include-defaults
14668 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14669 (add-to-list 'rtn org-effort-property))
14671 (when include-columns
14672 (save-excursion
14673 (save-restriction
14674 (widen)
14675 (goto-char (point-min))
14676 (while (re-search-forward
14677 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14678 nil t)
14679 (setq cfmt (match-string 2) s 0)
14680 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14681 cfmt s)
14682 (setq s (match-end 0)
14683 p (match-string 1 cfmt))
14684 (unless (or (equal p "ITEM")
14685 (member p org-special-properties))
14686 (add-to-list 'rtn (match-string 1 cfmt))))))))
14688 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14690 (defun org-property-values (key)
14691 "Return a list of all values of property KEY in the current buffer."
14692 (save-excursion
14693 (save-restriction
14694 (widen)
14695 (goto-char (point-min))
14696 (let ((re (org-re-property key))
14697 values)
14698 (while (re-search-forward re nil t)
14699 (add-to-list 'values (org-trim (match-string 1))))
14700 (delete "" values)))))
14702 (defun org-insert-property-drawer ()
14703 "Insert a property drawer into the current entry."
14704 (org-back-to-heading t)
14705 (looking-at org-outline-regexp)
14706 (let ((indent (if org-adapt-indentation
14707 (- (match-end 0) (match-beginning 0))
14709 (beg (point))
14710 (re (concat "^[ \t]*" org-keyword-time-regexp))
14711 end hiddenp)
14712 (outline-next-heading)
14713 (setq end (point))
14714 (goto-char beg)
14715 (while (re-search-forward re end t))
14716 (setq hiddenp (outline-invisible-p))
14717 (end-of-line 1)
14718 (and (equal (char-after) ?\n) (forward-char 1))
14719 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14720 (if (member (match-string 1) '("CLOCK:" ":END:"))
14721 ;; just skip this line
14722 (beginning-of-line 2)
14723 ;; Drawer start, find the end
14724 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14725 (beginning-of-line 1)))
14726 (org-skip-over-state-notes)
14727 (skip-chars-backward " \t\n\r")
14728 (if (eq (char-before) ?*) (forward-char 1))
14729 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14730 (beginning-of-line 0)
14731 (org-indent-to-column indent)
14732 (beginning-of-line 2)
14733 (org-indent-to-column indent)
14734 (beginning-of-line 0)
14735 (if hiddenp
14736 (save-excursion
14737 (org-back-to-heading t)
14738 (hide-entry))
14739 (org-flag-drawer t))))
14741 (defun org-insert-drawer (&optional arg drawer)
14742 "Insert a drawer at point.
14744 Optional argument DRAWER, when non-nil, is a string representing
14745 drawer's name. Otherwise, the user is prompted for a name.
14747 If a region is active, insert the drawer around that region
14748 instead.
14750 Point is left between drawer's boundaries."
14751 (interactive "P")
14752 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14753 "LOGBOOK"))
14754 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14755 ;; internally by Org. They are meant to be inserted
14756 ;; automatically.
14757 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14758 ;; Remove system drawers from list. Note: For some reason,
14759 ;; `org-completing-read' ignores the predicate while
14760 ;; `completing-read' handles it fine.
14761 (drawer (if arg "PROPERTIES"
14762 (or drawer
14763 (completing-read
14764 "Drawer: " org-drawers
14765 (lambda (d) (not (member d system-drawers))))))))
14766 (cond
14767 ;; With C-u, fall back on `org-insert-property-drawer'
14768 (arg (org-insert-property-drawer))
14769 ;; With an active region, insert a drawer at point.
14770 ((not (org-region-active-p))
14771 (progn
14772 (unless (bolp) (insert "\n"))
14773 (insert (format ":%s:\n\n:END:\n" drawer))
14774 (forward-line -2)))
14775 ;; Otherwise, insert the drawer at point
14777 (let ((rbeg (region-beginning))
14778 (rend (copy-marker (region-end))))
14779 (unwind-protect
14780 (progn
14781 (goto-char rbeg)
14782 (beginning-of-line)
14783 (when (save-excursion
14784 (re-search-forward org-outline-regexp-bol rend t))
14785 (error "Drawers cannot contain headlines"))
14786 ;; Position point at the beginning of the first
14787 ;; non-blank line in region. Insert drawer's opening
14788 ;; there, then indent it.
14789 (org-skip-whitespace)
14790 (beginning-of-line)
14791 (insert ":" drawer ":\n")
14792 (forward-line -1)
14793 (indent-for-tab-command)
14794 ;; Move point to the beginning of the first blank line
14795 ;; after the last non-blank line in region. Insert
14796 ;; drawer's closing, then indent it.
14797 (goto-char rend)
14798 (skip-chars-backward " \r\t\n")
14799 (insert "\n:END:")
14800 (deactivate-mark t)
14801 (indent-for-tab-command)
14802 (unless (eolp) (insert "\n")))
14803 ;; Clear marker, whatever the outcome of insertion is.
14804 (set-marker rend nil)))))))
14806 (defvar org-property-set-functions-alist nil
14807 "Property set function alist.
14808 Each entry should have the following format:
14810 (PROPERTY . READ-FUNCTION)
14812 The read function will be called with the same argument as
14813 `org-completing-read'.")
14815 (defun org-set-property-function (property)
14816 "Get the function that should be used to set PROPERTY.
14817 This is computed according to `org-property-set-functions-alist'."
14818 (or (cdr (assoc property org-property-set-functions-alist))
14819 'org-completing-read))
14821 (defun org-read-property-value (property)
14822 "Read PROPERTY value from user."
14823 (let* ((completion-ignore-case t)
14824 (allowed (org-property-get-allowed-values nil property 'table))
14825 (cur (org-entry-get nil property))
14826 (prompt (concat property " value"
14827 (if (and cur (string-match "\\S-" cur))
14828 (concat " [" cur "]") "") ": "))
14829 (set-function (org-set-property-function property))
14830 (val (if allowed
14831 (funcall set-function prompt allowed nil
14832 (not (get-text-property 0 'org-unrestricted
14833 (caar allowed))))
14834 (let (org-completion-use-ido org-completion-use-iswitchb)
14835 (funcall set-function prompt
14836 (mapcar 'list (org-property-values property))
14837 nil nil "" nil cur)))))
14838 (if (equal val "")
14840 val)))
14842 (defvar org-last-set-property nil)
14843 (defun org-read-property-name ()
14844 "Read a property name."
14845 (let* ((completion-ignore-case t)
14846 (keys (org-buffer-property-keys nil t t))
14847 (default-prop (or (save-excursion
14848 (save-match-data
14849 (beginning-of-line)
14850 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14851 (null (string= (match-string 1) "END"))
14852 (match-string 1))))
14853 org-last-set-property))
14854 (property (org-icompleting-read
14855 (concat "Property"
14856 (if default-prop (concat " [" default-prop "]") "")
14857 ": ")
14858 (mapcar 'list keys)
14859 nil nil nil nil
14860 default-prop
14862 (if (member property keys)
14863 property
14864 (or (cdr (assoc (downcase property)
14865 (mapcar (lambda (x) (cons (downcase x) x))
14866 keys)))
14867 property))))
14869 (defun org-set-property (property value)
14870 "In the current entry, set PROPERTY to VALUE.
14871 When called interactively, this will prompt for a property name, offering
14872 completion on existing and default properties. And then it will prompt
14873 for a value, offering completion either on allowed values (via an inherited
14874 xxx_ALL property) or on existing values in other instances of this property
14875 in the current file."
14876 (interactive (list nil nil))
14877 (let* ((property (or property (org-read-property-name)))
14878 (value (or value (org-read-property-value property)))
14879 (fn (cdr (assoc property org-properties-postprocess-alist))))
14880 (setq org-last-set-property property)
14881 ;; Possibly postprocess the inserted value:
14882 (when fn (setq value (funcall fn value)))
14883 (unless (equal (org-entry-get nil property) value)
14884 (org-entry-put nil property value))))
14886 (defun org-delete-property (property)
14887 "In the current entry, delete PROPERTY."
14888 (interactive
14889 (let* ((completion-ignore-case t)
14890 (prop (org-icompleting-read "Property: "
14891 (org-entry-properties nil 'standard))))
14892 (list prop)))
14893 (message "Property %s %s" property
14894 (if (org-entry-delete nil property)
14895 "deleted"
14896 "was not present in the entry")))
14898 (defun org-delete-property-globally (property)
14899 "Remove PROPERTY globally, from all entries."
14900 (interactive
14901 (let* ((completion-ignore-case t)
14902 (prop (org-icompleting-read
14903 "Globally remove property: "
14904 (mapcar 'list (org-buffer-property-keys)))))
14905 (list prop)))
14906 (save-excursion
14907 (save-restriction
14908 (widen)
14909 (goto-char (point-min))
14910 (let ((cnt 0))
14911 (while (re-search-forward
14912 (org-re-property property)
14913 nil t)
14914 (setq cnt (1+ cnt))
14915 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14916 (message "Property \"%s\" removed from %d entries" property cnt)))))
14918 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14920 (defun org-compute-property-at-point ()
14921 "Compute the property at point.
14922 This looks for an enclosing column format, extracts the operator and
14923 then applies it to the property in the column format's scope."
14924 (interactive)
14925 (unless (org-at-property-p)
14926 (error "Not at a property"))
14927 (let ((prop (org-match-string-no-properties 2)))
14928 (org-columns-get-format-and-top-level)
14929 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14930 (error "No operator defined for property %s" prop))
14931 (org-columns-compute prop)))
14933 (defvar org-property-allowed-value-functions nil
14934 "Hook for functions supplying allowed values for a specific property.
14935 The functions must take a single argument, the name of the property, and
14936 return a flat list of allowed values. If \":ETC\" is one of
14937 the values, this means that these values are intended as defaults for
14938 completion, but that other values should be allowed too.
14939 The functions must return nil if they are not responsible for this
14940 property.")
14942 (defun org-property-get-allowed-values (pom property &optional table)
14943 "Get allowed values for the property PROPERTY.
14944 When TABLE is non-nil, return an alist that can directly be used for
14945 completion."
14946 (let (vals)
14947 (cond
14948 ((equal property "TODO")
14949 (setq vals (org-with-point-at pom
14950 (append org-todo-keywords-1 '("")))))
14951 ((equal property "PRIORITY")
14952 (let ((n org-lowest-priority))
14953 (while (>= n org-highest-priority)
14954 (push (char-to-string n) vals)
14955 (setq n (1- n)))))
14956 ((member property org-special-properties))
14957 ((setq vals (run-hook-with-args-until-success
14958 'org-property-allowed-value-functions property)))
14960 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14961 (when (and vals (string-match "\\S-" vals))
14962 (setq vals (car (read-from-string (concat "(" vals ")"))))
14963 (setq vals (mapcar (lambda (x)
14964 (cond ((stringp x) x)
14965 ((numberp x) (number-to-string x))
14966 ((symbolp x) (symbol-name x))
14967 (t "???")))
14968 vals)))))
14969 (when (member ":ETC" vals)
14970 (setq vals (remove ":ETC" vals))
14971 (org-add-props (car vals) '(org-unrestricted t)))
14972 (if table (mapcar 'list vals) vals)))
14974 (defun org-property-previous-allowed-value (&optional previous)
14975 "Switch to the next allowed value for this property."
14976 (interactive)
14977 (org-property-next-allowed-value t))
14979 (defun org-property-next-allowed-value (&optional previous)
14980 "Switch to the next allowed value for this property."
14981 (interactive)
14982 (unless (org-at-property-p)
14983 (error "Not at a property"))
14984 (let* ((key (match-string 2))
14985 (value (match-string 3))
14986 (allowed (or (org-property-get-allowed-values (point) key)
14987 (and (member value '("[ ]" "[-]" "[X]"))
14988 '("[ ]" "[X]"))))
14989 nval)
14990 (unless allowed
14991 (error "Allowed values for this property have not been defined"))
14992 (if previous (setq allowed (reverse allowed)))
14993 (if (member value allowed)
14994 (setq nval (car (cdr (member value allowed)))))
14995 (setq nval (or nval (car allowed)))
14996 (if (equal nval value)
14997 (error "Only one allowed value for this property"))
14998 (org-at-property-p)
14999 (replace-match (concat " :" key ": " nval) t t)
15000 (org-indent-line)
15001 (beginning-of-line 1)
15002 (skip-chars-forward " \t")
15003 (run-hook-with-args 'org-property-changed-functions key nval)))
15005 (defun org-find-olp (path &optional this-buffer)
15006 "Return a marker pointing to the entry at outline path OLP.
15007 If anything goes wrong, throw an error.
15008 You can wrap this call to catch the error like this:
15010 (condition-case msg
15011 (org-mobile-locate-entry (match-string 4))
15012 (error (nth 1 msg)))
15014 The return value will then be either a string with the error message,
15015 or a marker if everything is OK.
15017 If THIS-BUFFER is set, the outline path does not contain a file,
15018 only headings."
15019 (let* ((file (if this-buffer buffer-file-name (pop path)))
15020 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15021 (level 1)
15022 (lmin 1)
15023 (lmax 1)
15024 limit re end found pos heading cnt flevel)
15025 (unless buffer (error "File not found :%s" file))
15026 (with-current-buffer buffer
15027 (save-excursion
15028 (save-restriction
15029 (widen)
15030 (setq limit (point-max))
15031 (goto-char (point-min))
15032 (while (setq heading (pop path))
15033 (setq re (format org-complex-heading-regexp-format
15034 (regexp-quote heading)))
15035 (setq cnt 0 pos (point))
15036 (while (re-search-forward re end t)
15037 (setq level (- (match-end 1) (match-beginning 1)))
15038 (if (and (>= level lmin) (<= level lmax))
15039 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15040 (when (= cnt 0) (error "Heading not found on level %d: %s"
15041 lmax heading))
15042 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15043 lmax heading))
15044 (goto-char found)
15045 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15046 (setq end (save-excursion (org-end-of-subtree t t))))
15047 (when (org-at-heading-p)
15048 (move-marker (make-marker) (point))))))))
15050 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15051 "Find node HEADING in BUFFER.
15052 Return a marker to the heading if it was found, or nil if not.
15053 If POS-ONLY is set, return just the position instead of a marker.
15055 The heading text must match exact, but it may have a TODO keyword,
15056 a priority cookie and tags in the standard locations."
15057 (with-current-buffer (or buffer (current-buffer))
15058 (save-excursion
15059 (save-restriction
15060 (widen)
15061 (goto-char (point-min))
15062 (let (case-fold-search)
15063 (if (re-search-forward
15064 (format org-complex-heading-regexp-format
15065 (regexp-quote heading)) nil t)
15066 (if pos-only
15067 (match-beginning 0)
15068 (move-marker (make-marker) (match-beginning 0)))))))))
15070 (defun org-find-exact-heading-in-directory (heading &optional dir)
15071 "Find Org node headline HEADING in all .org files in directory DIR.
15072 When the target headline is found, return a marker to this location."
15073 (let ((files (directory-files (or dir default-directory)
15074 nil "\\`[^.#].*\\.org\\'"))
15075 file visiting m buffer)
15076 (catch 'found
15077 (while (setq file (pop files))
15078 (message "trying %s" file)
15079 (setq visiting (org-find-base-buffer-visiting file))
15080 (setq buffer (or visiting (find-file-noselect file)))
15081 (setq m (org-find-exact-headline-in-buffer
15082 heading buffer))
15083 (when (and (not m) (not visiting)) (kill-buffer buffer))
15084 (and m (throw 'found m))))))
15086 (defun org-find-entry-with-id (ident)
15087 "Locate the entry that contains the ID property with exact value IDENT.
15088 IDENT can be a string, a symbol or a number, this function will search for
15089 the string representation of it.
15090 Return the position where this entry starts, or nil if there is no such entry."
15091 (interactive "sID: ")
15092 (let ((id (cond
15093 ((stringp ident) ident)
15094 ((symbol-name ident) (symbol-name ident))
15095 ((numberp ident) (number-to-string ident))
15096 (t (error "IDENT %s must be a string, symbol or number" ident))))
15097 (case-fold-search nil))
15098 (save-excursion
15099 (save-restriction
15100 (widen)
15101 (goto-char (point-min))
15102 (when (re-search-forward
15103 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15104 nil t)
15105 (org-back-to-heading t)
15106 (point))))))
15108 ;;;; Timestamps
15110 (defvar org-last-changed-timestamp nil)
15111 (defvar org-last-inserted-timestamp nil
15112 "The last time stamp inserted with `org-insert-time-stamp'.")
15113 (defvar org-time-was-given) ; dynamically scoped parameter
15114 (defvar org-end-time-was-given) ; dynamically scoped parameter
15115 (defvar org-ts-what) ; dynamically scoped parameter
15117 (defun org-time-stamp (arg &optional inactive)
15118 "Prompt for a date/time and insert a time stamp.
15119 If the user specifies a time like HH:MM or if this command is
15120 called with at least one prefix argument, the time stamp contains
15121 the date and the time. Otherwise, only the date is be included.
15123 All parts of a date not specified by the user is filled in from
15124 the current date/time. So if you just press return without
15125 typing anything, the time stamp will represent the current
15126 date/time.
15128 If there is already a timestamp at the cursor, it will be
15129 modified.
15131 With two universal prefix arguments, insert an active timestamp
15132 with the current time without prompting the user."
15133 (interactive "P")
15134 (let* ((ts nil)
15135 (default-time
15136 ;; Default time is either today, or, when entering a range,
15137 ;; the range start.
15138 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15139 (save-excursion
15140 (re-search-backward
15141 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15142 (- (point) 20) t)))
15143 (apply 'encode-time (org-parse-time-string (match-string 1)))
15144 (current-time)))
15145 (default-input (and ts (org-get-compact-tod ts)))
15146 (repeater (save-excursion
15147 (save-match-data
15148 (beginning-of-line)
15149 (when (re-search-forward
15150 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15151 (save-excursion (progn (end-of-line) (point))) t)
15152 (match-string 0)))))
15153 org-time-was-given org-end-time-was-given time)
15154 (cond
15155 ((and (org-at-timestamp-p t)
15156 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15157 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15158 (insert "--")
15159 (setq time (let ((this-command this-command))
15160 (org-read-date arg 'totime nil nil
15161 default-time default-input inactive)))
15162 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15163 ((org-at-timestamp-p t)
15164 (setq time (let ((this-command this-command))
15165 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15166 (when (org-at-timestamp-p t) ; just to get the match data
15167 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15168 (replace-match "")
15169 (setq org-last-changed-timestamp
15170 (org-insert-time-stamp
15171 time (or org-time-was-given arg)
15172 inactive nil nil (list org-end-time-was-given)))
15173 (when repeater (goto-char (1- (point))) (insert " " repeater)
15174 (setq org-last-changed-timestamp
15175 (concat (substring org-last-inserted-timestamp 0 -1)
15176 " " repeater ">"))))
15177 (message "Timestamp updated"))
15178 ((equal arg '(16))
15179 (org-insert-time-stamp (current-time) t))
15181 (setq time (let ((this-command this-command))
15182 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15183 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15184 nil nil (list org-end-time-was-given))))))
15186 ;; FIXME: can we use this for something else, like computing time differences?
15187 (defun org-get-compact-tod (s)
15188 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15189 (let* ((t1 (match-string 1 s))
15190 (h1 (string-to-number (match-string 2 s)))
15191 (m1 (string-to-number (match-string 3 s)))
15192 (t2 (and (match-end 4) (match-string 5 s)))
15193 (h2 (and t2 (string-to-number (match-string 6 s))))
15194 (m2 (and t2 (string-to-number (match-string 7 s))))
15195 dh dm)
15196 (if (not t2)
15198 (setq dh (- h2 h1) dm (- m2 m1))
15199 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15200 (concat t1 "+" (number-to-string dh)
15201 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15203 (defun org-time-stamp-inactive (&optional arg)
15204 "Insert an inactive time stamp.
15205 An inactive time stamp is enclosed in square brackets instead of angle
15206 brackets. It is inactive in the sense that it does not trigger agenda entries,
15207 does not link to the calendar and cannot be changed with the S-cursor keys.
15208 So these are more for recording a certain time/date."
15209 (interactive "P")
15210 (org-time-stamp arg 'inactive))
15212 (defvar org-date-ovl (make-overlay 1 1))
15213 (overlay-put org-date-ovl 'face 'org-date-selected)
15214 (org-detach-overlay org-date-ovl)
15216 (defvar org-ans1) ; dynamically scoped parameter
15217 (defvar org-ans2) ; dynamically scoped parameter
15219 (defvar org-plain-time-of-day-regexp) ; defined below
15221 (defvar org-overriding-default-time nil) ; dynamically scoped
15222 (defvar org-read-date-overlay nil)
15223 (defvar org-dcst nil) ; dynamically scoped
15224 (defvar org-read-date-history nil)
15225 (defvar org-read-date-final-answer nil)
15226 (defvar org-read-date-analyze-futurep nil)
15227 (defvar org-read-date-analyze-forced-year nil)
15228 (defvar org-read-date-inactive)
15230 (defun org-read-date (&optional org-with-time to-time from-string prompt
15231 default-time default-input inactive)
15232 "Read a date, possibly a time, and make things smooth for the user.
15233 The prompt will suggest to enter an ISO date, but you can also enter anything
15234 which will at least partially be understood by `parse-time-string'.
15235 Unrecognized parts of the date will default to the current day, month, year,
15236 hour and minute. If this command is called to replace a timestamp at point,
15237 or to enter the second timestamp of a range, the default time is taken
15238 from the existing stamp. Furthermore, the command prefers the future,
15239 so if you are giving a date where the year is not given, and the day-month
15240 combination is already past in the current year, it will assume you
15241 mean next year. For details, see the manual. A few examples:
15243 3-2-5 --> 2003-02-05
15244 feb 15 --> currentyear-02-15
15245 2/15 --> currentyear-02-15
15246 sep 12 9 --> 2009-09-12
15247 12:45 --> today 12:45
15248 22 sept 0:34 --> currentyear-09-22 0:34
15249 12 --> currentyear-currentmonth-12
15250 Fri --> nearest Friday (today or later)
15251 etc.
15253 Furthermore you can specify a relative date by giving, as the *first* thing
15254 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15255 change in days weeks, months, years.
15256 With a single plus or minus, the date is relative to today. With a double
15257 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15258 +4d --> four days from today
15259 +4 --> same as above
15260 +2w --> two weeks from today
15261 ++5 --> five days from default date
15263 The function understands only English month and weekday abbreviations.
15265 While prompting, a calendar is popped up - you can also select the
15266 date with the mouse (button 1). The calendar shows a period of three
15267 months. To scroll it to other months, use the keys `>' and `<'.
15268 If you don't like the calendar, turn it off with
15269 \(setq org-read-date-popup-calendar nil)
15271 With optional argument TO-TIME, the date will immediately be converted
15272 to an internal time.
15273 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15274 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15275 still enter a time, and this function will inform the calling routine
15276 about this change. The calling routine may then choose to change the
15277 format used to insert the time stamp into the buffer to include the time.
15278 With optional argument FROM-STRING, read from this string instead from
15279 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15280 the time/date that is used for everything that is not specified by the
15281 user."
15282 (require 'parse-time)
15283 (let* ((org-time-stamp-rounding-minutes
15284 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15285 (org-dcst org-display-custom-times)
15286 (ct (org-current-time))
15287 (org-def (or org-overriding-default-time default-time ct))
15288 (org-defdecode (decode-time org-def))
15289 (dummy (progn
15290 (when (< (nth 2 org-defdecode) org-extend-today-until)
15291 (setcar (nthcdr 2 org-defdecode) -1)
15292 (setcar (nthcdr 1 org-defdecode) 59)
15293 (setq org-def (apply 'encode-time org-defdecode)
15294 org-defdecode (decode-time org-def)))))
15295 (calendar-frame-setup nil)
15296 (calendar-setup nil)
15297 (calendar-move-hook nil)
15298 (calendar-view-diary-initially-flag nil)
15299 (calendar-view-holidays-initially-flag nil)
15300 (timestr (format-time-string
15301 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15302 (prompt (concat (if prompt (concat prompt " ") "")
15303 (format "Date+time [%s]: " timestr)))
15304 ans (org-ans0 "") org-ans1 org-ans2 final)
15306 (cond
15307 (from-string (setq ans from-string))
15308 (org-read-date-popup-calendar
15309 (save-excursion
15310 (save-window-excursion
15311 (calendar)
15312 (org-eval-in-calendar '(setq cursor-type nil) t)
15313 (unwind-protect
15314 (progn
15315 (calendar-forward-day (- (time-to-days org-def)
15316 (calendar-absolute-from-gregorian
15317 (calendar-current-date))))
15318 (org-eval-in-calendar nil t)
15319 (let* ((old-map (current-local-map))
15320 (map (copy-keymap calendar-mode-map))
15321 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15322 (org-defkey map (kbd "RET") 'org-calendar-select)
15323 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15324 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15325 (org-defkey minibuffer-local-map [(meta shift left)]
15326 (lambda () (interactive)
15327 (org-eval-in-calendar '(calendar-backward-month 1))))
15328 (org-defkey minibuffer-local-map [(meta shift right)]
15329 (lambda () (interactive)
15330 (org-eval-in-calendar '(calendar-forward-month 1))))
15331 (org-defkey minibuffer-local-map [(meta shift up)]
15332 (lambda () (interactive)
15333 (org-eval-in-calendar '(calendar-backward-year 1))))
15334 (org-defkey minibuffer-local-map [(meta shift down)]
15335 (lambda () (interactive)
15336 (org-eval-in-calendar '(calendar-forward-year 1))))
15337 (org-defkey minibuffer-local-map [?\e (shift left)]
15338 (lambda () (interactive)
15339 (org-eval-in-calendar '(calendar-backward-month 1))))
15340 (org-defkey minibuffer-local-map [?\e (shift right)]
15341 (lambda () (interactive)
15342 (org-eval-in-calendar '(calendar-forward-month 1))))
15343 (org-defkey minibuffer-local-map [?\e (shift up)]
15344 (lambda () (interactive)
15345 (org-eval-in-calendar '(calendar-backward-year 1))))
15346 (org-defkey minibuffer-local-map [?\e (shift down)]
15347 (lambda () (interactive)
15348 (org-eval-in-calendar '(calendar-forward-year 1))))
15349 (org-defkey minibuffer-local-map [(shift up)]
15350 (lambda () (interactive)
15351 (org-eval-in-calendar '(calendar-backward-week 1))))
15352 (org-defkey minibuffer-local-map [(shift down)]
15353 (lambda () (interactive)
15354 (org-eval-in-calendar '(calendar-forward-week 1))))
15355 (org-defkey minibuffer-local-map [(shift left)]
15356 (lambda () (interactive)
15357 (org-eval-in-calendar '(calendar-backward-day 1))))
15358 (org-defkey minibuffer-local-map [(shift right)]
15359 (lambda () (interactive)
15360 (org-eval-in-calendar '(calendar-forward-day 1))))
15361 (org-defkey minibuffer-local-map ">"
15362 (lambda () (interactive)
15363 (org-eval-in-calendar '(scroll-calendar-left 1))))
15364 (org-defkey minibuffer-local-map "<"
15365 (lambda () (interactive)
15366 (org-eval-in-calendar '(scroll-calendar-right 1))))
15367 (org-defkey minibuffer-local-map "\C-v"
15368 (lambda () (interactive)
15369 (org-eval-in-calendar
15370 '(calendar-scroll-left-three-months 1))))
15371 (org-defkey minibuffer-local-map "\M-v"
15372 (lambda () (interactive)
15373 (org-eval-in-calendar
15374 '(calendar-scroll-right-three-months 1))))
15375 (run-hooks 'org-read-date-minibuffer-setup-hook)
15376 (unwind-protect
15377 (progn
15378 (use-local-map map)
15379 (setq org-read-date-inactive inactive)
15380 (add-hook 'post-command-hook 'org-read-date-display)
15381 (setq org-ans0 (read-string prompt default-input
15382 'org-read-date-history nil))
15383 ;; org-ans0: from prompt
15384 ;; org-ans1: from mouse click
15385 ;; org-ans2: from calendar motion
15386 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15387 (remove-hook 'post-command-hook 'org-read-date-display)
15388 (use-local-map old-map)
15389 (when org-read-date-overlay
15390 (delete-overlay org-read-date-overlay)
15391 (setq org-read-date-overlay nil)))))
15392 (bury-buffer "*Calendar*")))))
15394 (t ; Naked prompt only
15395 (unwind-protect
15396 (setq ans (read-string prompt default-input
15397 'org-read-date-history timestr))
15398 (when org-read-date-overlay
15399 (delete-overlay org-read-date-overlay)
15400 (setq org-read-date-overlay nil)))))
15402 (setq final (org-read-date-analyze ans org-def org-defdecode))
15404 (when org-read-date-analyze-forced-year
15405 (message "Year was forced into %s"
15406 (if org-read-date-force-compatible-dates
15407 "compatible range (1970-2037)"
15408 "range representable on this machine"))
15409 (ding))
15411 ;; One round trip to get rid of 34th of August and stuff like that....
15412 (setq final (decode-time (apply 'encode-time final)))
15414 (setq org-read-date-final-answer ans)
15416 (if to-time
15417 (apply 'encode-time final)
15418 (if (and (boundp 'org-time-was-given) org-time-was-given)
15419 (format "%04d-%02d-%02d %02d:%02d"
15420 (nth 5 final) (nth 4 final) (nth 3 final)
15421 (nth 2 final) (nth 1 final))
15422 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15424 (defvar org-def)
15425 (defvar org-defdecode)
15426 (defvar org-with-time)
15427 (defun org-read-date-display ()
15428 "Display the current date prompt interpretation in the minibuffer."
15429 (when org-read-date-display-live
15430 (when org-read-date-overlay
15431 (delete-overlay org-read-date-overlay))
15432 (when (minibufferp (current-buffer))
15433 (save-excursion
15434 (end-of-line 1)
15435 (while (not (equal (buffer-substring
15436 (max (point-min) (- (point) 4)) (point))
15437 " "))
15438 (insert " ")))
15439 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15440 " " (or org-ans1 org-ans2)))
15441 (org-end-time-was-given nil)
15442 (f (org-read-date-analyze ans org-def org-defdecode))
15443 (fmts (if org-dcst
15444 org-time-stamp-custom-formats
15445 org-time-stamp-formats))
15446 (fmt (if (or org-with-time
15447 (and (boundp 'org-time-was-given) org-time-was-given))
15448 (cdr fmts)
15449 (car fmts)))
15450 (txt (format-time-string fmt (apply 'encode-time f)))
15451 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15452 (txt (concat "=> " txt)))
15453 (when (and org-end-time-was-given
15454 (string-match org-plain-time-of-day-regexp txt))
15455 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15456 org-end-time-was-given
15457 (substring txt (match-end 0)))))
15458 (when org-read-date-analyze-futurep
15459 (setq txt (concat txt " (=>F)")))
15460 (setq org-read-date-overlay
15461 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15462 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15464 (defun org-read-date-analyze (ans org-def org-defdecode)
15465 "Analyze the combined answer of the date prompt."
15466 ;; FIXME: cleanup and comment
15467 (let ((nowdecode (decode-time (current-time)))
15468 delta deltan deltaw deltadef year month day
15469 hour minute second wday pm h2 m2 tl wday1
15470 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15471 (setq org-read-date-analyze-futurep nil
15472 org-read-date-analyze-forced-year nil)
15473 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15474 (setq ans "+0"))
15476 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15477 (setq ans (replace-match "" t t ans)
15478 deltan (car delta)
15479 deltaw (nth 1 delta)
15480 deltadef (nth 2 delta)))
15482 ;; Check if there is an iso week date in there. If yes, store the
15483 ;; info and postpone interpreting it until the rest of the parsing
15484 ;; is done.
15485 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15486 (setq iso-year (if (match-end 1)
15487 (org-small-year-to-year
15488 (string-to-number (match-string 1 ans))))
15489 iso-weekday (if (match-end 3)
15490 (string-to-number (match-string 3 ans)))
15491 iso-week (string-to-number (match-string 2 ans)))
15492 (setq ans (replace-match "" t t ans)))
15494 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15495 (when (string-match
15496 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15497 (setq year (if (match-end 2)
15498 (string-to-number (match-string 2 ans))
15499 (progn (setq kill-year t)
15500 (string-to-number (format-time-string "%Y"))))
15501 month (string-to-number (match-string 3 ans))
15502 day (string-to-number (match-string 4 ans)))
15503 (if (< year 100) (setq year (+ 2000 year)))
15504 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15505 t nil ans)))
15507 ;; Help matching dotted european dates
15508 (when (string-match
15509 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15510 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15511 (setq kill-year t)
15512 (string-to-number (format-time-string "%Y")))
15513 day (string-to-number (match-string 1 ans))
15514 month (string-to-number (match-string 2 ans))
15515 ans (replace-match (format "%04d-%02d-%02d" year month day)
15516 t nil ans)))
15518 ;; Help matching american dates, like 5/30 or 5/30/7
15519 (when (string-match
15520 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15521 (setq year (if (match-end 4)
15522 (string-to-number (match-string 4 ans))
15523 (progn (setq kill-year t)
15524 (string-to-number (format-time-string "%Y"))))
15525 month (string-to-number (match-string 1 ans))
15526 day (string-to-number (match-string 2 ans)))
15527 (if (< year 100) (setq year (+ 2000 year)))
15528 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15529 t nil ans)))
15530 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15531 ;; If there is a time with am/pm, and *no* time without it, we convert
15532 ;; so that matching will be successful.
15533 (loop for i from 1 to 2 do ; twice, for end time as well
15534 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15535 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15536 (setq hour (string-to-number (match-string 1 ans))
15537 minute (if (match-end 3)
15538 (string-to-number (match-string 3 ans))
15540 pm (equal ?p
15541 (string-to-char (downcase (match-string 4 ans)))))
15542 (if (and (= hour 12) (not pm))
15543 (setq hour 0)
15544 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15545 (setq ans (replace-match (format "%02d:%02d" hour minute)
15546 t t ans))))
15548 ;; Check if a time range is given as a duration
15549 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15550 (setq hour (string-to-number (match-string 1 ans))
15551 h2 (+ hour (string-to-number (match-string 3 ans)))
15552 minute (string-to-number (match-string 2 ans))
15553 m2 (+ minute (if (match-end 5) (string-to-number
15554 (match-string 5 ans))0)))
15555 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15556 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15557 t t ans)))
15559 ;; Check if there is a time range
15560 (when (boundp 'org-end-time-was-given)
15561 (setq org-time-was-given nil)
15562 (when (and (string-match org-plain-time-of-day-regexp ans)
15563 (match-end 8))
15564 (setq org-end-time-was-given (match-string 8 ans))
15565 (setq ans (concat (substring ans 0 (match-beginning 7))
15566 (substring ans (match-end 7))))))
15568 (setq tl (parse-time-string ans)
15569 day (or (nth 3 tl) (nth 3 org-defdecode))
15570 month (or (nth 4 tl)
15571 (if (and org-read-date-prefer-future
15572 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15573 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15574 (nth 4 org-defdecode)))
15575 year (or (and (not kill-year) (nth 5 tl))
15576 (if (and org-read-date-prefer-future
15577 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15578 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15579 (nth 5 org-defdecode)))
15580 hour (or (nth 2 tl) (nth 2 org-defdecode))
15581 minute (or (nth 1 tl) (nth 1 org-defdecode))
15582 second (or (nth 0 tl) 0)
15583 wday (nth 6 tl))
15585 (when (and (eq org-read-date-prefer-future 'time)
15586 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15587 (equal day (nth 3 nowdecode))
15588 (equal month (nth 4 nowdecode))
15589 (equal year (nth 5 nowdecode))
15590 (nth 2 tl)
15591 (or (< (nth 2 tl) (nth 2 nowdecode))
15592 (and (= (nth 2 tl) (nth 2 nowdecode))
15593 (nth 1 tl)
15594 (< (nth 1 tl) (nth 1 nowdecode)))))
15595 (setq day (1+ day)
15596 futurep t))
15598 ;; Special date definitions below
15599 (cond
15600 (iso-week
15601 ;; There was an iso week
15602 (require 'cal-iso)
15603 (setq futurep nil)
15604 (setq year (or iso-year year)
15605 day (or iso-weekday wday 1)
15606 wday nil ; to make sure that the trigger below does not match
15607 iso-date (calendar-gregorian-from-absolute
15608 (calendar-absolute-from-iso
15609 (list iso-week day year))))
15610 ; FIXME: Should we also push ISO weeks into the future?
15611 ; (when (and org-read-date-prefer-future
15612 ; (not iso-year)
15613 ; (< (calendar-absolute-from-gregorian iso-date)
15614 ; (time-to-days (current-time))))
15615 ; (setq year (1+ year)
15616 ; iso-date (calendar-gregorian-from-absolute
15617 ; (calendar-absolute-from-iso
15618 ; (list iso-week day year)))))
15619 (setq month (car iso-date)
15620 year (nth 2 iso-date)
15621 day (nth 1 iso-date)))
15622 (deltan
15623 (setq futurep nil)
15624 (unless deltadef
15625 (let ((now (decode-time (current-time))))
15626 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15627 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15628 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15629 ((equal deltaw "m") (setq month (+ month deltan)))
15630 ((equal deltaw "y") (setq year (+ year deltan)))))
15631 ((and wday (not (nth 3 tl)))
15632 ;; Weekday was given, but no day, so pick that day in the week
15633 ;; on or after the derived date.
15634 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15635 (unless (equal wday wday1)
15636 (setq day (+ day (% (- wday wday1 -7) 7))))))
15637 (if (and (boundp 'org-time-was-given)
15638 (nth 2 tl))
15639 (setq org-time-was-given t))
15640 (if (< year 100) (setq year (+ 2000 year)))
15641 ;; Check of the date is representable
15642 (if org-read-date-force-compatible-dates
15643 (progn
15644 (if (< year 1970)
15645 (setq year 1970 org-read-date-analyze-forced-year t))
15646 (if (> year 2037)
15647 (setq year 2037 org-read-date-analyze-forced-year t)))
15648 (condition-case nil
15649 (ignore (encode-time second minute hour day month year))
15650 (error
15651 (setq year (nth 5 org-defdecode))
15652 (setq org-read-date-analyze-forced-year t))))
15653 (setq org-read-date-analyze-futurep futurep)
15654 (list second minute hour day month year)))
15656 (defvar parse-time-weekdays)
15657 (defun org-read-date-get-relative (s today default)
15658 "Check string S for special relative date string.
15659 TODAY and DEFAULT are internal times, for today and for a default.
15660 Return shift list (N what def-flag)
15661 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15662 N is the number of WHATs to shift.
15663 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15664 the DEFAULT date rather than TODAY."
15665 (require 'parse-time)
15666 (when (and
15667 (string-match
15668 (concat
15669 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15670 "\\([0-9]+\\)?"
15671 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15672 "\\([ \t]\\|$\\)") s)
15673 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15674 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15675 (string-to-char (substring (match-string 1 s) -1))
15676 ?+))
15677 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15678 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15679 (what (if (match-end 3) (match-string 3 s) "d"))
15680 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15681 (date (if rel default today))
15682 (wday (nth 6 (decode-time date)))
15683 delta)
15684 (if wday1
15685 (progn
15686 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15687 (if (= dir ?-) (setq delta (- delta 7)))
15688 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15689 (list delta "d" rel))
15690 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15692 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15693 "Turn a user-specified date into the internal representation.
15694 The internal representation needed by the calendar is (month day year).
15695 This is a wrapper to handle the brain-dead convention in calendar that
15696 user function argument order change dependent on argument order."
15697 (if (boundp 'calendar-date-style)
15698 (cond
15699 ((eq calendar-date-style 'american)
15700 (list arg1 arg2 arg3))
15701 ((eq calendar-date-style 'european)
15702 (list arg2 arg1 arg3))
15703 ((eq calendar-date-style 'iso)
15704 (list arg2 arg3 arg1)))
15705 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15706 (if (org-bound-and-true-p european-calendar-style)
15707 (list arg2 arg1 arg3)
15708 (list arg1 arg2 arg3)))))
15710 (defun org-eval-in-calendar (form &optional keepdate)
15711 "Eval FORM in the calendar window and return to current window.
15712 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15713 otherwise stick to the current value of `org-ans2'."
15714 (let ((sf (selected-frame))
15715 (sw (selected-window)))
15716 (select-window (get-buffer-window "*Calendar*" t))
15717 (eval form)
15718 (when (and (not keepdate) (calendar-cursor-to-date))
15719 (let* ((date (calendar-cursor-to-date))
15720 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15721 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15722 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15723 (select-window sw)
15724 (org-select-frame-set-input-focus sf)))
15726 (defun org-calendar-select ()
15727 "Return to `org-read-date' with the date currently selected.
15728 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15729 (interactive)
15730 (when (calendar-cursor-to-date)
15731 (let* ((date (calendar-cursor-to-date))
15732 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15733 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15734 (if (active-minibuffer-window) (exit-minibuffer))))
15736 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15737 "Insert a date stamp for the date given by the internal TIME.
15738 WITH-HM means use the stamp format that includes the time of the day.
15739 INACTIVE means use square brackets instead of angular ones, so that the
15740 stamp will not contribute to the agenda.
15741 PRE and POST are optional strings to be inserted before and after the
15742 stamp.
15743 The command returns the inserted time stamp."
15744 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15745 stamp)
15746 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15747 (insert-before-markers (or pre ""))
15748 (when (listp extra)
15749 (setq extra (car extra))
15750 (if (and (stringp extra)
15751 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15752 (setq extra (format "-%02d:%02d"
15753 (string-to-number (match-string 1 extra))
15754 (string-to-number (match-string 2 extra))))
15755 (setq extra nil)))
15756 (when extra
15757 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15758 (insert-before-markers (setq stamp (format-time-string fmt time)))
15759 (insert-before-markers (or post ""))
15760 (setq org-last-inserted-timestamp stamp)))
15762 (defun org-toggle-time-stamp-overlays ()
15763 "Toggle the use of custom time stamp formats."
15764 (interactive)
15765 (setq org-display-custom-times (not org-display-custom-times))
15766 (unless org-display-custom-times
15767 (let ((p (point-min)) (bmp (buffer-modified-p)))
15768 (while (setq p (next-single-property-change p 'display))
15769 (if (and (get-text-property p 'display)
15770 (eq (get-text-property p 'face) 'org-date))
15771 (remove-text-properties
15772 p (setq p (next-single-property-change p 'display))
15773 '(display t))))
15774 (set-buffer-modified-p bmp)))
15775 (if (featurep 'xemacs)
15776 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15777 (org-restart-font-lock)
15778 (setq org-table-may-need-update t)
15779 (if org-display-custom-times
15780 (message "Time stamps are overlaid with custom format")
15781 (message "Time stamp overlays removed")))
15783 (defun org-display-custom-time (beg end)
15784 "Overlay modified time stamp format over timestamp between BEG and END."
15785 (let* ((ts (buffer-substring beg end))
15786 t1 w1 with-hm tf time str w2 (off 0))
15787 (save-match-data
15788 (setq t1 (org-parse-time-string ts t))
15789 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15790 (setq off (- (match-end 0) (match-beginning 0)))))
15791 (setq end (- end off))
15792 (setq w1 (- end beg)
15793 with-hm (and (nth 1 t1) (nth 2 t1))
15794 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15795 time (org-fix-decoded-time t1)
15796 str (org-add-props
15797 (format-time-string
15798 (substring tf 1 -1) (apply 'encode-time time))
15799 nil 'mouse-face 'highlight)
15800 w2 (length str))
15801 (if (not (= w2 w1))
15802 (add-text-properties (1+ beg) (+ 2 beg)
15803 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15804 (if (featurep 'xemacs)
15805 (progn
15806 (put-text-property beg end 'invisible t)
15807 (put-text-property beg end 'end-glyph (make-glyph str)))
15808 (put-text-property beg end 'display str))))
15810 (defun org-translate-time (string)
15811 "Translate all timestamps in STRING to custom format.
15812 But do this only if the variable `org-display-custom-times' is set."
15813 (when org-display-custom-times
15814 (save-match-data
15815 (let* ((start 0)
15816 (re org-ts-regexp-both)
15817 t1 with-hm inactive tf time str beg end)
15818 (while (setq start (string-match re string start))
15819 (setq beg (match-beginning 0)
15820 end (match-end 0)
15821 t1 (save-match-data
15822 (org-parse-time-string (substring string beg end) t))
15823 with-hm (and (nth 1 t1) (nth 2 t1))
15824 inactive (equal (substring string beg (1+ beg)) "[")
15825 tf (funcall (if with-hm 'cdr 'car)
15826 org-time-stamp-custom-formats)
15827 time (org-fix-decoded-time t1)
15828 str (format-time-string
15829 (concat
15830 (if inactive "[" "<") (substring tf 1 -1)
15831 (if inactive "]" ">"))
15832 (apply 'encode-time time))
15833 string (replace-match str t t string)
15834 start (+ start (length str)))))))
15835 string)
15837 (defun org-fix-decoded-time (time)
15838 "Set 0 instead of nil for the first 6 elements of time.
15839 Don't touch the rest."
15840 (let ((n 0))
15841 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15843 (defun org-days-to-time (timestamp-string)
15844 "Difference between TIMESTAMP-STRING and now in days."
15845 (- (time-to-days (org-time-string-to-time timestamp-string))
15846 (time-to-days (current-time))))
15848 (defun org-deadline-close (timestamp-string &optional ndays)
15849 "Is the time in TIMESTAMP-STRING close to the current date?"
15850 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15851 (and (< (org-days-to-time timestamp-string) ndays)
15852 (not (org-entry-is-done-p))))
15854 (defun org-get-wdays (ts)
15855 "Get the deadline lead time appropriate for timestring TS."
15856 (cond
15857 ((<= org-deadline-warning-days 0)
15858 ;; 0 or negative, enforce this value no matter what
15859 (- org-deadline-warning-days))
15860 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15861 ;; lead time is specified.
15862 (floor (* (string-to-number (match-string 1 ts))
15863 (cdr (assoc (match-string 2 ts)
15864 '(("d" . 1) ("w" . 7)
15865 ("m" . 30.4) ("y" . 365.25)))))))
15866 ;; go for the default.
15867 (t org-deadline-warning-days)))
15869 (defun org-calendar-select-mouse (ev)
15870 "Return to `org-read-date' with the date currently selected.
15871 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15872 (interactive "e")
15873 (mouse-set-point ev)
15874 (when (calendar-cursor-to-date)
15875 (let* ((date (calendar-cursor-to-date))
15876 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15877 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15878 (if (active-minibuffer-window) (exit-minibuffer))))
15880 (defun org-check-deadlines (ndays)
15881 "Check if there are any deadlines due or past due.
15882 A deadline is considered due if it happens within `org-deadline-warning-days'
15883 days from today's date. If the deadline appears in an entry marked DONE,
15884 it is not shown. The prefix arg NDAYS can be used to test that many
15885 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15886 (interactive "P")
15887 (let* ((org-warn-days
15888 (cond
15889 ((equal ndays '(4)) 100000)
15890 (ndays (prefix-numeric-value ndays))
15891 (t (abs org-deadline-warning-days))))
15892 (case-fold-search nil)
15893 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15894 (callback
15895 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15897 (message "%d deadlines past-due or due within %d days"
15898 (org-occur regexp nil callback)
15899 org-warn-days)))
15901 (defsubst org-re-timestamp (type)
15902 "Return a regexp for timestamp TYPE.
15903 Allowed values for TYPE are:
15905 all: all timestamps
15906 active: only active timestamps (<...>)
15907 inactive: only inactive timestamps ([...])
15908 scheduled: only scheduled timestamps
15909 deadline: only deadline timestamps
15911 When TYPE is nil, fall back on returning a regexp that matches
15912 both scheduled and deadline timestamps."
15913 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15914 ((eq type 'active) org-ts-regexp)
15915 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15916 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15917 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15918 ((eq type 'scheduled-or-deadline)
15919 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15921 (defun org-check-before-date (date)
15922 "Check if there are deadlines or scheduled entries before DATE."
15923 (interactive (list (org-read-date)))
15924 (let ((case-fold-search nil)
15925 (regexp (org-re-timestamp org-ts-type))
15926 (callback
15927 (lambda () (time-less-p
15928 (org-time-string-to-time (match-string 1))
15929 (org-time-string-to-time date)))))
15930 (message "%d entries before %s"
15931 (org-occur regexp nil callback) date)))
15933 (defun org-check-after-date (date)
15934 "Check if there are deadlines or scheduled entries after DATE."
15935 (interactive (list (org-read-date)))
15936 (let ((case-fold-search nil)
15937 (regexp (org-re-timestamp org-ts-type))
15938 (callback
15939 (lambda () (not
15940 (time-less-p
15941 (org-time-string-to-time (match-string 1))
15942 (org-time-string-to-time date))))))
15943 (message "%d entries after %s"
15944 (org-occur regexp nil callback) date)))
15946 (defun org-check-dates-range (start-date end-date)
15947 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15948 (interactive (list (org-read-date nil nil nil "Range starts")
15949 (org-read-date nil nil nil "Range end")))
15950 (let ((case-fold-search nil)
15951 (regexp (org-re-timestamp org-ts-type))
15952 (callback
15953 (lambda ()
15954 (let ((match (match-string 1)))
15955 (and
15956 (not (time-less-p
15957 (org-time-string-to-time match)
15958 (org-time-string-to-time start-date)))
15959 (time-less-p
15960 (org-time-string-to-time match)
15961 (org-time-string-to-time end-date)))))))
15962 (message "%d entries between %s and %s"
15963 (org-occur regexp nil callback) start-date end-date)))
15965 (defun org-evaluate-time-range (&optional to-buffer)
15966 "Evaluate a time range by computing the difference between start and end.
15967 Normally the result is just printed in the echo area, but with prefix arg
15968 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15969 If the time range is actually in a table, the result is inserted into the
15970 next column.
15971 For time difference computation, a year is assumed to be exactly 365
15972 days in order to avoid rounding problems."
15973 (interactive "P")
15975 (org-clock-update-time-maybe)
15976 (save-excursion
15977 (unless (org-at-date-range-p t)
15978 (goto-char (point-at-bol))
15979 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15980 (if (not (org-at-date-range-p t))
15981 (error "Not at a time-stamp range, and none found in current line")))
15982 (let* ((ts1 (match-string 1))
15983 (ts2 (match-string 2))
15984 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15985 (match-end (match-end 0))
15986 (time1 (org-time-string-to-time ts1))
15987 (time2 (org-time-string-to-time ts2))
15988 (t1 (org-float-time time1))
15989 (t2 (org-float-time time2))
15990 (diff (abs (- t2 t1)))
15991 (negative (< (- t2 t1) 0))
15992 ;; (ys (floor (* 365 24 60 60)))
15993 (ds (* 24 60 60))
15994 (hs (* 60 60))
15995 (fy "%dy %dd %02d:%02d")
15996 (fy1 "%dy %dd")
15997 (fd "%dd %02d:%02d")
15998 (fd1 "%dd")
15999 (fh "%02d:%02d")
16000 y d h m align)
16001 (if havetime
16002 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16004 d (floor (/ diff ds)) diff (mod diff ds)
16005 h (floor (/ diff hs)) diff (mod diff hs)
16006 m (floor (/ diff 60)))
16007 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16009 d (floor (+ (/ diff ds) 0.5))
16010 h 0 m 0))
16011 (if (not to-buffer)
16012 (message "%s" (org-make-tdiff-string y d h m))
16013 (if (org-at-table-p)
16014 (progn
16015 (goto-char match-end)
16016 (setq align t)
16017 (and (looking-at " *|") (goto-char (match-end 0))))
16018 (goto-char match-end))
16019 (if (looking-at
16020 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16021 (replace-match ""))
16022 (if negative (insert " -"))
16023 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16024 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16025 (insert " " (format fh h m))))
16026 (if align (org-table-align))
16027 (message "Time difference inserted")))))
16029 (defun org-make-tdiff-string (y d h m)
16030 (let ((fmt "")
16031 (l nil))
16032 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16033 l (push y l)))
16034 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16035 l (push d l)))
16036 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16037 l (push h l)))
16038 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16039 l (push m l)))
16040 (apply 'format fmt (nreverse l))))
16042 (defun org-time-string-to-time (s &optional buffer pos)
16043 "Convert a timestamp string into internal time."
16044 (condition-case errdata
16045 (apply 'encode-time (org-parse-time-string s))
16046 (error (error "Bad timestamp `%s'%s\nError was: %s"
16047 s (if (not (and buffer pos))
16049 (format " at %d in buffer `%s'" pos buffer))
16050 (cdr errdata)))))
16052 (defun org-time-string-to-seconds (s)
16053 "Convert a timestamp string to a number of seconds."
16054 (org-float-time (org-time-string-to-time s)))
16056 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16057 "Convert a time stamp to an absolute day number.
16058 If there is a specifier for a cyclic time stamp, get the closest date to
16059 DAYNR.
16060 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16061 The variable date is bound by the calendar when this is called."
16062 (cond
16063 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16064 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16065 daynr
16066 (+ daynr 1000)))
16067 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16068 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16069 (time-to-days (current-time))) (match-string 0 s)
16070 prefer show-all))
16071 (t (time-to-days
16072 (condition-case errdata
16073 (apply 'encode-time (org-parse-time-string s))
16074 (error (error "Bad timestamp `%s'%s\nError was: %s"
16075 s (if (not (and buffer pos))
16077 (format " at %d in buffer `%s'" pos buffer))
16078 (cdr errdata))))))))
16080 (defun org-days-to-iso-week (days)
16081 "Return the iso week number."
16082 (require 'cal-iso)
16083 (car (calendar-iso-from-absolute days)))
16085 (defun org-small-year-to-year (year)
16086 "Convert 2-digit years into 4-digit years.
16087 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16088 The year 2000 cannot be abbreviated. Any year larger than 99
16089 is returned unchanged."
16090 (if (< year 38)
16091 (setq year (+ 2000 year))
16092 (if (< year 100)
16093 (setq year (+ 1900 year))))
16094 year)
16096 (defun org-time-from-absolute (d)
16097 "Return the time corresponding to date D.
16098 D may be an absolute day number, or a calendar-type list (month day year)."
16099 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16100 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16102 (defun org-calendar-holiday ()
16103 "List of holidays, for Diary display in Org-mode."
16104 (require 'holidays)
16105 (let ((hl (funcall
16106 (if (fboundp 'calendar-check-holidays)
16107 'calendar-check-holidays 'check-calendar-holidays) date)))
16108 (if hl (mapconcat 'identity hl "; "))))
16110 (defun org-diary-sexp-entry (sexp entry date)
16111 "Process a SEXP diary ENTRY for DATE."
16112 (require 'diary-lib)
16113 (let ((result (if calendar-debug-sexp
16114 (let ((stack-trace-on-error t))
16115 (eval (car (read-from-string sexp))))
16116 (condition-case nil
16117 (eval (car (read-from-string sexp)))
16118 (error
16119 (beep)
16120 (message "Bad sexp at line %d in %s: %s"
16121 (org-current-line)
16122 (buffer-file-name) sexp)
16123 (sleep-for 2))))))
16124 (cond ((stringp result) (split-string result "; "))
16125 ((and (consp result)
16126 (not (consp (cdr result)))
16127 (stringp (cdr result))) (cdr result))
16128 ((and (consp result)
16129 (stringp (car result))) result)
16130 (result entry))))
16132 (defun org-diary-to-ical-string (frombuf)
16133 "Get iCalendar entries from diary entries in buffer FROMBUF.
16134 This uses the icalendar.el library."
16135 (let* ((tmpdir (if (featurep 'xemacs)
16136 (temp-directory)
16137 temporary-file-directory))
16138 (tmpfile (make-temp-name
16139 (expand-file-name "orgics" tmpdir)))
16140 buf rtn b e)
16141 (with-current-buffer frombuf
16142 (icalendar-export-region (point-min) (point-max) tmpfile)
16143 (setq buf (find-buffer-visiting tmpfile))
16144 (set-buffer buf)
16145 (goto-char (point-min))
16146 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16147 (setq b (match-beginning 0)))
16148 (goto-char (point-max))
16149 (if (re-search-backward "^END:VEVENT" nil t)
16150 (setq e (match-end 0)))
16151 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16152 (kill-buffer buf)
16153 (delete-file tmpfile)
16154 rtn))
16156 (defun org-closest-date (start current change prefer show-all)
16157 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16158 When PREFER is `past', return a date that is either CURRENT or past.
16159 When PREFER is `future', return a date that is either CURRENT or future.
16160 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16161 ;; Make the proper lists from the dates
16162 (catch 'exit
16163 (let ((a1 '(("h" . hour)
16164 ("d" . day)
16165 ("w" . week)
16166 ("m" . month)
16167 ("y" . year)))
16168 (shour (nth 2 (org-parse-time-string start)))
16169 dn dw sday cday n1 n2 n0
16170 d m y y1 y2 date1 date2 nmonths nm ny m2)
16172 (setq start (org-date-to-gregorian start)
16173 current (org-date-to-gregorian
16174 (if show-all
16175 current
16176 (time-to-days (current-time))))
16177 sday (calendar-absolute-from-gregorian start)
16178 cday (calendar-absolute-from-gregorian current))
16180 (if (<= cday sday) (throw 'exit sday))
16182 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16183 (setq dn (string-to-number (match-string 1 change))
16184 dw (cdr (assoc (match-string 2 change) a1)))
16185 (error "Invalid change specifier: %s" change))
16186 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16187 (cond
16188 ((eq dw 'hour)
16189 (let ((missing-hours
16190 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16191 dn)))
16192 (setq n1 (if (zerop missing-hours) cday
16193 (- cday (1+ (floor (/ missing-hours 24)))))
16194 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16195 ((eq dw 'day)
16196 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16197 n2 (+ n1 dn)))
16198 ((eq dw 'year)
16199 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16200 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16201 (setq date1 (list m d y1)
16202 n1 (calendar-absolute-from-gregorian date1)
16203 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16204 n2 (calendar-absolute-from-gregorian date2)))
16205 ((eq dw 'month)
16206 ;; approx number of month between the two dates
16207 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16208 ;; How often does dn fit in there?
16209 (setq d (nth 1 start) m (car start) y (nth 2 start)
16210 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16211 m (+ m nm)
16212 ny (floor (/ m 12))
16213 y (+ y ny)
16214 m (- m (* ny 12)))
16215 (while (> m 12) (setq m (- m 12) y (1+ y)))
16216 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16217 (setq m2 (+ m dn) y2 y)
16218 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16219 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16220 (while (<= n2 cday)
16221 (setq n1 n2 m m2 y y2)
16222 (setq m2 (+ m dn) y2 y)
16223 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16224 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16225 ;; Make sure n1 is the earlier date
16226 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16227 (if show-all
16228 (cond
16229 ((eq prefer 'past) (if (= cday n2) n2 n1))
16230 ((eq prefer 'future) (if (= cday n1) n1 n2))
16231 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16232 (cond
16233 ((eq prefer 'past) (if (= cday n2) n2 n1))
16234 ((eq prefer 'future) (if (= cday n1) n1 n2))
16235 (t (if (= cday n1) n1 n2)))))))
16237 (defun org-date-to-gregorian (date)
16238 "Turn any specification of DATE into a Gregorian date for the calendar."
16239 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16240 ((and (listp date) (= (length date) 3)) date)
16241 ((stringp date)
16242 (setq date (org-parse-time-string date))
16243 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16244 ((listp date)
16245 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16247 (defun org-parse-time-string (s &optional nodefault)
16248 "Parse the standard Org-mode time string.
16249 This should be a lot faster than the normal `parse-time-string'.
16250 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16251 hour and minute fields will be nil if not given."
16252 (if (string-match org-ts-regexp0 s)
16253 (list 0
16254 (if (or (match-beginning 8) (not nodefault))
16255 (string-to-number (or (match-string 8 s) "0")))
16256 (if (or (match-beginning 7) (not nodefault))
16257 (string-to-number (or (match-string 7 s) "0")))
16258 (string-to-number (match-string 4 s))
16259 (string-to-number (match-string 3 s))
16260 (string-to-number (match-string 2 s))
16261 nil nil nil)
16262 (error "Not a standard Org-mode time string: %s" s)))
16264 (defun org-timestamp-up (&optional arg)
16265 "Increase the date item at the cursor by one.
16266 If the cursor is on the year, change the year. If it is on the month,
16267 the day or the time, change that.
16268 With prefix ARG, change by that many units."
16269 (interactive "p")
16270 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16272 (defun org-timestamp-down (&optional arg)
16273 "Decrease the date item at the cursor by one.
16274 If the cursor is on the year, change the year. If it is on the month,
16275 the day or the time, change that.
16276 With prefix ARG, change by that many units."
16277 (interactive "p")
16278 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16280 (defun org-timestamp-up-day (&optional arg)
16281 "Increase the date in the time stamp by one day.
16282 With prefix ARG, change that many days."
16283 (interactive "p")
16284 (if (and (not (org-at-timestamp-p t))
16285 (org-at-heading-p))
16286 (org-todo 'up)
16287 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16289 (defun org-timestamp-down-day (&optional arg)
16290 "Decrease the date in the time stamp by one day.
16291 With prefix ARG, change that many days."
16292 (interactive "p")
16293 (if (and (not (org-at-timestamp-p t))
16294 (org-at-heading-p))
16295 (org-todo 'down)
16296 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16298 (defun org-at-timestamp-p (&optional inactive-ok)
16299 "Determine if the cursor is in or at a timestamp."
16300 (interactive)
16301 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16302 (pos (point))
16303 (ans (or (looking-at tsr)
16304 (save-excursion
16305 (skip-chars-backward "^[<\n\r\t")
16306 (if (> (point) (point-min)) (backward-char 1))
16307 (and (looking-at tsr)
16308 (> (- (match-end 0) pos) -1))))))
16309 (and ans
16310 (boundp 'org-ts-what)
16311 (setq org-ts-what
16312 (cond
16313 ((= pos (match-beginning 0)) 'bracket)
16314 ;; Point is considered to be "on the bracket" whether
16315 ;; it's really on it or right after it.
16316 ((= pos (1- (match-end 0))) 'bracket)
16317 ((= pos (match-end 0)) 'after)
16318 ((org-pos-in-match-range pos 2) 'year)
16319 ((org-pos-in-match-range pos 3) 'month)
16320 ((org-pos-in-match-range pos 7) 'hour)
16321 ((org-pos-in-match-range pos 8) 'minute)
16322 ((or (org-pos-in-match-range pos 4)
16323 (org-pos-in-match-range pos 5)) 'day)
16324 ((and (> pos (or (match-end 8) (match-end 5)))
16325 (< pos (match-end 0)))
16326 (- pos (or (match-end 8) (match-end 5))))
16327 (t 'day))))
16328 ans))
16330 (defun org-toggle-timestamp-type ()
16331 "Toggle the type (<active> or [inactive]) of a time stamp."
16332 (interactive)
16333 (when (org-at-timestamp-p t)
16334 (let ((beg (match-beginning 0)) (end (match-end 0))
16335 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16336 (save-excursion
16337 (goto-char beg)
16338 (while (re-search-forward "[][<>]" end t)
16339 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16340 t t)))
16341 (message "Timestamp is now %sactive"
16342 (if (equal (char-after beg) ?<) "" "in")))))
16344 (defvar org-clock-history) ; defined in org-clock.el
16345 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16346 (defun org-timestamp-change (n &optional what updown)
16347 "Change the date in the time stamp at point.
16348 The date will be changed by N times WHAT. WHAT can be `day', `month',
16349 `year', `minute', `second'. If WHAT is not given, the cursor position
16350 in the timestamp determines what will be changed."
16351 (let ((origin (point)) origin-cat
16352 with-hm inactive
16353 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16354 org-ts-what
16355 extra rem
16356 ts time time0 fixnext clrgx)
16357 (if (not (org-at-timestamp-p t))
16358 (error "Not at a timestamp"))
16359 (if (and (not what) (eq org-ts-what 'bracket))
16360 (org-toggle-timestamp-type)
16361 ;; Point isn't on brackets. Remember the part of the time-stamp
16362 ;; the point was in. Indeed, size of time-stamps may change,
16363 ;; but point must be kept in the same category nonetheless.
16364 (setq origin-cat org-ts-what)
16365 (if (and (not what) (not (eq org-ts-what 'day))
16366 org-display-custom-times
16367 (get-text-property (point) 'display)
16368 (not (get-text-property (1- (point)) 'display)))
16369 (setq org-ts-what 'day))
16370 (setq org-ts-what (or what org-ts-what)
16371 inactive (= (char-after (match-beginning 0)) ?\[)
16372 ts (match-string 0))
16373 (replace-match "")
16374 (if (string-match
16375 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16377 (setq extra (match-string 1 ts)))
16378 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16379 (setq with-hm t))
16380 (setq time0 (org-parse-time-string ts))
16381 (when (and updown
16382 (eq org-ts-what 'minute)
16383 (not current-prefix-arg))
16384 ;; This looks like s-up and s-down. Change by one rounding step.
16385 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16386 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16387 (setcar (cdr time0) (+ (nth 1 time0)
16388 (if (> n 0) (- rem) (- dm rem))))))
16389 (setq time
16390 (encode-time (or (car time0) 0)
16391 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16392 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16393 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16394 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16395 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16396 (nthcdr 6 time0)))
16397 (when (and (member org-ts-what '(hour minute))
16398 extra
16399 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16400 (setq extra (org-modify-ts-extra
16401 extra
16402 (if (eq org-ts-what 'hour) 2 5)
16403 n dm)))
16404 (when (integerp org-ts-what)
16405 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16406 (if (eq what 'calendar)
16407 (let ((cal-date (org-get-date-from-calendar)))
16408 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16409 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16410 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16411 (setcar time0 (or (car time0) 0))
16412 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16413 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16414 (setq time (apply 'encode-time time0))))
16415 ;; Insert the new time-stamp, and ensure point stays in the same
16416 ;; category as before (i.e. not after the last position in that
16417 ;; category).
16418 (let ((pos (point)))
16419 ;; Stay before inserted string. `save-excursion' is of no use.
16420 (setq org-last-changed-timestamp
16421 (org-insert-time-stamp time with-hm inactive nil nil extra))
16422 (goto-char pos))
16423 (save-match-data
16424 (looking-at org-ts-regexp3)
16425 (goto-char (cond
16426 ;; `day' category ends before `hour' if any, or at
16427 ;; the end of the day name.
16428 ((eq origin-cat 'day)
16429 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16430 ((eq origin-cat 'hour) (min (match-end 7) origin))
16431 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16432 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16433 ;; `year' and `month' have both fixed size: point
16434 ;; couldn't have moved into another part.
16435 (t origin))))
16436 ;; Update clock if on a CLOCK line.
16437 (org-clock-update-time-maybe)
16438 ;; Maybe adjust the closest clock in `org-clock-history'
16439 (when org-clock-adjust-closest
16440 (if (not (and (org-at-clock-log-p)
16441 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16442 org-clock-history))))))
16443 (message "No clock to adjust")
16444 (cond ((save-excursion ; fix previous clock?
16445 (re-search-backward org-ts-regexp0 nil t)
16446 (org-looking-back (concat org-clock-string " \\[")))
16447 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16448 ((save-excursion ; fix next clock?
16449 (re-search-backward org-ts-regexp0 nil t)
16450 (looking-at (concat org-ts-regexp0 "\\] =>")))
16451 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16452 (save-window-excursion
16453 ;; Find closest clock to point, adjust the previous/next one in history
16454 (let* ((p (save-excursion (org-back-to-heading t)))
16455 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16456 (clfixnth
16457 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16458 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16459 (if (not clfixpos)
16460 (message "No clock to adjust")
16461 (save-excursion
16462 (org-goto-marker-or-bmk clfixpos)
16463 (org-show-subtree)
16464 (when (re-search-forward clrgx nil t)
16465 (goto-char (match-beginning 1))
16466 (let (org-clock-adjust-closest)
16467 (org-timestamp-change n org-ts-what updown))
16468 (message "Clock adjusted in %s for heading: %s"
16469 (file-name-nondirectory (buffer-file-name))
16470 (org-get-heading t t)))))))))
16471 ;; Try to recenter the calendar window, if any.
16472 (if (and org-calendar-follow-timestamp-change
16473 (get-buffer-window "*Calendar*" t)
16474 (memq org-ts-what '(day month year)))
16475 (org-recenter-calendar (time-to-days time))))))
16477 (defun org-modify-ts-extra (s pos n dm)
16478 "Change the different parts of the lead-time and repeat fields in timestamp."
16479 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16480 ng h m new rem)
16481 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16482 (cond
16483 ((or (org-pos-in-match-range pos 2)
16484 (org-pos-in-match-range pos 3))
16485 (setq m (string-to-number (match-string 3 s))
16486 h (string-to-number (match-string 2 s)))
16487 (if (org-pos-in-match-range pos 2)
16488 (setq h (+ h n))
16489 (setq n (* dm (org-no-warnings (signum n))))
16490 (when (not (= 0 (setq rem (% m dm))))
16491 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16492 (setq m (+ m n)))
16493 (if (< m 0) (setq m (+ m 60) h (1- h)))
16494 (if (> m 59) (setq m (- m 60) h (1+ h)))
16495 (setq h (min 24 (max 0 h)))
16496 (setq ng 1 new (format "-%02d:%02d" h m)))
16497 ((org-pos-in-match-range pos 6)
16498 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16499 ((org-pos-in-match-range pos 5)
16500 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16502 ((org-pos-in-match-range pos 9)
16503 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16504 ((org-pos-in-match-range pos 8)
16505 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16507 (when ng
16508 (setq s (concat
16509 (substring s 0 (match-beginning ng))
16511 (substring s (match-end ng))))))
16514 (defun org-recenter-calendar (date)
16515 "If the calendar is visible, recenter it to DATE."
16516 (let ((cwin (get-buffer-window "*Calendar*" t)))
16517 (when cwin
16518 (let ((calendar-move-hook nil))
16519 (with-selected-window cwin
16520 (calendar-goto-date (if (listp date) date
16521 (calendar-gregorian-from-absolute date))))))))
16523 (defun org-goto-calendar (&optional arg)
16524 "Go to the Emacs calendar at the current date.
16525 If there is a time stamp in the current line, go to that date.
16526 A prefix ARG can be used to force the current date."
16527 (interactive "P")
16528 (let ((tsr org-ts-regexp) diff
16529 (calendar-move-hook nil)
16530 (calendar-view-holidays-initially-flag nil)
16531 (calendar-view-diary-initially-flag nil))
16532 (if (or (org-at-timestamp-p)
16533 (save-excursion
16534 (beginning-of-line 1)
16535 (looking-at (concat ".*" tsr))))
16536 (let ((d1 (time-to-days (current-time)))
16537 (d2 (time-to-days
16538 (org-time-string-to-time (match-string 1)))))
16539 (setq diff (- d2 d1))))
16540 (calendar)
16541 (calendar-goto-today)
16542 (if (and diff (not arg)) (calendar-forward-day diff))))
16544 (defun org-get-date-from-calendar ()
16545 "Return a list (month day year) of date at point in calendar."
16546 (with-current-buffer "*Calendar*"
16547 (save-match-data
16548 (calendar-cursor-to-date))))
16550 (defun org-date-from-calendar ()
16551 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16552 If there is already a time stamp at the cursor position, update it."
16553 (interactive)
16554 (if (org-at-timestamp-p t)
16555 (org-timestamp-change 0 'calendar)
16556 (let ((cal-date (org-get-date-from-calendar)))
16557 (org-insert-time-stamp
16558 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16560 (defun org-minutes-to-hh:mm-string (m)
16561 "Compute H:MM from a number of minutes."
16562 (let ((h (/ m 60)))
16563 (setq m (- m (* 60 h)))
16564 (format org-time-clocksum-format h m)))
16566 (defun org-hh:mm-string-to-minutes (s)
16567 "Convert a string H:MM to a number of minutes.
16568 If the string is just a number, interpret it as minutes.
16569 In fact, the first hh:mm or number in the string will be taken,
16570 there can be extra stuff in the string.
16571 If no number is found, the return value is 0."
16572 (cond
16573 ((integerp s) s)
16574 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16575 (+ (* (string-to-number (match-string 1 s)) 60)
16576 (string-to-number (match-string 2 s))))
16577 ((string-match "\\([0-9]+\\)" s)
16578 (string-to-number (match-string 1 s)))
16579 (t 0)))
16581 (defcustom org-effort-durations
16582 `(("h" . 60)
16583 ("d" . ,(* 60 8))
16584 ("w" . ,(* 60 8 5))
16585 ("m" . ,(* 60 8 5 4))
16586 ("y" . ,(* 60 8 5 40)))
16587 "Conversion factor to minutes for an effort modifier.
16589 Each entry has the form (MODIFIER . MINUTES).
16591 In an effort string, a number followed by MODIFIER is multiplied
16592 by the specified number of MINUTES to obtain an effort in
16593 minutes.
16595 For example, if the value of this variable is ((\"hours\" . 60)), then an
16596 effort string \"2hours\" is equivalent to 120 minutes."
16597 :group 'org-agenda
16598 :version "24.1"
16599 :type '(alist :key-type (string :tag "Modifier")
16600 :value-type (number :tag "Minutes")))
16602 (defun org-duration-string-to-minutes (s &optional output-to-string)
16603 "Convert a duration string S to minutes.
16605 A bare number is interpreted as minutes, modifiers can be set by
16606 customizing `org-effort-durations' (which see).
16608 Entries containing a colon are interpreted as H:MM by
16609 `org-hh:mm-string-to-minutes'."
16610 (let ((result 0)
16611 (re (concat "\\([0-9.]+\\) *\\("
16612 (regexp-opt (mapcar 'car org-effort-durations))
16613 "\\)")))
16614 (while (string-match re s)
16615 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16616 (string-to-number (match-string 1 s))))
16617 (setq s (replace-match "" nil t s)))
16618 (setq result (floor result))
16619 (incf result (org-hh:mm-string-to-minutes s))
16620 (if output-to-string (number-to-string result) result)))
16622 ;;;; Files
16624 (defun org-save-all-org-buffers ()
16625 "Save all Org-mode buffers without user confirmation."
16626 (interactive)
16627 (message "Saving all Org-mode buffers...")
16628 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16629 (when (featurep 'org-id) (org-id-locations-save))
16630 (message "Saving all Org-mode buffers... done"))
16632 (defun org-revert-all-org-buffers ()
16633 "Revert all Org-mode buffers.
16634 Prompt for confirmation when there are unsaved changes.
16635 Be sure you know what you are doing before letting this function
16636 overwrite your changes.
16638 This function is useful in a setup where one tracks org files
16639 with a version control system, to revert on one machine after pulling
16640 changes from another. I believe the procedure must be like this:
16642 1. M-x org-save-all-org-buffers
16643 2. Pull changes from the other machine, resolve conflicts
16644 3. M-x org-revert-all-org-buffers"
16645 (interactive)
16646 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16647 (error "Abort"))
16648 (save-excursion
16649 (save-window-excursion
16650 (mapc
16651 (lambda (b)
16652 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16653 (with-current-buffer b buffer-file-name))
16654 (org-pop-to-buffer-same-window b)
16655 (revert-buffer t 'no-confirm)))
16656 (buffer-list))
16657 (when (and (featurep 'org-id) org-id-track-globally)
16658 (org-id-locations-load)))))
16660 ;;;; Agenda files
16662 ;;;###autoload
16663 (defun org-switchb (&optional arg)
16664 "Switch between Org buffers.
16665 With one prefix argument, restrict available buffers to files.
16666 With two prefix arguments, restrict available buffers to agenda files.
16668 Defaults to `iswitchb' for buffer name completion.
16669 Set `org-completion-use-ido' to make it use ido instead."
16670 (interactive "P")
16671 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16672 ((equal arg '(16)) (org-buffer-list 'agenda))
16673 (t (org-buffer-list))))
16674 (org-completion-use-iswitchb org-completion-use-iswitchb)
16675 (org-completion-use-ido org-completion-use-ido))
16676 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16677 (setq org-completion-use-iswitchb t))
16678 (org-pop-to-buffer-same-window
16679 (org-icompleting-read "Org buffer: "
16680 (mapcar 'list (mapcar 'buffer-name blist))
16681 nil t))))
16683 ;;; Define some older names previously used for this functionality
16684 ;;;###autoload
16685 (defalias 'org-ido-switchb 'org-switchb)
16686 ;;;###autoload
16687 (defalias 'org-iswitchb 'org-switchb)
16689 (defun org-buffer-list (&optional predicate exclude-tmp)
16690 "Return a list of Org buffers.
16691 PREDICATE can be `export', `files' or `agenda'.
16693 export restrict the list to Export buffers.
16694 files restrict the list to buffers visiting Org files.
16695 agenda restrict the list to buffers visiting agenda files.
16697 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16698 (let* ((bfn nil)
16699 (agenda-files (and (eq predicate 'agenda)
16700 (mapcar 'file-truename (org-agenda-files t))))
16701 (filter
16702 (cond
16703 ((eq predicate 'files)
16704 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16705 ((eq predicate 'export)
16706 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16707 ((eq predicate 'agenda)
16708 (lambda (b)
16709 (with-current-buffer b
16710 (and (derived-mode-p 'org-mode)
16711 (setq bfn (buffer-file-name b))
16712 (member (file-truename bfn) agenda-files)))))
16713 (t (lambda (b) (with-current-buffer b
16714 (or (derived-mode-p 'org-mode)
16715 (string-match "\*Org .*Export"
16716 (buffer-name b)))))))))
16717 (delq nil
16718 (mapcar
16719 (lambda(b)
16720 (if (and (funcall filter b)
16721 (or (not exclude-tmp)
16722 (not (string-match "tmp" (buffer-name b)))))
16724 nil))
16725 (buffer-list)))))
16727 (defun org-agenda-files (&optional unrestricted archives)
16728 "Get the list of agenda files.
16729 Optional UNRESTRICTED means return the full list even if a restriction
16730 is currently in place.
16731 When ARCHIVES is t, include all archive files that are really being
16732 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16733 `org-agenda-archives-mode' is t."
16734 (let ((files
16735 (cond
16736 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16737 ((stringp org-agenda-files) (org-read-agenda-file-list))
16738 ((listp org-agenda-files) org-agenda-files)
16739 (t (error "Invalid value of `org-agenda-files'")))))
16740 (setq files (apply 'append
16741 (mapcar (lambda (f)
16742 (if (file-directory-p f)
16743 (directory-files
16744 f t org-agenda-file-regexp)
16745 (list f)))
16746 files)))
16747 (when org-agenda-skip-unavailable-files
16748 (setq files (delq nil
16749 (mapcar (function
16750 (lambda (file)
16751 (and (file-readable-p file) file)))
16752 files))))
16753 (when (or (eq archives t)
16754 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16755 (setq files (org-add-archive-files files)))
16756 files))
16758 (defun org-agenda-file-p (&optional file)
16759 "Return non-nil, if FILE is an agenda file.
16760 If FILE is omitted, use the file associated with the current
16761 buffer."
16762 (member (or file (buffer-file-name))
16763 (org-agenda-files t)))
16765 (defun org-edit-agenda-file-list ()
16766 "Edit the list of agenda files.
16767 Depending on setup, this either uses customize to edit the variable
16768 `org-agenda-files', or it visits the file that is holding the list. In the
16769 latter case, the buffer is set up in a way that saving it automatically kills
16770 the buffer and restores the previous window configuration."
16771 (interactive)
16772 (if (stringp org-agenda-files)
16773 (let ((cw (current-window-configuration)))
16774 (find-file org-agenda-files)
16775 (org-set-local 'org-window-configuration cw)
16776 (org-add-hook 'after-save-hook
16777 (lambda ()
16778 (set-window-configuration
16779 (prog1 org-window-configuration
16780 (kill-buffer (current-buffer))))
16781 (org-install-agenda-files-menu)
16782 (message "New agenda file list installed"))
16783 nil 'local)
16784 (message "%s" (substitute-command-keys
16785 "Edit list and finish with \\[save-buffer]")))
16786 (customize-variable 'org-agenda-files)))
16788 (defun org-store-new-agenda-file-list (list)
16789 "Set new value for the agenda file list and save it correctly."
16790 (if (stringp org-agenda-files)
16791 (let ((fe (org-read-agenda-file-list t)) b u)
16792 (while (setq b (find-buffer-visiting org-agenda-files))
16793 (kill-buffer b))
16794 (with-temp-file org-agenda-files
16795 (insert
16796 (mapconcat
16797 (lambda (f) ;; Keep un-expanded entries.
16798 (if (setq u (assoc f fe))
16799 (cdr u)
16801 list "\n")
16802 "\n")))
16803 (let ((org-mode-hook nil) (org-inhibit-startup t)
16804 (org-insert-mode-line-in-empty-file nil))
16805 (setq org-agenda-files list)
16806 (customize-save-variable 'org-agenda-files org-agenda-files))))
16808 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16809 "Read the list of agenda files from a file.
16810 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16811 filenames, used by `org-store-new-agenda-file-list' to write back
16812 un-expanded file names."
16813 (when (file-directory-p org-agenda-files)
16814 (error "`org-agenda-files' cannot be a single directory"))
16815 (when (stringp org-agenda-files)
16816 (with-temp-buffer
16817 (insert-file-contents org-agenda-files)
16818 (mapcar
16819 (lambda (f)
16820 (let ((e (expand-file-name (substitute-in-file-name f)
16821 org-directory)))
16822 (if pair-with-expansion
16823 (cons e f)
16824 e)))
16825 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16827 ;;;###autoload
16828 (defun org-cycle-agenda-files ()
16829 "Cycle through the files in `org-agenda-files'.
16830 If the current buffer visits an agenda file, find the next one in the list.
16831 If the current buffer does not, find the first agenda file."
16832 (interactive)
16833 (let* ((fs (org-agenda-files t))
16834 (files (append fs (list (car fs))))
16835 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16836 file)
16837 (unless files (error "No agenda files"))
16838 (catch 'exit
16839 (while (setq file (pop files))
16840 (if (equal (file-truename file) tcf)
16841 (when (car files)
16842 (find-file (car files))
16843 (throw 'exit t))))
16844 (find-file (car fs)))
16845 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16847 (defun org-agenda-file-to-front (&optional to-end)
16848 "Move/add the current file to the top of the agenda file list.
16849 If the file is not present in the list, it is added to the front. If it is
16850 present, it is moved there. With optional argument TO-END, add/move to the
16851 end of the list."
16852 (interactive "P")
16853 (let ((org-agenda-skip-unavailable-files nil)
16854 (file-alist (mapcar (lambda (x)
16855 (cons (file-truename x) x))
16856 (org-agenda-files t)))
16857 (ctf (file-truename
16858 (or buffer-file-name
16859 (error "Please save the current buffer to a file"))))
16860 x had)
16861 (setq x (assoc ctf file-alist) had x)
16863 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16864 (if to-end
16865 (setq file-alist (append (delq x file-alist) (list x)))
16866 (setq file-alist (cons x (delq x file-alist))))
16867 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16868 (org-install-agenda-files-menu)
16869 (message "File %s to %s of agenda file list"
16870 (if had "moved" "added") (if to-end "end" "front"))))
16872 (defun org-remove-file (&optional file)
16873 "Remove current file from the list of files in variable `org-agenda-files'.
16874 These are the files which are being checked for agenda entries.
16875 Optional argument FILE means use this file instead of the current."
16876 (interactive)
16877 (let* ((org-agenda-skip-unavailable-files nil)
16878 (file (or file buffer-file-name
16879 (error "Current buffer does not visit a file")))
16880 (true-file (file-truename file))
16881 (afile (abbreviate-file-name file))
16882 (files (delq nil (mapcar
16883 (lambda (x)
16884 (if (equal true-file
16885 (file-truename x))
16886 nil x))
16887 (org-agenda-files t)))))
16888 (if (not (= (length files) (length (org-agenda-files t))))
16889 (progn
16890 (org-store-new-agenda-file-list files)
16891 (org-install-agenda-files-menu)
16892 (message "Removed file: %s" afile))
16893 (message "File was not in list: %s (not removed)" afile))))
16895 (defun org-file-menu-entry (file)
16896 (vector file (list 'find-file file) t))
16898 (defun org-check-agenda-file (file)
16899 "Make sure FILE exists. If not, ask user what to do."
16900 (when (not (file-exists-p file))
16901 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16902 (abbreviate-file-name file))
16903 (let ((r (downcase (read-char-exclusive))))
16904 (cond
16905 ((equal r ?r)
16906 (org-remove-file file)
16907 (throw 'nextfile t))
16908 (t (error "Abort"))))))
16910 (defun org-get-agenda-file-buffer (file)
16911 "Get a buffer visiting FILE. If the buffer needs to be created, add
16912 it to the list of buffers which might be released later."
16913 (let ((buf (org-find-base-buffer-visiting file)))
16914 (if buf
16915 buf ; just return it
16916 ;; Make a new buffer and remember it
16917 (setq buf (find-file-noselect file))
16918 (if buf (push buf org-agenda-new-buffers))
16919 buf)))
16921 (defun org-release-buffers (blist)
16922 "Release all buffers in list, asking the user for confirmation when needed.
16923 When a buffer is unmodified, it is just killed. When modified, it is saved
16924 \(if the user agrees) and then killed."
16925 (let (buf file)
16926 (while (setq buf (pop blist))
16927 (setq file (buffer-file-name buf))
16928 (when (and (buffer-modified-p buf)
16929 file
16930 (y-or-n-p (format "Save file %s? " file)))
16931 (with-current-buffer buf (save-buffer)))
16932 (kill-buffer buf))))
16934 (defun org-agenda-prepare-buffers (files)
16935 "Create buffers for all agenda files, protect archived trees and comments."
16936 (interactive)
16937 (let ((pa '(:org-archived t))
16938 (pc '(:org-comment t))
16939 (pall '(:org-archived t :org-comment t))
16940 (inhibit-read-only t)
16941 (rea (concat ":" org-archive-tag ":"))
16942 bmp file re)
16943 (save-excursion
16944 (save-restriction
16945 (while (setq file (pop files))
16946 (catch 'nextfile
16947 (if (bufferp file)
16948 (set-buffer file)
16949 (org-check-agenda-file file)
16950 (set-buffer (org-get-agenda-file-buffer file)))
16951 (widen)
16952 (setq bmp (buffer-modified-p))
16953 (org-refresh-category-properties)
16954 (setq org-todo-keywords-for-agenda
16955 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16956 (setq org-done-keywords-for-agenda
16957 (append org-done-keywords-for-agenda org-done-keywords))
16958 (setq org-todo-keyword-alist-for-agenda
16959 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16960 (setq org-drawers-for-agenda
16961 (append org-drawers-for-agenda org-drawers))
16962 (setq org-tag-alist-for-agenda
16963 (append org-tag-alist-for-agenda org-tag-alist))
16965 (save-excursion
16966 (remove-text-properties (point-min) (point-max) pall)
16967 (when org-agenda-skip-archived-trees
16968 (goto-char (point-min))
16969 (while (re-search-forward rea nil t)
16970 (if (org-at-heading-p t)
16971 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16972 (goto-char (point-min))
16973 (setq re (format org-heading-keyword-regexp-format
16974 org-comment-string))
16975 (while (re-search-forward re nil t)
16976 (add-text-properties
16977 (match-beginning 0) (org-end-of-subtree t) pc)))
16978 (set-buffer-modified-p bmp)))))
16979 (setq org-todo-keywords-for-agenda
16980 (org-uniquify org-todo-keywords-for-agenda))
16981 (setq org-todo-keyword-alist-for-agenda
16982 (org-uniquify org-todo-keyword-alist-for-agenda)
16983 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16985 ;;;; Embedded LaTeX
16987 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16988 "Keymap for the minor `org-cdlatex-mode'.")
16990 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16991 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16992 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16993 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16994 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16996 (defvar org-cdlatex-texmathp-advice-is-done nil
16997 "Flag remembering if we have applied the advice to texmathp already.")
16999 (define-minor-mode org-cdlatex-mode
17000 "Toggle the minor `org-cdlatex-mode'.
17001 This mode supports entering LaTeX environment and math in LaTeX fragments
17002 in Org-mode.
17003 \\{org-cdlatex-mode-map}"
17004 nil " OCDL" nil
17005 (when org-cdlatex-mode
17006 (require 'cdlatex)
17007 (run-hooks 'cdlatex-mode-hook)
17008 (cdlatex-compute-tables))
17009 (unless org-cdlatex-texmathp-advice-is-done
17010 (setq org-cdlatex-texmathp-advice-is-done t)
17011 (defadvice texmathp (around org-math-always-on activate)
17012 "Always return t in org-mode buffers.
17013 This is because we want to insert math symbols without dollars even outside
17014 the LaTeX math segments. If Orgmode thinks that point is actually inside
17015 an embedded LaTeX fragment, let texmathp do its job.
17016 \\[org-cdlatex-mode-map]"
17017 (interactive)
17018 (let (p)
17019 (cond
17020 ((not (derived-mode-p 'org-mode)) ad-do-it)
17021 ((eq this-command 'cdlatex-math-symbol)
17022 (setq ad-return-value t
17023 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17025 (let ((p (org-inside-LaTeX-fragment-p)))
17026 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17027 (setq ad-return-value t
17028 texmathp-why '("Org-mode embedded math" . 0))
17029 (if p ad-do-it)))))))))
17031 (defun turn-on-org-cdlatex ()
17032 "Unconditionally turn on `org-cdlatex-mode'."
17033 (org-cdlatex-mode 1))
17035 (defun org-inside-LaTeX-fragment-p ()
17036 "Test if point is inside a LaTeX fragment.
17037 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17038 sequence appearing also before point.
17039 Even though the matchers for math are configurable, this function assumes
17040 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17041 delimiters are skipped when they have been removed by customization.
17042 The return value is nil, or a cons cell with the delimiter and the
17043 position of this delimiter.
17045 This function does a reasonably good job, but can locally be fooled by
17046 for example currency specifications. For example it will assume being in
17047 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17048 fragments that are properly closed, but during editing, we have to live
17049 with the uncertainty caused by missing closing delimiters. This function
17050 looks only before point, not after."
17051 (catch 'exit
17052 (let ((pos (point))
17053 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17054 (lim (progn
17055 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17056 (point)))
17057 dd-on str (start 0) m re)
17058 (goto-char pos)
17059 (when dodollar
17060 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17061 re (nth 1 (assoc "$" org-latex-regexps)))
17062 (while (string-match re str start)
17063 (cond
17064 ((= (match-end 0) (length str))
17065 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17066 ((= (match-end 0) (- (length str) 5))
17067 (throw 'exit nil))
17068 (t (setq start (match-end 0))))))
17069 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17070 (goto-char pos)
17071 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17072 (and (match-beginning 2) (throw 'exit nil))
17073 ;; count $$
17074 (while (re-search-backward "\\$\\$" lim t)
17075 (setq dd-on (not dd-on)))
17076 (goto-char pos)
17077 (if dd-on (cons "$$" m))))))
17079 (defun org-inside-latex-macro-p ()
17080 "Is point inside a LaTeX macro or its arguments?"
17081 (save-match-data
17082 (org-in-regexp
17083 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17085 (defun org-try-cdlatex-tab ()
17086 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17087 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17088 - inside a LaTeX fragment, or
17089 - after the first word in a line, where an abbreviation expansion could
17090 insert a LaTeX environment."
17091 (when org-cdlatex-mode
17092 (cond
17093 ;; Before any word on the line: No expansion possible.
17094 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17095 ;; Just after first word on the line: Expand it. Make sure it
17096 ;; cannot happen on headlines, though.
17097 ((save-excursion
17098 (skip-chars-backward "a-zA-Z0-9*")
17099 (skip-chars-backward " \t")
17100 (and (bolp) (not (org-at-heading-p))))
17101 (cdlatex-tab) t)
17102 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17104 (defun org-cdlatex-underscore-caret (&optional arg)
17105 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17106 Revert to the normal definition outside of these fragments."
17107 (interactive "P")
17108 (if (org-inside-LaTeX-fragment-p)
17109 (call-interactively 'cdlatex-sub-superscript)
17110 (let (org-cdlatex-mode)
17111 (call-interactively (key-binding (vector last-input-event))))))
17113 (defun org-cdlatex-math-modify (&optional arg)
17114 "Execute `cdlatex-math-modify' in LaTeX fragments.
17115 Revert to the normal definition outside of these fragments."
17116 (interactive "P")
17117 (if (org-inside-LaTeX-fragment-p)
17118 (call-interactively 'cdlatex-math-modify)
17119 (let (org-cdlatex-mode)
17120 (call-interactively (key-binding (vector last-input-event))))))
17122 (defvar org-latex-fragment-image-overlays nil
17123 "List of overlays carrying the images of latex fragments.")
17124 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17126 (defun org-remove-latex-fragment-image-overlays ()
17127 "Remove all overlays with LaTeX fragment images in current buffer."
17128 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17129 (setq org-latex-fragment-image-overlays nil))
17131 (defun org-preview-latex-fragment (&optional subtree)
17132 "Preview the LaTeX fragment at point, or all locally or globally.
17133 If the cursor is in a LaTeX fragment, create the image and overlay
17134 it over the source code. If there is no fragment at point, display
17135 all fragments in the current text, from one headline to the next. With
17136 prefix SUBTREE, display all fragments in the current subtree. With a
17137 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17138 the cursor is before the first headline,
17139 display all fragments in the buffer.
17140 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17141 (interactive "P")
17142 (unless buffer-file-name
17143 (error "Can't preview LaTeX fragment in a non-file buffer"))
17144 (org-remove-latex-fragment-image-overlays)
17145 (save-excursion
17146 (save-restriction
17147 (let (beg end at msg)
17148 (cond
17149 ((or (equal subtree '(16))
17150 (not (save-excursion
17151 (re-search-backward org-outline-regexp-bol nil t))))
17152 (setq beg (point-min) end (point-max)
17153 msg "Creating images for buffer...%s"))
17154 ((equal subtree '(4))
17155 (org-back-to-heading)
17156 (setq beg (point) end (org-end-of-subtree t)
17157 msg "Creating images for subtree...%s"))
17159 (if (setq at (org-inside-LaTeX-fragment-p))
17160 (goto-char (max (point-min) (- (cdr at) 2)))
17161 (org-back-to-heading))
17162 (setq beg (point) end (progn (outline-next-heading) (point))
17163 msg (if at "Creating image...%s"
17164 "Creating images for entry...%s"))))
17165 (message msg "")
17166 (narrow-to-region beg end)
17167 (goto-char beg)
17168 (org-format-latex
17169 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17170 (file-name-nondirectory
17171 buffer-file-name)))
17172 default-directory 'overlays msg at 'forbuffer
17173 org-latex-create-formula-image-program)
17174 (message msg "done. Use `C-c C-c' to remove images.")))))
17176 (defvar org-latex-regexps
17177 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17178 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17179 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17180 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17181 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17182 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17183 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17184 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17185 "Regular expressions for matching embedded LaTeX.")
17187 (defvar org-export-have-math nil) ;; dynamic scoping
17188 (defun org-format-latex (prefix &optional dir overlays msg at
17189 forbuffer processing-type)
17190 "Replace LaTeX fragments with links to an image, and produce images.
17191 Some of the options can be changed using the variable
17192 `org-format-latex-options'."
17193 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17194 (let* ((prefixnodir (file-name-nondirectory prefix))
17195 (absprefix (expand-file-name prefix dir))
17196 (todir (file-name-directory absprefix))
17197 (opt org-format-latex-options)
17198 (matchers (plist-get opt :matchers))
17199 (re-list org-latex-regexps)
17200 (org-format-latex-header-extra
17201 (plist-get (org-infile-export-plist) :latex-header-extra))
17202 (cnt 0) txt hash link beg end re e checkdir
17203 executables-checked string
17204 m n block-type block linkfile movefile ov)
17205 ;; Check the different regular expressions
17206 (while (setq e (pop re-list))
17207 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17208 block (if block-type "\n\n" ""))
17209 (when (member m matchers)
17210 (goto-char (point-min))
17211 (while (re-search-forward re nil t)
17212 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17213 (not (get-text-property (match-beginning n)
17214 'org-protected))
17215 (or (not overlays)
17216 (not (eq (get-char-property (match-beginning n)
17217 'org-overlay-type)
17218 'org-latex-overlay))))
17219 (setq org-export-have-math t)
17220 (cond
17221 ((eq processing-type 'verbatim)
17222 ;; Leave the text verbatim, just protect it
17223 (add-text-properties (match-beginning n) (match-end n)
17224 '(org-protected t)))
17225 ((eq processing-type 'mathjax)
17226 ;; Prepare for MathJax processing
17227 (setq string (match-string n))
17228 (if (member m '("$" "$1"))
17229 (save-excursion
17230 (delete-region (match-beginning n) (match-end n))
17231 (goto-char (match-beginning n))
17232 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17233 "\\)")
17234 '(org-protected t))))
17235 (add-text-properties (match-beginning n) (match-end n)
17236 '(org-protected t))))
17237 ((or (eq processing-type 'dvipng)
17238 (eq processing-type 'imagemagick))
17239 ;; Process to an image
17240 (setq txt (match-string n)
17241 beg (match-beginning n) end (match-end n)
17242 cnt (1+ cnt))
17243 (let (print-length print-level) ; make sure full list is printed
17244 (setq hash (sha1 (prin1-to-string
17245 (list org-format-latex-header
17246 org-format-latex-header-extra
17247 org-export-latex-default-packages-alist
17248 org-export-latex-packages-alist
17249 org-format-latex-options
17250 forbuffer txt)))
17251 linkfile (format "%s_%s.png" prefix hash)
17252 movefile (format "%s_%s.png" absprefix hash)))
17253 (setq link (concat block "[[file:" linkfile "]]" block))
17254 (if msg (message msg cnt))
17255 (goto-char beg)
17256 (unless checkdir ; make sure the directory exists
17257 (setq checkdir t)
17258 (or (file-directory-p todir) (make-directory todir t)))
17259 (cond
17260 ((eq processing-type 'dvipng)
17261 (unless executables-checked
17262 (org-check-external-command
17263 "latex" "needed to convert LaTeX fragments to images")
17264 (org-check-external-command
17265 "dvipng" "needed to convert LaTeX fragments to images")
17266 (setq executables-checked t))
17267 (unless (file-exists-p movefile)
17268 (org-create-formula-image-with-dvipng
17269 txt movefile opt forbuffer)))
17270 ((eq processing-type 'imagemagick)
17271 (unless executables-checked
17272 (org-check-external-command
17273 "convert" "you need to install imagemagick")
17274 (setq executables-checked t))
17275 (unless (file-exists-p movefile)
17276 (org-create-formula-image-with-imagemagick
17277 txt movefile opt forbuffer))))
17278 (if overlays
17279 (progn
17280 (mapc (lambda (o)
17281 (if (eq (overlay-get o 'org-overlay-type)
17282 'org-latex-overlay)
17283 (delete-overlay o)))
17284 (overlays-in beg end))
17285 (setq ov (make-overlay beg end))
17286 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17287 (if (featurep 'xemacs)
17288 (progn
17289 (overlay-put ov 'invisible t)
17290 (overlay-put
17291 ov 'end-glyph
17292 (make-glyph (vector 'png :file movefile))))
17293 (overlay-put
17294 ov 'display
17295 (list 'image :type 'png :file movefile :ascent 'center)))
17296 (push ov org-latex-fragment-image-overlays)
17297 (goto-char end))
17298 (delete-region beg end)
17299 (insert (org-add-props link
17300 (list 'org-latex-src
17301 (replace-regexp-in-string
17302 "\"" "" txt)
17303 'org-latex-src-embed-type
17304 (if block-type 'paragraph 'character))))))
17305 ((eq processing-type 'mathml)
17306 ;; Process to MathML
17307 (unless executables-checked
17308 (unless (save-match-data (org-format-latex-mathml-available-p))
17309 (error "LaTeX to MathML converter not configured"))
17310 (setq executables-checked t))
17311 (setq txt (match-string n)
17312 beg (match-beginning n) end (match-end n)
17313 cnt (1+ cnt))
17314 (if msg (message msg cnt))
17315 (goto-char beg)
17316 (delete-region beg end)
17317 (insert (org-format-latex-as-mathml
17318 txt block-type prefix dir)))
17320 (error "Unknown conversion type %s for latex fragments"
17321 processing-type)))))))))
17323 (defun org-create-math-formula (latex-frag &optional mathml-file)
17324 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17325 Use `org-latex-to-mathml-convert-command'. If the conversion is
17326 sucessful, return the portion between \"<math...> </math>\"
17327 elements otherwise return nil. When MATHML-FILE is specified,
17328 write the results in to that file. When invoked as an
17329 interactive command, prompt for LATEX-FRAG, with initial value
17330 set to the current active region and echo the results for user
17331 inspection."
17332 (interactive (list (let ((frag (when (org-region-active-p)
17333 (buffer-substring-no-properties
17334 (region-beginning) (region-end)))))
17335 (read-string "LaTeX Fragment: " frag nil frag))))
17336 (unless latex-frag (error "Invalid latex-frag"))
17337 (let* ((tmp-in-file (file-relative-name
17338 (make-temp-name (expand-file-name "ltxmathml-in"))))
17339 (ignore (write-region latex-frag nil tmp-in-file))
17340 (tmp-out-file (file-relative-name
17341 (make-temp-name (expand-file-name "ltxmathml-out"))))
17342 (cmd (format-spec
17343 org-latex-to-mathml-convert-command
17344 `((?j . ,(shell-quote-argument
17345 (expand-file-name org-latex-to-mathml-jar-file)))
17346 (?I . ,(shell-quote-argument tmp-in-file))
17347 (?o . ,(shell-quote-argument tmp-out-file)))))
17348 mathml shell-command-output)
17349 (when (org-called-interactively-p 'any)
17350 (unless (org-format-latex-mathml-available-p)
17351 (error "LaTeX to MathML converter not configured")))
17352 (message "Running %s" cmd)
17353 (setq shell-command-output (shell-command-to-string cmd))
17354 (setq mathml
17355 (when (file-readable-p tmp-out-file)
17356 (with-current-buffer (find-file-noselect tmp-out-file t)
17357 (goto-char (point-min))
17358 (when (re-search-forward
17359 (concat
17360 (regexp-quote
17361 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17362 "\\(.\\|\n\\)*"
17363 (regexp-quote "</math>")) nil t)
17364 (prog1 (match-string 0) (kill-buffer))))))
17365 (cond
17366 (mathml
17367 (setq mathml
17368 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17369 (when mathml-file
17370 (write-region mathml nil mathml-file))
17371 (when (org-called-interactively-p 'any)
17372 (message mathml)))
17373 ((message "LaTeX to MathML conversion failed")
17374 (message shell-command-output)))
17375 (delete-file tmp-in-file)
17376 (when (file-exists-p tmp-out-file)
17377 (delete-file tmp-out-file))
17378 mathml))
17380 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17381 prefix &optional dir)
17382 "Use `org-create-math-formula' but check local cache first."
17383 (let* ((absprefix (expand-file-name prefix dir))
17384 (print-length nil) (print-level nil)
17385 (formula-id (concat
17386 "formula-"
17387 (sha1
17388 (prin1-to-string
17389 (list latex-frag
17390 org-latex-to-mathml-convert-command)))))
17391 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17392 (formula-cache-dir (file-name-directory formula-cache)))
17394 (unless (file-directory-p formula-cache-dir)
17395 (make-directory formula-cache-dir t))
17397 (unless (file-exists-p formula-cache)
17398 (org-create-math-formula latex-frag formula-cache))
17400 (if (file-exists-p formula-cache)
17401 ;; Successful conversion. Return the link to MathML file.
17402 (org-add-props
17403 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17404 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17405 'org-latex-src-embed-type (if latex-frag-type
17406 'paragraph 'character)))
17407 ;; Failed conversion. Return the LaTeX fragment verbatim
17408 (add-text-properties
17409 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17410 latex-frag)))
17412 ;; This function borrows from Ganesh Swami's latex2png.el
17413 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17414 "This calls dvipng."
17415 (require 'org-latex)
17416 (let* ((tmpdir (if (featurep 'xemacs)
17417 (temp-directory)
17418 temporary-file-directory))
17419 (texfilebase (make-temp-name
17420 (expand-file-name "orgtex" tmpdir)))
17421 (texfile (concat texfilebase ".tex"))
17422 (dvifile (concat texfilebase ".dvi"))
17423 (pngfile (concat texfilebase ".png"))
17424 (fnh (if (featurep 'xemacs)
17425 (font-height (face-font 'default))
17426 (face-attribute 'default :height nil)))
17427 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17428 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17429 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17430 "Black"))
17431 (bg (or (plist-get options (if buffer :background :html-background))
17432 "Transparent")))
17433 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17434 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17435 (with-temp-file texfile
17436 (insert (org-splice-latex-header
17437 org-format-latex-header
17438 org-export-latex-default-packages-alist
17439 org-export-latex-packages-alist t
17440 org-format-latex-header-extra))
17441 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17442 (require 'org-latex)
17443 (org-export-latex-fix-inputenc))
17444 (let ((dir default-directory))
17445 (condition-case nil
17446 (progn
17447 (cd tmpdir)
17448 (call-process "latex" nil nil nil texfile))
17449 (error nil))
17450 (cd dir))
17451 (if (not (file-exists-p dvifile))
17452 (progn (message "Failed to create dvi file from %s" texfile) nil)
17453 (condition-case nil
17454 (if (featurep 'xemacs)
17455 (call-process "dvipng" nil nil nil
17456 "-fg" fg "-bg" bg
17457 "-T" "tight"
17458 "-o" pngfile
17459 dvifile)
17460 (call-process "dvipng" nil nil nil
17461 "-fg" fg "-bg" bg
17462 "-D" dpi
17463 ;;"-x" scale "-y" scale
17464 "-T" "tight"
17465 "-o" pngfile
17466 dvifile))
17467 (error nil))
17468 (if (not (file-exists-p pngfile))
17469 (if org-format-latex-signal-error
17470 (error "Failed to create png file from %s" texfile)
17471 (message "Failed to create png file from %s" texfile)
17472 nil)
17473 ;; Use the requested file name and clean up
17474 (copy-file pngfile tofile 'replace)
17475 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17476 (if (file-exists-p (concat texfilebase e))
17477 (delete-file (concat texfilebase e))))
17478 pngfile))))
17480 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17481 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17482 "This calls convert, which is included into imagemagick."
17483 (require 'org-latex)
17484 (let* ((tmpdir (if (featurep 'xemacs)
17485 (temp-directory)
17486 temporary-file-directory))
17487 (texfilebase (make-temp-name
17488 (expand-file-name "orgtex" tmpdir)))
17489 (texfile (concat texfilebase ".tex"))
17490 (pdffile (concat texfilebase ".pdf"))
17491 (pngfile (concat texfilebase ".png"))
17492 (fnh (if (featurep 'xemacs)
17493 (font-height (face-font 'default))
17494 (face-attribute 'default :height nil)))
17495 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17496 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17497 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17498 "black"))
17499 (bg (or (plist-get options (if buffer :background :html-background))
17500 "white")))
17501 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17502 (setq fg (org-latex-color-format fg)))
17503 (if (eq bg 'default) (setq bg (org-latex-color :background))
17504 (setq bg (org-latex-color-format
17505 (if (string= bg "Transparent")(setq bg "white")))))
17506 (with-temp-file texfile
17507 (insert (org-splice-latex-header
17508 org-format-latex-header
17509 org-export-latex-default-packages-alist
17510 org-export-latex-packages-alist t
17511 org-format-latex-header-extra))
17512 (insert "\n\\begin{document}\n"
17513 "\\definecolor{fg}{rgb}{" fg "}\n"
17514 "\\definecolor{bg}{rgb}{" bg "}\n"
17515 "\n\\pagecolor{bg}\n"
17516 "\n{\\color{fg}\n"
17517 string
17518 "\n}\n"
17519 "\n\\end{document}\n" )
17520 (require 'org-latex)
17521 (org-export-latex-fix-inputenc))
17522 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17523 (condition-case nil
17524 (progn
17525 (cd tmpdir)
17526 (setq cmds org-latex-to-pdf-process)
17527 (while cmds
17528 (setq latex-frags-cmds (pop cmds))
17529 (if (listp latex-frags-cmds)
17530 (setq cmds nil)
17531 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17532 (while latex-frags-cmds
17533 (setq cmd (pop latex-frags-cmds))
17534 (while (string-match "%b" cmd)
17535 (setq cmd (replace-match
17536 (save-match-data
17537 (shell-quote-argument texfile))
17538 t t cmd)))
17539 (while (string-match "%f" cmd)
17540 (setq cmd (replace-match
17541 (save-match-data
17542 (shell-quote-argument (file-name-nondirectory texfile)))
17543 t t cmd)))
17544 (while (string-match "%o" cmd)
17545 (setq cmd (replace-match
17546 (save-match-data
17547 (shell-quote-argument (file-name-directory texfile)))
17548 t t cmd)))
17549 (setq cmd (split-string cmd))
17550 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17551 (error nil))
17552 (cd dir))
17553 (if (not (file-exists-p pdffile))
17554 (progn (message "Failed to create pdf file from %s" texfile) nil)
17555 (condition-case nil
17556 (if (featurep 'xemacs)
17557 (call-process "convert" nil nil nil
17558 "-density" "96"
17559 "-trim"
17560 "-antialias"
17561 pdffile
17562 "-quality" "100"
17563 ;; "-sharpen" "0x1.0"
17564 pngfile)
17565 (call-process "convert" nil nil nil
17566 "-density" dpi
17567 "-trim"
17568 "-antialias"
17569 pdffile
17570 "-quality" "100"
17571 ; "-sharpen" "0x1.0"
17572 pngfile))
17573 (error nil))
17574 (if (not (file-exists-p pngfile))
17575 (if org-format-latex-signal-error
17576 (error "Failed to create png file from %s" texfile)
17577 (message "Failed to create png file from %s" texfile)
17578 nil)
17579 ;; Use the requested file name and clean up
17580 (copy-file pngfile tofile 'replace)
17581 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17582 (if (file-exists-p (concat texfilebase e))
17583 (delete-file (concat texfilebase e))))
17584 pngfile))))
17586 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17587 "Fill a LaTeX header template TPL.
17588 In the template, the following place holders will be recognized:
17590 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17591 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17592 [PACKAGES] \\usepackage statements for PKG
17593 [NO-PACKAGES] do not include PKG
17594 [EXTRA] the string EXTRA
17595 [NO-EXTRA] do not include EXTRA
17597 For backward compatibility, if both the positive and the negative place
17598 holder is missing, the positive one (without the \"NO-\") will be
17599 assumed to be present at the end of the template.
17600 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17601 EXTRA is a string.
17602 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17603 (let (rpl (end ""))
17604 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17605 (setq rpl (if (or (match-end 1) (not def-pkg))
17606 "" (org-latex-packages-to-string def-pkg snippets-p t))
17607 tpl (replace-match rpl t t tpl))
17608 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17610 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17611 (setq rpl (if (or (match-end 1) (not pkg))
17612 "" (org-latex-packages-to-string pkg snippets-p t))
17613 tpl (replace-match rpl t t tpl))
17614 (if pkg (setq end
17615 (concat end "\n"
17616 (org-latex-packages-to-string pkg snippets-p)))))
17618 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17619 (setq rpl (if (or (match-end 1) (not extra))
17620 "" (concat extra "\n"))
17621 tpl (replace-match rpl t t tpl))
17622 (if (and extra (string-match "\\S-" extra))
17623 (setq end (concat end "\n" extra))))
17625 (if (string-match "\\S-" end)
17626 (concat tpl "\n" end)
17627 tpl)))
17629 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17630 "Turn an alist of packages into a string with the \\usepackage macros."
17631 (setq pkg (mapconcat (lambda(p)
17632 (cond
17633 ((stringp p) p)
17634 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17635 (format "%% Package %s omitted" (cadr p)))
17636 ((equal "" (car p))
17637 (format "\\usepackage{%s}" (cadr p)))
17639 (format "\\usepackage[%s]{%s}"
17640 (car p) (cadr p)))))
17642 "\n"))
17643 (if newline (concat pkg "\n") pkg))
17645 (defun org-dvipng-color (attr)
17646 "Return a RGB color specification for dvipng."
17647 (apply 'format "rgb %s %s %s"
17648 (mapcar 'org-normalize-color
17649 (if (featurep 'xemacs)
17650 (color-rgb-components
17651 (face-property 'default
17652 (cond ((eq attr :foreground) 'foreground)
17653 ((eq attr :background) 'background))))
17654 (color-values (face-attribute 'default attr nil))))))
17656 (defun org-latex-color (attr)
17657 "Return a RGB color for the LaTeX color package."
17658 (apply 'format "%s,%s,%s"
17659 (mapcar 'org-normalize-color
17660 (if (featurep 'xemacs)
17661 (color-rgb-components
17662 (face-property 'default
17663 (cond ((eq attr :foreground) 'foreground)
17664 ((eq attr :background) 'background))))
17665 (color-values (face-attribute 'default attr nil))))))
17667 (defun org-latex-color-format (color-name)
17668 "Convert COLOR-NAME to a RGB color value."
17669 (apply 'format "%s,%s,%s"
17670 (mapcar 'org-normalize-color
17671 (color-values color-name))))
17673 (defun org-normalize-color (value)
17674 "Return string to be used as color value for an RGB component."
17675 (format "%g" (/ value 65535.0)))
17677 ;; Image display
17680 (defvar org-inline-image-overlays nil)
17681 (make-variable-buffer-local 'org-inline-image-overlays)
17683 (defun org-toggle-inline-images (&optional include-linked)
17684 "Toggle the display of inline images.
17685 INCLUDE-LINKED is passed to `org-display-inline-images'."
17686 (interactive "P")
17687 (if org-inline-image-overlays
17688 (progn
17689 (org-remove-inline-images)
17690 (message "Inline image display turned off"))
17691 (org-display-inline-images include-linked)
17692 (if org-inline-image-overlays
17693 (message "%d images displayed inline"
17694 (length org-inline-image-overlays))
17695 (message "No images to display inline"))))
17697 (defun org-redisplay-inline-images ()
17698 "Refresh the display of inline images."
17699 (interactive)
17700 (if (not org-inline-image-overlays)
17701 (org-toggle-inline-images)
17702 (org-toggle-inline-images)
17703 (org-toggle-inline-images)))
17705 (defun org-display-inline-images (&optional include-linked refresh beg end)
17706 "Display inline images.
17707 Normally only links without a description part are inlined, because this
17708 is how it will work for export. When INCLUDE-LINKED is set, also links
17709 with a description part will be inlined. This can be nice for a quick
17710 look at those images, but it does not reflect what exported files will look
17711 like.
17712 When REFRESH is set, refresh existing images between BEG and END.
17713 This will create new image displays only if necessary.
17714 BEG and END default to the buffer boundaries."
17715 (interactive "P")
17716 (unless refresh
17717 (org-remove-inline-images)
17718 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17719 (save-excursion
17720 (save-restriction
17721 (widen)
17722 (setq beg (or beg (point-min)) end (or end (point-max)))
17723 (goto-char beg)
17724 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17725 (substring (org-image-file-name-regexp) 0 -2)
17726 "\\)\\]" (if include-linked "" "\\]")))
17727 old file ov img)
17728 (while (re-search-forward re end t)
17729 (setq old (get-char-property-and-overlay (match-beginning 1)
17730 'org-image-overlay))
17731 (setq file (expand-file-name
17732 (concat (or (match-string 3) "") (match-string 4))))
17733 (when (file-exists-p file)
17734 (if (and (car-safe old) refresh)
17735 (image-refresh (overlay-get (cdr old) 'display))
17736 (setq img (save-match-data (create-image file)))
17737 (when img
17738 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17739 (overlay-put ov 'display img)
17740 (overlay-put ov 'face 'default)
17741 (overlay-put ov 'org-image-overlay t)
17742 (overlay-put ov 'modification-hooks
17743 (list 'org-display-inline-remove-overlay))
17744 (push ov org-inline-image-overlays)))))))))
17746 (define-obsolete-function-alias
17747 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17749 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17750 "Remove inline-display overlay if a corresponding region is modified."
17751 (let ((inhibit-modification-hooks t))
17752 (when (and ov after)
17753 (delete ov org-inline-image-overlays)
17754 (delete-overlay ov))))
17756 (defun org-remove-inline-images ()
17757 "Remove inline display of images."
17758 (interactive)
17759 (mapc 'delete-overlay org-inline-image-overlays)
17760 (setq org-inline-image-overlays nil))
17762 ;;;; Key bindings
17764 ;; Outline functions from `outline-mode-prefix-map'
17765 ;; that can be remapped in Org:
17766 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17767 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17768 (define-key org-mode-map [remap outline-forward-same-level]
17769 'org-forward-heading-same-level)
17770 (define-key org-mode-map [remap outline-backward-same-level]
17771 'org-backward-heading-same-level)
17772 (define-key org-mode-map [remap show-branches]
17773 'org-kill-note-or-show-branches)
17774 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17775 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17776 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17778 ;; Outline functions from `outline-mode-prefix-map' that can not
17779 ;; be remapped in Org:
17781 ;; - the column "key binding" shows whether the Outline function is still
17782 ;; available in Org mode on the same key that it has been bound to in
17783 ;; Outline mode:
17784 ;; - "overridden": key used for a different functionality in Org mode
17785 ;; - else: key still bound to the same Outline function in Org mode
17787 ;; | Outline function | key binding | Org replacement |
17788 ;; |------------------------------------+-------------+-----------------------|
17789 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17790 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17791 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17792 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17793 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17794 ;; | `show-entry' | overridden | no replacement |
17795 ;; | `show-children' | `C-c C-i' | visibility cycling |
17796 ;; | `show-branches' | `C-c C-k' | still same function |
17797 ;; | `show-subtree' | overridden | visibility cycling |
17798 ;; | `show-all' | overridden | no replacement |
17799 ;; | `hide-subtree' | overridden | visibility cycling |
17800 ;; | `hide-body' | overridden | no replacement |
17801 ;; | `hide-entry' | overridden | visibility cycling |
17802 ;; | `hide-leaves' | overridden | no replacement |
17803 ;; | `hide-sublevels' | overridden | no replacement |
17804 ;; | `hide-other' | overridden | no replacement |
17806 ;; Make `C-c C-x' a prefix key
17807 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17809 ;; TAB key with modifiers
17810 (org-defkey org-mode-map "\C-i" 'org-cycle)
17811 (org-defkey org-mode-map [(tab)] 'org-cycle)
17812 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17813 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17814 ;; The following line is necessary under Suse GNU/Linux
17815 (unless (featurep 'xemacs)
17816 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17817 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17818 (define-key org-mode-map [backtab] 'org-shifttab)
17820 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17821 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17822 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17824 ;; Cursor keys with modifiers
17825 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17826 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17827 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17828 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17830 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17831 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17832 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17833 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17835 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17836 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17837 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17838 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17840 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17841 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17842 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17843 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17845 ;; Babel keys
17846 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17847 (mapc (lambda (pair)
17848 (define-key org-babel-map (car pair) (cdr pair)))
17849 org-babel-key-bindings)
17851 ;;; Extra keys for tty access.
17852 ;; We only set them when really needed because otherwise the
17853 ;; menus don't show the simple keys
17855 (when (or org-use-extra-keys
17856 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17857 (not window-system))
17858 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17859 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17860 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17861 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17862 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17863 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17864 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17865 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17866 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17867 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17868 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17869 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17870 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17871 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17872 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17873 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17874 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17875 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17876 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17877 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17878 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17879 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17880 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17881 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17882 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17883 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17884 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17885 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17887 ;; All the other keys
17889 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17890 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17891 (if (boundp 'narrow-map)
17892 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17893 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17894 (if (boundp 'narrow-map)
17895 (org-defkey narrow-map "b" 'org-narrow-to-block)
17896 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17897 (if (boundp 'narrow-map)
17898 (org-defkey narrow-map "e" 'org-narrow-to-element)
17899 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17900 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17901 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17902 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17903 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17904 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17905 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17906 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17907 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17908 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17909 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17910 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17911 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17912 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17913 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17914 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17915 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17916 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17917 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17918 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17919 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17920 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17921 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17922 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17923 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17924 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17925 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17926 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17927 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17928 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17929 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17930 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17931 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17932 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17933 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17934 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17935 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17936 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17937 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17938 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17939 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17940 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17941 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17942 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17943 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17944 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17945 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17946 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17947 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17948 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17949 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17950 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17951 (org-defkey org-mode-map "\C-c^" 'org-sort)
17952 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17953 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17954 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17955 (org-defkey org-mode-map "\C-m" 'org-return)
17956 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17957 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17958 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17959 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17960 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17961 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17962 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17963 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17964 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17965 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17966 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17967 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17968 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17969 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17970 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17971 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17972 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17973 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17974 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17975 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17976 (org-defkey org-mode-map "\M-h" 'org-mark-element)
17977 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17978 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17980 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17981 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17982 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17984 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17985 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17986 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
17987 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
17988 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17989 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17990 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
17991 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17992 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17993 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17994 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17995 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17996 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
17997 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17998 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17999 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18000 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18001 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18002 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18003 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18004 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18005 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18007 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18008 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18009 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18010 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18011 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18013 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18015 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18017 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18018 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18020 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18023 (when (featurep 'xemacs)
18024 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18027 (defconst org-speed-commands-default
18029 ("Outline Navigation")
18030 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18031 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18032 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18033 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18034 ("u" . (org-speed-move-safe 'outline-up-heading))
18035 ("j" . org-goto)
18036 ("g" . (org-refile t))
18037 ("Outline Visibility")
18038 ("c" . org-cycle)
18039 ("C" . org-shifttab)
18040 (" " . org-display-outline-path)
18041 (":" . org-columns)
18042 ("Outline Structure Editing")
18043 ("U" . org-shiftmetaup)
18044 ("D" . org-shiftmetadown)
18045 ("r" . org-metaright)
18046 ("l" . org-metaleft)
18047 ("R" . org-shiftmetaright)
18048 ("L" . org-shiftmetaleft)
18049 ("i" . (progn (forward-char 1) (call-interactively
18050 'org-insert-heading-respect-content)))
18051 ("^" . org-sort)
18052 ("w" . org-refile)
18053 ("a" . org-archive-subtree-default-with-confirmation)
18054 ("." . org-mark-subtree)
18055 ("#" . org-toggle-comment)
18056 ("Clock Commands")
18057 ("I" . org-clock-in)
18058 ("O" . org-clock-out)
18059 ("Meta Data Editing")
18060 ("t" . org-todo)
18061 ("," . (org-priority))
18062 ("0" . (org-priority ?\ ))
18063 ("1" . (org-priority ?A))
18064 ("2" . (org-priority ?B))
18065 ("3" . (org-priority ?C))
18066 (";" . org-set-tags-command)
18067 ("e" . org-set-effort)
18068 ("E" . org-inc-effort)
18069 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18070 (org-entry-put (point) "APPT_WARNTIME" m)))
18071 ("Agenda Views etc")
18072 ("v" . org-agenda)
18073 ("/" . org-sparse-tree)
18074 ("Misc")
18075 ("o" . org-open-at-point)
18076 ("?" . org-speed-command-help)
18077 ("<" . (org-agenda-set-restriction-lock 'subtree))
18078 (">" . (org-agenda-remove-restriction-lock))
18080 "The default speed commands.")
18082 (defun org-print-speed-command (e)
18083 (if (> (length (car e)) 1)
18084 (progn
18085 (princ "\n")
18086 (princ (car e))
18087 (princ "\n")
18088 (princ (make-string (length (car e)) ?-))
18089 (princ "\n"))
18090 (princ (car e))
18091 (princ " ")
18092 (if (symbolp (cdr e))
18093 (princ (symbol-name (cdr e)))
18094 (prin1 (cdr e)))
18095 (princ "\n")))
18097 (defun org-speed-command-help ()
18098 "Show the available speed commands."
18099 (interactive)
18100 (if (not org-use-speed-commands)
18101 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18102 (with-output-to-temp-buffer "*Help*"
18103 (princ "User-defined Speed commands\n===========================\n")
18104 (mapc 'org-print-speed-command org-speed-commands-user)
18105 (princ "\n")
18106 (princ "Built-in Speed commands\n=======================\n")
18107 (mapc 'org-print-speed-command org-speed-commands-default))
18108 (with-current-buffer "*Help*"
18109 (setq truncate-lines t))))
18111 (defun org-speed-move-safe (cmd)
18112 "Execute CMD, but make sure that the cursor always ends up in a headline.
18113 If not, return to the original position and throw an error."
18114 (interactive)
18115 (let ((pos (point)))
18116 (call-interactively cmd)
18117 (unless (and (bolp) (org-at-heading-p))
18118 (goto-char pos)
18119 (error "Boundary reached while executing %s" cmd))))
18121 (defvar org-self-insert-command-undo-counter 0)
18123 (defvar org-table-auto-blank-field) ; defined in org-table.el
18124 (defvar org-speed-command nil)
18126 (define-obsolete-function-alias
18127 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18129 (defun org-speed-command-activate (keys)
18130 "Hook for activating single-letter speed commands.
18131 `org-speed-commands-default' specifies a minimal command set.
18132 Use `org-speed-commands-user' for further customization."
18133 (when (or (and (bolp) (looking-at org-outline-regexp))
18134 (and (functionp org-use-speed-commands)
18135 (funcall org-use-speed-commands)))
18136 (cdr (assoc keys (append org-speed-commands-user
18137 org-speed-commands-default)))))
18139 (define-obsolete-function-alias
18140 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18142 (defun org-babel-speed-command-activate (keys)
18143 "Hook for activating single-letter code block commands."
18144 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18145 (cdr (assoc keys org-babel-key-bindings))))
18147 (defcustom org-speed-command-hook
18148 '(org-speed-command-default-hook org-babel-speed-command-hook)
18149 "Hook for activating speed commands at strategic locations.
18150 Hook functions are called in sequence until a valid handler is
18151 found.
18153 Each hook takes a single argument, a user-pressed command key
18154 which is also a `self-insert-command' from the global map.
18156 Within the hook, examine the cursor position and the command key
18157 and return nil or a valid handler as appropriate. Handler could
18158 be one of an interactive command, a function, or a form.
18160 Set `org-use-speed-commands' to non-nil value to enable this
18161 hook. The default setting is `org-speed-command-activate'."
18162 :group 'org-structure
18163 :version "24.1"
18164 :type 'hook)
18166 (defun org-self-insert-command (N)
18167 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18168 If the cursor is in a table looking at whitespace, the whitespace is
18169 overwritten, and the table is not marked as requiring realignment."
18170 (interactive "p")
18171 (org-check-before-invisible-edit 'insert)
18172 (cond
18173 ((and org-use-speed-commands
18174 (setq org-speed-command
18175 (run-hook-with-args-until-success
18176 'org-speed-command-hook (this-command-keys))))
18177 (cond
18178 ((commandp org-speed-command)
18179 (setq this-command org-speed-command)
18180 (call-interactively org-speed-command))
18181 ((functionp org-speed-command)
18182 (funcall org-speed-command))
18183 ((and org-speed-command (listp org-speed-command))
18184 (eval org-speed-command))
18185 (t (let (org-use-speed-commands)
18186 (call-interactively 'org-self-insert-command)))))
18187 ((and
18188 (org-table-p)
18189 (progn
18190 ;; check if we blank the field, and if that triggers align
18191 (and (featurep 'org-table) org-table-auto-blank-field
18192 (member last-command
18193 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18194 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18195 ;; got extra space, this field does not determine column width
18196 (let (org-table-may-need-update) (org-table-blank-field))
18197 ;; no extra space, this field may determine column width
18198 (org-table-blank-field)))
18200 (eq N 1)
18201 (looking-at "[^|\n]* |"))
18202 (let (org-table-may-need-update)
18203 (goto-char (1- (match-end 0)))
18204 (backward-delete-char 1)
18205 (goto-char (match-beginning 0))
18206 (self-insert-command N)))
18208 (setq org-table-may-need-update t)
18209 (self-insert-command N)
18210 (org-fix-tags-on-the-fly)
18211 (if org-self-insert-cluster-for-undo
18212 (if (not (eq last-command 'org-self-insert-command))
18213 (setq org-self-insert-command-undo-counter 1)
18214 (if (>= org-self-insert-command-undo-counter 20)
18215 (setq org-self-insert-command-undo-counter 1)
18216 (and (> org-self-insert-command-undo-counter 0)
18217 buffer-undo-list (listp buffer-undo-list)
18218 (not (cadr buffer-undo-list)) ; remove nil entry
18219 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18220 (setq org-self-insert-command-undo-counter
18221 (1+ org-self-insert-command-undo-counter))))))))
18223 (defun org-check-before-invisible-edit (kind)
18224 "Check is editing if kind KIND would be dangerous with invisible text around.
18225 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18226 ;; First, try to get out of here as quickly as possible, to reduce overhead
18227 (if (and org-catch-invisible-edits
18228 (or (not (boundp 'visible-mode)) (not visible-mode))
18229 (or (get-char-property (point) 'invisible)
18230 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18231 ;; OK, we need to take a closer look
18232 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18233 (invisible-before-point (if (bobp) nil (get-char-property
18234 (1- (point)) 'invisible)))
18235 (border-and-ok-direction
18237 ;; Check if we are acting predictably before invisible text
18238 (and invisible-at-point (not invisible-before-point)
18239 (memq kind '(insert delete-backward)))
18240 ;; Check if we are acting predictably after invisible text
18241 ;; This works not well, and I have turned it off. It seems
18242 ;; better to always show and stop after invisible text.
18243 ;; (and (not invisible-at-point) invisible-before-point
18244 ;; (memq kind '(insert delete)))
18246 (when (or (memq invisible-at-point '(outline org-hide-block t))
18247 (memq invisible-before-point '(outline org-hide-block t)))
18248 (if (eq org-catch-invisible-edits 'error)
18249 (error "Editing in invisible areas is prohibited - make visible first"))
18250 (if (and org-custom-properties-overlays
18251 (y-or-n-p "Display invisible properties in this buffer? "))
18252 (org-toggle-custom-properties-visibility)
18253 ;; Make the area visible
18254 (save-excursion
18255 (if invisible-before-point
18256 (goto-char (previous-single-char-property-change
18257 (point) 'invisible)))
18258 (org-cycle))
18259 (cond
18260 ((eq org-catch-invisible-edits 'show)
18261 ;; That's it, we do the edit after showing
18262 (message
18263 "Unfolding invisible region around point before editing")
18264 (sit-for 1))
18265 ((and (eq org-catch-invisible-edits 'smart)
18266 border-and-ok-direction)
18267 (message "Unfolding invisible region around point before editing"))
18269 ;; Don't do the edit, make the user repeat it in full visibility
18270 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18272 (defun org-fix-tags-on-the-fly ()
18273 (when (and (equal (char-after (point-at-bol)) ?*)
18274 (org-at-heading-p))
18275 (org-align-tags-here org-tags-column)))
18277 (defun org-delete-backward-char (N)
18278 "Like `delete-backward-char', insert whitespace at field end in tables.
18279 When deleting backwards, in tables this function will insert whitespace in
18280 front of the next \"|\" separator, to keep the table aligned. The table will
18281 still be marked for re-alignment if the field did fill the entire column,
18282 because, in this case the deletion might narrow the column."
18283 (interactive "p")
18284 (org-check-before-invisible-edit 'delete-backward)
18285 (if (and (org-table-p)
18286 (eq N 1)
18287 (string-match "|" (buffer-substring (point-at-bol) (point)))
18288 (looking-at ".*?|"))
18289 (let ((pos (point))
18290 (noalign (looking-at "[^|\n\r]* |"))
18291 (c org-table-may-need-update))
18292 (backward-delete-char N)
18293 (if (not overwrite-mode)
18294 (progn
18295 (skip-chars-forward "^|")
18296 (insert " ")
18297 (goto-char (1- pos))))
18298 ;; noalign: if there were two spaces at the end, this field
18299 ;; does not determine the width of the column.
18300 (if noalign (setq org-table-may-need-update c)))
18301 (backward-delete-char N)
18302 (org-fix-tags-on-the-fly)))
18304 (defun org-delete-char (N)
18305 "Like `delete-char', but insert whitespace at field end in tables.
18306 When deleting characters, in tables this function will insert whitespace in
18307 front of the next \"|\" separator, to keep the table aligned. The table will
18308 still be marked for re-alignment if the field did fill the entire column,
18309 because, in this case the deletion might narrow the column."
18310 (interactive "p")
18311 (org-check-before-invisible-edit 'delete)
18312 (if (and (org-table-p)
18313 (not (bolp))
18314 (not (= (char-after) ?|))
18315 (eq N 1))
18316 (if (looking-at ".*?|")
18317 (let ((pos (point))
18318 (noalign (looking-at "[^|\n\r]* |"))
18319 (c org-table-may-need-update))
18320 (replace-match (concat
18321 (substring (match-string 0) 1 -1)
18322 " |"))
18323 (goto-char pos)
18324 ;; noalign: if there were two spaces at the end, this field
18325 ;; does not determine the width of the column.
18326 (if noalign (setq org-table-may-need-update c)))
18327 (delete-char N))
18328 (delete-char N)
18329 (org-fix-tags-on-the-fly)))
18331 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18332 (put 'org-self-insert-command 'delete-selection t)
18333 (put 'orgtbl-self-insert-command 'delete-selection t)
18334 (put 'org-delete-char 'delete-selection 'supersede)
18335 (put 'org-delete-backward-char 'delete-selection 'supersede)
18336 (put 'org-yank 'delete-selection 'yank)
18338 ;; Make `flyspell-mode' delay after some commands
18339 (put 'org-self-insert-command 'flyspell-delayed t)
18340 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18341 (put 'org-delete-char 'flyspell-delayed t)
18342 (put 'org-delete-backward-char 'flyspell-delayed t)
18344 ;; Make pabbrev-mode expand after org-mode commands
18345 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18346 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18348 ;; How to do this: Measure non-white length of current string
18349 ;; If equal to column width, we should realign.
18351 (defun org-remap (map &rest commands)
18352 "In MAP, remap the functions given in COMMANDS.
18353 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18354 (let (new old)
18355 (while commands
18356 (setq old (pop commands) new (pop commands))
18357 (if (fboundp 'command-remapping)
18358 (org-defkey map (vector 'remap old) new)
18359 (substitute-key-definition old new map global-map)))))
18361 (when (eq org-enable-table-editor 'optimized)
18362 ;; If the user wants maximum table support, we need to hijack
18363 ;; some standard editing functions
18364 (org-remap org-mode-map
18365 'self-insert-command 'org-self-insert-command
18366 'delete-char 'org-delete-char
18367 'delete-backward-char 'org-delete-backward-char)
18368 (org-defkey org-mode-map "|" 'org-force-self-insert))
18370 (defvar org-ctrl-c-ctrl-c-hook nil
18371 "Hook for functions attaching themselves to `C-c C-c'.
18373 This can be used to add additional functionality to the C-c C-c
18374 key which executes context-dependent commands. This hook is run
18375 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18376 run after the last test.
18378 Each function will be called with no arguments. The function
18379 must check if the context is appropriate for it to act. If yes,
18380 it should do its thing and then return a non-nil value. If the
18381 context is wrong, just do nothing and return nil.")
18383 (defvar org-ctrl-c-ctrl-c-final-hook nil
18384 "Hook for functions attaching themselves to `C-c C-c'.
18386 This can be used to add additional functionality to the C-c C-c
18387 key which executes context-dependent commands. This hook is run
18388 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18389 before the first test.
18391 Each function will be called with no arguments. The function
18392 must check if the context is appropriate for it to act. If yes,
18393 it should do its thing and then return a non-nil value. If the
18394 context is wrong, just do nothing and return nil.")
18396 (defvar org-tab-first-hook nil
18397 "Hook for functions to attach themselves to TAB.
18398 See `org-ctrl-c-ctrl-c-hook' for more information.
18399 This hook runs as the first action when TAB is pressed, even before
18400 `org-cycle' messes around with the `outline-regexp' to cater for
18401 inline tasks and plain list item folding.
18402 If any function in this hook returns t, any other actions that
18403 would have been caused by TAB (such as table field motion or visibility
18404 cycling) will not occur.")
18406 (defvar org-tab-after-check-for-table-hook nil
18407 "Hook for functions to attach themselves to TAB.
18408 See `org-ctrl-c-ctrl-c-hook' for more information.
18409 This hook runs after it has been established that the cursor is not in a
18410 table, but before checking if the cursor is in a headline or if global cycling
18411 should be done.
18412 If any function in this hook returns t, not other actions like visibility
18413 cycling will be done.")
18415 (defvar org-tab-after-check-for-cycling-hook nil
18416 "Hook for functions to attach themselves to TAB.
18417 See `org-ctrl-c-ctrl-c-hook' for more information.
18418 This hook runs after it has been established that not table field motion and
18419 not visibility should be done because of current context. This is probably
18420 the place where a package like yasnippets can hook in.")
18422 (defvar org-tab-before-tab-emulation-hook nil
18423 "Hook for functions to attach themselves to TAB.
18424 See `org-ctrl-c-ctrl-c-hook' for more information.
18425 This hook runs after every other options for TAB have been exhausted, but
18426 before indentation and \t insertion takes place.")
18428 (defvar org-metaleft-hook nil
18429 "Hook for functions attaching themselves to `M-left'.
18430 See `org-ctrl-c-ctrl-c-hook' for more information.")
18431 (defvar org-metaright-hook nil
18432 "Hook for functions attaching themselves to `M-right'.
18433 See `org-ctrl-c-ctrl-c-hook' for more information.")
18434 (defvar org-metaup-hook nil
18435 "Hook for functions attaching themselves to `M-up'.
18436 See `org-ctrl-c-ctrl-c-hook' for more information.")
18437 (defvar org-metadown-hook nil
18438 "Hook for functions attaching themselves to `M-down'.
18439 See `org-ctrl-c-ctrl-c-hook' for more information.")
18440 (defvar org-shiftmetaleft-hook nil
18441 "Hook for functions attaching themselves to `M-S-left'.
18442 See `org-ctrl-c-ctrl-c-hook' for more information.")
18443 (defvar org-shiftmetaright-hook nil
18444 "Hook for functions attaching themselves to `M-S-right'.
18445 See `org-ctrl-c-ctrl-c-hook' for more information.")
18446 (defvar org-shiftmetaup-hook nil
18447 "Hook for functions attaching themselves to `M-S-up'.
18448 See `org-ctrl-c-ctrl-c-hook' for more information.")
18449 (defvar org-shiftmetadown-hook nil
18450 "Hook for functions attaching themselves to `M-S-down'.
18451 See `org-ctrl-c-ctrl-c-hook' for more information.")
18452 (defvar org-metareturn-hook nil
18453 "Hook for functions attaching themselves to `M-RET'.
18454 See `org-ctrl-c-ctrl-c-hook' for more information.")
18455 (defvar org-shiftup-hook nil
18456 "Hook for functions attaching themselves to `S-up'.
18457 See `org-ctrl-c-ctrl-c-hook' for more information.")
18458 (defvar org-shiftup-final-hook nil
18459 "Hook for functions attaching themselves to `S-up'.
18460 This one runs after all other options except shift-select have been excluded.
18461 See `org-ctrl-c-ctrl-c-hook' for more information.")
18462 (defvar org-shiftdown-hook nil
18463 "Hook for functions attaching themselves to `S-down'.
18464 See `org-ctrl-c-ctrl-c-hook' for more information.")
18465 (defvar org-shiftdown-final-hook nil
18466 "Hook for functions attaching themselves to `S-down'.
18467 This one runs after all other options except shift-select have been excluded.
18468 See `org-ctrl-c-ctrl-c-hook' for more information.")
18469 (defvar org-shiftleft-hook nil
18470 "Hook for functions attaching themselves to `S-left'.
18471 See `org-ctrl-c-ctrl-c-hook' for more information.")
18472 (defvar org-shiftleft-final-hook nil
18473 "Hook for functions attaching themselves to `S-left'.
18474 This one runs after all other options except shift-select have been excluded.
18475 See `org-ctrl-c-ctrl-c-hook' for more information.")
18476 (defvar org-shiftright-hook nil
18477 "Hook for functions attaching themselves to `S-right'.
18478 See `org-ctrl-c-ctrl-c-hook' for more information.")
18479 (defvar org-shiftright-final-hook nil
18480 "Hook for functions attaching themselves to `S-right'.
18481 This one runs after all other options except shift-select have been excluded.
18482 See `org-ctrl-c-ctrl-c-hook' for more information.")
18484 (defun org-modifier-cursor-error ()
18485 "Throw an error, a modified cursor command was applied in wrong context."
18486 (error "This command is active in special context like tables, headlines or items"))
18488 (defun org-shiftselect-error ()
18489 "Throw an error because Shift-Cursor command was applied in wrong context."
18490 (if (and (boundp 'shift-select-mode) shift-select-mode)
18491 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18492 (error "This command works only in special context like headlines or timestamps")))
18494 (defun org-call-for-shift-select (cmd)
18495 (let ((this-command-keys-shift-translated t))
18496 (call-interactively cmd)))
18498 (defun org-shifttab (&optional arg)
18499 "Global visibility cycling or move to previous table field.
18500 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18501 on context.
18502 See the individual commands for more information."
18503 (interactive "P")
18504 (cond
18505 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18506 ((integerp arg)
18507 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18508 (message "Content view to level: %d" arg)
18509 (org-content (prefix-numeric-value arg2))
18510 (setq org-cycle-global-status 'overview)))
18511 (t (call-interactively 'org-global-cycle))))
18513 (defun org-shiftmetaleft ()
18514 "Promote subtree or delete table column.
18515 Calls `org-promote-subtree', `org-outdent-item-tree', or
18516 `org-table-delete-column', depending on context. See the
18517 individual commands for more information."
18518 (interactive)
18519 (cond
18520 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18521 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18522 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18523 ((if (not (org-region-active-p)) (org-at-item-p)
18524 (save-excursion (goto-char (region-beginning))
18525 (org-at-item-p)))
18526 (call-interactively 'org-outdent-item-tree))
18527 (t (org-modifier-cursor-error))))
18529 (defun org-shiftmetaright ()
18530 "Demote subtree or insert table column.
18531 Calls `org-demote-subtree', `org-indent-item-tree', or
18532 `org-table-insert-column', depending on context. See the
18533 individual commands for more information."
18534 (interactive)
18535 (cond
18536 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18537 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18538 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18539 ((if (not (org-region-active-p)) (org-at-item-p)
18540 (save-excursion (goto-char (region-beginning))
18541 (org-at-item-p)))
18542 (call-interactively 'org-indent-item-tree))
18543 (t (org-modifier-cursor-error))))
18545 (defun org-shiftmetaup (&optional arg)
18546 "Move subtree up or kill table row.
18547 Calls `org-move-subtree-up' or `org-table-kill-row' or
18548 `org-move-item-up' or `org-timestamp-up', depending on context.
18549 See the individual commands for more information."
18550 (interactive "P")
18551 (cond
18552 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18553 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18554 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18555 ((org-at-item-p) (call-interactively 'org-move-item-up))
18556 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18557 (call-interactively 'org-timestamp-up)))
18558 (t (org-modifier-cursor-error))))
18560 (defun org-shiftmetadown (&optional arg)
18561 "Move subtree down or insert table row.
18562 Calls `org-move-subtree-down' or `org-table-insert-row' or
18563 `org-move-item-down' or `org-timestamp-up', depending on context.
18564 See the individual commands for more information."
18565 (interactive "P")
18566 (cond
18567 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18568 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18569 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18570 ((org-at-item-p) (call-interactively 'org-move-item-down))
18571 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18572 (call-interactively 'org-timestamp-down)))
18573 (t (org-modifier-cursor-error))))
18575 (defsubst org-hidden-tree-error ()
18576 (error
18577 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18579 (defun org-metaleft (&optional arg)
18580 "Promote heading or move table column to left.
18581 Calls `org-do-promote' or `org-table-move-column', depending on context.
18582 With no specific context, calls the Emacs default `backward-word'.
18583 See the individual commands for more information."
18584 (interactive "P")
18585 (cond
18586 ((run-hook-with-args-until-success 'org-metaleft-hook))
18587 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18588 ((org-with-limited-levels
18589 (or (org-at-heading-p)
18590 (and (org-region-active-p)
18591 (save-excursion
18592 (goto-char (region-beginning))
18593 (org-at-heading-p)))))
18594 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18595 (call-interactively 'org-do-promote))
18596 ;; At an inline task.
18597 ((org-at-heading-p)
18598 (call-interactively 'org-inlinetask-promote))
18599 ((or (org-at-item-p)
18600 (and (org-region-active-p)
18601 (save-excursion
18602 (goto-char (region-beginning))
18603 (org-at-item-p))))
18604 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18605 (call-interactively 'org-outdent-item))
18606 (t (call-interactively 'backward-word))))
18608 (defun org-metaright (&optional arg)
18609 "Demote a subtree, a list item or move table column to right.
18610 In front of a drawer or a block keyword, indent it correctly.
18611 With no specific context, calls the Emacs default `forward-word'.
18612 See the individual commands for more information."
18613 (interactive "P")
18614 (cond
18615 ((run-hook-with-args-until-success 'org-metaright-hook))
18616 ((org-at-table-p) (call-interactively 'org-table-move-column))
18617 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18618 ((org-at-block-p) (call-interactively 'org-indent-block))
18619 ((org-with-limited-levels
18620 (or (org-at-heading-p)
18621 (and (org-region-active-p)
18622 (save-excursion
18623 (goto-char (region-beginning))
18624 (org-at-heading-p)))))
18625 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18626 (call-interactively 'org-do-demote))
18627 ;; At an inline task.
18628 ((org-at-heading-p)
18629 (call-interactively 'org-inlinetask-demote))
18630 ((or (org-at-item-p)
18631 (and (org-region-active-p)
18632 (save-excursion
18633 (goto-char (region-beginning))
18634 (org-at-item-p))))
18635 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18636 (call-interactively 'org-indent-item))
18637 (t (call-interactively 'forward-word))))
18639 (defun org-check-for-hidden (what)
18640 "Check if there are hidden headlines/items in the current visual line.
18641 WHAT can be either `headlines' or `items'. If the current line is
18642 an outline or item heading and it has a folded subtree below it,
18643 this function returns t, nil otherwise."
18644 (let ((re (cond
18645 ((eq what 'headlines) org-outline-regexp-bol)
18646 ((eq what 'items) (org-item-beginning-re))
18647 (t (error "This should not happen"))))
18648 beg end)
18649 (save-excursion
18650 (catch 'exit
18651 (unless (org-region-active-p)
18652 (setq beg (point-at-bol))
18653 (beginning-of-line 2)
18654 (while (and (not (eobp)) ;; this is like `next-line'
18655 (get-char-property (1- (point)) 'invisible))
18656 (beginning-of-line 2))
18657 (setq end (point))
18658 (goto-char beg)
18659 (goto-char (point-at-eol))
18660 (setq end (max end (point)))
18661 (while (re-search-forward re end t)
18662 (if (get-char-property (match-beginning 0) 'invisible)
18663 (throw 'exit t))))
18664 nil))))
18666 (autoload 'org-element-at-point "org-element")
18667 (autoload 'org-element-type "org-element")
18669 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18670 (declare-function org-element-type "org-element" (element))
18671 (declare-function org-element-contents "org-element" (element))
18672 (declare-function org-element-property "org-element" (property element))
18673 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18674 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18675 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18676 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18677 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18679 (defun org-metaup (&optional arg)
18680 "Move subtree up or move table row up.
18681 Calls `org-move-subtree-up' or `org-table-move-row' or
18682 `org-move-item-up', depending on context. See the individual commands
18683 for more information."
18684 (interactive "P")
18685 (cond
18686 ((run-hook-with-args-until-success 'org-metaup-hook))
18687 ((org-region-active-p)
18688 (let* ((a (min (region-beginning) (region-end)))
18689 (b (1- (max (region-beginning) (region-end))))
18690 (c (save-excursion (goto-char a)
18691 (move-beginning-of-line 0)))
18692 (d (save-excursion (goto-char a)
18693 (move-end-of-line 0) (point))))
18694 (transpose-regions a b c d)
18695 (goto-char c)))
18696 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18697 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18698 ((org-at-item-p) (call-interactively 'org-move-item-up))
18699 (t (org-drag-element-backward))))
18701 (defun org-metadown (&optional arg)
18702 "Move subtree down or move table row down.
18703 Calls `org-move-subtree-down' or `org-table-move-row' or
18704 `org-move-item-down', depending on context. See the individual
18705 commands for more information."
18706 (interactive "P")
18707 (cond
18708 ((run-hook-with-args-until-success 'org-metadown-hook))
18709 ((org-region-active-p)
18710 (let* ((a (min (region-beginning) (region-end)))
18711 (b (max (region-beginning) (region-end)))
18712 (c (save-excursion (goto-char b)
18713 (move-beginning-of-line 1)))
18714 (d (save-excursion (goto-char b)
18715 (move-end-of-line 1) (1+ (point)))))
18716 (transpose-regions a b c d)
18717 (goto-char d)))
18718 ((org-at-table-p) (call-interactively 'org-table-move-row))
18719 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18720 ((org-at-item-p) (call-interactively 'org-move-item-down))
18721 (t (org-drag-element-forward))))
18723 (defun org-shiftup (&optional arg)
18724 "Increase item in timestamp or increase priority of current headline.
18725 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18726 depending on context. See the individual commands for more information."
18727 (interactive "P")
18728 (cond
18729 ((run-hook-with-args-until-success 'org-shiftup-hook))
18730 ((and org-support-shift-select (org-region-active-p))
18731 (org-call-for-shift-select 'previous-line))
18732 ((org-at-timestamp-p t)
18733 (call-interactively (if org-edit-timestamp-down-means-later
18734 'org-timestamp-down 'org-timestamp-up)))
18735 ((and (not (eq org-support-shift-select 'always))
18736 org-enable-priority-commands
18737 (org-at-heading-p))
18738 (call-interactively 'org-priority-up))
18739 ((and (not org-support-shift-select) (org-at-item-p))
18740 (call-interactively 'org-previous-item))
18741 ((org-clocktable-try-shift 'up arg))
18742 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18743 (org-support-shift-select
18744 (org-call-for-shift-select 'previous-line))
18745 (t (org-shiftselect-error))))
18747 (defun org-shiftdown (&optional arg)
18748 "Decrease item in timestamp or decrease priority of current headline.
18749 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18750 depending on context. See the individual commands for more information."
18751 (interactive "P")
18752 (cond
18753 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18754 ((and org-support-shift-select (org-region-active-p))
18755 (org-call-for-shift-select 'next-line))
18756 ((org-at-timestamp-p t)
18757 (call-interactively (if org-edit-timestamp-down-means-later
18758 'org-timestamp-up 'org-timestamp-down)))
18759 ((and (not (eq org-support-shift-select 'always))
18760 org-enable-priority-commands
18761 (org-at-heading-p))
18762 (call-interactively 'org-priority-down))
18763 ((and (not org-support-shift-select) (org-at-item-p))
18764 (call-interactively 'org-next-item))
18765 ((org-clocktable-try-shift 'down arg))
18766 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18767 (org-support-shift-select
18768 (org-call-for-shift-select 'next-line))
18769 (t (org-shiftselect-error))))
18771 (defun org-shiftright (&optional arg)
18772 "Cycle the thing at point or in the current line, depending on context.
18773 Depending on context, this does one of the following:
18775 - switch a timestamp at point one day into the future
18776 - on a headline, switch to the next TODO keyword.
18777 - on an item, switch entire list to the next bullet type
18778 - on a property line, switch to the next allowed value
18779 - on a clocktable definition line, move time block into the future"
18780 (interactive "P")
18781 (cond
18782 ((run-hook-with-args-until-success 'org-shiftright-hook))
18783 ((and org-support-shift-select (org-region-active-p))
18784 (org-call-for-shift-select 'forward-char))
18785 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18786 ((and (not (eq org-support-shift-select 'always))
18787 (org-at-heading-p))
18788 (let ((org-inhibit-logging
18789 (not org-treat-S-cursor-todo-selection-as-state-change))
18790 (org-inhibit-blocking
18791 (not org-treat-S-cursor-todo-selection-as-state-change)))
18792 (org-call-with-arg 'org-todo 'right)))
18793 ((or (and org-support-shift-select
18794 (not (eq org-support-shift-select 'always))
18795 (org-at-item-bullet-p))
18796 (and (not org-support-shift-select) (org-at-item-p)))
18797 (org-call-with-arg 'org-cycle-list-bullet nil))
18798 ((and (not (eq org-support-shift-select 'always))
18799 (org-at-property-p))
18800 (call-interactively 'org-property-next-allowed-value))
18801 ((org-clocktable-try-shift 'right arg))
18802 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18803 (org-support-shift-select
18804 (org-call-for-shift-select 'forward-char))
18805 (t (org-shiftselect-error))))
18807 (defun org-shiftleft (&optional arg)
18808 "Cycle the thing at point or in the current line, depending on context.
18809 Depending on context, this does one of the following:
18811 - switch a timestamp at point one day into the past
18812 - on a headline, switch to the previous TODO keyword.
18813 - on an item, switch entire list to the previous bullet type
18814 - on a property line, switch to the previous allowed value
18815 - on a clocktable definition line, move time block into the past"
18816 (interactive "P")
18817 (cond
18818 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18819 ((and org-support-shift-select (org-region-active-p))
18820 (org-call-for-shift-select 'backward-char))
18821 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18822 ((and (not (eq org-support-shift-select 'always))
18823 (org-at-heading-p))
18824 (let ((org-inhibit-logging
18825 (not org-treat-S-cursor-todo-selection-as-state-change))
18826 (org-inhibit-blocking
18827 (not org-treat-S-cursor-todo-selection-as-state-change)))
18828 (org-call-with-arg 'org-todo 'left)))
18829 ((or (and org-support-shift-select
18830 (not (eq org-support-shift-select 'always))
18831 (org-at-item-bullet-p))
18832 (and (not org-support-shift-select) (org-at-item-p)))
18833 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18834 ((and (not (eq org-support-shift-select 'always))
18835 (org-at-property-p))
18836 (call-interactively 'org-property-previous-allowed-value))
18837 ((org-clocktable-try-shift 'left arg))
18838 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18839 (org-support-shift-select
18840 (org-call-for-shift-select 'backward-char))
18841 (t (org-shiftselect-error))))
18843 (defun org-shiftcontrolright ()
18844 "Switch to next TODO set."
18845 (interactive)
18846 (cond
18847 ((and org-support-shift-select (org-region-active-p))
18848 (org-call-for-shift-select 'forward-word))
18849 ((and (not (eq org-support-shift-select 'always))
18850 (org-at-heading-p))
18851 (org-call-with-arg 'org-todo 'nextset))
18852 (org-support-shift-select
18853 (org-call-for-shift-select 'forward-word))
18854 (t (org-shiftselect-error))))
18856 (defun org-shiftcontrolleft ()
18857 "Switch to previous TODO set."
18858 (interactive)
18859 (cond
18860 ((and org-support-shift-select (org-region-active-p))
18861 (org-call-for-shift-select 'backward-word))
18862 ((and (not (eq org-support-shift-select 'always))
18863 (org-at-heading-p))
18864 (org-call-with-arg 'org-todo 'previousset))
18865 (org-support-shift-select
18866 (org-call-for-shift-select 'backward-word))
18867 (t (org-shiftselect-error))))
18869 (defun org-shiftcontrolup ()
18870 "Change timestamps synchronously up in CLOCK log lines."
18871 (interactive)
18872 (cond ((and (not org-support-shift-select)
18873 (org-at-clock-log-p)
18874 (org-at-timestamp-p t))
18875 (org-clock-timestamps-up))
18876 (t (org-shiftselect-error))))
18878 (defun org-shiftcontroldown ()
18879 "Change timestamps synchronously down in CLOCK log lines."
18880 (interactive)
18881 (cond ((and (not org-support-shift-select)
18882 (org-at-clock-log-p)
18883 (org-at-timestamp-p t))
18884 (org-clock-timestamps-down))
18885 (t (org-shiftselect-error))))
18887 (defun org-ctrl-c-ret ()
18888 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18889 (interactive)
18890 (cond
18891 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18892 (t (call-interactively 'org-insert-heading))))
18894 (defun org-find-visible ()
18895 (let ((s (point)))
18896 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18897 (get-char-property s 'invisible)))
18899 (defun org-find-invisible ()
18900 (let ((s (point)))
18901 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18902 (not (get-char-property s 'invisible))))
18905 (defun org-copy-visible (beg end)
18906 "Copy the visible parts of the region."
18907 (interactive "r")
18908 (let (snippets s)
18909 (save-excursion
18910 (save-restriction
18911 (narrow-to-region beg end)
18912 (setq s (goto-char (point-min)))
18913 (while (not (= (point) (point-max)))
18914 (goto-char (org-find-invisible))
18915 (push (buffer-substring s (point)) snippets)
18916 (setq s (goto-char (org-find-visible))))))
18917 (kill-new (apply 'concat (nreverse snippets)))))
18919 (defun org-copy-special ()
18920 "Copy region in table or copy current subtree.
18921 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18922 See the individual commands for more information."
18923 (interactive)
18924 (call-interactively
18925 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18927 (defun org-cut-special ()
18928 "Cut region in table or cut current subtree.
18929 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18930 See the individual commands for more information."
18931 (interactive)
18932 (call-interactively
18933 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18935 (defun org-paste-special (arg)
18936 "Paste rectangular region into table, or past subtree relative to level.
18937 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18938 See the individual commands for more information."
18939 (interactive "P")
18940 (if (org-at-table-p)
18941 (org-table-paste-rectangle)
18942 (org-paste-subtree arg)))
18944 (defun org-edit-special (&optional arg)
18945 "Call a special editor for the stuff at point.
18946 When at a table, call the formula editor with `org-table-edit-formulas'.
18947 When at the first line of an src example, call `org-edit-src-code'.
18948 When in an #+include line, visit the include file. Otherwise call
18949 `ffap' to visit the file at point."
18950 (interactive)
18951 ;; possibly prep session before editing source
18952 (when arg
18953 (let* ((info (org-babel-get-src-block-info))
18954 (lang (nth 0 info))
18955 (params (nth 2 info))
18956 (session (cdr (assoc :session params))))
18957 (when (and info session) ;; we are in a source-code block with a session
18958 (funcall
18959 (intern (concat "org-babel-prep-session:" lang)) session params))))
18960 (cond ;; proceed with `org-edit-special'
18961 ((save-excursion
18962 (beginning-of-line 1)
18963 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18964 (find-file (org-trim (match-string 1))))
18965 ((org-edit-src-code))
18966 ((org-edit-fixed-width-region))
18967 ((org-at-table.el-p)
18968 (org-edit-src-code))
18969 ((or (org-at-table-p)
18970 (save-excursion
18971 (beginning-of-line 1)
18972 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18973 (call-interactively 'org-table-edit-formulas))
18974 (t (call-interactively 'ffap))))
18976 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18977 (defun org-ctrl-c-ctrl-c (&optional arg)
18978 "Set tags in headline, or update according to changed information at point.
18980 This command does many different things, depending on context:
18982 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18983 this is what we do.
18985 - If the cursor is on a statistics cookie, update it.
18987 - If the cursor is in a headline, prompt for tags and insert them
18988 into the current line, aligned to `org-tags-column'. When called
18989 with prefix arg, realign all tags in the current buffer.
18991 - If the cursor is in one of the special #+KEYWORD lines, this
18992 triggers scanning the buffer for these lines and updating the
18993 information.
18995 - If the cursor is inside a table, realign the table. This command
18996 works even if the automatic table editor has been turned off.
18998 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18999 the entire table.
19001 - If the cursor is at a footnote reference or definition, jump to
19002 the corresponding definition or references, respectively.
19004 - If the cursor is a the beginning of a dynamic block, update it.
19006 - If the current buffer is a capture buffer, close note and file it.
19008 - If the cursor is on a <<<target>>>, update radio targets and
19009 corresponding links in this buffer.
19011 - If the cursor is on a numbered item in a plain list, renumber the
19012 ordered list.
19014 - If the cursor is on a checkbox, toggle it.
19016 - If the cursor is on a code block, evaluate it. The variable
19017 `org-confirm-babel-evaluate' can be used to control prompting
19018 before code block evaluation, by default every code block
19019 evaluation requires confirmation. Code block evaluation can be
19020 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19021 (interactive "P")
19022 (let ((org-enable-table-editor t))
19023 (cond
19024 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19025 org-occur-highlights
19026 org-latex-fragment-image-overlays)
19027 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19028 (org-remove-occur-highlights)
19029 (org-remove-latex-fragment-image-overlays)
19030 (message "Temporary highlights/overlays removed from current buffer"))
19031 ((and (local-variable-p 'org-finish-function (current-buffer))
19032 (fboundp org-finish-function))
19033 (funcall org-finish-function))
19034 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19035 ((org-in-regexp org-ts-regexp-both)
19036 (org-timestamp-change 0 'day))
19037 ((or (looking-at org-property-start-re)
19038 (org-at-property-p))
19039 (call-interactively 'org-property-action))
19040 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19041 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19042 (or (org-at-heading-p) (org-at-item-p)))
19043 (call-interactively 'org-update-statistics-cookies))
19044 ((org-at-heading-p) (call-interactively 'org-set-tags))
19045 ((org-at-table.el-p)
19046 (message "Use C-c ' to edit table.el tables"))
19047 ((org-at-table-p)
19048 (org-table-maybe-eval-formula)
19049 (if arg
19050 (call-interactively 'org-table-recalculate)
19051 (org-table-maybe-recalculate-line))
19052 (call-interactively 'org-table-align)
19053 (orgtbl-send-table 'maybe))
19054 ((or (org-footnote-at-reference-p)
19055 (org-footnote-at-definition-p))
19056 (call-interactively 'org-footnote-action))
19057 ((org-at-item-checkbox-p)
19058 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19059 ;; list only if at top item.
19060 (let* ((cbox (match-string 1))
19061 (struct (org-list-struct))
19062 (old-struct (copy-tree struct))
19063 (parents (org-list-parents-alist struct))
19064 (orderedp (org-entry-get nil "ORDERED"))
19065 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19066 block-item)
19067 ;; Use a light version of `org-toggle-checkbox' to avoid
19068 ;; computing list structure twice.
19069 (let ((new-box (cond
19070 ((equal arg '(16)) "[-]")
19071 ((equal arg '(4)) nil)
19072 ((equal "[X]" cbox) "[ ]")
19073 (t "[X]"))))
19074 (if (and firstp arg)
19075 ;; If at first item of sub-list, remove check-box from
19076 ;; every item at the same level.
19077 (mapc
19078 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19079 (org-list-get-all-items
19080 (point-at-bol) struct (org-list-prevs-alist struct)))
19081 (org-list-set-checkbox (point-at-bol) struct new-box)))
19082 ;; Replicate `org-list-write-struct', while grabbing a return
19083 ;; value from `org-list-struct-fix-box'.
19084 (org-list-struct-fix-ind struct parents 2)
19085 (org-list-struct-fix-item-end struct)
19086 (let ((prevs (org-list-prevs-alist struct)))
19087 (org-list-struct-fix-bul struct prevs)
19088 (org-list-struct-fix-ind struct parents)
19089 (setq block-item
19090 (org-list-struct-fix-box struct parents prevs orderedp)))
19091 (org-list-struct-apply-struct struct old-struct)
19092 (org-update-checkbox-count-maybe)
19093 (when block-item
19094 (message
19095 "Checkboxes were removed due to unchecked box at line %d"
19096 (org-current-line block-item)))
19097 (when firstp (org-list-send-list 'maybe))))
19098 ((org-at-item-p)
19099 ;; Cursor at an item: repair list. Do checkbox related actions
19100 ;; only if function was called with an argument. Send list only
19101 ;; if at top item.
19102 (let* ((struct (org-list-struct))
19103 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19104 old-struct)
19105 (when arg
19106 (setq old-struct (copy-tree struct))
19107 (if firstp
19108 ;; If at first item of sub-list, add check-box to every
19109 ;; item at the same level.
19110 (mapc
19111 (lambda (pos)
19112 (unless (org-list-get-checkbox pos struct)
19113 (org-list-set-checkbox pos struct "[ ]")))
19114 (org-list-get-all-items
19115 (point-at-bol) struct (org-list-prevs-alist struct)))
19116 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19117 (org-list-write-struct
19118 struct (org-list-parents-alist struct) old-struct)
19119 (when arg (org-update-checkbox-count-maybe))
19120 (when firstp (org-list-send-list 'maybe))))
19121 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19122 ;; Dynamic block
19123 (beginning-of-line 1)
19124 (save-excursion (org-update-dblock)))
19125 ((save-excursion
19126 (let ((case-fold-search t))
19127 (beginning-of-line 1)
19128 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19129 (cond
19130 ((or (equal (match-string 1) "TBLFM")
19131 (equal (match-string 1) "tblfm"))
19132 ;; Recalculate the table before this line
19133 (save-excursion
19134 (beginning-of-line 1)
19135 (skip-chars-backward " \r\n\t")
19136 (if (org-at-table-p)
19137 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19139 (let ((org-inhibit-startup-visibility-stuff t)
19140 (org-startup-align-all-tables nil))
19141 (when (boundp 'org-table-coordinate-overlays)
19142 (mapc 'delete-overlay org-table-coordinate-overlays)
19143 (setq org-table-coordinate-overlays nil))
19144 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19145 (message "Local setup has been refreshed"))))
19146 ((org-clock-update-time-maybe))
19148 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19149 (error "C-c C-c can do nothing useful at this location"))))))
19151 (defun org-mode-restart ()
19152 "Restart Org-mode, to scan again for special lines.
19153 Also updates the keyword regular expressions."
19154 (interactive)
19155 (org-mode)
19156 (message "Org-mode restarted"))
19158 (defun org-kill-note-or-show-branches ()
19159 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19160 (interactive)
19161 (if (not org-finish-function)
19162 (progn
19163 (hide-subtree)
19164 (call-interactively 'show-branches))
19165 (let ((org-note-abort t))
19166 (funcall org-finish-function))))
19168 (defun org-return (&optional indent)
19169 "Goto next table row or insert a newline.
19170 Calls `org-table-next-row' or `newline', depending on context.
19171 See the individual commands for more information."
19172 (interactive)
19173 (let (org-ts-what)
19174 (cond
19175 ((or (bobp) (org-in-src-block-p))
19176 (if indent (newline-and-indent) (newline)))
19177 ((org-at-table-p)
19178 (org-table-justify-field-maybe)
19179 (call-interactively 'org-table-next-row))
19180 ;; when `newline-and-indent' is called within a list, make sure
19181 ;; text moved stays inside the item.
19182 ((and (org-in-item-p) indent)
19183 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19184 (progn
19185 (save-match-data (newline))
19186 (org-indent-line-to (length (match-string 0))))
19187 (let ((ind (org-get-indentation)))
19188 (newline)
19189 (if (org-looking-back org-list-end-re)
19190 (org-indent-line)
19191 (org-indent-line-to ind)))))
19192 ((and org-return-follows-link
19193 (org-at-timestamp-p t)
19194 (not (eq org-ts-what 'after)))
19195 (org-follow-timestamp-link))
19196 ((and org-return-follows-link
19197 (let ((tprop (get-text-property (point) 'face)))
19198 (or (eq tprop 'org-link)
19199 (and (listp tprop) (memq 'org-link tprop)))))
19200 (call-interactively 'org-open-at-point))
19201 ((and (org-at-heading-p)
19202 (looking-at
19203 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19204 (org-show-entry)
19205 (end-of-line 1)
19206 (newline))
19207 (t (if indent (newline-and-indent) (newline))))))
19209 (defun org-return-indent ()
19210 "Goto next table row or insert a newline and indent.
19211 Calls `org-table-next-row' or `newline-and-indent', depending on
19212 context. See the individual commands for more information."
19213 (interactive)
19214 (org-return t))
19216 (defun org-ctrl-c-star ()
19217 "Compute table, or change heading status of lines.
19218 Calls `org-table-recalculate' or `org-toggle-heading',
19219 depending on context."
19220 (interactive)
19221 (cond
19222 ((org-at-table-p)
19223 (call-interactively 'org-table-recalculate))
19225 ;; Convert all lines in region to list items
19226 (call-interactively 'org-toggle-heading))))
19228 (defun org-ctrl-c-minus ()
19229 "Insert separator line in table or modify bullet status of line.
19230 Also turns a plain line or a region of lines into list items.
19231 Calls `org-table-insert-hline', `org-toggle-item', or
19232 `org-cycle-list-bullet', depending on context."
19233 (interactive)
19234 (cond
19235 ((org-at-table-p)
19236 (call-interactively 'org-table-insert-hline))
19237 ((org-region-active-p)
19238 (call-interactively 'org-toggle-item))
19239 ((org-in-item-p)
19240 (call-interactively 'org-cycle-list-bullet))
19242 (call-interactively 'org-toggle-item))))
19244 (defun org-toggle-item (arg)
19245 "Convert headings or normal lines to items, items to normal lines.
19246 If there is no active region, only the current line is considered.
19248 If the first non blank line in the region is an headline, convert
19249 all headlines to items, shifting text accordingly.
19251 If it is an item, convert all items to normal lines.
19253 If it is normal text, change region into an item. With a prefix
19254 argument ARG, change each line in region into an item."
19255 (interactive "P")
19256 (let ((shift-text
19257 (function
19258 ;; Shift text in current section to IND, from point to END.
19259 ;; The function leaves point to END line.
19260 (lambda (ind end)
19261 (let ((min-i 1000) (end (copy-marker end)))
19262 ;; First determine the minimum indentation (MIN-I) of
19263 ;; the text.
19264 (save-excursion
19265 (catch 'exit
19266 (while (< (point) end)
19267 (let ((i (org-get-indentation)))
19268 (cond
19269 ;; Skip blank lines and inline tasks.
19270 ((looking-at "^[ \t]*$"))
19271 ((looking-at org-outline-regexp-bol))
19272 ;; We can't find less than 0 indentation.
19273 ((zerop i) (throw 'exit (setq min-i 0)))
19274 ((< i min-i) (setq min-i i))))
19275 (forward-line))))
19276 ;; Then indent each line so that a line indented to
19277 ;; MIN-I becomes indented to IND. Ignore blank lines
19278 ;; and inline tasks in the process.
19279 (let ((delta (- ind min-i)))
19280 (while (< (point) end)
19281 (unless (or (looking-at "^[ \t]*$")
19282 (looking-at org-outline-regexp-bol))
19283 (org-indent-line-to (+ (org-get-indentation) delta)))
19284 (forward-line)))))))
19285 (skip-blanks
19286 (function
19287 ;; Return beginning of first non-blank line, starting from
19288 ;; line at POS.
19289 (lambda (pos)
19290 (save-excursion
19291 (goto-char pos)
19292 (skip-chars-forward " \r\t\n")
19293 (point-at-bol)))))
19294 beg end)
19295 ;; Determine boundaries of changes.
19296 (if (org-region-active-p)
19297 (setq beg (funcall skip-blanks (region-beginning))
19298 end (copy-marker (region-end)))
19299 (setq beg (funcall skip-blanks (point-at-bol))
19300 end (copy-marker (point-at-eol))))
19301 ;; Depending on the starting line, choose an action on the text
19302 ;; between BEG and END.
19303 (org-with-limited-levels
19304 (save-excursion
19305 (goto-char beg)
19306 (cond
19307 ;; Case 1. Start at an item: de-itemize. Note that it only
19308 ;; happens when a region is active: `org-ctrl-c-minus'
19309 ;; would call `org-cycle-list-bullet' otherwise.
19310 ((org-at-item-p)
19311 (while (< (point) end)
19312 (when (org-at-item-p)
19313 (skip-chars-forward " \t")
19314 (delete-region (point) (match-end 0)))
19315 (forward-line)))
19316 ;; Case 2. Start at an heading: convert to items.
19317 ((org-at-heading-p)
19318 (let* ((bul (org-list-bullet-string "-"))
19319 (bul-len (length bul))
19320 ;; Indentation of the first heading. It should be
19321 ;; relative to the indentation of its parent, if any.
19322 (start-ind (save-excursion
19323 (cond
19324 ((not org-adapt-indentation) 0)
19325 ((not (outline-previous-heading)) 0)
19326 (t (length (match-string 0))))))
19327 ;; Level of first heading. Further headings will be
19328 ;; compared to it to determine hierarchy in the list.
19329 (ref-level (org-reduced-level (org-outline-level))))
19330 (while (< (point) end)
19331 (let* ((level (org-reduced-level (org-outline-level)))
19332 (delta (max 0 (- level ref-level))))
19333 ;; If current headline is less indented than the first
19334 ;; one, set it as reference, in order to preserve
19335 ;; subtrees.
19336 (when (< level ref-level) (setq ref-level level))
19337 (replace-match bul t t)
19338 (org-indent-line-to (+ start-ind (* delta bul-len)))
19339 ;; Ensure all text down to END (or SECTION-END) belongs
19340 ;; to the newly created item.
19341 (let ((section-end (save-excursion
19342 (or (outline-next-heading) (point)))))
19343 (forward-line)
19344 (funcall shift-text
19345 (+ start-ind (* (1+ delta) bul-len))
19346 (min end section-end)))))))
19347 ;; Case 3. Normal line with ARG: turn each non-item line into
19348 ;; an item.
19349 (arg
19350 (while (< (point) end)
19351 (unless (or (org-at-heading-p) (org-at-item-p))
19352 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19353 (replace-match
19354 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19355 (forward-line)))
19356 ;; Case 4. Normal line without ARG: make the first line of
19357 ;; region an item, and shift indentation of others
19358 ;; lines to set them as item's body.
19359 (t (let* ((bul (org-list-bullet-string "-"))
19360 (bul-len (length bul))
19361 (ref-ind (org-get-indentation)))
19362 (skip-chars-forward " \t")
19363 (insert bul)
19364 (forward-line)
19365 (while (< (point) end)
19366 ;; Ensure that lines less indented than first one
19367 ;; still get included in item body.
19368 (funcall shift-text
19369 (+ ref-ind bul-len)
19370 (min end (save-excursion (or (outline-next-heading)
19371 (point)))))
19372 (forward-line)))))))))
19374 (defun org-toggle-heading (&optional nstars)
19375 "Convert headings to normal text, or items or text to headings.
19376 If there is no active region, only the current line is considered.
19378 With a \\[universal-argument] prefix, convert the whole list at
19379 point into heading.
19381 In a region:
19383 - If the first non blank line is an headline, remove the stars
19384 from all headlines in the region.
19386 - If it is a normal line turn each and every normal line (i.e. not an
19387 heading or an item) in the region into a heading.
19389 - If it is a plain list item, turn all plain list items into headings.
19391 When converting a line into a heading, the number of stars is chosen
19392 such that the lines become children of the current entry. However,
19393 when a prefix argument is given, its value determines the number of
19394 stars to add."
19395 (interactive "P")
19396 (let ((skip-blanks
19397 (function
19398 ;; Return beginning of first non-blank line, starting from
19399 ;; line at POS.
19400 (lambda (pos)
19401 (save-excursion
19402 (goto-char pos)
19403 (while (org-at-comment-p) (forward-line))
19404 (skip-chars-forward " \r\t\n")
19405 (point-at-bol)))))
19406 beg end toggled)
19407 ;; Determine boundaries of changes. If a universal prefix has
19408 ;; been given, put the list in a region. If region ends at a bol,
19409 ;; do not consider the last line to be in the region.
19411 (when (and current-prefix-arg (org-at-item-p))
19412 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19413 (org-mark-element))
19415 (if (org-region-active-p)
19416 (setq beg (funcall skip-blanks (region-beginning))
19417 end (copy-marker (save-excursion
19418 (goto-char (region-end))
19419 (if (bolp) (point) (point-at-eol)))))
19420 (setq beg (funcall skip-blanks (point-at-bol))
19421 end (copy-marker (point-at-eol))))
19422 ;; Ensure inline tasks don't count as headings.
19423 (org-with-limited-levels
19424 (save-excursion
19425 (goto-char beg)
19426 (cond
19427 ;; Case 1. Started at an heading: de-star headings.
19428 ((org-at-heading-p)
19429 (while (< (point) end)
19430 (when (org-at-heading-p t)
19431 (looking-at org-outline-regexp) (replace-match "")
19432 (setq toggled t))
19433 (forward-line)))
19434 ;; Case 2. Started at an item: change items into headlines.
19435 ;; One star will be added by `org-list-to-subtree'.
19436 ((org-at-item-p)
19437 (let* ((stars (make-string
19438 (if nstars
19439 ;; subtract the star that will be added again by
19440 ;; `org-list-to-subtree'
19441 (1- (prefix-numeric-value current-prefix-arg))
19442 (or (org-current-level) 0))
19443 ?*))
19444 (add-stars
19445 (cond (nstars "") ; stars from prefix only
19446 ((equal stars "") "") ; before first heading
19447 (org-odd-levels-only "*") ; inside heading, odd
19448 (t "")))) ; inside heading, oddeven
19449 (while (< (point) end)
19450 (when (org-at-item-p)
19451 ;; Pay attention to cases when region ends before list.
19452 (let* ((struct (org-list-struct))
19453 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19454 (save-restriction
19455 (narrow-to-region (point) list-end)
19456 (insert
19457 (org-list-to-subtree
19458 (org-list-parse-list t)
19459 '(:istart (concat stars add-stars (funcall get-stars depth))
19460 :icount (concat stars add-stars (funcall get-stars depth)))))))
19461 (setq toggled t))
19462 (forward-line))))
19463 ;; Case 3. Started at normal text: make every line an heading,
19464 ;; skipping headlines and items.
19465 (t (let* ((stars (make-string
19466 (if nstars
19467 (prefix-numeric-value current-prefix-arg)
19468 (or (org-current-level) 0))
19469 ?*))
19470 (add-stars
19471 (cond (nstars "") ; stars from prefix only
19472 ((equal stars "") "*") ; before first heading
19473 (org-odd-levels-only "**") ; inside heading, odd
19474 (t "*"))) ; inside heading, oddeven
19475 (rpl (concat stars add-stars " ")))
19476 (while (< (point) end)
19477 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19478 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19479 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19480 (forward-line)))))))
19481 (unless toggled (message "Cannot toggle heading from here"))))
19483 (defun org-meta-return (&optional arg)
19484 "Insert a new heading or wrap a region in a table.
19485 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19486 See the individual commands for more information."
19487 (interactive "P")
19488 (cond
19489 ((run-hook-with-args-until-success 'org-metareturn-hook))
19490 ((or (org-at-drawer-p) (org-at-property-p))
19491 (newline-and-indent))
19492 ((org-at-table-p)
19493 (call-interactively 'org-table-wrap-region))
19494 (t (call-interactively 'org-insert-heading))))
19496 ;;; Menu entries
19498 (defsubst org-in-subtree-not-table-p ()
19499 "Are we in a subtree and not in a table?"
19500 (and (not (org-before-first-heading-p))
19501 (not (org-at-table-p))))
19503 ;; Define the Org-mode menus
19504 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19505 '("Tbl"
19506 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19507 ["Next Field" org-cycle (org-at-table-p)]
19508 ["Previous Field" org-shifttab (org-at-table-p)]
19509 ["Next Row" org-return (org-at-table-p)]
19510 "--"
19511 ["Blank Field" org-table-blank-field (org-at-table-p)]
19512 ["Edit Field" org-table-edit-field (org-at-table-p)]
19513 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19514 "--"
19515 ("Column"
19516 ["Move Column Left" org-metaleft (org-at-table-p)]
19517 ["Move Column Right" org-metaright (org-at-table-p)]
19518 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19519 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19520 ("Row"
19521 ["Move Row Up" org-metaup (org-at-table-p)]
19522 ["Move Row Down" org-metadown (org-at-table-p)]
19523 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19524 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19525 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19526 "--"
19527 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19528 ("Rectangle"
19529 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19530 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19531 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19532 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19533 "--"
19534 ("Calculate"
19535 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19536 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19537 ["Edit Formulas" org-edit-special (org-at-table-p)]
19538 "--"
19539 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19540 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19541 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19542 "--"
19543 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19544 "--"
19545 ["Sum Column/Rectangle" org-table-sum
19546 (or (org-at-table-p) (org-region-active-p))]
19547 ["Which Column?" org-table-current-column (org-at-table-p)])
19548 ["Debug Formulas"
19549 org-table-toggle-formula-debugger
19550 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19551 ["Show Col/Row Numbers"
19552 org-table-toggle-coordinate-overlays
19553 :style toggle
19554 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19555 "--"
19556 ["Create" org-table-create (and (not (org-at-table-p))
19557 org-enable-table-editor)]
19558 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19559 ["Import from File" org-table-import (not (org-at-table-p))]
19560 ["Export to File" org-table-export (org-at-table-p)]
19561 "--"
19562 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19564 (easy-menu-define org-org-menu org-mode-map "Org menu"
19565 '("Org"
19566 ("Show/Hide"
19567 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19568 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19569 ["Sparse Tree..." org-sparse-tree t]
19570 ["Reveal Context" org-reveal t]
19571 ["Show All" show-all t]
19572 "--"
19573 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19574 "--"
19575 ["New Heading" org-insert-heading t]
19576 ("Navigate Headings"
19577 ["Up" outline-up-heading t]
19578 ["Next" outline-next-visible-heading t]
19579 ["Previous" outline-previous-visible-heading t]
19580 ["Next Same Level" outline-forward-same-level t]
19581 ["Previous Same Level" outline-backward-same-level t]
19582 "--"
19583 ["Jump" org-goto t])
19584 ("Edit Structure"
19585 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19586 "--"
19587 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19588 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19589 "--"
19590 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19591 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19592 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19593 "--"
19594 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19595 "--"
19596 ["Copy visible text" org-copy-visible t]
19597 "--"
19598 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19599 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19600 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19601 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19602 "--"
19603 ["Sort Region/Children" org-sort t]
19604 "--"
19605 ["Convert to odd levels" org-convert-to-odd-levels t]
19606 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19607 ("Editing"
19608 ["Emphasis..." org-emphasize t]
19609 ["Edit Source Example" org-edit-special t]
19610 "--"
19611 ["Footnote new/jump" org-footnote-action t]
19612 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19613 ("Archive"
19614 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19615 "--"
19616 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19617 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19618 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19620 "--"
19621 ("Hyperlinks"
19622 ["Store Link (Global)" org-store-link t]
19623 ["Find existing link to here" org-occur-link-in-agenda-files t]
19624 ["Insert Link" org-insert-link t]
19625 ["Follow Link" org-open-at-point t]
19626 "--"
19627 ["Next link" org-next-link t]
19628 ["Previous link" org-previous-link t]
19629 "--"
19630 ["Descriptive Links"
19631 org-toggle-link-display
19632 :style radio
19633 :selected org-descriptive-links
19635 ["Literal Links"
19636 org-toggle-link-display
19637 :style radio
19638 :selected (not org-descriptive-links)])
19639 "--"
19640 ("TODO Lists"
19641 ["TODO/DONE/-" org-todo t]
19642 ("Select keyword"
19643 ["Next keyword" org-shiftright (org-at-heading-p)]
19644 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19645 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19646 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19647 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19648 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19649 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19650 "--"
19651 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19652 :selected org-enforce-todo-dependencies :style toggle :active t]
19653 "Settings for tree at point"
19654 ["Do Children sequentially" org-toggle-ordered-property :style radio
19655 :selected (org-entry-get nil "ORDERED")
19656 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19657 ["Do Children parallel" org-toggle-ordered-property :style radio
19658 :selected (not (org-entry-get nil "ORDERED"))
19659 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19660 "--"
19661 ["Set Priority" org-priority t]
19662 ["Priority Up" org-shiftup t]
19663 ["Priority Down" org-shiftdown t]
19664 "--"
19665 ["Get news from all feeds" org-feed-update-all t]
19666 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19667 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19668 ("TAGS and Properties"
19669 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19670 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19671 "--"
19672 ["Set property" org-set-property (not (org-before-first-heading-p))]
19673 ["Column view of properties" org-columns t]
19674 ["Insert Column View DBlock" org-insert-columns-dblock t])
19675 ("Dates and Scheduling"
19676 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19677 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19678 ("Change Date"
19679 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19680 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19681 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19682 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19683 ["Compute Time Range" org-evaluate-time-range t]
19684 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19685 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19686 "--"
19687 ["Custom time format" org-toggle-time-stamp-overlays
19688 :style radio :selected org-display-custom-times]
19689 "--"
19690 ["Goto Calendar" org-goto-calendar t]
19691 ["Date from Calendar" org-date-from-calendar t]
19692 "--"
19693 ["Start/Restart Timer" org-timer-start t]
19694 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19695 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19696 ["Insert Timer String" org-timer t]
19697 ["Insert Timer Item" org-timer-item t])
19698 ("Logging work"
19699 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19700 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19701 ["Clock out" org-clock-out t]
19702 ["Clock cancel" org-clock-cancel t]
19703 "--"
19704 ["Mark as default task" org-clock-mark-default-task t]
19705 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19706 ["Goto running clock" org-clock-goto t]
19707 "--"
19708 ["Display times" org-clock-display t]
19709 ["Create clock table" org-clock-report t]
19710 "--"
19711 ["Record DONE time"
19712 (progn (setq org-log-done (not org-log-done))
19713 (message "Switching to %s will %s record a timestamp"
19714 (car org-done-keywords)
19715 (if org-log-done "automatically" "not")))
19716 :style toggle :selected org-log-done])
19717 "--"
19718 ["Agenda Command..." org-agenda t]
19719 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19720 ("File List for Agenda")
19721 ("Special views current file"
19722 ["TODO Tree" org-show-todo-tree t]
19723 ["Check Deadlines" org-check-deadlines t]
19724 ["Timeline" org-timeline t]
19725 ["Tags/Property tree" org-match-sparse-tree t])
19726 "--"
19727 ["Export/Publish..." org-export t]
19728 ("LaTeX"
19729 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19730 :selected org-cdlatex-mode]
19731 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19732 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19733 ["Modify math symbol" org-cdlatex-math-modify
19734 (org-inside-LaTeX-fragment-p)]
19735 ["Insert citation" org-reftex-citation t]
19736 "--"
19737 ["Template for BEAMER" (progn (require 'org-beamer)
19738 (org-insert-beamer-options-template)) t])
19739 "--"
19740 ("MobileOrg"
19741 ["Push Files and Views" org-mobile-push t]
19742 ["Get Captured and Flagged" org-mobile-pull t]
19743 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19744 "--"
19745 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19746 "--"
19747 ("Documentation"
19748 ["Show Version" org-version t]
19749 ["Info Documentation" org-info t])
19750 ("Customize"
19751 ["Browse Org Group" org-customize t]
19752 "--"
19753 ["Expand This Menu" org-create-customize-menu
19754 (fboundp 'customize-menu-create)])
19755 ["Send bug report" org-submit-bug-report t]
19756 "--"
19757 ("Refresh/Reload"
19758 ["Refresh setup current buffer" org-mode-restart t]
19759 ["Reload Org (after update)" org-reload t]
19760 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19763 (defun org-info (&optional node)
19764 "Read documentation for Org-mode in the info system.
19765 With optional NODE, go directly to that node."
19766 (interactive)
19767 (info (format "(org)%s" (or node ""))))
19769 ;;;###autoload
19770 (defun org-submit-bug-report ()
19771 "Submit a bug report on Org-mode via mail.
19773 Don't hesitate to report any problems or inaccurate documentation.
19775 If you don't have setup sending mail from (X)Emacs, please copy the
19776 output buffer into your mail program, as it gives us important
19777 information about your Org-mode version and configuration."
19778 (interactive)
19779 (require 'reporter)
19780 (org-load-modules-maybe)
19781 (org-require-autoloaded-modules)
19782 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19783 (reporter-submit-bug-report
19784 "emacs-orgmode@gnu.org"
19785 (org-version nil 'full)
19786 (let (list)
19787 (save-window-excursion
19788 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19789 (delete-other-windows)
19790 (erase-buffer)
19791 (insert "You are about to submit a bug report to the Org-mode mailing list.
19793 We would like to add your full Org-mode and Outline configuration to the
19794 bug report. This greatly simplifies the work of the maintainer and
19795 other experts on the mailing list.
19797 HOWEVER, some variables you have customized may contain private
19798 information. The names of customers, colleagues, or friends, might
19799 appear in the form of file names, tags, todo states, or search strings.
19800 If you answer yes to the prompt, you might want to check and remove
19801 such private information before sending the email.")
19802 (add-text-properties (point-min) (point-max) '(face org-warning))
19803 (when (yes-or-no-p "Include your Org-mode configuration ")
19804 (mapatoms
19805 (lambda (v)
19806 (and (boundp v)
19807 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19808 (or (and (symbol-value v)
19809 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19810 (and
19811 (get v 'custom-type) (get v 'standard-value)
19812 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19813 (push v list)))))
19814 (kill-buffer (get-buffer "*Warn about privacy*"))
19815 list))
19816 nil nil
19817 "Remember to cover the basics, that is, what you expected to happen and
19818 what in fact did happen. You don't know how to make a good report? See
19820 http://orgmode.org/manual/Feedback.html#Feedback
19822 Your bug report will be posted to the Org-mode mailing list.
19823 ------------------------------------------------------------------------")
19824 (save-excursion
19825 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19826 (replace-match "\\1Bug: \\3 [\\2]")))))
19829 (defun org-install-agenda-files-menu ()
19830 (let ((bl (buffer-list)))
19831 (save-excursion
19832 (while bl
19833 (set-buffer (pop bl))
19834 (if (derived-mode-p 'org-mode) (setq bl nil)))
19835 (when (derived-mode-p 'org-mode)
19836 (easy-menu-change
19837 '("Org") "File List for Agenda"
19838 (append
19839 (list
19840 ["Edit File List" (org-edit-agenda-file-list) t]
19841 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19842 ["Remove Current File from List" org-remove-file t]
19843 ["Cycle through agenda files" org-cycle-agenda-files t]
19844 ["Occur in all agenda files" org-occur-in-agenda-files t]
19845 "--")
19846 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19848 ;;;; Documentation
19850 (defun org-require-autoloaded-modules ()
19851 (interactive)
19852 (mapc 'require
19853 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19854 org-docbook org-exp org-html org-icalendar
19855 org-id org-latex
19856 org-publish org-remember org-table
19857 org-timer org-xoxo)))
19859 ;;;###autoload
19860 (defun org-reload (&optional uncompiled)
19861 "Reload all org lisp files.
19862 With prefix arg UNCOMPILED, load the uncompiled versions."
19863 (interactive "P")
19864 (require 'find-func)
19865 (let* ((file-re "^org\\(-.*\\)?\\.el")
19866 (dir-org (file-name-directory (org-find-library-dir "org")))
19867 (dir-org-contrib (ignore-errors
19868 (file-name-directory
19869 (org-find-library-dir "org-contribdir"))))
19870 (babel-files
19871 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19872 (append (list nil "comint" "eval" "exp" "keys"
19873 "lob" "ref" "table" "tangle")
19874 (delq nil
19875 (mapcar
19876 (lambda (lang)
19877 (when (cdr lang) (symbol-name (car lang))))
19878 org-babel-load-languages)))))
19879 (files
19880 (append babel-files
19881 (and dir-org-contrib
19882 (directory-files dir-org-contrib t file-re))
19883 (directory-files dir-org t file-re)))
19884 (remove-re (concat (if (featurep 'xemacs)
19885 "org-colview" "org-colview-xemacs")
19886 "\\'")))
19887 (setq files (mapcar 'file-name-sans-extension files))
19888 (setq files (mapcar
19889 (lambda (x) (if (string-match remove-re x) nil x))
19890 files))
19891 (setq files (delq nil files))
19892 (mapc
19893 (lambda (f)
19894 (when (featurep (intern (file-name-nondirectory f)))
19895 (if (and (not uncompiled)
19896 (file-exists-p (concat f ".elc")))
19897 (load (concat f ".elc") nil nil 'nosuffix)
19898 (load (concat f ".el") nil nil 'nosuffix))))
19899 files)
19900 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19901 (org-version nil 'full 'message))
19903 ;;;###autoload
19904 (defun org-customize ()
19905 "Call the customize function with org as argument."
19906 (interactive)
19907 (org-load-modules-maybe)
19908 (org-require-autoloaded-modules)
19909 (customize-browse 'org))
19911 (defun org-create-customize-menu ()
19912 "Create a full customization menu for Org-mode, insert it into the menu."
19913 (interactive)
19914 (org-load-modules-maybe)
19915 (org-require-autoloaded-modules)
19916 (if (fboundp 'customize-menu-create)
19917 (progn
19918 (easy-menu-change
19919 '("Org") "Customize"
19920 `(["Browse Org group" org-customize t]
19921 "--"
19922 ,(customize-menu-create 'org)
19923 ["Set" Custom-set t]
19924 ["Save" Custom-save t]
19925 ["Reset to Current" Custom-reset-current t]
19926 ["Reset to Saved" Custom-reset-saved t]
19927 ["Reset to Standard Settings" Custom-reset-standard t]))
19928 (message "\"Org\"-menu now contains full customization menu"))
19929 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19931 ;;;; Miscellaneous stuff
19933 ;;; Generally useful functions
19935 (defun org-get-at-bol (property)
19936 "Get text property PROPERTY at beginning of line."
19937 (get-text-property (point-at-bol) property))
19939 (defun org-find-text-property-in-string (prop s)
19940 "Return the first non-nil value of property PROP in string S."
19941 (or (get-text-property 0 prop s)
19942 (get-text-property (or (next-single-property-change 0 prop s) 0)
19943 prop s)))
19945 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19946 "Display the given MESSAGE as a warning."
19947 (if (fboundp 'display-warning)
19948 (display-warning 'org message
19949 (if (featurep 'xemacs) 'warning :warning))
19950 (let ((buf (get-buffer-create "*Org warnings*")))
19951 (with-current-buffer buf
19952 (goto-char (point-max))
19953 (insert "Warning (Org): " message)
19954 (unless (bolp)
19955 (newline)))
19956 (display-buffer buf)
19957 (sit-for 0))))
19959 (defun org-eval (form)
19960 "Eval FORM and return result."
19961 (condition-case error
19962 (eval form)
19963 (error (format "%%![Error: %s]" error))))
19965 (defun org-in-clocktable-p ()
19966 "Check if the cursor is in a clocktable."
19967 (let ((pos (point)) start)
19968 (save-excursion
19969 (end-of-line 1)
19970 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19971 (setq start (match-beginning 0))
19972 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19973 (>= (match-end 0) pos)
19974 start))))
19976 (defun org-in-commented-line ()
19977 "Is point in a line starting with `#'?"
19978 (equal (char-after (point-at-bol)) ?#))
19980 (defun org-in-indented-comment-line ()
19981 "Is point in a line starting with `#' after some white space?"
19982 (save-excursion
19983 (save-match-data
19984 (goto-char (point-at-bol))
19985 (looking-at "[ \t]*#"))))
19987 (defun org-in-verbatim-emphasis ()
19988 (save-match-data
19989 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19991 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19992 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19993 (if (and marker (marker-buffer marker)
19994 (buffer-live-p (marker-buffer marker)))
19995 (progn
19996 (org-pop-to-buffer-same-window (marker-buffer marker))
19997 (if (or (> marker (point-max)) (< marker (point-min)))
19998 (widen))
19999 (goto-char marker)
20000 (org-show-context 'org-goto))
20001 (if bookmark
20002 (bookmark-jump bookmark)
20003 (error "Cannot find location"))))
20005 (defun org-quote-csv-field (s)
20006 "Quote field for inclusion in CSV material."
20007 (if (string-match "[\",]" s)
20008 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20011 (defun org-force-self-insert (N)
20012 "Needed to enforce self-insert under remapping."
20013 (interactive "p")
20014 (self-insert-command N))
20016 (defun org-string-width (s)
20017 "Compute width of string, ignoring invisible characters.
20018 This ignores character with invisibility property `org-link', and also
20019 characters with property `org-cwidth', because these will become invisible
20020 upon the next fontification round."
20021 (let (b l)
20022 (when (or (eq t buffer-invisibility-spec)
20023 (assq 'org-link buffer-invisibility-spec))
20024 (while (setq b (text-property-any 0 (length s)
20025 'invisible 'org-link s))
20026 (setq s (concat (substring s 0 b)
20027 (substring s (or (next-single-property-change
20028 b 'invisible s) (length s)))))))
20029 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20030 (setq s (concat (substring s 0 b)
20031 (substring s (or (next-single-property-change
20032 b 'org-cwidth s) (length s))))))
20033 (setq l (string-width s) b -1)
20034 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20035 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20038 (defun org-shorten-string (s maxlength)
20039 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20040 If the string is shorter or has length MAXLENGTH, just return the
20041 original string. If it is longer, the functions finds a space in the
20042 string, breaks this string off at that locations and adds three dots
20043 as ellipsis. Including the ellipsis, the string will not be longer
20044 than MAXLENGTH. If finding a good breaking point in the string does
20045 not work, the string is just chopped off in the middle of a word
20046 if necessary."
20047 (if (<= (length s) maxlength)
20049 (let* ((n (max (- maxlength 4) 1))
20050 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20051 (if (string-match re s)
20052 (concat (match-string 1 s) "...")
20053 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20055 (defun org-get-indentation (&optional line)
20056 "Get the indentation of the current line, interpreting tabs.
20057 When LINE is given, assume it represents a line and compute its indentation."
20058 (if line
20059 (if (string-match "^ *" (org-remove-tabs line))
20060 (match-end 0))
20061 (save-excursion
20062 (beginning-of-line 1)
20063 (skip-chars-forward " \t")
20064 (current-column))))
20066 (defun org-get-string-indentation (s)
20067 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20068 (let ((n -1) (i 0) (w tab-width) c)
20069 (catch 'exit
20070 (while (< (setq n (1+ n)) (length s))
20071 (setq c (aref s n))
20072 (cond ((= c ?\ ) (setq i (1+ i)))
20073 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20074 (t (throw 'exit t)))))
20077 (defun org-remove-tabs (s &optional width)
20078 "Replace tabulators in S with spaces.
20079 Assumes that s is a single line, starting in column 0."
20080 (setq width (or width tab-width))
20081 (while (string-match "\t" s)
20082 (setq s (replace-match
20083 (make-string
20084 (- (* width (/ (+ (match-beginning 0) width) width))
20085 (match-beginning 0)) ?\ )
20086 t t s)))
20089 (defun org-fix-indentation (line ind)
20090 "Fix indentation in LINE.
20091 IND is a cons cell with target and minimum indentation.
20092 If the current indentation in LINE is smaller than the minimum,
20093 leave it alone. If it is larger than ind, set it to the target."
20094 (let* ((l (org-remove-tabs line))
20095 (i (org-get-indentation l))
20096 (i1 (car ind)) (i2 (cdr ind)))
20097 (if (>= i i2) (setq l (substring line i2)))
20098 (if (> i1 0)
20099 (concat (make-string i1 ?\ ) l)
20100 l)))
20102 (defun org-remove-indentation (code &optional n)
20103 "Remove the maximum common indentation from the lines in CODE.
20104 N may optionally be the number of spaces to remove."
20105 (with-temp-buffer
20106 (insert code)
20107 (org-do-remove-indentation n)
20108 (buffer-string)))
20110 (defun org-do-remove-indentation (&optional n)
20111 "Remove the maximum common indentation from the buffer."
20112 (untabify (point-min) (point-max))
20113 (let ((min 10000) re)
20114 (if n
20115 (setq min n)
20116 (goto-char (point-min))
20117 (while (re-search-forward "^ *[^ \n]" nil t)
20118 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20119 (unless (or (= min 0) (= min 10000))
20120 (setq re (format "^ \\{%d\\}" min))
20121 (goto-char (point-min))
20122 (while (re-search-forward re nil t)
20123 (replace-match "")
20124 (end-of-line 1))
20125 min)))
20127 (defun org-fill-template (template alist)
20128 "Find each %key of ALIST in TEMPLATE and replace it."
20129 (let ((case-fold-search nil)
20130 entry key value)
20131 (setq alist (sort (copy-sequence alist)
20132 (lambda (a b) (< (length (car a)) (length (car b))))))
20133 (while (setq entry (pop alist))
20134 (setq template
20135 (replace-regexp-in-string
20136 (concat "%" (regexp-quote (car entry)))
20137 (or (cdr entry) "") template t t)))
20138 template))
20140 (defun org-base-buffer (buffer)
20141 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20142 (if (not buffer)
20143 buffer
20144 (or (buffer-base-buffer buffer)
20145 buffer)))
20147 (defun org-trim (s)
20148 "Remove whitespace at beginning and end of string."
20149 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20150 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20153 (defun org-wrap (string &optional width lines)
20154 "Wrap string to either a number of lines, or a width in characters.
20155 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20156 that costs. If there is a word longer than WIDTH, the text is actually
20157 wrapped to the length of that word.
20158 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20159 many lines, whatever width that takes.
20160 The return value is a list of lines, without newlines at the end."
20161 (let* ((words (org-split-string string "[ \t\n]+"))
20162 (maxword (apply 'max (mapcar 'org-string-width words)))
20163 w ll)
20164 (cond (width
20165 (org-do-wrap words (max maxword width)))
20166 (lines
20167 (setq w maxword)
20168 (setq ll (org-do-wrap words maxword))
20169 (if (<= (length ll) lines)
20171 (setq ll words)
20172 (while (> (length ll) lines)
20173 (setq w (1+ w))
20174 (setq ll (org-do-wrap words w)))
20175 ll))
20176 (t (error "Cannot wrap this")))))
20178 (defun org-do-wrap (words width)
20179 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20180 (let (lines line)
20181 (while words
20182 (setq line (pop words))
20183 (while (and words (< (+ (length line) (length (car words))) width))
20184 (setq line (concat line " " (pop words))))
20185 (setq lines (push line lines)))
20186 (nreverse lines)))
20188 (defun org-split-string (string &optional separators)
20189 "Splits STRING into substrings at SEPARATORS.
20190 No empty strings are returned if there are matches at the beginning
20191 and end of string."
20192 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20193 (start 0)
20194 notfirst
20195 (list nil))
20196 (while (and (string-match rexp string
20197 (if (and notfirst
20198 (= start (match-beginning 0))
20199 (< start (length string)))
20200 (1+ start) start))
20201 (< (match-beginning 0) (length string)))
20202 (setq notfirst t)
20203 (or (eq (match-beginning 0) 0)
20204 (and (eq (match-beginning 0) (match-end 0))
20205 (eq (match-beginning 0) start))
20206 (setq list
20207 (cons (substring string start (match-beginning 0))
20208 list)))
20209 (setq start (match-end 0)))
20210 (or (eq start (length string))
20211 (setq list
20212 (cons (substring string start)
20213 list)))
20214 (nreverse list)))
20216 (defun org-quote-vert (s)
20217 "Replace \"|\" with \"\\vert\"."
20218 (while (string-match "|" s)
20219 (setq s (replace-match "\\vert" t t s)))
20222 (defun org-uuidgen-p (s)
20223 "Is S an ID created by UUIDGEN?"
20224 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20226 (defun org-in-src-block-p nil
20227 "Whether point is in a code source block."
20228 (let (ov)
20229 (when (setq ov (overlays-at (point)))
20230 (memq 'org-block-background
20231 (overlay-properties
20232 (car ov))))))
20234 (defun org-context ()
20235 "Return a list of contexts of the current cursor position.
20236 If several contexts apply, all are returned.
20237 Each context entry is a list with a symbol naming the context, and
20238 two positions indicating start and end of the context. Possible
20239 contexts are:
20241 :headline anywhere in a headline
20242 :headline-stars on the leading stars in a headline
20243 :todo-keyword on a TODO keyword (including DONE) in a headline
20244 :tags on the TAGS in a headline
20245 :priority on the priority cookie in a headline
20246 :item on the first line of a plain list item
20247 :item-bullet on the bullet/number of a plain list item
20248 :checkbox on the checkbox in a plain list item
20249 :table in an org-mode table
20250 :table-special on a special filed in a table
20251 :table-table in a table.el table
20252 :clocktable in a clocktable
20253 :src-block in a source block
20254 :link on a hyperlink
20255 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20256 :target on a <<target>>
20257 :radio-target on a <<<radio-target>>>
20258 :latex-fragment on a LaTeX fragment
20259 :latex-preview on a LaTeX fragment with overlaid preview image
20261 This function expects the position to be visible because it uses font-lock
20262 faces as a help to recognize the following contexts: :table-special, :link,
20263 and :keyword."
20264 (let* ((f (get-text-property (point) 'face))
20265 (faces (if (listp f) f (list f)))
20266 (case-fold-search t)
20267 (p (point)) clist o)
20268 ;; First the large context
20269 (cond
20270 ((org-at-heading-p t)
20271 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20272 (when (progn
20273 (beginning-of-line 1)
20274 (looking-at org-todo-line-tags-regexp))
20275 (push (org-point-in-group p 1 :headline-stars) clist)
20276 (push (org-point-in-group p 2 :todo-keyword) clist)
20277 (push (org-point-in-group p 4 :tags) clist))
20278 (goto-char p)
20279 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20280 (if (looking-at "\\[#[A-Z0-9]\\]")
20281 (push (org-point-in-group p 0 :priority) clist)))
20283 ((org-at-item-p)
20284 (push (org-point-in-group p 2 :item-bullet) clist)
20285 (push (list :item (point-at-bol)
20286 (save-excursion (org-end-of-item) (point)))
20287 clist)
20288 (and (org-at-item-checkbox-p)
20289 (push (org-point-in-group p 0 :checkbox) clist)))
20291 ((org-at-table-p)
20292 (push (list :table (org-table-begin) (org-table-end)) clist)
20293 (if (memq 'org-formula faces)
20294 (push (list :table-special
20295 (previous-single-property-change p 'face)
20296 (next-single-property-change p 'face)) clist)))
20297 ((org-at-table-p 'any)
20298 (push (list :table-table) clist)))
20299 (goto-char p)
20301 (let ((case-fold-search t))
20302 ;; New the "medium" contexts: clocktables, source blocks
20303 (cond ((org-in-clocktable-p)
20304 (push (list :clocktable
20305 (and (or (looking-at "#\\+BEGIN: clocktable")
20306 (search-backward "#+BEGIN: clocktable" nil t))
20307 (match-beginning 0))
20308 (and (re-search-forward "#\\+END:?" nil t)
20309 (match-end 0))) clist))
20310 ((org-in-src-block-p)
20311 (push (list :src-block
20312 (and (or (looking-at "#\\+BEGIN_SRC")
20313 (search-backward "#+BEGIN_SRC" nil t))
20314 (match-beginning 0))
20315 (and (search-forward "#+END_SRC" nil t)
20316 (match-beginning 0))) clist))))
20317 (goto-char p)
20319 ;; Now the small context
20320 (cond
20321 ((org-at-timestamp-p)
20322 (push (org-point-in-group p 0 :timestamp) clist))
20323 ((memq 'org-link faces)
20324 (push (list :link
20325 (previous-single-property-change p 'face)
20326 (next-single-property-change p 'face)) clist))
20327 ((memq 'org-special-keyword faces)
20328 (push (list :keyword
20329 (previous-single-property-change p 'face)
20330 (next-single-property-change p 'face)) clist))
20331 ((org-at-target-p)
20332 (push (org-point-in-group p 0 :target) clist)
20333 (goto-char (1- (match-beginning 0)))
20334 (if (looking-at org-radio-target-regexp)
20335 (push (org-point-in-group p 0 :radio-target) clist))
20336 (goto-char p))
20337 ((setq o (car (delq nil
20338 (mapcar
20339 (lambda (x)
20340 (if (memq x org-latex-fragment-image-overlays) x))
20341 (overlays-at (point))))))
20342 (push (list :latex-fragment
20343 (overlay-start o) (overlay-end o)) clist)
20344 (push (list :latex-preview
20345 (overlay-start o) (overlay-end o)) clist))
20346 ((org-inside-LaTeX-fragment-p)
20347 ;; FIXME: positions wrong.
20348 (push (list :latex-fragment (point) (point)) clist)))
20350 (setq clist (nreverse (delq nil clist)))
20351 clist))
20353 ;; FIXME: Compare with at-regexp-p Do we need both?
20354 (defun org-in-regexp (re &optional nlines visually)
20355 "Check if point is inside a match of regexp.
20356 Normally only the current line is checked, but you can include NLINES extra
20357 lines both before and after point into the search.
20358 If VISUALLY is set, require that the cursor is not after the match but
20359 really on, so that the block visually is on the match."
20360 (catch 'exit
20361 (let ((pos (point))
20362 (eol (point-at-eol (+ 1 (or nlines 0))))
20363 (inc (if visually 1 0)))
20364 (save-excursion
20365 (beginning-of-line (- 1 (or nlines 0)))
20366 (while (re-search-forward re eol t)
20367 (if (and (<= (match-beginning 0) pos)
20368 (>= (+ inc (match-end 0)) pos))
20369 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20371 (defun org-at-regexp-p (regexp)
20372 "Is point inside a match of REGEXP in the current line?"
20373 (catch 'exit
20374 (save-excursion
20375 (let ((pos (point)) (end (point-at-eol)))
20376 (beginning-of-line 1)
20377 (while (re-search-forward regexp end t)
20378 (if (and (<= (match-beginning 0) pos)
20379 (>= (match-end 0) pos))
20380 (throw 'exit t)))
20381 nil))))
20383 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20384 "Non-nil when point is between matches of START-RE and END-RE.
20386 Also return a non-nil value when point is on one of the matches.
20388 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20389 buffer positions. Default values are the positions of headlines
20390 surrounding the point.
20392 The functions returns a cons cell whose car (resp. cdr) is the
20393 position before START-RE (resp. after END-RE)."
20394 (save-match-data
20395 (let ((pos (point))
20396 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20397 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20398 beg end)
20399 (save-excursion
20400 ;; Point is on a block when on START-RE or if START-RE can be
20401 ;; found before it...
20402 (and (or (org-at-regexp-p start-re)
20403 (re-search-backward start-re limit-up t))
20404 (setq beg (match-beginning 0))
20405 ;; ... and END-RE after it...
20406 (goto-char (match-end 0))
20407 (re-search-forward end-re limit-down t)
20408 (> (setq end (match-end 0)) pos)
20409 ;; ... without another START-RE in-between.
20410 (goto-char (match-beginning 0))
20411 (not (re-search-backward start-re (1+ beg) t))
20412 ;; Return value.
20413 (cons beg end))))))
20415 (defun org-in-block-p (names)
20416 "Non-nil when point belongs to a block whose name belongs to NAMES.
20418 NAMES is a list of strings containing names of blocks.
20420 Return first block name matched, or nil. Beware that in case of
20421 nested blocks, the returned name may not belong to the closest
20422 block from point."
20423 (save-match-data
20424 (catch 'exit
20425 (let ((case-fold-search t)
20426 (lim-up (save-excursion (outline-previous-heading)))
20427 (lim-down (save-excursion (outline-next-heading))))
20428 (mapc (lambda (name)
20429 (let ((n (regexp-quote name)))
20430 (when (org-between-regexps-p
20431 (concat "^[ \t]*#\\+begin_" n)
20432 (concat "^[ \t]*#\\+end_" n)
20433 lim-up lim-down)
20434 (throw 'exit n))))
20435 names))
20436 nil)))
20438 (defun org-occur-in-agenda-files (regexp &optional nlines)
20439 "Call `multi-occur' with buffers for all agenda files."
20440 (interactive "sOrg-files matching: \np")
20441 (let* ((files (org-agenda-files))
20442 (tnames (mapcar 'file-truename files))
20443 (extra org-agenda-text-search-extra-files)
20445 (when (eq (car extra) 'agenda-archives)
20446 (setq extra (cdr extra))
20447 (setq files (org-add-archive-files files)))
20448 (while (setq f (pop extra))
20449 (unless (member (file-truename f) tnames)
20450 (add-to-list 'files f 'append)
20451 (add-to-list 'tnames (file-truename f) 'append)))
20452 (multi-occur
20453 (mapcar (lambda (x)
20454 (with-current-buffer
20455 (or (get-file-buffer x) (find-file-noselect x))
20456 (widen)
20457 (current-buffer)))
20458 files)
20459 regexp)))
20461 (if (boundp 'occur-mode-find-occurrence-hook)
20462 ;; Emacs 23
20463 (add-hook 'occur-mode-find-occurrence-hook
20464 (lambda ()
20465 (when (derived-mode-p 'org-mode)
20466 (org-reveal))))
20467 ;; Emacs 22
20468 (defadvice occur-mode-goto-occurrence
20469 (after org-occur-reveal activate)
20470 (and (derived-mode-p 'org-mode) (org-reveal)))
20471 (defadvice occur-mode-goto-occurrence-other-window
20472 (after org-occur-reveal activate)
20473 (and (derived-mode-p 'org-mode) (org-reveal)))
20474 (defadvice occur-mode-display-occurrence
20475 (after org-occur-reveal activate)
20476 (when (derived-mode-p 'org-mode)
20477 (let ((pos (occur-mode-find-occurrence)))
20478 (with-current-buffer (marker-buffer pos)
20479 (save-excursion
20480 (goto-char pos)
20481 (org-reveal)))))))
20483 (defun org-occur-link-in-agenda-files ()
20484 "Create a link and search for it in the agendas.
20485 The link is not stored in `org-stored-links', it is just created
20486 for the search purpose."
20487 (interactive)
20488 (let ((link (condition-case nil
20489 (org-store-link nil)
20490 (error "Unable to create a link to here"))))
20491 (org-occur-in-agenda-files (regexp-quote link))))
20493 (defun org-uniquify (list)
20494 "Remove duplicate elements from LIST."
20495 (let (res)
20496 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20497 res))
20499 (defun org-delete-all (elts list)
20500 "Remove all elements in ELTS from LIST."
20501 (while elts
20502 (setq list (delete (pop elts) list)))
20503 list)
20505 (defun org-count (cl-item cl-seq)
20506 "Count the number of occurrences of ITEM in SEQ.
20507 Taken from `count' in cl-seq.el with all keyword arguments removed."
20508 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20509 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20510 (while (< cl-start cl-end)
20511 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20512 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20513 (setq cl-start (1+ cl-start)))
20514 cl-count))
20516 (defun org-remove-if (predicate seq)
20517 "Remove everything from SEQ that fulfills PREDICATE."
20518 (let (res e)
20519 (while seq
20520 (setq e (pop seq))
20521 (if (not (funcall predicate e)) (push e res)))
20522 (nreverse res)))
20524 (defun org-remove-if-not (predicate seq)
20525 "Remove everything from SEQ that does not fulfill PREDICATE."
20526 (let (res e)
20527 (while seq
20528 (setq e (pop seq))
20529 (if (funcall predicate e) (push e res)))
20530 (nreverse res)))
20532 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20533 "Reduce two-argument FUNCTION across SEQ.
20534 Taken from `reduce' in cl-seq.el with all keyword arguments but
20535 \":initial-value\" removed."
20536 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20537 (cadr (memq :initial-value cl-keys)))
20538 (cl-seq (pop cl-seq))
20539 (t (funcall cl-func)))))
20540 (while cl-seq
20541 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20542 cl-accum))
20544 (defun org-back-over-empty-lines ()
20545 "Move backwards over whitespace, to the beginning of the first empty line.
20546 Returns the number of empty lines passed."
20547 (let ((pos (point)))
20548 (if (cdr (assoc 'heading org-blank-before-new-entry))
20549 (skip-chars-backward " \t\n\r")
20550 (unless (eobp)
20551 (forward-line -1)))
20552 (beginning-of-line 2)
20553 (goto-char (min (point) pos))
20554 (count-lines (point) pos)))
20556 (defun org-skip-whitespace ()
20557 (skip-chars-forward " \t\n\r"))
20559 (defun org-point-in-group (point group &optional context)
20560 "Check if POINT is in match-group GROUP.
20561 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20562 match. If the match group does not exist or point is not inside it,
20563 return nil."
20564 (and (match-beginning group)
20565 (>= point (match-beginning group))
20566 (<= point (match-end group))
20567 (if context
20568 (list context (match-beginning group) (match-end group))
20569 t)))
20571 (defun org-switch-to-buffer-other-window (&rest args)
20572 "Switch to buffer in a second window on the current frame.
20573 In particular, do not allow pop-up frames.
20574 Returns the newly created buffer."
20575 (let (pop-up-frames special-display-buffer-names special-display-regexps
20576 special-display-function)
20577 (apply 'switch-to-buffer-other-window args)))
20579 (defun org-combine-plists (&rest plists)
20580 "Create a single property list from all plists in PLISTS.
20581 The process starts by copying the first list, and then setting properties
20582 from the other lists. Settings in the last list are the most significant
20583 ones and overrule settings in the other lists."
20584 (let ((rtn (copy-sequence (pop plists)))
20585 p v ls)
20586 (while plists
20587 (setq ls (pop plists))
20588 (while ls
20589 (setq p (pop ls) v (pop ls))
20590 (setq rtn (plist-put rtn p v))))
20591 rtn))
20593 (defun org-replace-escapes (string table)
20594 "Replace %-escapes in STRING with values in TABLE.
20595 TABLE is an association list with keys like \"%a\" and string values.
20596 The sequences in STRING may contain normal field width and padding information,
20597 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20598 so values can contain further %-escapes if they are define later in TABLE."
20599 (let ((tbl (copy-alist table))
20600 (case-fold-search nil)
20601 (pchg 0)
20602 e re rpl)
20603 (while (setq e (pop tbl))
20604 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20605 (when (and (cdr e) (string-match re (cdr e)))
20606 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20607 (safe "SREF"))
20608 (add-text-properties 0 3 (list 'sref sref) safe)
20609 (setcdr e (replace-match safe t t (cdr e)))))
20610 (while (string-match re string)
20611 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20612 (cdr e)))
20613 (setq string (replace-match rpl t t string))))
20614 (while (setq pchg (next-property-change pchg string))
20615 (let ((sref (get-text-property pchg 'sref string)))
20616 (when (and sref (string-match "SREF" string pchg))
20617 (setq string (replace-match sref t t string)))))
20618 string))
20620 (defun org-sublist (list start end)
20621 "Return a section of LIST, from START to END.
20622 Counting starts at 1."
20623 (let (rtn (c start))
20624 (setq list (nthcdr (1- start) list))
20625 (while (and list (<= c end))
20626 (push (pop list) rtn)
20627 (setq c (1+ c)))
20628 (nreverse rtn)))
20630 (defun org-find-base-buffer-visiting (file)
20631 "Like `find-buffer-visiting' but always return the base buffer and
20632 not an indirect buffer."
20633 (let ((buf (or (get-file-buffer file)
20634 (find-buffer-visiting file))))
20635 (if buf
20636 (or (buffer-base-buffer buf) buf)
20637 nil)))
20639 (defun org-image-file-name-regexp (&optional extensions)
20640 "Return regexp matching the file names of images.
20641 If EXTENSIONS is given, only match these."
20642 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20643 (image-file-name-regexp)
20644 (let ((image-file-name-extensions
20645 (or extensions
20646 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20647 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20648 (concat "\\."
20649 (regexp-opt (nconc (mapcar 'upcase
20650 image-file-name-extensions)
20651 image-file-name-extensions)
20653 "\\'"))))
20655 (defun org-file-image-p (file &optional extensions)
20656 "Return non-nil if FILE is an image."
20657 (save-match-data
20658 (string-match (org-image-file-name-regexp extensions) file)))
20660 (defun org-get-cursor-date ()
20661 "Return the date at cursor in as a time.
20662 This works in the calendar and in the agenda, anywhere else it just
20663 returns the current time."
20664 (let (date day defd)
20665 (cond
20666 ((eq major-mode 'calendar-mode)
20667 (setq date (calendar-cursor-to-date)
20668 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20669 ((eq major-mode 'org-agenda-mode)
20670 (setq day (get-text-property (point) 'day))
20671 (if day
20672 (setq date (calendar-gregorian-from-absolute day)
20673 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20674 (nth 2 date))))))
20675 (or defd (current-time))))
20677 (defun org-mark-subtree (&optional up)
20678 "Mark the current subtree.
20679 This puts point at the start of the current subtree, and mark at
20680 the end. If a numeric prefix UP is given, move up into the
20681 hierarchy of headlines by UP levels before marking the subtree."
20682 (interactive "P")
20683 (org-with-limited-levels
20684 (cond ((org-at-heading-p) (beginning-of-line))
20685 ((org-before-first-heading-p) (error "Not in a subtree"))
20686 (t (outline-previous-visible-heading 1))))
20687 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20688 (if (org-called-interactively-p 'any)
20689 (call-interactively 'org-mark-element)
20690 (org-mark-element)))
20692 ;;; Indentation
20694 (defun org-indent-line ()
20695 "Indent line depending on context."
20696 (interactive)
20697 (let* ((pos (point))
20698 (itemp (org-at-item-p))
20699 (case-fold-search t)
20700 (org-drawer-regexp (or org-drawer-regexp "\000"))
20701 (inline-task-p (and (featurep 'org-inlinetask)
20702 (org-inlinetask-in-task-p)))
20703 (inline-re (and inline-task-p
20704 (org-inlinetask-outline-regexp)))
20705 column)
20706 (if (and orgstruct-is-++ (eq pos (point)))
20707 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20708 (indent-according-to-mode))
20709 (beginning-of-line 1)
20710 (cond
20711 ;; Headings
20712 ((looking-at org-outline-regexp) (setq column 0))
20713 ;; Included files
20714 ((looking-at "#\\+include:") (setq column 0))
20715 ;; Footnote definition
20716 ((looking-at org-footnote-definition-re) (setq column 0))
20717 ;; Literal examples
20718 ((looking-at "[ \t]*:\\( \\|$\\)")
20719 (setq column (org-get-indentation))) ; do nothing
20720 ;; Lists
20721 ((ignore-errors (goto-char (org-in-item-p)))
20722 (setq column (if itemp
20723 (org-get-indentation)
20724 (org-list-item-body-column (point))))
20725 (goto-char pos))
20726 ;; Drawers
20727 ((and (looking-at "[ \t]*:END:")
20728 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20729 (save-excursion
20730 (goto-char (1- (match-beginning 1)))
20731 (setq column (current-column))))
20732 ;; Special blocks
20733 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20734 (save-excursion
20735 (re-search-backward
20736 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20737 (setq column (org-get-indentation (match-string 0))))
20738 ((and (not (looking-at "[ \t]*#\\+begin_"))
20739 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20740 (save-excursion
20741 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20742 (setq column
20743 (cond ((equal (downcase (match-string 1)) "src")
20744 ;; src blocks: let `org-edit-src-exit' handle them
20745 (org-get-indentation))
20746 ((equal (downcase (match-string 1)) "example")
20747 (max (org-get-indentation)
20748 (org-get-indentation (match-string 0))))
20750 (org-get-indentation (match-string 0))))))
20751 ;; This line has nothing special, look at the previous relevant
20752 ;; line to compute indentation
20754 (beginning-of-line 0)
20755 (while (and (not (bobp))
20756 (not (looking-at org-drawer-regexp))
20757 ;; When point started in an inline task, do not move
20758 ;; above task starting line.
20759 (not (and inline-task-p (looking-at inline-re)))
20760 ;; Skip drawers, blocks, empty lines, verbatim,
20761 ;; comments, tables, footnotes definitions, lists,
20762 ;; inline tasks.
20763 (or (and (looking-at "[ \t]*:END:")
20764 (re-search-backward org-drawer-regexp nil t))
20765 (and (looking-at "[ \t]*#\\+end_")
20766 (re-search-backward "[ \t]*#\\+begin_"nil t))
20767 (looking-at "[ \t]*[\n:#|]")
20768 (looking-at org-footnote-definition-re)
20769 (and (ignore-errors (goto-char (org-in-item-p)))
20770 (goto-char
20771 (org-list-get-top-point (org-list-struct))))
20772 (and (not inline-task-p)
20773 (featurep 'org-inlinetask)
20774 (org-inlinetask-in-task-p)
20775 (or (org-inlinetask-goto-beginning) t))))
20776 (beginning-of-line 0))
20777 (cond
20778 ;; There was an heading above.
20779 ((looking-at "\\*+[ \t]+")
20780 (if (not org-adapt-indentation)
20781 (setq column 0)
20782 (goto-char (match-end 0))
20783 (setq column (current-column))))
20784 ;; A drawer had started and is unfinished
20785 ((looking-at org-drawer-regexp)
20786 (goto-char (1- (match-beginning 1)))
20787 (setq column (current-column)))
20788 ;; Else, nothing noticeable found: get indentation and go on.
20789 (t (setq column (org-get-indentation))))))
20790 ;; Now apply indentation and move cursor accordingly
20791 (goto-char pos)
20792 (if (<= (current-column) (current-indentation))
20793 (org-indent-line-to column)
20794 (save-excursion (org-indent-line-to column)))
20795 ;; Special polishing for properties, see `org-property-format'
20796 (setq column (current-column))
20797 (beginning-of-line 1)
20798 (if (looking-at
20799 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20800 (replace-match (concat (match-string 1)
20801 (format org-property-format
20802 (match-string 2) (match-string 3)))
20803 t t))
20804 (org-move-to-column column))))
20806 (defun org-indent-drawer ()
20807 "Indent the drawer at point."
20808 (interactive)
20809 (let ((p (point))
20810 (e (and (save-excursion (re-search-forward ":END:" nil t))
20811 (match-end 0)))
20812 (folded
20813 (save-excursion
20814 (end-of-line)
20815 (when (overlays-at (point))
20816 (member 'invisible (overlay-properties
20817 (car (overlays-at (point)))))))))
20818 (when folded (org-cycle))
20819 (indent-for-tab-command)
20820 (while (and (move-beginning-of-line 2) (< (point) e))
20821 (indent-for-tab-command))
20822 (goto-char p)
20823 (when folded (org-cycle)))
20824 (message "Drawer at point indented"))
20826 (defun org-indent-block ()
20827 "Indent the block at point."
20828 (interactive)
20829 (let ((p (point))
20830 (case-fold-search t)
20831 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20832 (match-end 0)))
20833 (folded
20834 (save-excursion
20835 (end-of-line)
20836 (when (overlays-at (point))
20837 (member 'invisible (overlay-properties
20838 (car (overlays-at (point)))))))))
20839 (when folded (org-cycle))
20840 (indent-for-tab-command)
20841 (while (and (move-beginning-of-line 2) (< (point) e))
20842 (indent-for-tab-command))
20843 (goto-char p)
20844 (when folded (org-cycle)))
20845 (message "Block at point indented"))
20847 (defun org-indent-region (start end)
20848 "Indent region."
20849 (interactive "r")
20850 (save-excursion
20851 (let ((line-end (org-current-line end)))
20852 (goto-char start)
20853 (while (< (org-current-line) line-end)
20854 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20855 (t (call-interactively 'org-indent-line)))
20856 (move-beginning-of-line 2)))))
20859 ;;; Filling
20861 ;; We use our own fill-paragraph and auto-fill functions.
20863 ;; `org-fill-paragraph' relies on adaptive filling and context
20864 ;; checking. Appropriate `fill-prefix' is computed with
20865 ;; `org-adaptive-fill-function'.
20867 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20868 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20869 ;; `org-adaptive-fill-function' value. Internally,
20870 ;; `org-comment-line-break-function' breaks the line.
20872 ;; `org-setup-filling' installs filling and auto-filling related
20873 ;; variables during `org-mode' initialization.
20875 (defun org-setup-filling ()
20876 (interactive)
20877 ;; Prevent auto-fill from inserting unwanted new items.
20878 (when (boundp 'fill-nobreak-predicate)
20879 (org-set-local
20880 'fill-nobreak-predicate
20881 (org-uniquify
20882 (append fill-nobreak-predicate
20883 '(org-fill-paragraph-separate-nobreak-p
20884 org-fill-line-break-nobreak-p)))))
20885 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20886 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20887 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20888 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20890 (defvar org-element-paragraph-separate) ; org-element.el
20891 (defun org-fill-paragraph-separate-nobreak-p ()
20892 "Non-nil when a line break at point would insert a new item."
20893 (looking-at (substring org-element-paragraph-separate 1)))
20895 (defun org-fill-line-break-nobreak-p ()
20896 "Non-nil when a line break at point would create an Org line break."
20897 (save-excursion
20898 (skip-chars-backward "[ \t]")
20899 (skip-chars-backward "\\\\")
20900 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20902 (declare-function message-in-body-p "message" ())
20903 (defvar org-element--affiliated-re) ; From org-element.el
20904 (defun org-adaptive-fill-function ()
20905 "Compute a fill prefix for the current line.
20906 Return fill prefix, as a string, or nil if current line isn't
20907 meant to be filled."
20908 (org-with-wide-buffer
20909 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
20910 ;; FIXME: This is really the job of orgstruct++-mode
20911 (let* ((p (line-beginning-position))
20912 (element (save-excursion (beginning-of-line)
20913 (org-element-at-point)))
20914 (type (org-element-type element))
20915 (post-affiliated
20916 (save-excursion
20917 (goto-char (org-element-property :begin element))
20918 (while (looking-at org-element--affiliated-re) (forward-line))
20919 (point))))
20920 (unless (< p post-affiliated)
20921 (case type
20922 (comment (looking-at "[ \t]*# ?") (match-string 0))
20923 (footnote-definition "")
20924 ((item plain-list)
20925 (make-string (org-list-item-body-column post-affiliated) ? ))
20926 (paragraph
20927 ;; Fill prefix is usually the same as the current line,
20928 ;; except if the paragraph is at the beginning of an item.
20929 (let ((parent (org-element-property :parent element)))
20930 (cond ((eq (org-element-type parent) 'item)
20931 (make-string (org-list-item-body-column
20932 (org-element-property :begin parent))
20933 ? ))
20934 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20935 (match-string 0))
20936 (t ""))))
20937 (comment-block
20938 ;; Only fill contents if P is within block boundaries.
20939 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20940 (forward-line)
20941 (point)))
20942 (cend (save-excursion
20943 (goto-char (org-element-property :end element))
20944 (skip-chars-backward " \r\t\n")
20945 (line-beginning-position))))
20946 (when (and (>= p cbeg) (< p cend))
20947 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20948 (match-string 0)
20949 ""))))))))))
20951 (declare-function message-goto-body "message" ())
20952 (defvar message-cite-prefix-regexp) ; From message.el
20953 (defvar org-element-all-objects) ; From org-element.el
20954 (defun org-fill-paragraph (&optional justify)
20955 "Fill element at point, when applicable.
20957 This function only applies to comment blocks, comments, example
20958 blocks and paragraphs. Also, as a special case, re-align table
20959 when point is at one.
20961 If JUSTIFY is non-nil (interactively, with prefix argument),
20962 justify as well. If `sentence-end-double-space' is non-nil, then
20963 period followed by one space does not end a sentence, so don't
20964 break a line there. The variable `fill-column' controls the
20965 width for filling.
20967 For convenience, when point is at a plain list, an item or
20968 a footnote definition, try to fill the first paragraph within."
20969 ;; Falls back on message-fill-paragraph when necessary
20970 (interactive)
20971 (if (and (derived-mode-p 'message-mode)
20972 (or (not (message-in-body-p))
20973 (save-excursion (move-beginning-of-line 1)
20974 (looking-at message-cite-prefix-regexp))))
20975 (let ((fill-paragraph-function
20976 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
20977 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
20978 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
20979 (paragraph-separate
20980 (cadadr (assoc 'paragraph-separate org-fb-vars))))
20981 (fill-paragraph nil))
20982 (save-excursion
20983 ;; Move to end of line in order to get the first paragraph
20984 ;; within a plain list or a footnote definition.
20985 (end-of-line)
20986 (let ((element (org-element-at-point)))
20987 ;; First check if point is in a blank line at the beginning of
20988 ;; the buffer. In that case, ignore filling.
20989 (if (< (point) (org-element-property :begin element)) t
20990 (case (org-element-type element)
20991 ;; Align Org tables, leave table.el tables as-is.
20992 (table-row (org-table-align) t)
20993 (table
20994 (when (eq (org-element-property :type element) 'org)
20995 (org-table-align))
20997 (paragraph
20998 ;; Paragraphs may contain `line-break' type objects.
20999 (let ((beg (max (point-min)
21000 (org-element-property :contents-begin element)))
21001 (end (min (point-max)
21002 (org-element-property :contents-end element))))
21003 ;; Do nothing if point is at an affiliated keyword.
21004 (if (< (point) beg) t
21005 (when (derived-mode-p 'message-mode)
21006 ;; In `message-mode', do not fill following
21007 ;; citation in current paragraph nor text before
21008 ;; message body.
21009 (let ((body-start (save-excursion (message-goto-body))))
21010 (when body-start (setq beg (max body-start beg))))
21011 (when (save-excursion
21012 (re-search-forward
21013 (concat "^" message-cite-prefix-regexp) end t))
21014 (setq end (match-beginning 0))))
21015 ;; Fill paragraph, taking line breaks into
21016 ;; consideration. For that, slice the paragraph
21017 ;; using line breaks as separators, and fill the
21018 ;; parts in reverse order to avoid messing with
21019 ;; markers.
21020 (save-excursion
21021 (goto-char end)
21022 (mapc
21023 (lambda (pos)
21024 (fill-region-as-paragraph pos (point) justify)
21025 (goto-char pos))
21026 ;; Find the list of ending positions for line
21027 ;; breaks in the current paragraph. Add paragraph
21028 ;; beginning to include first slice.
21029 (nreverse
21030 (cons
21032 (org-element-map
21033 (org-element--parse-objects
21034 beg end nil org-element-all-objects)
21035 'line-break
21036 (lambda (lb) (org-element-property :end lb)))))))
21037 t)))
21038 ;; Contents of `comment-block' type elements should be
21039 ;; filled as plain text, but only if point is within block
21040 ;; markers.
21041 (comment-block
21042 (let* ((case-fold-search t)
21043 (beg (save-excursion
21044 (goto-char (org-element-property :begin element))
21045 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21046 (forward-line)
21047 (point)))
21048 (end (save-excursion
21049 (goto-char (org-element-property :end element))
21050 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21051 (line-beginning-position))))
21052 (when (and (>= (point) beg) (< (point) end))
21053 (fill-region-as-paragraph
21054 (save-excursion
21055 (end-of-line)
21056 (re-search-backward "^[ \t]*$" beg 'move)
21057 (line-beginning-position))
21058 (save-excursion
21059 (beginning-of-line)
21060 (re-search-forward "^[ \t]*$" end 'move)
21061 (line-beginning-position))
21062 justify)))
21064 ;; Fill comments.
21065 (comment (fill-comment-paragraph justify))
21066 ;; Ignore every other element.
21067 (otherwise t)))))))
21069 (defun org-auto-fill-function ()
21070 "Auto-fill function."
21071 ;; Check if auto-filling is meaningful.
21072 (let ((fc (current-fill-column)))
21073 (when (and fc (> (current-column) fc))
21074 (let* ((fill-prefix (org-adaptive-fill-function))
21075 ;; Enforce empty fill prefix, if required. Otherwise, it
21076 ;; will be computed again.
21077 (adaptive-fill-mode (not (equal fill-prefix ""))))
21078 (when fill-prefix (do-auto-fill))))))
21080 (defun org-comment-line-break-function (&optional soft)
21081 "Break line at point and indent, continuing comment if within one.
21082 The inserted newline is marked hard if variable
21083 `use-hard-newlines' is true, unless optional argument SOFT is
21084 non-nil."
21085 (if soft (insert-and-inherit ?\n) (newline 1))
21086 (save-excursion (forward-char -1) (delete-horizontal-space))
21087 (delete-horizontal-space)
21088 (indent-to-left-margin)
21089 (insert-before-markers-and-inherit fill-prefix))
21092 ;;; Comments
21094 ;; Org comments syntax is quite complex. It requires the entire line
21095 ;; to be just a comment. Also, even with the right syntax at the
21096 ;; beginning of line, some some elements (i.e. verse-block or
21097 ;; example-block) don't accept comments. Usual Emacs comment commands
21098 ;; cannot cope with those requirements. Therefore, Org replaces them.
21100 ;; Org still relies on `comment-dwim', but cannot trust
21101 ;; `comment-only-p'. So, `comment-region-function' and
21102 ;; `uncomment-region-function' both point
21103 ;; to`org-comment-or-uncomment-region'. Eventually,
21104 ;; `org-insert-comment' takes care of insertion of comments at the
21105 ;; beginning of line.
21107 ;; `org-setup-comments-handling' install comments related variables
21108 ;; during `org-mode' initialization.
21110 (defun org-setup-comments-handling ()
21111 (interactive)
21112 (org-set-local 'comment-use-syntax nil)
21113 (org-set-local 'comment-start "# ")
21114 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21115 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21116 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21117 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21119 (defun org-insert-comment ()
21120 "Insert an empty comment above current line.
21121 If the line is empty, insert comment at its beginning."
21122 (beginning-of-line)
21123 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21124 (org-indent-line)
21125 (insert "# "))
21127 (defvar comment-empty-lines) ; From newcomment.el.
21128 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21129 "Comment or uncomment each non-blank line in the region.
21130 Uncomment each non-blank line between BEG and END if it only
21131 contains commented lines. Otherwise, comment them."
21132 (save-restriction
21133 ;; Restrict region
21134 (narrow-to-region (save-excursion (goto-char beg)
21135 (skip-chars-forward " \r\t\n" end)
21136 (line-beginning-position))
21137 (save-excursion (goto-char end)
21138 (skip-chars-backward " \r\t\n" beg)
21139 (line-end-position)))
21140 (let ((uncommentp
21141 ;; UNCOMMENTP is non-nil when every non blank line between
21142 ;; BEG and END is a comment.
21143 (save-excursion
21144 (goto-char (point-min))
21145 (while (and (not (eobp))
21146 (let ((element (org-element-at-point)))
21147 (and (eq (org-element-type element) 'comment)
21148 (goto-char (min (point-max)
21149 (org-element-property
21150 :end element)))))))
21151 (eobp))))
21152 (if uncommentp
21153 ;; Only blank lines and comments in region: uncomment it.
21154 (save-excursion
21155 (goto-char (point-min))
21156 (while (not (eobp))
21157 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21158 (replace-match "" nil nil nil 1))
21159 (forward-line)))
21160 ;; Comment each line in region.
21161 (let ((min-indent (point-max)))
21162 ;; First find the minimum indentation across all lines.
21163 (save-excursion
21164 (goto-char (point-min))
21165 (while (and (not (eobp)) (not (zerop min-indent)))
21166 (unless (looking-at "[ \t]*$")
21167 (setq min-indent (min min-indent (current-indentation))))
21168 (forward-line)))
21169 ;; Then loop over all lines.
21170 (save-excursion
21171 (goto-char (point-min))
21172 (while (not (eobp))
21173 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21174 (org-move-to-column min-indent t)
21175 (insert comment-start))
21176 (forward-line))))))))
21179 ;;; Other stuff.
21181 (defun org-toggle-fixed-width-section (arg)
21182 "Toggle the fixed-width export.
21183 If there is no active region, the QUOTE keyword at the current headline is
21184 inserted or removed. When present, it causes the text between this headline
21185 and the next to be exported as fixed-width text, and unmodified.
21186 If there is an active region, this command adds or removes a colon as the
21187 first character of this line. If the first character of a line is a colon,
21188 this line is also exported in fixed-width font."
21189 (interactive "P")
21190 (let* ((cc 0)
21191 (regionp (org-region-active-p))
21192 (beg (if regionp (region-beginning) (point)))
21193 (end (if regionp (region-end)))
21194 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21195 (case-fold-search nil)
21196 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21197 off)
21198 (if regionp
21199 (save-excursion
21200 (goto-char beg)
21201 (setq cc (current-column))
21202 (beginning-of-line 1)
21203 (setq off (looking-at re))
21204 (while (> nlines 0)
21205 (setq nlines (1- nlines))
21206 (beginning-of-line 1)
21207 (cond
21208 (arg
21209 (org-move-to-column cc t)
21210 (insert ": \n")
21211 (forward-line -1))
21212 ((and off (looking-at re))
21213 (replace-match "" t t nil 1))
21214 ((not off) (org-move-to-column cc t) (insert ": ")))
21215 (forward-line 1)))
21216 (save-excursion
21217 (org-back-to-heading)
21218 (cond
21219 ((looking-at (format org-heading-keyword-regexp-format
21220 org-quote-string))
21221 (goto-char (match-end 1))
21222 (looking-at (concat " +" org-quote-string))
21223 (replace-match "" t t)
21224 (when (eolp) (insert " ")))
21225 ((looking-at org-outline-regexp)
21226 (goto-char (match-end 0))
21227 (insert org-quote-string " ")))))))
21229 (defun org-reftex-citation ()
21230 "Use reftex-citation to insert a citation into the buffer.
21231 This looks for a line like
21233 #+BIBLIOGRAPHY: foo plain option:-d
21235 and derives from it that foo.bib is the bibliography file relevant
21236 for this document. It then installs the necessary environment for RefTeX
21237 to work in this buffer and calls `reftex-citation' to insert a citation
21238 into the buffer.
21240 Export of such citations to both LaTeX and HTML is handled by the contributed
21241 package org-exp-bibtex by Taru Karttunen."
21242 (interactive)
21243 (let ((reftex-docstruct-symbol 'rds)
21244 (reftex-cite-format "\\cite{%l}")
21245 rds bib)
21246 (save-excursion
21247 (save-restriction
21248 (widen)
21249 (let ((case-fold-search t)
21250 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21251 (if (not (save-excursion
21252 (or (re-search-forward re nil t)
21253 (re-search-backward re nil t))))
21254 (error "No bibliography defined in file")
21255 (setq bib (concat (match-string 1) ".bib")
21256 rds (list (list 'bib bib)))))))
21257 (call-interactively 'reftex-citation)))
21259 ;;;; Functions extending outline functionality
21261 (defun org-beginning-of-line (&optional arg)
21262 "Go to the beginning of the current line. If that is invisible, continue
21263 to a visible line beginning. This makes the function of C-a more intuitive.
21264 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21265 first attempt, and only move to after the tags when the cursor is already
21266 beyond the end of the headline."
21267 (interactive "P")
21268 (let ((pos (point))
21269 (special (if (consp org-special-ctrl-a/e)
21270 (car org-special-ctrl-a/e)
21271 org-special-ctrl-a/e))
21272 refpos)
21273 (if (org-bound-and-true-p line-move-visual)
21274 (beginning-of-visual-line 1)
21275 (beginning-of-line 1))
21276 (if (and arg (fboundp 'move-beginning-of-line))
21277 (call-interactively 'move-beginning-of-line)
21278 (if (bobp)
21280 (backward-char 1)
21281 (if (org-truely-invisible-p)
21282 (while (and (not (bobp)) (org-truely-invisible-p))
21283 (backward-char 1)
21284 (beginning-of-line 1))
21285 (forward-char 1))))
21286 (when special
21287 (cond
21288 ((and (looking-at org-complex-heading-regexp)
21289 (= (char-after (match-end 1)) ?\ ))
21290 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21291 (point-at-eol)))
21292 (goto-char
21293 (if (eq special t)
21294 (cond ((> pos refpos) refpos)
21295 ((= pos (point)) refpos)
21296 (t (point)))
21297 (cond ((> pos (point)) (point))
21298 ((not (eq last-command this-command)) (point))
21299 (t refpos)))))
21300 ((org-at-item-p)
21301 ;; Being at an item and not looking at an the item means point
21302 ;; was previously moved to beginning of a visual line, which
21303 ;; doesn't contain the item. Therefore, do nothing special,
21304 ;; just stay here.
21305 (when (looking-at org-list-full-item-re)
21306 ;; Set special position at first white space character after
21307 ;; bullet, and check-box, if any.
21308 (let ((after-bullet
21309 (let ((box (match-end 3)))
21310 (if (not box) (match-end 1)
21311 (let ((after (char-after box)))
21312 (if (and after (= after ? )) (1+ box) box))))))
21313 ;; Special case: Move point to special position when
21314 ;; currently after it or at beginning of line.
21315 (if (eq special t)
21316 (when (or (> pos after-bullet) (= (point) pos))
21317 (goto-char after-bullet))
21318 ;; Reversed case: Move point to special position when
21319 ;; point was already at beginning of line and command is
21320 ;; repeated.
21321 (when (and (= (point) pos) (eq last-command this-command))
21322 (goto-char after-bullet))))))))
21323 (org-no-warnings
21324 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21326 (defun org-end-of-line (&optional arg)
21327 "Go to the end of the line.
21328 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21329 tags on the first attempt, and only move to after the tags when
21330 the cursor is already beyond the end of the headline."
21331 (interactive "P")
21332 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21333 org-special-ctrl-a/e))
21334 (type (org-element-type
21335 (save-excursion (beginning-of-line) (org-element-at-point)))))
21336 (cond
21337 ((or (not special) arg)
21338 (call-interactively
21339 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line)))
21340 ((memq type '(headline inlinetask))
21341 (let ((pos (point)))
21342 (beginning-of-line 1)
21343 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21344 (if (eq special t)
21345 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21346 (goto-char (match-beginning 1))
21347 (goto-char (match-end 0)))
21348 (if (or (< pos (match-end 0))
21349 (not (eq this-command last-command)))
21350 (goto-char (match-end 0))
21351 (goto-char (match-beginning 1))))
21352 (call-interactively
21353 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line)))))
21354 ((memq type
21355 '(center-block comment-block drawer dynamic-block example-block
21356 export-block item plain-list property-drawer
21357 quote-block special-block src-block verse-block))
21358 ;; Never move past the ellipsis.
21359 (or (eolp) (move-end-of-line 1))
21360 (when (org-invisible-p2) (backward-char)))
21362 (call-interactively
21363 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line))))
21364 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21366 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21367 (define-key org-mode-map "\C-e" 'org-end-of-line)
21369 (defun org-backward-sentence (&optional arg)
21370 "Go to beginning of sentence, or beginning of table field.
21371 This will call `backward-sentence' or `org-table-beginning-of-field',
21372 depending on context."
21373 (interactive "P")
21374 (cond
21375 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21376 (t (call-interactively 'backward-sentence))))
21378 (defun org-forward-sentence (&optional arg)
21379 "Go to end of sentence, or end of table field.
21380 This will call `forward-sentence' or `org-table-end-of-field',
21381 depending on context."
21382 (interactive "P")
21383 (cond
21384 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21385 (t (call-interactively 'forward-sentence))))
21387 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21388 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21390 (defun org-kill-line (&optional arg)
21391 "Kill line, to tags or end of line."
21392 (interactive "P")
21393 (cond
21394 ((or (not org-special-ctrl-k)
21395 (bolp)
21396 (not (org-at-heading-p)))
21397 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21398 org-ctrl-k-protect-subtree)
21399 (if (or (eq org-ctrl-k-protect-subtree 'error)
21400 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21401 (error "C-k aborted - would kill hidden subtree")))
21402 (call-interactively
21403 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21404 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21405 (kill-region (point) (match-beginning 1))
21406 (org-set-tags nil t))
21407 (t (kill-region (point) (point-at-eol)))))
21409 (define-key org-mode-map "\C-k" 'org-kill-line)
21411 (defun org-yank (&optional arg)
21412 "Yank. If the kill is a subtree, treat it specially.
21413 This command will look at the current kill and check if is a single
21414 subtree, or a series of subtrees[1]. If it passes the test, and if the
21415 cursor is at the beginning of a line or after the stars of a currently
21416 empty headline, then the yank is handled specially. How exactly depends
21417 on the value of the following variables, both set by default.
21419 org-yank-folded-subtrees
21420 When set, the subtree(s) will be folded after insertion, but only
21421 if doing so would now swallow text after the yanked text.
21423 org-yank-adjusted-subtrees
21424 When set, the subtree will be promoted or demoted in order to
21425 fit into the local outline tree structure, which means that the level
21426 will be adjusted so that it becomes the smaller one of the two
21427 *visible* surrounding headings.
21429 Any prefix to this command will cause `yank' to be called directly with
21430 no special treatment. In particular, a simple \\[universal-argument] prefix \
21431 will just
21432 plainly yank the text as it is.
21434 \[1] The test checks if the first non-white line is a heading
21435 and if there are no other headings with fewer stars."
21436 (interactive "P")
21437 (org-yank-generic 'yank arg))
21439 (defun org-yank-generic (command arg)
21440 "Perform some yank-like command.
21442 This function implements the behavior described in the `org-yank'
21443 documentation. However, it has been generalized to work for any
21444 interactive command with similar behavior."
21446 ;; pretend to be command COMMAND
21447 (setq this-command command)
21449 (if arg
21450 (call-interactively command)
21452 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21453 (and (org-kill-is-subtree-p)
21454 (or (bolp)
21455 (and (looking-at "[ \t]*$")
21456 (string-match
21457 "\\`\\*+\\'"
21458 (buffer-substring (point-at-bol) (point)))))))
21459 swallowp)
21460 (cond
21461 ((and subtreep org-yank-folded-subtrees)
21462 (let ((beg (point))
21463 end)
21464 (if (and subtreep org-yank-adjusted-subtrees)
21465 (org-paste-subtree nil nil 'for-yank)
21466 (call-interactively command))
21468 (setq end (point))
21469 (goto-char beg)
21470 (when (and (bolp) subtreep
21471 (not (setq swallowp
21472 (org-yank-folding-would-swallow-text beg end))))
21473 (org-with-limited-levels
21474 (or (looking-at org-outline-regexp)
21475 (re-search-forward org-outline-regexp-bol end t))
21476 (while (and (< (point) end) (looking-at org-outline-regexp))
21477 (hide-subtree)
21478 (org-cycle-show-empty-lines 'folded)
21479 (condition-case nil
21480 (outline-forward-same-level 1)
21481 (error (goto-char end))))))
21482 (when swallowp
21483 (message
21484 "Inserted text not folded because that would swallow text"))
21486 (goto-char end)
21487 (skip-chars-forward " \t\n\r")
21488 (beginning-of-line 1)
21489 (push-mark beg 'nomsg)))
21490 ((and subtreep org-yank-adjusted-subtrees)
21491 (let ((beg (point-at-bol)))
21492 (org-paste-subtree nil nil 'for-yank)
21493 (push-mark beg 'nomsg)))
21495 (call-interactively command))))))
21497 (defun org-yank-folding-would-swallow-text (beg end)
21498 "Would hide-subtree at BEG swallow any text after END?"
21499 (let (level)
21500 (org-with-limited-levels
21501 (save-excursion
21502 (goto-char beg)
21503 (when (or (looking-at org-outline-regexp)
21504 (re-search-forward org-outline-regexp-bol end t))
21505 (setq level (org-outline-level)))
21506 (goto-char end)
21507 (skip-chars-forward " \t\r\n\v\f")
21508 (if (or (eobp)
21509 (and (bolp) (looking-at org-outline-regexp)
21510 (<= (org-outline-level) level)))
21511 nil ; Nothing would be swallowed
21512 t))))) ; something would swallow
21514 (define-key org-mode-map "\C-y" 'org-yank)
21516 (defun org-truely-invisible-p ()
21517 "Check if point is at a character currently not visible.
21518 This version does not only check the character property, but also
21519 `visible-mode'."
21520 ;; Early versions of noutline don't have `outline-invisible-p'.
21521 (if (org-bound-and-true-p visible-mode)
21523 (outline-invisible-p)))
21525 (defun org-invisible-p2 ()
21526 "Check if point is at a character currently not visible."
21527 (save-excursion
21528 (if (and (eolp) (not (bobp))) (backward-char 1))
21529 ;; Early versions of noutline don't have `outline-invisible-p'.
21530 (outline-invisible-p)))
21532 (defun org-back-to-heading (&optional invisible-ok)
21533 "Call `outline-back-to-heading', but provide a better error message."
21534 (condition-case nil
21535 (outline-back-to-heading invisible-ok)
21536 (error (error "Before first headline at position %d in buffer %s"
21537 (point) (current-buffer)))))
21539 (defun org-before-first-heading-p ()
21540 "Before first heading?"
21541 (save-excursion
21542 (end-of-line)
21543 (null (re-search-backward org-outline-regexp-bol nil t))))
21545 (defun org-at-heading-p (&optional ignored)
21546 (outline-on-heading-p t))
21547 ;; Compatibility alias with Org versions < 7.8.03
21548 (defalias 'org-on-heading-p 'org-at-heading-p)
21550 (defun org-at-comment-p nil
21551 "Is cursor in a line starting with a # character?"
21552 (save-excursion
21553 (beginning-of-line)
21554 (looking-at "^#")))
21556 (defun org-at-drawer-p nil
21557 "Is cursor at a drawer keyword?"
21558 (save-excursion
21559 (move-beginning-of-line 1)
21560 (looking-at org-drawer-regexp)))
21562 (defun org-at-block-p nil
21563 "Is cursor at a block keyword?"
21564 (save-excursion
21565 (move-beginning-of-line 1)
21566 (looking-at org-block-regexp)))
21568 (defun org-point-at-end-of-empty-headline ()
21569 "If point is at the end of an empty headline, return t, else nil.
21570 If the heading only contains a TODO keyword, it is still still considered
21571 empty."
21572 (and (looking-at "[ \t]*$")
21573 (when org-todo-line-regexp
21574 (save-excursion
21575 (beginning-of-line 1)
21576 (let ((case-fold-search nil))
21577 (looking-at org-todo-line-regexp)
21578 (string= (match-string 3) ""))))))
21580 (defun org-at-heading-or-item-p ()
21581 (or (org-at-heading-p) (org-at-item-p)))
21583 (defun org-at-target-p ()
21584 (or (org-in-regexp org-radio-target-regexp)
21585 (org-in-regexp org-target-regexp)))
21586 ;; Compatibility alias with Org versions < 7.8.03
21587 (defalias 'org-on-target-p 'org-at-target-p)
21589 (defun org-up-heading-all (arg)
21590 "Move to the heading line of which the present line is a subheading.
21591 This function considers both visible and invisible heading lines.
21592 With argument, move up ARG levels."
21593 (if (fboundp 'outline-up-heading-all)
21594 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21595 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21597 (defun org-up-heading-safe ()
21598 "Move to the heading line of which the present line is a subheading.
21599 This version will not throw an error. It will return the level of the
21600 headline found, or nil if no higher level is found.
21602 Also, this function will be a lot faster than `outline-up-heading',
21603 because it relies on stars being the outline starters. This can really
21604 make a significant difference in outlines with very many siblings."
21605 (let (start-level re)
21606 (org-back-to-heading t)
21607 (setq start-level (funcall outline-level))
21608 (if (equal start-level 1)
21610 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21611 (if (re-search-backward re nil t)
21612 (funcall outline-level)))))
21614 (defun org-first-sibling-p ()
21615 "Is this heading the first child of its parents?"
21616 (interactive)
21617 (let ((re org-outline-regexp-bol)
21618 level l)
21619 (unless (org-at-heading-p t)
21620 (error "Not at a heading"))
21621 (setq level (funcall outline-level))
21622 (save-excursion
21623 (if (not (re-search-backward re nil t))
21625 (setq l (funcall outline-level))
21626 (< l level)))))
21628 (defun org-goto-sibling (&optional previous)
21629 "Goto the next sibling, even if it is invisible.
21630 When PREVIOUS is set, go to the previous sibling instead. Returns t
21631 when a sibling was found. When none is found, return nil and don't
21632 move point."
21633 (let ((fun (if previous 're-search-backward 're-search-forward))
21634 (pos (point))
21635 (re org-outline-regexp-bol)
21636 level l)
21637 (when (condition-case nil (org-back-to-heading t) (error nil))
21638 (setq level (funcall outline-level))
21639 (catch 'exit
21640 (or previous (forward-char 1))
21641 (while (funcall fun re nil t)
21642 (setq l (funcall outline-level))
21643 (when (< l level) (goto-char pos) (throw 'exit nil))
21644 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21645 (goto-char pos)
21646 nil))))
21648 (defun org-show-siblings ()
21649 "Show all siblings of the current headline."
21650 (save-excursion
21651 (while (org-goto-sibling) (org-flag-heading nil)))
21652 (save-excursion
21653 (while (org-goto-sibling 'previous)
21654 (org-flag-heading nil))))
21656 (defun org-goto-first-child ()
21657 "Goto the first child, even if it is invisible.
21658 Return t when a child was found. Otherwise don't move point and
21659 return nil."
21660 (let (level (pos (point)) (re org-outline-regexp-bol))
21661 (when (condition-case nil (org-back-to-heading t) (error nil))
21662 (setq level (outline-level))
21663 (forward-char 1)
21664 (if (and (re-search-forward re nil t) (> (outline-level) level))
21665 (progn (goto-char (match-beginning 0)) t)
21666 (goto-char pos) nil))))
21668 (defun org-show-hidden-entry ()
21669 "Show an entry where even the heading is hidden."
21670 (save-excursion
21671 (org-show-entry)))
21673 (defun org-flag-heading (flag &optional entry)
21674 "Flag the current heading. FLAG non-nil means make invisible.
21675 When ENTRY is non-nil, show the entire entry."
21676 (save-excursion
21677 (org-back-to-heading t)
21678 ;; Check if we should show the entire entry
21679 (if entry
21680 (progn
21681 (org-show-entry)
21682 (save-excursion
21683 (and (outline-next-heading)
21684 (org-flag-heading nil))))
21685 (outline-flag-region (max (point-min) (1- (point)))
21686 (save-excursion (outline-end-of-heading) (point))
21687 flag))))
21689 (defun org-get-next-sibling ()
21690 "Move to next heading of the same level, and return point.
21691 If there is no such heading, return nil.
21692 This is like outline-next-sibling, but invisible headings are ok."
21693 (let ((level (funcall outline-level)))
21694 (outline-next-heading)
21695 (while (and (not (eobp)) (> (funcall outline-level) level))
21696 (outline-next-heading))
21697 (if (or (eobp) (< (funcall outline-level) level))
21699 (point))))
21701 (defun org-get-last-sibling ()
21702 "Move to previous heading of the same level, and return point.
21703 If there is no such heading, return nil."
21704 (let ((opoint (point))
21705 (level (funcall outline-level)))
21706 (outline-previous-heading)
21707 (when (and (/= (point) opoint) (outline-on-heading-p t))
21708 (while (and (> (funcall outline-level) level)
21709 (not (bobp)))
21710 (outline-previous-heading))
21711 (if (< (funcall outline-level) level)
21713 (point)))))
21715 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21716 "Goto to the end of a subtree."
21717 ;; This contains an exact copy of the original function, but it uses
21718 ;; `org-back-to-heading', to make it work also in invisible
21719 ;; trees. And is uses an invisible-ok argument.
21720 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21721 ;; Furthermore, when used inside Org, finding the end of a large subtree
21722 ;; with many children and grandchildren etc, this can be much faster
21723 ;; than the outline version.
21724 (org-back-to-heading invisible-ok)
21725 (let ((first t)
21726 (level (funcall outline-level)))
21727 (if (and (derived-mode-p 'org-mode) (< level 1000))
21728 ;; A true heading (not a plain list item), in Org-mode
21729 ;; This means we can easily find the end by looking
21730 ;; only for the right number of stars. Using a regexp to do
21731 ;; this is so much faster than using a Lisp loop.
21732 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21733 (forward-char 1)
21734 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21735 ;; something else, do it the slow way
21736 (while (and (not (eobp))
21737 (or first (> (funcall outline-level) level)))
21738 (setq first nil)
21739 (outline-next-heading)))
21740 (unless to-heading
21741 (if (memq (preceding-char) '(?\n ?\^M))
21742 (progn
21743 ;; Go to end of line before heading
21744 (forward-char -1)
21745 (if (memq (preceding-char) '(?\n ?\^M))
21746 ;; leave blank line before heading
21747 (forward-char -1))))))
21748 (point))
21750 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21751 "Use Org version in org-mode, for dramatic speed-up."
21752 (if (derived-mode-p 'org-mode)
21753 (progn
21754 (org-end-of-subtree nil t)
21755 (unless (eobp) (backward-char 1)))
21756 ad-do-it))
21758 (defun org-end-of-meta-data-and-drawers ()
21759 "Jump to the first text after meta data and drawers in the current entry.
21760 This will move over empty lines, lines with planning time stamps,
21761 clocking lines, and drawers."
21762 (org-back-to-heading t)
21763 (let ((end (save-excursion (outline-next-heading) (point)))
21764 (re (concat "\\(" org-drawer-regexp "\\)"
21765 "\\|" "[ \t]*" org-keyword-time-regexp)))
21766 (forward-line 1)
21767 (while (re-search-forward re end t)
21768 (if (not (match-end 1))
21769 ;; empty or planning line
21770 (forward-line 1)
21771 ;; a drawer, find the end
21772 (re-search-forward "^[ \t]*:END:" end 'move)
21773 (forward-line 1)))
21774 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21775 (point)))
21777 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21778 "Move forward to the arg'th subheading at same level as this one.
21779 Stop at the first and last subheadings of a superior heading.
21780 Normally this only looks at visible headings, but when INVISIBLE-OK is
21781 non-nil it will also look at invisible ones."
21782 (interactive "p")
21783 (org-back-to-heading invisible-ok)
21784 (org-at-heading-p)
21785 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21786 (re (format "^\\*\\{1,%d\\} " level))
21788 (forward-char 1)
21789 (while (> arg 0)
21790 (while (and (re-search-forward re nil 'move)
21791 (setq l (- (match-end 0) (match-beginning 0) 1))
21792 (= l level)
21793 (not invisible-ok)
21794 (progn (backward-char 1) (outline-invisible-p)))
21795 (if (< l level) (setq arg 1)))
21796 (setq arg (1- arg)))
21797 (beginning-of-line 1)))
21799 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21800 "Move backward to the arg'th subheading at same level as this one.
21801 Stop at the first and last subheadings of a superior heading."
21802 (interactive "p")
21803 (org-back-to-heading)
21804 (org-at-heading-p)
21805 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21806 (re (format "^\\*\\{1,%d\\} " level))
21808 (while (> arg 0)
21809 (while (and (re-search-backward re nil 'move)
21810 (setq l (- (match-end 0) (match-beginning 0) 1))
21811 (= l level)
21812 (not invisible-ok)
21813 (outline-invisible-p))
21814 (if (< l level) (setq arg 1)))
21815 (setq arg (1- arg)))))
21817 (defun org-forward-element ()
21818 "Move forward by one element.
21819 Move to the next element at the same level, when possible."
21820 (interactive)
21821 (cond ((eobp) (error "Cannot move further down"))
21822 ((org-with-limited-levels (org-at-heading-p))
21823 (let ((origin (point)))
21824 (org-forward-heading-same-level 1)
21825 (unless (org-with-limited-levels (org-at-heading-p))
21826 (goto-char origin)
21827 (error "Cannot move further down"))))
21829 (let* ((elem (org-element-at-point))
21830 (end (org-element-property :end elem))
21831 (parent (org-element-property :parent elem)))
21832 (if (and parent (= (org-element-property :contents-end parent) end))
21833 (goto-char (org-element-property :end parent))
21834 (goto-char end))))))
21836 (defun org-backward-element ()
21837 "Move backward by one element.
21838 Move to the previous element at the same level, when possible."
21839 (interactive)
21840 (cond ((bobp) (error "Cannot move further up"))
21841 ((org-with-limited-levels (org-at-heading-p))
21842 ;; At an headline, move to the previous one, if any, or stay
21843 ;; here.
21844 (let ((origin (point)))
21845 (org-backward-heading-same-level 1)
21846 (unless (org-with-limited-levels (org-at-heading-p))
21847 (goto-char origin)
21848 (error "Cannot move further up"))))
21850 (let* ((trail (org-element-at-point 'keep-trail))
21851 (elem (car trail))
21852 (prev-elem (nth 1 trail))
21853 (beg (org-element-property :begin elem)))
21854 (cond
21855 ;; Move to beginning of current element if point isn't
21856 ;; there already.
21857 ((/= (point) beg) (goto-char beg))
21858 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21859 ((org-before-first-heading-p) (goto-char (point-min)))
21860 (t (org-back-to-heading)))))))
21862 (defun org-up-element ()
21863 "Move to upper element."
21864 (interactive)
21865 (if (org-with-limited-levels (org-at-heading-p))
21866 (unless (org-up-heading-safe) (error "No surrounding element"))
21867 (let* ((elem (org-element-at-point))
21868 (parent (org-element-property :parent elem)))
21869 (if parent (goto-char (org-element-property :begin parent))
21870 (if (org-with-limited-levels (org-before-first-heading-p))
21871 (error "No surrounding element")
21872 (org-with-limited-levels (org-back-to-heading)))))))
21874 (defvar org-element-greater-elements)
21875 (defun org-down-element ()
21876 "Move to inner element."
21877 (interactive)
21878 (let ((element (org-element-at-point)))
21879 (cond
21880 ((memq (org-element-type element) '(plain-list table))
21881 (goto-char (org-element-property :contents-begin element))
21882 (forward-char))
21883 ((memq (org-element-type element) org-element-greater-elements)
21884 ;; If contents are hidden, first disclose them.
21885 (when (org-element-property :hiddenp element) (org-cycle))
21886 (goto-char (or (org-element-property :contents-begin element)
21887 (error "No content for this element"))))
21888 (t (error "No inner element")))))
21890 (defun org-drag-element-backward ()
21891 "Move backward element at point."
21892 (interactive)
21893 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21894 (let* ((trail (org-element-at-point 'keep-trail))
21895 (elem (car trail))
21896 (prev-elem (nth 1 trail)))
21897 ;; Error out if no previous element or previous element is
21898 ;; a parent of the current one.
21899 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21900 (error "Cannot drag element backward")
21901 (let ((pos (point)))
21902 (org-element-swap-A-B prev-elem elem)
21903 (goto-char (+ (org-element-property :begin prev-elem)
21904 (- pos (org-element-property :begin elem)))))))))
21906 (defun org-drag-element-forward ()
21907 "Move forward element at point."
21908 (interactive)
21909 (let* ((pos (point))
21910 (elem (org-element-at-point)))
21911 (when (= (point-max) (org-element-property :end elem))
21912 (error "Cannot drag element forward"))
21913 (goto-char (org-element-property :end elem))
21914 (let ((next-elem (org-element-at-point)))
21915 (when (or (org-element-nested-p elem next-elem)
21916 (and (eq (org-element-type next-elem) 'headline)
21917 (not (eq (org-element-type elem) 'headline))))
21918 (goto-char pos)
21919 (error "Cannot drag element forward"))
21920 ;; Compute new position of point: it's shifted by NEXT-ELEM
21921 ;; body's length (without final blanks) and by the length of
21922 ;; blanks between ELEM and NEXT-ELEM.
21923 (let ((size-next (- (save-excursion
21924 (goto-char (org-element-property :end next-elem))
21925 (skip-chars-backward " \r\t\n")
21926 (forward-line)
21927 ;; Small correction if buffer doesn't end
21928 ;; with a newline character.
21929 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
21930 (org-element-property :begin next-elem)))
21931 (size-blank (- (org-element-property :end elem)
21932 (save-excursion
21933 (goto-char (org-element-property :end elem))
21934 (skip-chars-backward " \r\t\n")
21935 (forward-line)
21936 (point)))))
21937 (org-element-swap-A-B elem next-elem)
21938 (goto-char (+ pos size-next size-blank))))))
21940 (defun org-mark-element ()
21941 "Put point at beginning of this element, mark at end.
21943 Interactively, if this command is repeated or (in Transient Mark
21944 mode) if the mark is active, it marks the next element after the
21945 ones already marked."
21946 (interactive)
21947 (let (deactivate-mark)
21948 (if (and (org-called-interactively-p 'any)
21949 (or (and (eq last-command this-command) (mark t))
21950 (and transient-mark-mode mark-active)))
21951 (set-mark
21952 (save-excursion
21953 (goto-char (mark))
21954 (goto-char (org-element-property :end (org-element-at-point)))))
21955 (let ((element (org-element-at-point)))
21956 (end-of-line)
21957 (push-mark (org-element-property :end element) t t)
21958 (goto-char (org-element-property :begin element))))))
21960 (defun org-narrow-to-element ()
21961 "Narrow buffer to current element."
21962 (interactive)
21963 (let ((elem (org-element-at-point)))
21964 (cond
21965 ((eq (car elem) 'headline)
21966 (narrow-to-region
21967 (org-element-property :begin elem)
21968 (org-element-property :end elem)))
21969 ((memq (car elem) org-element-greater-elements)
21970 (narrow-to-region
21971 (org-element-property :contents-begin elem)
21972 (org-element-property :contents-end elem)))
21974 (narrow-to-region
21975 (org-element-property :begin elem)
21976 (org-element-property :end elem))))))
21978 (defun org-transpose-element ()
21979 "Transpose current and previous elements, keeping blank lines between.
21980 Point is moved after both elements."
21981 (interactive)
21982 (org-skip-whitespace)
21983 (let ((end (org-element-property :end (org-element-at-point))))
21984 (org-drag-element-backward)
21985 (goto-char end)))
21987 (defun org-unindent-buffer ()
21988 "Un-indent the visible part of the buffer.
21989 Relative indentation (between items, inside blocks, etc.) isn't
21990 modified."
21991 (interactive)
21992 (unless (eq major-mode 'org-mode)
21993 (error "Cannot un-indent a buffer not in Org mode"))
21994 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
21995 unindent-tree ; For byte-compiler.
21996 (unindent-tree
21997 (function
21998 (lambda (contents)
21999 (mapc
22000 (lambda (element)
22001 (if (memq (org-element-type element) '(headline section))
22002 (funcall unindent-tree (org-element-contents element))
22003 (save-excursion
22004 (save-restriction
22005 (narrow-to-region
22006 (org-element-property :begin element)
22007 (org-element-property :end element))
22008 (org-do-remove-indentation)))))
22009 (reverse contents))))))
22010 (funcall unindent-tree (org-element-contents parse-tree))))
22012 (defun org-show-subtree ()
22013 "Show everything after this heading at deeper levels."
22014 (interactive)
22015 (outline-flag-region
22016 (point)
22017 (save-excursion
22018 (org-end-of-subtree t t))
22019 nil))
22021 (defun org-show-entry ()
22022 "Show the body directly following this heading.
22023 Show the heading too, if it is currently invisible."
22024 (interactive)
22025 (save-excursion
22026 (condition-case nil
22027 (progn
22028 (org-back-to-heading t)
22029 (outline-flag-region
22030 (max (point-min) (1- (point)))
22031 (save-excursion
22032 (if (re-search-forward
22033 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22034 (match-beginning 1)
22035 (point-max)))
22036 nil)
22037 (org-cycle-hide-drawers 'children))
22038 (error nil))))
22040 (defun org-make-options-regexp (kwds &optional extra)
22041 "Make a regular expression for keyword lines."
22042 (concat
22043 "^#\\+\\("
22044 (mapconcat 'regexp-quote kwds "\\|")
22045 (if extra (concat "\\|" extra))
22046 "\\):[ \t]*\\(.*\\)"))
22048 ;; Make isearch reveal the necessary context
22049 (defun org-isearch-end ()
22050 "Reveal context after isearch exits."
22051 (when isearch-success ; only if search was successful
22052 (if (featurep 'xemacs)
22053 ;; Under XEmacs, the hook is run in the correct place,
22054 ;; we directly show the context.
22055 (org-show-context 'isearch)
22056 ;; In Emacs the hook runs *before* restoring the overlays.
22057 ;; So we have to use a one-time post-command-hook to do this.
22058 ;; (Emacs 22 has a special variable, see function `org-mode')
22059 (unless (and (boundp 'isearch-mode-end-hook-quit)
22060 isearch-mode-end-hook-quit)
22061 ;; Only when the isearch was not quitted.
22062 (org-add-hook 'post-command-hook 'org-isearch-post-command
22063 'append 'local)))))
22065 (defun org-isearch-post-command ()
22066 "Remove self from hook, and show context."
22067 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22068 (org-show-context 'isearch))
22071 ;;;; Integration with and fixes for other packages
22073 ;;; Imenu support
22075 (defvar org-imenu-markers nil
22076 "All markers currently used by Imenu.")
22077 (make-variable-buffer-local 'org-imenu-markers)
22079 (defun org-imenu-new-marker (&optional pos)
22080 "Return a new marker for use by Imenu, and remember the marker."
22081 (let ((m (make-marker)))
22082 (move-marker m (or pos (point)))
22083 (push m org-imenu-markers)
22086 (defun org-imenu-get-tree ()
22087 "Produce the index for Imenu."
22088 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22089 (setq org-imenu-markers nil)
22090 (let* ((n org-imenu-depth)
22091 (re (concat "^" (org-get-limited-outline-regexp)))
22092 (subs (make-vector (1+ n) nil))
22093 (last-level 0)
22094 m level head)
22095 (save-excursion
22096 (save-restriction
22097 (widen)
22098 (goto-char (point-max))
22099 (while (re-search-backward re nil t)
22100 (setq level (org-reduced-level (funcall outline-level)))
22101 (when (and (<= level n)
22102 (looking-at org-complex-heading-regexp))
22103 (setq head (org-link-display-format
22104 (org-match-string-no-properties 4))
22105 m (org-imenu-new-marker))
22106 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22107 (if (>= level last-level)
22108 (push (cons head m) (aref subs level))
22109 (push (cons head (aref subs (1+ level))) (aref subs level))
22110 (loop for i from (1+ level) to n do (aset subs i nil)))
22111 (setq last-level level)))))
22112 (aref subs 1)))
22114 (eval-after-load "imenu"
22115 '(progn
22116 (add-hook 'imenu-after-jump-hook
22117 (lambda ()
22118 (if (derived-mode-p 'org-mode)
22119 (org-show-context 'org-goto))))))
22121 (defun org-link-display-format (link)
22122 "Replace a link with either the description, or the link target
22123 if no description is present"
22124 (save-match-data
22125 (if (string-match org-bracket-link-analytic-regexp link)
22126 (replace-match (if (match-end 5)
22127 (match-string 5 link)
22128 (concat (match-string 1 link)
22129 (match-string 3 link)))
22130 nil t link)
22131 link)))
22133 (defun org-toggle-link-display ()
22134 "Toggle the literal or descriptive display of links."
22135 (interactive)
22136 (if org-descriptive-links
22137 (progn (org-remove-from-invisibility-spec '(org-link))
22138 (org-restart-font-lock)
22139 (setq org-descriptive-links nil))
22140 (progn (add-to-invisibility-spec '(org-link))
22141 (org-restart-font-lock)
22142 (setq org-descriptive-links t))))
22144 ;; Speedbar support
22146 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22147 "Overlay marking the agenda restriction line in speedbar.")
22148 (overlay-put org-speedbar-restriction-lock-overlay
22149 'face 'org-agenda-restriction-lock)
22150 (overlay-put org-speedbar-restriction-lock-overlay
22151 'help-echo "Agendas are currently limited to this item.")
22152 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22154 (defun org-speedbar-set-agenda-restriction ()
22155 "Restrict future agenda commands to the location at point in speedbar.
22156 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22157 (interactive)
22158 (require 'org-agenda)
22159 (let (p m tp np dir txt)
22160 (cond
22161 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22162 'org-imenu t))
22163 (setq m (get-text-property p 'org-imenu-marker))
22164 (with-current-buffer (marker-buffer m)
22165 (goto-char m)
22166 (org-agenda-set-restriction-lock 'subtree)))
22167 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22168 'speedbar-function 'speedbar-find-file))
22169 (setq tp (previous-single-property-change
22170 (1+ p) 'speedbar-function)
22171 np (next-single-property-change
22172 tp 'speedbar-function)
22173 dir (speedbar-line-directory)
22174 txt (buffer-substring-no-properties (or tp (point-min))
22175 (or np (point-max))))
22176 (with-current-buffer (find-file-noselect
22177 (let ((default-directory dir))
22178 (expand-file-name txt)))
22179 (unless (derived-mode-p 'org-mode)
22180 (error "Cannot restrict to non-Org-mode file"))
22181 (org-agenda-set-restriction-lock 'file)))
22182 (t (error "Don't know how to restrict Org-mode's agenda")))
22183 (move-overlay org-speedbar-restriction-lock-overlay
22184 (point-at-bol) (point-at-eol))
22185 (setq current-prefix-arg nil)
22186 (org-agenda-maybe-redo)))
22188 (eval-after-load "speedbar"
22189 '(progn
22190 (speedbar-add-supported-extension ".org")
22191 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22192 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22193 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22194 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22195 (add-hook 'speedbar-visiting-tag-hook
22196 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22198 ;;; Fixes and Hacks for problems with other packages
22200 ;; Make flyspell not check words in links, to not mess up our keymap
22201 (defun org-mode-flyspell-verify ()
22202 "Don't let flyspell put overlays at active buttons, or on
22203 {todo,all-time,additional-option-like}-keywords."
22204 (let ((pos (max (1- (point)) (point-min)))
22205 (word (thing-at-point 'word)))
22206 (and (not (get-text-property pos 'keymap))
22207 (not (get-text-property pos 'org-no-flyspell))
22208 (not (member word org-todo-keywords-1))
22209 (not (member word org-all-time-keywords))
22210 (not (member word org-options-keywords))
22211 (not (member word (mapcar 'car org-startup-options)))
22212 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22214 (defun org-remove-flyspell-overlays-in (beg end)
22215 "Remove flyspell overlays in region."
22216 (and (org-bound-and-true-p flyspell-mode)
22217 (fboundp 'flyspell-delete-region-overlays)
22218 (flyspell-delete-region-overlays beg end))
22219 (add-text-properties beg end '(org-no-flyspell t)))
22221 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22222 (eval-after-load "bookmark"
22223 '(if (boundp 'bookmark-after-jump-hook)
22224 ;; We can use the hook
22225 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22226 ;; Hook not available, use advice
22227 (defadvice bookmark-jump (after org-make-visible activate)
22228 "Make the position visible."
22229 (org-bookmark-jump-unhide))))
22231 ;; Make sure saveplace shows the location if it was hidden
22232 (eval-after-load "saveplace"
22233 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22234 "Make the position visible."
22235 (org-bookmark-jump-unhide)))
22237 ;; Make sure ecb shows the location if it was hidden
22238 (eval-after-load "ecb"
22239 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22240 "Make hierarchy visible when jumping into location from ECB tree buffer."
22241 (if (derived-mode-p 'org-mode)
22242 (org-show-context))))
22244 (defun org-bookmark-jump-unhide ()
22245 "Unhide the current position, to show the bookmark location."
22246 (and (derived-mode-p 'org-mode)
22247 (or (outline-invisible-p)
22248 (save-excursion (goto-char (max (point-min) (1- (point))))
22249 (outline-invisible-p)))
22250 (org-show-context 'bookmark-jump)))
22252 ;; Make session.el ignore our circular variable
22253 (eval-after-load "session"
22254 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22256 ;;;; Experimental code
22258 (defun org-closed-in-range ()
22259 "Sparse tree of items closed in a certain time range.
22260 Still experimental, may disappear in the future."
22261 (interactive)
22262 ;; Get the time interval from the user.
22263 (let* ((time1 (org-float-time
22264 (org-read-date nil 'to-time nil "Starting date: ")))
22265 (time2 (org-float-time
22266 (org-read-date nil 'to-time nil "End date:")))
22267 ;; callback function
22268 (callback (lambda ()
22269 (let ((time
22270 (org-float-time
22271 (apply 'encode-time
22272 (org-parse-time-string
22273 (match-string 1))))))
22274 ;; check if time in interval
22275 (and (>= time time1) (<= time time2))))))
22276 ;; make tree, check each match with the callback
22277 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22279 ;;;; Finish up
22281 (provide 'org)
22283 (run-hooks 'org-load-hook)
22285 ;;; org.el ends here