* fileio.c (Finsert_file_contents): Avoid double-close.
[emacs.git] / lisp / org / org.el
blobcc4c93f22ebca7853c9022ff548b3acc26d78677
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-clock-timestamps-up "org-clock" ())
118 (declare-function org-clock-timestamps-down "org-clock" ())
119 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
121 (declare-function orgtbl-mode "org-table" (&optional arg))
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-beamer-mode "org-beamer" ())
124 (declare-function org-table-edit-field "org-table" (arg))
125 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
126 (declare-function org-id-get-create "org-id" (&optional force))
127 (declare-function org-id-find-id-file "org-id" (id))
128 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
129 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
130 (declare-function org-table-align "org-table" ())
131 (declare-function org-table-paste-rectangle "org-table" ())
132 (declare-function org-table-maybe-eval-formula "org-table" ())
133 (declare-function org-table-maybe-recalculate-line "org-table" ())
135 ;; load languages based on value of `org-babel-load-languages'
136 (defvar org-babel-load-languages)
138 ;;;###autoload
139 (defun org-babel-do-load-languages (sym value)
140 "Load the languages defined in `org-babel-load-languages'."
141 (set-default sym value)
142 (mapc (lambda (pair)
143 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
144 (if active
145 (progn
146 (require (intern (concat "ob-" lang))))
147 (progn
148 (funcall 'fmakunbound
149 (intern (concat "org-babel-execute:" lang)))
150 (funcall 'fmakunbound
151 (intern (concat "org-babel-expand-body:" lang)))))))
152 org-babel-load-languages))
154 (defcustom org-babel-load-languages '((emacs-lisp . t))
155 "Languages which can be evaluated in Org-mode buffers.
156 This list can be used to load support for any of the languages
157 below, note that each language will depend on a different set of
158 system executables and/or Emacs modes. When a language is
159 \"loaded\", then code blocks in that language can be evaluated
160 with `org-babel-execute-src-block' bound by default to C-c
161 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
162 be set to remove code block evaluation from the C-c C-c
163 keybinding. By default only Emacs Lisp (which has no
164 requirements) is loaded."
165 :group 'org-babel
166 :set 'org-babel-do-load-languages
167 :version "24.1"
168 :type '(alist :tag "Babel Languages"
169 :key-type
170 (choice
171 (const :tag "Awk" awk)
172 (const :tag "C" C)
173 (const :tag "R" R)
174 (const :tag "Asymptote" asymptote)
175 (const :tag "Calc" calc)
176 (const :tag "Clojure" clojure)
177 (const :tag "CSS" css)
178 (const :tag "Ditaa" ditaa)
179 (const :tag "Dot" dot)
180 (const :tag "Emacs Lisp" emacs-lisp)
181 (const :tag "Fortran" fortran)
182 (const :tag "Gnuplot" gnuplot)
183 (const :tag "Haskell" haskell)
184 (const :tag "IO" io)
185 (const :tag "Java" java)
186 (const :tag "Javascript" js)
187 (const :tag "LaTeX" latex)
188 (const :tag "Ledger" ledger)
189 (const :tag "Lilypond" lilypond)
190 (const :tag "Lisp" lisp)
191 (const :tag "Maxima" maxima)
192 (const :tag "Matlab" matlab)
193 (const :tag "Mscgen" mscgen)
194 (const :tag "Ocaml" ocaml)
195 (const :tag "Octave" octave)
196 (const :tag "Org" org)
197 (const :tag "Perl" perl)
198 (const :tag "Pico Lisp" picolisp)
199 (const :tag "PlantUML" plantuml)
200 (const :tag "Python" python)
201 (const :tag "Ruby" ruby)
202 (const :tag "Sass" sass)
203 (const :tag "Scala" scala)
204 (const :tag "Scheme" scheme)
205 (const :tag "Screen" screen)
206 (const :tag "Shell Script" sh)
207 (const :tag "Shen" shen)
208 (const :tag "Sql" sql)
209 (const :tag "Sqlite" sqlite))
210 :value-type (boolean :tag "Activate" :value t)))
212 ;;;; Customization variables
213 (defcustom org-clone-delete-id nil
214 "Remove ID property of clones of a subtree.
215 When non-nil, clones of a subtree don't inherit the ID property.
216 Otherwise they inherit the ID property with a new unique
217 identifier."
218 :type 'boolean
219 :version "24.1"
220 :group 'org-id)
222 ;;; Version
223 (require 'org-compat)
224 (org-check-version)
226 ;;;###autoload
227 (defun org-version (&optional here full message)
228 "Show the org-mode version in the echo area.
229 With prefix argument HERE, insert it at point.
230 When FULL is non-nil, use a verbose version string.
231 When MESSAGE is non-nil, display a message with the version."
232 (interactive "P")
233 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
234 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
235 (org-trash (or
236 (and (fboundp 'org-release) (fboundp 'org-git-version))
237 (load (concat org-dir "org-version.el")
238 'noerror 'nomessage 'nosuffix)))
239 (org-version (org-release))
240 (git-version (org-git-version))
241 (version (format "Org-mode version %s (%s @ %s)"
242 org-version
243 git-version
244 (if org-install-dir
245 (if (string= org-dir org-install-dir)
246 org-install-dir
247 (concat "mixed installation! " org-install-dir " and " org-dir))
248 "org-loaddefs.el can not be found!")))
249 (_version (if full version org-version)))
250 (if (org-called-interactively-p 'interactive)
251 (if here
252 (insert version)
253 (message version))
254 (if message (message _version))
255 _version)))
257 (defconst org-version (org-version))
259 ;;; Compatibility constants
261 ;;; The custom variables
263 (defgroup org nil
264 "Outline-based notes management and organizer."
265 :tag "Org"
266 :group 'outlines
267 :group 'calendar)
269 (defcustom org-mode-hook nil
270 "Mode hook for Org-mode, run after the mode was turned on."
271 :group 'org
272 :type 'hook)
274 (defcustom org-load-hook nil
275 "Hook that is run after org.el has been loaded."
276 :group 'org
277 :type 'hook)
279 (defcustom org-log-buffer-setup-hook nil
280 "Hook that is run after an Org log buffer is created."
281 :group 'org
282 :version "24.1"
283 :type 'hook)
285 (defvar org-modules) ; defined below
286 (defvar org-modules-loaded nil
287 "Have the modules been loaded already?")
289 (defun org-load-modules-maybe (&optional force)
290 "Load all extensions listed in `org-modules'."
291 (when (or force (not org-modules-loaded))
292 (mapc (lambda (ext)
293 (condition-case nil (require ext)
294 (error (message "Problems while trying to load feature `%s'" ext))))
295 org-modules)
296 (setq org-modules-loaded t)))
298 (defun org-set-modules (var value)
299 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
300 (set var value)
301 (when (featurep 'org)
302 (org-load-modules-maybe 'force)))
304 (when (org-bound-and-true-p org-modules)
305 (let ((a (member 'org-infojs org-modules)))
306 (and a (setcar a 'org-jsinfo))))
308 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
309 "Modules that should always be loaded together with org.el.
310 If a description starts with <C>, the file is not part of Emacs
311 and loading it will require that you have downloaded and properly installed
312 the org-mode distribution.
314 You can also use this system to load external packages (i.e. neither Org
315 core modules, nor modules from the CONTRIB directory). Just add symbols
316 to the end of the list. If the package is called org-xyz.el, then you need
317 to add the symbol `xyz', and the package must have a call to
319 (provide 'org-xyz)"
320 :group 'org
321 :set 'org-set-modules
322 :type
323 '(set :greedy t
324 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
325 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
326 (const :tag " crypt: Encryption of subtrees" org-crypt)
327 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
328 (const :tag " docview: Links to doc-view buffers" org-docview)
329 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
330 (const :tag " id: Global IDs for identifying entries" org-id)
331 (const :tag " info: Links to Info nodes" org-info)
332 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
333 (const :tag " habit: Track your consistency with habits" org-habit)
334 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
335 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
336 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
337 (const :tag " mew Links to Mew folders/messages" org-mew)
338 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
339 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
340 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
341 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
342 (const :tag " vm: Links to VM folders/messages" org-vm)
343 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
344 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
345 (const :tag " mouse: Additional mouse support" org-mouse)
346 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
348 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
349 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
350 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
351 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
352 (const :tag "C collector: Collect properties into tables" org-collector)
353 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
354 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
355 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
356 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
357 (const :tag "C eval: Include command output as text" org-eval)
358 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
359 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
360 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
361 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
362 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
364 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
366 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
367 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
368 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
369 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
370 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
371 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
372 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
373 (const :tag "C mtags: Support for muse-like tags" org-mtags)
374 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
375 (const :tag "C registry: A registry for Org-mode links" org-registry)
376 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
377 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
378 (const :tag "C secretary: Team management with org-mode" org-secretary)
379 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
380 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
381 (const :tag "C track: Keep up with Org-mode development" org-track)
382 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
383 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
384 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
386 (defcustom org-support-shift-select nil
387 "Non-nil means make shift-cursor commands select text when possible.
389 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
390 start selecting a region, or enlarge regions started in this way.
391 In Org-mode, in special contexts, these same keys are used for
392 other purposes, important enough to compete with shift selection.
393 Org tries to balance these needs by supporting `shift-select-mode'
394 outside these special contexts, under control of this variable.
396 The default of this variable is nil, to avoid confusing behavior. Shifted
397 cursor keys will then execute Org commands in the following contexts:
398 - on a headline, changing TODO state (left/right) and priority (up/down)
399 - on a time stamp, changing the time
400 - in a plain list item, changing the bullet type
401 - in a property definition line, switching between allowed values
402 - in the BEGIN line of a clock table (changing the time block).
403 Outside these contexts, the commands will throw an error.
405 When this variable is t and the cursor is not in a special
406 context, Org-mode will support shift-selection for making and
407 enlarging regions. To make this more effective, the bullet
408 cycling will no longer happen anywhere in an item line, but only
409 if the cursor is exactly on the bullet.
411 If you set this variable to the symbol `always', then the keys
412 will not be special in headlines, property lines, and item lines,
413 to make shift selection work there as well. If this is what you
414 want, you can use the following alternative commands: `C-c C-t'
415 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
416 can be used to switch TODO sets, `C-c -' to cycle item bullet
417 types, and properties can be edited by hand or in column view.
419 However, when the cursor is on a timestamp, shift-cursor commands
420 will still edit the time stamp - this is just too good to give up.
422 XEmacs user should have this variable set to nil, because
423 `shift-select-mode' is in Emacs 23 or later only."
424 :group 'org
425 :type '(choice
426 (const :tag "Never" nil)
427 (const :tag "When outside special context" t)
428 (const :tag "Everywhere except timestamps" always)))
430 (defcustom org-loop-over-headlines-in-active-region nil
431 "Shall some commands act upon headlines in the active region?
433 When set to `t', some commands will be performed in all headlines
434 within the active region.
436 When set to `start-level', some commands will be performed in all
437 headlines within the active region, provided that these headlines
438 are of the same level than the first one.
440 When set to a string, those commands will be performed on the
441 matching headlines within the active region. Such string must be
442 a tags/property/todo match as it is used in the agenda tags view.
444 The list of commands is: `org-schedule', `org-deadline',
445 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
446 `org-archive-to-archive-sibling'. The archiving commands skip
447 already archived entries."
448 :type '(choice (const :tag "Don't loop" nil)
449 (const :tag "All headlines in active region" t)
450 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
451 (string :tag "Tags/Property/Todo matcher"))
452 :version "24.1"
453 :group 'org-todo
454 :group 'org-archive)
456 (defgroup org-startup nil
457 "Options concerning startup of Org-mode."
458 :tag "Org Startup"
459 :group 'org)
461 (defcustom org-startup-folded t
462 "Non-nil means entering Org-mode will switch to OVERVIEW.
463 This can also be configured on a per-file basis by adding one of
464 the following lines anywhere in the buffer:
466 #+STARTUP: fold (or `overview', this is equivalent)
467 #+STARTUP: nofold (or `showall', this is equivalent)
468 #+STARTUP: content
469 #+STARTUP: showeverything
471 By default, this option is ignored when Org opens agenda files
472 for the first time. If you want the agenda to honor the startup
473 option, set `org-agenda-inhibit-startup' to nil."
474 :group 'org-startup
475 :type '(choice
476 (const :tag "nofold: show all" nil)
477 (const :tag "fold: overview" t)
478 (const :tag "content: all headlines" content)
479 (const :tag "show everything, even drawers" showeverything)))
481 (defcustom org-startup-truncated t
482 "Non-nil means entering Org-mode will set `truncate-lines'.
483 This is useful since some lines containing links can be very long and
484 uninteresting. Also tables look terrible when wrapped."
485 :group 'org-startup
486 :type 'boolean)
488 (defcustom org-startup-indented nil
489 "Non-nil means turn on `org-indent-mode' on startup.
490 This can also be configured on a per-file basis by adding one of
491 the following lines anywhere in the buffer:
493 #+STARTUP: indent
494 #+STARTUP: noindent"
495 :group 'org-structure
496 :type '(choice
497 (const :tag "Not" nil)
498 (const :tag "Globally (slow on startup in large files)" t)))
500 (defcustom org-use-sub-superscripts t
501 "Non-nil means interpret \"_\" and \"^\" for export.
502 When this option is turned on, you can use TeX-like syntax for sub- and
503 superscripts. Several characters after \"_\" or \"^\" will be
504 considered as a single item - so grouping with {} is normally not
505 needed. For example, the following things will be parsed as single
506 sub- or superscripts.
508 10^24 or 10^tau several digits will be considered 1 item.
509 10^-12 or 10^-tau a leading sign with digits or a word
510 x^2-y^3 will be read as x^2 - y^3, because items are
511 terminated by almost any nonword/nondigit char.
512 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
514 Still, ambiguity is possible - so when in doubt use {} to enclose the
515 sub/superscript. If you set this variable to the symbol `{}',
516 the braces are *required* in order to trigger interpretations as
517 sub/superscript. This can be helpful in documents that need \"_\"
518 frequently in plain text.
520 Not all export backends support this, but HTML does.
522 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
523 :group 'org-startup
524 :group 'org-export-translation
525 :version "24.1"
526 :type '(choice
527 (const :tag "Always interpret" t)
528 (const :tag "Only with braces" {})
529 (const :tag "Never interpret" nil)))
531 (if (fboundp 'defvaralias)
532 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
535 (defcustom org-startup-with-beamer-mode nil
536 "Non-nil means turn on `org-beamer-mode' on startup.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
540 #+STARTUP: beamer"
541 :group 'org-startup
542 :version "24.1"
543 :type 'boolean)
545 (defcustom org-startup-align-all-tables nil
546 "Non-nil means align all tables when visiting a file.
547 This is useful when the column width in tables is forced with <N> cookies
548 in table fields. Such tables will look correct only after the first re-align.
549 This can also be configured on a per-file basis by adding one of
550 the following lines anywhere in the buffer:
551 #+STARTUP: align
552 #+STARTUP: noalign"
553 :group 'org-startup
554 :type 'boolean)
556 (defcustom org-startup-with-inline-images nil
557 "Non-nil means show inline images when loading a new Org file.
558 This can also be configured on a per-file basis by adding one of
559 the following lines anywhere in the buffer:
560 #+STARTUP: inlineimages
561 #+STARTUP: noinlineimages"
562 :group 'org-startup
563 :version "24.1"
564 :type 'boolean)
566 (defcustom org-insert-mode-line-in-empty-file nil
567 "Non-nil means insert the first line setting Org-mode in empty files.
568 When the function `org-mode' is called interactively in an empty file, this
569 normally means that the file name does not automatically trigger Org-mode.
570 To ensure that the file will always be in Org-mode in the future, a
571 line enforcing Org-mode will be inserted into the buffer, if this option
572 has been set."
573 :group 'org-startup
574 :type 'boolean)
576 (defcustom org-replace-disputed-keys nil
577 "Non-nil means use alternative key bindings for some keys.
578 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
579 These keys are also used by other packages like shift-selection-mode'
580 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
581 If you want to use Org-mode together with one of these other modes,
582 or more generally if you would like to move some Org-mode commands to
583 other keys, set this variable and configure the keys with the variable
584 `org-disputed-keys'.
586 This option is only relevant at load-time of Org-mode, and must be set
587 *before* org.el is loaded. Changing it requires a restart of Emacs to
588 become effective."
589 :group 'org-startup
590 :type 'boolean)
592 (defcustom org-use-extra-keys nil
593 "Non-nil means use extra key sequence definitions for certain commands.
594 This happens automatically if you run XEmacs or if `window-system'
595 is nil. This variable lets you do the same manually. You must
596 set it before loading org.
598 Example: on Carbon Emacs 22 running graphically, with an external
599 keyboard on a Powerbook, the default way of setting M-left might
600 not work for either Alt or ESC. Setting this variable will make
601 it work for ESC."
602 :group 'org-startup
603 :type 'boolean)
605 (if (fboundp 'defvaralias)
606 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
608 (defcustom org-disputed-keys
609 '(([(shift up)] . [(meta p)])
610 ([(shift down)] . [(meta n)])
611 ([(shift left)] . [(meta -)])
612 ([(shift right)] . [(meta +)])
613 ([(control shift right)] . [(meta shift +)])
614 ([(control shift left)] . [(meta shift -)]))
615 "Keys for which Org-mode and other modes compete.
616 This is an alist, cars are the default keys, second element specifies
617 the alternative to use when `org-replace-disputed-keys' is t.
619 Keys can be specified in any syntax supported by `define-key'.
620 The value of this option takes effect only at Org-mode's startup,
621 therefore you'll have to restart Emacs to apply it after changing."
622 :group 'org-startup
623 :type 'alist)
625 (defun org-key (key)
626 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
627 Or return the original if not disputed.
628 Also apply the translations defined in `org-xemacs-key-equivalents'."
629 (when org-replace-disputed-keys
630 (let* ((nkey (key-description key))
631 (x (org-find-if (lambda (x)
632 (equal (key-description (car x)) nkey))
633 org-disputed-keys)))
634 (setq key (if x (cdr x) key))))
635 (when (featurep 'xemacs)
636 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
637 key)
639 (defun org-find-if (predicate seq)
640 (catch 'exit
641 (while seq
642 (if (funcall predicate (car seq))
643 (throw 'exit (car seq))
644 (pop seq)))))
646 (defun org-defkey (keymap key def)
647 "Define a key, possibly translated, as returned by `org-key'."
648 (define-key keymap (org-key key) def))
650 (defcustom org-ellipsis nil
651 "The ellipsis to use in the Org-mode outline.
652 When nil, just use the standard three dots. When a string, use that instead,
653 When a face, use the standard 3 dots, but with the specified face.
654 The change affects only Org-mode (which will then use its own display table).
655 Changing this requires executing `M-x org-mode' in a buffer to become
656 effective."
657 :group 'org-startup
658 :type '(choice (const :tag "Default" nil)
659 (face :tag "Face" :value org-warning)
660 (string :tag "String" :value "...#")))
662 (defvar org-display-table nil
663 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
665 (defgroup org-keywords nil
666 "Keywords in Org-mode."
667 :tag "Org Keywords"
668 :group 'org)
670 (defcustom org-deadline-string "DEADLINE:"
671 "String to mark deadline entries.
672 A deadline is this string, followed by a time stamp. Should be a word,
673 terminated by a colon. You can insert a schedule keyword and
674 a timestamp with \\[org-deadline].
675 Changes become only effective after restarting Emacs."
676 :group 'org-keywords
677 :type 'string)
679 (defcustom org-scheduled-string "SCHEDULED:"
680 "String to mark scheduled TODO entries.
681 A schedule is this string, followed by a time stamp. Should be a word,
682 terminated by a colon. You can insert a schedule keyword and
683 a timestamp with \\[org-schedule].
684 Changes become only effective after restarting Emacs."
685 :group 'org-keywords
686 :type 'string)
688 (defcustom org-closed-string "CLOSED:"
689 "String used as the prefix for timestamps logging closing a TODO entry."
690 :group 'org-keywords
691 :type 'string)
693 (defcustom org-clock-string "CLOCK:"
694 "String used as prefix for timestamps clocking work hours on an item."
695 :group 'org-keywords
696 :type 'string)
698 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
699 org-scheduled-string "\\|"
700 org-deadline-string "\\|"
701 org-closed-string "\\|"
702 org-clock-string "\\)")
703 "Matches a line with planning or clock info.")
705 (defcustom org-comment-string "COMMENT"
706 "Entries starting with this keyword will never be exported.
707 An entry can be toggled between COMMENT and normal with
708 \\[org-toggle-comment].
709 Changes become only effective after restarting Emacs."
710 :group 'org-keywords
711 :type 'string)
713 (defcustom org-quote-string "QUOTE"
714 "Entries starting with this keyword will be exported in fixed-width font.
715 Quoting applies only to the text in the entry following the headline, and does
716 not extend beyond the next headline, even if that is lower level.
717 An entry can be toggled between QUOTE and normal with
718 \\[org-toggle-fixed-width-section]."
719 :group 'org-keywords
720 :type 'string)
722 (defconst org-repeat-re
723 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
724 "Regular expression for specifying repeated events.
725 After a match, group 1 contains the repeat expression.")
727 (defgroup org-structure nil
728 "Options concerning the general structure of Org-mode files."
729 :tag "Org Structure"
730 :group 'org)
732 (defgroup org-reveal-location nil
733 "Options about how to make context of a location visible."
734 :tag "Org Reveal Location"
735 :group 'org-structure)
737 (defconst org-context-choice
738 '(choice
739 (const :tag "Always" t)
740 (const :tag "Never" nil)
741 (repeat :greedy t :tag "Individual contexts"
742 (cons
743 (choice :tag "Context"
744 (const agenda)
745 (const org-goto)
746 (const occur-tree)
747 (const tags-tree)
748 (const link-search)
749 (const mark-goto)
750 (const bookmark-jump)
751 (const isearch)
752 (const default))
753 (boolean))))
754 "Contexts for the reveal options.")
756 (defcustom org-show-hierarchy-above '((default . t))
757 "Non-nil means show full hierarchy when revealing a location.
758 Org-mode often shows locations in an org-mode file which might have
759 been invisible before. When this is set, the hierarchy of headings
760 above the exposed location is shown.
761 Turning this off for example for sparse trees makes them very compact.
762 Instead of t, this can also be an alist specifying this option for different
763 contexts. Valid contexts are
764 agenda when exposing an entry from the agenda
765 org-goto when using the command `org-goto' on key C-c C-j
766 occur-tree when using the command `org-occur' on key C-c /
767 tags-tree when constructing a sparse tree based on tags matches
768 link-search when exposing search matches associated with a link
769 mark-goto when exposing the jump goal of a mark
770 bookmark-jump when exposing a bookmark location
771 isearch when exiting from an incremental search
772 default default for all contexts not set explicitly"
773 :group 'org-reveal-location
774 :type org-context-choice)
776 (defcustom org-show-following-heading '((default . nil))
777 "Non-nil means show following heading when revealing a location.
778 Org-mode often shows locations in an org-mode file which might have
779 been invisible before. When this is set, the heading following the
780 match is shown.
781 Turning this off for example for sparse trees makes them very compact,
782 but makes it harder to edit the location of the match. In such a case,
783 use the command \\[org-reveal] to show more context.
784 Instead of t, this can also be an alist specifying this option for different
785 contexts. See `org-show-hierarchy-above' for valid contexts."
786 :group 'org-reveal-location
787 :type org-context-choice)
789 (defcustom org-show-siblings '((default . nil) (isearch t))
790 "Non-nil means show all sibling heading when revealing a location.
791 Org-mode often shows locations in an org-mode file which might have
792 been invisible before. When this is set, the sibling of the current entry
793 heading are all made visible. If `org-show-hierarchy-above' is t,
794 the same happens on each level of the hierarchy above the current entry.
796 By default this is on for the isearch context, off for all other contexts.
797 Turning this off for example for sparse trees makes them very compact,
798 but makes it harder to edit the location of the match. In such a case,
799 use the command \\[org-reveal] to show more context.
800 Instead of t, this can also be an alist specifying this option for different
801 contexts. See `org-show-hierarchy-above' for valid contexts."
802 :group 'org-reveal-location
803 :type org-context-choice)
805 (defcustom org-show-entry-below '((default . nil))
806 "Non-nil means show the entry below a headline when revealing a location.
807 Org-mode often shows locations in an org-mode file which might have
808 been invisible before. When this is set, the text below the headline that is
809 exposed is also shown.
811 By default this is off for all contexts.
812 Instead of t, this can also be an alist specifying this option for different
813 contexts. See `org-show-hierarchy-above' for valid contexts."
814 :group 'org-reveal-location
815 :type org-context-choice)
817 (defcustom org-indirect-buffer-display 'other-window
818 "How should indirect tree buffers be displayed?
819 This applies to indirect buffers created with the commands
820 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
821 Valid values are:
822 current-window Display in the current window
823 other-window Just display in another window.
824 dedicated-frame Create one new frame, and re-use it each time.
825 new-frame Make a new frame each time. Note that in this case
826 previously-made indirect buffers are kept, and you need to
827 kill these buffers yourself."
828 :group 'org-structure
829 :group 'org-agenda-windows
830 :type '(choice
831 (const :tag "In current window" current-window)
832 (const :tag "In current frame, other window" other-window)
833 (const :tag "Each time a new frame" new-frame)
834 (const :tag "One dedicated frame" dedicated-frame)))
836 (defcustom org-use-speed-commands nil
837 "Non-nil means activate single letter commands at beginning of a headline.
838 This may also be a function to test for appropriate locations where speed
839 commands should be active."
840 :group 'org-structure
841 :type '(choice
842 (const :tag "Never" nil)
843 (const :tag "At beginning of headline stars" t)
844 (function)))
846 (defcustom org-speed-commands-user nil
847 "Alist of additional speed commands.
848 This list will be checked before `org-speed-commands-default'
849 when the variable `org-use-speed-commands' is non-nil
850 and when the cursor is at the beginning of a headline.
851 The car if each entry is a string with a single letter, which must
852 be assigned to `self-insert-command' in the global map.
853 The cdr is either a command to be called interactively, a function
854 to be called, or a form to be evaluated.
855 An entry that is just a list with a single string will be interpreted
856 as a descriptive headline that will be added when listing the speed
857 commands in the Help buffer using the `?' speed command."
858 :group 'org-structure
859 :type '(repeat :value ("k" . ignore)
860 (choice :value ("k" . ignore)
861 (list :tag "Descriptive Headline" (string :tag "Headline"))
862 (cons :tag "Letter and Command"
863 (string :tag "Command letter")
864 (choice
865 (function)
866 (sexp))))))
868 (defgroup org-cycle nil
869 "Options concerning visibility cycling in Org-mode."
870 :tag "Org Cycle"
871 :group 'org-structure)
873 (defcustom org-cycle-skip-children-state-if-no-children t
874 "Non-nil means skip CHILDREN state in entries that don't have any."
875 :group 'org-cycle
876 :type 'boolean)
878 (defcustom org-cycle-max-level nil
879 "Maximum level which should still be subject to visibility cycling.
880 Levels higher than this will, for cycling, be treated as text, not a headline.
881 When `org-odd-levels-only' is set, a value of N in this variable actually
882 means 2N-1 stars as the limiting headline.
883 When nil, cycle all levels.
884 Note that the limiting level of cycling is also influenced by
885 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
886 `org-inlinetask-min-level' is, cycling will be limited to levels one less
887 than its value."
888 :group 'org-cycle
889 :type '(choice
890 (const :tag "No limit" nil)
891 (integer :tag "Maximum level")))
893 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
894 "Names of drawers. Drawers are not opened by cycling on the headline above.
895 Drawers only open with a TAB on the drawer line itself. A drawer looks like
896 this:
897 :DRAWERNAME:
898 .....
899 :END:
900 The drawer \"PROPERTIES\" is special for capturing properties through
901 the property API.
903 Drawers can be defined on the per-file basis with a line like:
905 #+DRAWERS: HIDDEN STATE PROPERTIES"
906 :group 'org-structure
907 :group 'org-cycle
908 :type '(repeat (string :tag "Drawer Name")))
910 (defcustom org-hide-block-startup nil
911 "Non-nil means entering Org-mode will fold all blocks.
912 This can also be set in on a per-file basis with
914 #+STARTUP: hideblocks
915 #+STARTUP: showblocks"
916 :group 'org-startup
917 :group 'org-cycle
918 :type 'boolean)
920 (defcustom org-cycle-global-at-bob nil
921 "Cycle globally if cursor is at beginning of buffer and not at a headline.
922 This makes it possible to do global cycling without having to use S-TAB or
923 \\[universal-argument] TAB. For this special case to work, the first line
924 of the buffer must not be a headline -- it may be empty or some other text.
925 When used in this way, `org-cycle-hook' is disabled temporarily to make
926 sure the cursor stays at the beginning of the buffer. When this option is
927 nil, don't do anything special at the beginning of the buffer."
928 :group 'org-cycle
929 :type 'boolean)
931 (defcustom org-cycle-level-after-item/entry-creation t
932 "Non-nil means cycle entry level or item indentation in new empty entries.
934 When the cursor is at the end of an empty headline, i.e., with only stars
935 and maybe a TODO keyword, TAB will then switch the entry to become a child,
936 and then all possible ancestor states, before returning to the original state.
937 This makes data entry extremely fast: M-RET to create a new headline,
938 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
940 When the cursor is at the end of an empty plain list item, one TAB will
941 make it a subitem, two or more tabs will back up to make this an item
942 higher up in the item hierarchy."
943 :group 'org-cycle
944 :type 'boolean)
946 (defcustom org-cycle-emulate-tab t
947 "Where should `org-cycle' emulate TAB.
948 nil Never
949 white Only in completely white lines
950 whitestart Only at the beginning of lines, before the first non-white char
951 t Everywhere except in headlines
952 exc-hl-bol Everywhere except at the start of a headline
953 If TAB is used in a place where it does not emulate TAB, the current subtree
954 visibility is cycled."
955 :group 'org-cycle
956 :type '(choice (const :tag "Never" nil)
957 (const :tag "Only in completely white lines" white)
958 (const :tag "Before first char in a line" whitestart)
959 (const :tag "Everywhere except in headlines" t)
960 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
963 (defcustom org-cycle-separator-lines 2
964 "Number of empty lines needed to keep an empty line between collapsed trees.
965 If you leave an empty line between the end of a subtree and the following
966 headline, this empty line is hidden when the subtree is folded.
967 Org-mode will leave (exactly) one empty line visible if the number of
968 empty lines is equal or larger to the number given in this variable.
969 So the default 2 means at least 2 empty lines after the end of a subtree
970 are needed to produce free space between a collapsed subtree and the
971 following headline.
973 If the number is negative, and the number of empty lines is at least -N,
974 all empty lines are shown.
976 Special case: when 0, never leave empty lines in collapsed view."
977 :group 'org-cycle
978 :type 'integer)
979 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
981 (defcustom org-pre-cycle-hook nil
982 "Hook that is run before visibility cycling is happening.
983 The function(s) in this hook must accept a single argument which indicates
984 the new state that will be set right after running this hook. The
985 argument is a symbol. Before a global state change, it can have the values
986 `overview', `content', or `all'. Before a local state change, it can have
987 the values `folded', `children', or `subtree'."
988 :group 'org-cycle
989 :type 'hook)
991 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
992 org-cycle-hide-drawers
993 org-cycle-show-empty-lines
994 org-optimize-window-after-visibility-change)
995 "Hook that is run after `org-cycle' has changed the buffer visibility.
996 The function(s) in this hook must accept a single argument which indicates
997 the new state that was set by the most recent `org-cycle' command. The
998 argument is a symbol. After a global state change, it can have the values
999 `overview', `contents', or `all'. After a local state change, it can have
1000 the values `folded', `children', or `subtree'."
1001 :group 'org-cycle
1002 :type 'hook)
1004 (defgroup org-edit-structure nil
1005 "Options concerning structure editing in Org-mode."
1006 :tag "Org Edit Structure"
1007 :group 'org-structure)
1009 (defcustom org-odd-levels-only nil
1010 "Non-nil means skip even levels and only use odd levels for the outline.
1011 This has the effect that two stars are being added/taken away in
1012 promotion/demotion commands. It also influences how levels are
1013 handled by the exporters.
1014 Changing it requires restart of `font-lock-mode' to become effective
1015 for fontification also in regions already fontified.
1016 You may also set this on a per-file basis by adding one of the following
1017 lines to the buffer:
1019 #+STARTUP: odd
1020 #+STARTUP: oddeven"
1021 :group 'org-edit-structure
1022 :group 'org-appearance
1023 :type 'boolean)
1025 (defcustom org-adapt-indentation t
1026 "Non-nil means adapt indentation to outline node level.
1028 When this variable is set, Org assumes that you write outlines by
1029 indenting text in each node to align with the headline (after the stars).
1030 The following issues are influenced by this variable:
1032 - When this is set and the *entire* text in an entry is indented, the
1033 indentation is increased by one space in a demotion command, and
1034 decreased by one in a promotion command. If any line in the entry
1035 body starts with text at column 0, indentation is not changed at all.
1037 - Property drawers and planning information is inserted indented when
1038 this variable s set. When nil, they will not be indented.
1040 - TAB indents a line relative to context. The lines below a headline
1041 will be indented when this variable is set.
1043 Note that this is all about true indentation, by adding and removing
1044 space characters. See also `org-indent.el' which does level-dependent
1045 indentation in a virtual way, i.e. at display time in Emacs."
1046 :group 'org-edit-structure
1047 :type 'boolean)
1049 (defcustom org-special-ctrl-a/e nil
1050 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1052 When t, `C-a' will bring back the cursor to the beginning of the
1053 headline text, i.e. after the stars and after a possible TODO
1054 keyword. In an item, this will be the position after bullet and
1055 check-box, if any. When the cursor is already at that position,
1056 another `C-a' will bring it to the beginning of the line.
1058 `C-e' will jump to the end of the headline, ignoring the presence
1059 of tags in the headline. A second `C-e' will then jump to the
1060 true end of the line, after any tags. This also means that, when
1061 this variable is non-nil, `C-e' also will never jump beyond the
1062 end of the heading of a folded section, i.e. not after the
1063 ellipses.
1065 When set to the symbol `reversed', the first `C-a' or `C-e' works
1066 normally, going to the true line boundary first. Only a directly
1067 following, identical keypress will bring the cursor to the
1068 special positions.
1070 This may also be a cons cell where the behavior for `C-a' and
1071 `C-e' is set separately."
1072 :group 'org-edit-structure
1073 :type '(choice
1074 (const :tag "off" nil)
1075 (const :tag "on: after stars/bullet and before tags first" t)
1076 (const :tag "reversed: true line boundary first" reversed)
1077 (cons :tag "Set C-a and C-e separately"
1078 (choice :tag "Special C-a"
1079 (const :tag "off" nil)
1080 (const :tag "on: after stars/bullet first" t)
1081 (const :tag "reversed: before stars/bullet first" reversed))
1082 (choice :tag "Special C-e"
1083 (const :tag "off" nil)
1084 (const :tag "on: before tags first" t)
1085 (const :tag "reversed: after tags first" reversed)))))
1086 (if (fboundp 'defvaralias)
1087 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1089 (defcustom org-special-ctrl-k nil
1090 "Non-nil means `C-k' will behave specially in headlines.
1091 When nil, `C-k' will call the default `kill-line' command.
1092 When t, the following will happen while the cursor is in the headline:
1094 - When the cursor is at the beginning of a headline, kill the entire
1095 line and possible the folded subtree below the line.
1096 - When in the middle of the headline text, kill the headline up to the tags.
1097 - When after the headline text, kill the tags."
1098 :group 'org-edit-structure
1099 :type 'boolean)
1101 (defcustom org-ctrl-k-protect-subtree nil
1102 "Non-nil means, do not delete a hidden subtree with C-k.
1103 When set to the symbol `error', simply throw an error when C-k is
1104 used to kill (part-of) a headline that has hidden text behind it.
1105 Any other non-nil value will result in a query to the user, if it is
1106 OK to kill that hidden subtree. When nil, kill without remorse."
1107 :group 'org-edit-structure
1108 :version "24.1"
1109 :type '(choice
1110 (const :tag "Do not protect hidden subtrees" nil)
1111 (const :tag "Protect hidden subtrees with a security query" t)
1112 (const :tag "Never kill a hidden subtree with C-k" error)))
1114 (defcustom org-catch-invisible-edits nil
1115 "Check if in invisible region before inserting or deleting a character.
1116 Valid values are:
1118 nil Do not check, so just do invisible edits.
1119 error Throw an error and do nothing.
1120 show Make point visible, and do the requested edit.
1121 show-and-error Make point visible, then throw an error and abort the edit.
1122 smart Make point visible, and do insertion/deletion if it is
1123 adjacent to visible text and the change feels predictable.
1124 Never delete a previously invisible character or add in the
1125 middle or right after an invisible region. Basically, this
1126 allows insertion and backward-delete right before ellipses.
1127 FIXME: maybe in this case we should not even show?"
1128 :group 'org-edit-structure
1129 :version "24.1"
1130 :type '(choice
1131 (const :tag "Do not check" nil)
1132 (const :tag "Throw error when trying to edit" error)
1133 (const :tag "Unhide, but do not do the edit" show-and-error)
1134 (const :tag "Show invisible part and do the edit" show)
1135 (const :tag "Be smart and do the right thing" smart)))
1137 (defcustom org-yank-folded-subtrees t
1138 "Non-nil means when yanking subtrees, fold them.
1139 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1140 it starts with a heading and all other headings in it are either children
1141 or siblings, then fold all the subtrees. However, do this only if no
1142 text after the yank would be swallowed into a folded tree by this action."
1143 :group 'org-edit-structure
1144 :type 'boolean)
1146 (defcustom org-yank-adjusted-subtrees nil
1147 "Non-nil means when yanking subtrees, adjust the level.
1148 With this setting, `org-paste-subtree' is used to insert the subtree, see
1149 this function for details."
1150 :group 'org-edit-structure
1151 :type 'boolean)
1153 (defcustom org-M-RET-may-split-line '((default . t))
1154 "Non-nil means M-RET will split the line at the cursor position.
1155 When nil, it will go to the end of the line before making a
1156 new line.
1157 You may also set this option in a different way for different
1158 contexts. Valid contexts are:
1160 headline when creating a new headline
1161 item when creating a new item
1162 table in a table field
1163 default the value to be used for all contexts not explicitly
1164 customized"
1165 :group 'org-structure
1166 :group 'org-table
1167 :type '(choice
1168 (const :tag "Always" t)
1169 (const :tag "Never" nil)
1170 (repeat :greedy t :tag "Individual contexts"
1171 (cons
1172 (choice :tag "Context"
1173 (const headline)
1174 (const item)
1175 (const table)
1176 (const default))
1177 (boolean)))))
1180 (defcustom org-insert-heading-respect-content nil
1181 "Non-nil means insert new headings after the current subtree.
1182 When nil, the new heading is created directly after the current line.
1183 The commands \\[org-insert-heading-respect-content] and
1184 \\[org-insert-todo-heading-respect-content] turn this variable on
1185 for the duration of the command."
1186 :group 'org-structure
1187 :type 'boolean)
1189 (defcustom org-blank-before-new-entry '((heading . auto)
1190 (plain-list-item . auto))
1191 "Should `org-insert-heading' leave a blank line before new heading/item?
1192 The value is an alist, with `heading' and `plain-list-item' as CAR,
1193 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1194 which case Org will look at the surrounding headings/items and try to
1195 make an intelligent decision whether to insert a blank line or not.
1197 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1198 set, the setting here is ignored and no empty line is inserted, to avoid
1199 breaking the list structure."
1200 :group 'org-edit-structure
1201 :type '(list
1202 (cons (const heading)
1203 (choice (const :tag "Never" nil)
1204 (const :tag "Always" t)
1205 (const :tag "Auto" auto)))
1206 (cons (const plain-list-item)
1207 (choice (const :tag "Never" nil)
1208 (const :tag "Always" t)
1209 (const :tag "Auto" auto)))))
1211 (defcustom org-insert-heading-hook nil
1212 "Hook being run after inserting a new heading."
1213 :group 'org-edit-structure
1214 :type 'hook)
1216 (defcustom org-enable-fixed-width-editor t
1217 "Non-nil means lines starting with \":\" are treated as fixed-width.
1218 This currently only means they are never auto-wrapped.
1219 When nil, such lines will be treated like ordinary lines.
1220 See also the QUOTE keyword."
1221 :group 'org-edit-structure
1222 :type 'boolean)
1224 (defcustom org-goto-auto-isearch t
1225 "Non-nil means typing characters in `org-goto' starts incremental search.
1226 When nil, you can use these keybindings to navigate the buffer:
1228 q Quit the org-goto interface
1229 n Go to the next visible heading
1230 p Go to the previous visible heading
1231 f Go one heading forward on same level
1232 b Go one heading backward on same level
1233 u Go one heading up"
1234 :group 'org-edit-structure
1235 :type 'boolean)
1237 (defgroup org-sparse-trees nil
1238 "Options concerning sparse trees in Org-mode."
1239 :tag "Org Sparse Trees"
1240 :group 'org-structure)
1242 (defcustom org-highlight-sparse-tree-matches t
1243 "Non-nil means highlight all matches that define a sparse tree.
1244 The highlights will automatically disappear the next time the buffer is
1245 changed by an edit command."
1246 :group 'org-sparse-trees
1247 :type 'boolean)
1249 (defcustom org-remove-highlights-with-change t
1250 "Non-nil means any change to the buffer will remove temporary highlights.
1251 Such highlights are created by `org-occur' and `org-clock-display'.
1252 When nil, `C-c C-c needs to be used to get rid of the highlights.
1253 The highlights created by `org-preview-latex-fragment' always need
1254 `C-c C-c' to be removed."
1255 :group 'org-sparse-trees
1256 :group 'org-time
1257 :type 'boolean)
1260 (defcustom org-occur-hook '(org-first-headline-recenter)
1261 "Hook that is run after `org-occur' has constructed a sparse tree.
1262 This can be used to recenter the window to show as much of the structure
1263 as possible."
1264 :group 'org-sparse-trees
1265 :type 'hook)
1267 (defgroup org-imenu-and-speedbar nil
1268 "Options concerning imenu and speedbar in Org-mode."
1269 :tag "Org Imenu and Speedbar"
1270 :group 'org-structure)
1272 (defcustom org-imenu-depth 2
1273 "The maximum level for Imenu access to Org-mode headlines.
1274 This also applied for speedbar access."
1275 :group 'org-imenu-and-speedbar
1276 :type 'integer)
1278 (defgroup org-table nil
1279 "Options concerning tables in Org-mode."
1280 :tag "Org Table"
1281 :group 'org)
1283 (defcustom org-enable-table-editor 'optimized
1284 "Non-nil means lines starting with \"|\" are handled by the table editor.
1285 When nil, such lines will be treated like ordinary lines.
1287 When equal to the symbol `optimized', the table editor will be optimized to
1288 do the following:
1289 - Automatic overwrite mode in front of whitespace in table fields.
1290 This makes the structure of the table stay in tact as long as the edited
1291 field does not exceed the column width.
1292 - Minimize the number of realigns. Normally, the table is aligned each time
1293 TAB or RET are pressed to move to another field. With optimization this
1294 happens only if changes to a field might have changed the column width.
1295 Optimization requires replacing the functions `self-insert-command',
1296 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1297 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1298 very good at guessing when a re-align will be necessary, but you can always
1299 force one with \\[org-ctrl-c-ctrl-c].
1301 If you would like to use the optimized version in Org-mode, but the
1302 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1304 This variable can be used to turn on and off the table editor during a session,
1305 but in order to toggle optimization, a restart is required.
1307 See also the variable `org-table-auto-blank-field'."
1308 :group 'org-table
1309 :type '(choice
1310 (const :tag "off" nil)
1311 (const :tag "on" t)
1312 (const :tag "on, optimized" optimized)))
1314 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1315 (version<= emacs-version "24.1"))
1316 "Non-nil means cluster self-insert commands for undo when possible.
1317 If this is set, then, like in the Emacs command loop, 20 consecutive
1318 characters will be undone together.
1319 This is configurable, because there is some impact on typing performance."
1320 :group 'org-table
1321 :type 'boolean)
1323 (defcustom org-table-tab-recognizes-table.el t
1324 "Non-nil means TAB will automatically notice a table.el table.
1325 When it sees such a table, it moves point into it and - if necessary -
1326 calls `table-recognize-table'."
1327 :group 'org-table-editing
1328 :type 'boolean)
1330 (defgroup org-link nil
1331 "Options concerning links in Org-mode."
1332 :tag "Org Link"
1333 :group 'org)
1335 (defvar org-link-abbrev-alist-local nil
1336 "Buffer-local version of `org-link-abbrev-alist', which see.
1337 The value of this is taken from the #+LINK lines.")
1338 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1340 (defcustom org-link-abbrev-alist nil
1341 "Alist of link abbreviations.
1342 The car of each element is a string, to be replaced at the start of a link.
1343 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1344 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1346 [[linkkey:tag][description]]
1348 The 'linkkey' must be a word word, starting with a letter, followed
1349 by letters, numbers, '-' or '_'.
1351 If REPLACE is a string, the tag will simply be appended to create the link.
1352 If the string contains \"%s\", the tag will be inserted there. If the string
1353 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1354 at that point (see the function `url-hexify-string'). If the string contains
1355 the specifier \"%(my-function)\", then the custom function `my-function' will
1356 be invoked: this function takes the tag as its only argument and must return
1357 a string.
1359 REPLACE may also be a function that will be called with the tag as the
1360 only argument to create the link, which should be returned as a string.
1362 See the manual for examples."
1363 :group 'org-link
1364 :type '(repeat
1365 (cons
1366 (string :tag "Protocol")
1367 (choice
1368 (string :tag "Format")
1369 (function)))))
1371 (defcustom org-descriptive-links t
1372 "Non-nil means Org will display descriptive links.
1373 E.g. [[http://orgmode.org][Org website]] will be displayed as
1374 \"Org Website\", hiding the link itself and just displaying its
1375 description. When set to `nil', Org will display the full links
1376 literally.
1378 You can interactively set the value of this variable by calling
1379 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1380 :group 'org-link
1381 :type 'boolean)
1383 (defcustom org-link-file-path-type 'adaptive
1384 "How the path name in file links should be stored.
1385 Valid values are:
1387 relative Relative to the current directory, i.e. the directory of the file
1388 into which the link is being inserted.
1389 absolute Absolute path, if possible with ~ for home directory.
1390 noabbrev Absolute path, no abbreviation of home directory.
1391 adaptive Use relative path for files in the current directory and sub-
1392 directories of it. For other files, use an absolute path."
1393 :group 'org-link
1394 :type '(choice
1395 (const relative)
1396 (const absolute)
1397 (const noabbrev)
1398 (const adaptive)))
1400 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1401 "Types of links that should be activated in Org-mode files.
1402 This is a list of symbols, each leading to the activation of a certain link
1403 type. In principle, it does not hurt to turn on most link types - there may
1404 be a small gain when turning off unused link types. The types are:
1406 bracket The recommended [[link][description]] or [[link]] links with hiding.
1407 angle Links in angular brackets that may contain whitespace like
1408 <bbdb:Carsten Dominik>.
1409 plain Plain links in normal text, no whitespace, like http://google.com.
1410 radio Text that is matched by a radio target, see manual for details.
1411 tag Tag settings in a headline (link to tag search).
1412 date Time stamps (link to calendar).
1413 footnote Footnote labels.
1415 Changing this variable requires a restart of Emacs to become effective."
1416 :group 'org-link
1417 :type '(set :greedy t
1418 (const :tag "Double bracket links" bracket)
1419 (const :tag "Angular bracket links" angle)
1420 (const :tag "Plain text links" plain)
1421 (const :tag "Radio target matches" radio)
1422 (const :tag "Tags" tag)
1423 (const :tag "Timestamps" date)
1424 (const :tag "Footnotes" footnote)))
1426 (defcustom org-make-link-description-function nil
1427 "Function to use for generating link descriptions from links.
1428 When nil, the link location will be used. This function must take
1429 two parameters: the first one is the link, the second one is the
1430 description generated by `org-insert-link'. The function should
1431 return the description to use."
1432 :group 'org-link
1433 :type 'function)
1435 (defgroup org-link-store nil
1436 "Options concerning storing links in Org-mode."
1437 :tag "Org Store Link"
1438 :group 'org-link)
1440 (defcustom org-url-hexify-p t
1441 "When non-nil, hexify URL when creating a link."
1442 :type 'boolean
1443 :version "24.3"
1444 :group 'org-link-store)
1446 (defcustom org-email-link-description-format "Email %c: %.30s"
1447 "Format of the description part of a link to an email or usenet message.
1448 The following %-escapes will be replaced by corresponding information:
1450 %F full \"From\" field
1451 %f name, taken from \"From\" field, address if no name
1452 %T full \"To\" field
1453 %t first name in \"To\" field, address if no name
1454 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1455 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1456 %s subject
1457 %d date
1458 %m message-id.
1460 You may use normal field width specification between the % and the letter.
1461 This is for example useful to limit the length of the subject.
1463 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1464 :group 'org-link-store
1465 :type 'string)
1467 (defcustom org-from-is-user-regexp
1468 (let (r1 r2)
1469 (when (and user-mail-address (not (string= user-mail-address "")))
1470 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1471 (when (and user-full-name (not (string= user-full-name "")))
1472 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1473 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1474 "Regexp matched against the \"From:\" header of an email or usenet message.
1475 It should match if the message is from the user him/herself."
1476 :group 'org-link-store
1477 :type 'regexp)
1479 (defcustom org-context-in-file-links t
1480 "Non-nil means file links from `org-store-link' contain context.
1481 A search string will be added to the file name with :: as separator and
1482 used to find the context when the link is activated by the command
1483 `org-open-at-point'. When this option is t, the entire active region
1484 will be placed in the search string of the file link. If set to a
1485 positive integer, only the first n lines of context will be stored.
1487 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1488 negates this setting for the duration of the command."
1489 :group 'org-link-store
1490 :type '(choice boolean integer))
1492 (defcustom org-keep-stored-link-after-insertion nil
1493 "Non-nil means keep link in list for entire session.
1495 The command `org-store-link' adds a link pointing to the current
1496 location to an internal list. These links accumulate during a session.
1497 The command `org-insert-link' can be used to insert links into any
1498 Org-mode file (offering completion for all stored links). When this
1499 option is nil, every link which has been inserted once using \\[org-insert-link]
1500 will be removed from the list, to make completing the unused links
1501 more efficient."
1502 :group 'org-link-store
1503 :type 'boolean)
1505 (defgroup org-link-follow nil
1506 "Options concerning following links in Org-mode."
1507 :tag "Org Follow Link"
1508 :group 'org-link)
1510 (defcustom org-link-translation-function nil
1511 "Function to translate links with different syntax to Org syntax.
1512 This can be used to translate links created for example by the Planner
1513 or emacs-wiki packages to Org syntax.
1514 The function must accept two parameters, a TYPE containing the link
1515 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1516 which is everything after the link protocol. It should return a cons
1517 with possibly modified values of type and path.
1518 Org contains a function for this, so if you set this variable to
1519 `org-translate-link-from-planner', you should be able follow many
1520 links created by planner."
1521 :group 'org-link-follow
1522 :type 'function)
1524 (defcustom org-follow-link-hook nil
1525 "Hook that is run after a link has been followed."
1526 :group 'org-link-follow
1527 :type 'hook)
1529 (defcustom org-tab-follows-link nil
1530 "Non-nil means on links TAB will follow the link.
1531 Needs to be set before org.el is loaded.
1532 This really should not be used, it does not make sense, and the
1533 implementation is bad."
1534 :group 'org-link-follow
1535 :type 'boolean)
1537 (defcustom org-return-follows-link nil
1538 "Non-nil means on links RET will follow the link."
1539 :group 'org-link-follow
1540 :type 'boolean)
1542 (defcustom org-mouse-1-follows-link
1543 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1544 "Non-nil means mouse-1 on a link will follow the link.
1545 A longer mouse click will still set point. Does not work on XEmacs.
1546 Needs to be set before org.el is loaded."
1547 :group 'org-link-follow
1548 :type 'boolean)
1550 (defcustom org-mark-ring-length 4
1551 "Number of different positions to be recorded in the ring.
1552 Changing this requires a restart of Emacs to work correctly."
1553 :group 'org-link-follow
1554 :type 'integer)
1556 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1557 "Non-nil means internal links in Org files must exactly match a headline.
1558 When nil, the link search tries to match a phrase with all words
1559 in the search text."
1560 :group 'org-link-follow
1561 :version "24.1"
1562 :type '(choice
1563 (const :tag "Use fuzzy text search" nil)
1564 (const :tag "Match only exact headline" t)
1565 (const :tag "Match exact headline or query to create it"
1566 query-to-create)))
1568 (defcustom org-link-frame-setup
1569 '((vm . vm-visit-folder-other-frame)
1570 (vm-imap . vm-visit-imap-folder-other-frame)
1571 (gnus . org-gnus-no-new-news)
1572 (file . find-file-other-window)
1573 (wl . wl-other-frame))
1574 "Setup the frame configuration for following links.
1575 When following a link with Emacs, it may often be useful to display
1576 this link in another window or frame. This variable can be used to
1577 set this up for the different types of links.
1578 For VM, use any of
1579 `vm-visit-folder'
1580 `vm-visit-folder-other-window'
1581 `vm-visit-folder-other-frame'
1582 For Gnus, use any of
1583 `gnus'
1584 `gnus-other-frame'
1585 `org-gnus-no-new-news'
1586 For FILE, use any of
1587 `find-file'
1588 `find-file-other-window'
1589 `find-file-other-frame'
1590 For Wanderlust use any of
1591 `wl'
1592 `wl-other-frame'
1593 For the calendar, use the variable `calendar-setup'.
1594 For BBDB, it is currently only possible to display the matches in
1595 another window."
1596 :group 'org-link-follow
1597 :type '(list
1598 (cons (const vm)
1599 (choice
1600 (const vm-visit-folder)
1601 (const vm-visit-folder-other-window)
1602 (const vm-visit-folder-other-frame)))
1603 (cons (const gnus)
1604 (choice
1605 (const gnus)
1606 (const gnus-other-frame)
1607 (const org-gnus-no-new-news)))
1608 (cons (const file)
1609 (choice
1610 (const find-file)
1611 (const find-file-other-window)
1612 (const find-file-other-frame)))
1613 (cons (const wl)
1614 (choice
1615 (const wl)
1616 (const wl-other-frame)))))
1618 (defcustom org-display-internal-link-with-indirect-buffer nil
1619 "Non-nil means use indirect buffer to display infile links.
1620 Activating internal links (from one location in a file to another location
1621 in the same file) normally just jumps to the location. When the link is
1622 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1623 is displayed in
1624 another window. When this option is set, the other window actually displays
1625 an indirect buffer clone of the current buffer, to avoid any visibility
1626 changes to the current buffer."
1627 :group 'org-link-follow
1628 :type 'boolean)
1630 (defcustom org-open-non-existing-files nil
1631 "Non-nil means `org-open-file' will open non-existing files.
1632 When nil, an error will be generated.
1633 This variable applies only to external applications because they
1634 might choke on non-existing files. If the link is to a file that
1635 will be opened in Emacs, the variable is ignored."
1636 :group 'org-link-follow
1637 :type 'boolean)
1639 (defcustom org-open-directory-means-index-dot-org nil
1640 "Non-nil means a link to a directory really means to index.org.
1641 When nil, following a directory link will run dired or open a finder/explorer
1642 window on that directory."
1643 :group 'org-link-follow
1644 :type 'boolean)
1646 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1647 "Function and arguments to call for following mailto links.
1648 This is a list with the first element being a Lisp function, and the
1649 remaining elements being arguments to the function. In string arguments,
1650 %a will be replaced by the address, and %s will be replaced by the subject
1651 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1652 :group 'org-link-follow
1653 :type '(choice
1654 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1655 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1656 (const :tag "message-mail" (message-mail "%a" "%s"))
1657 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1659 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1660 "Non-nil means ask for confirmation before executing shell links.
1661 Shell links can be dangerous: just think about a link
1663 [[shell:rm -rf ~/*][Google Search]]
1665 This link would show up in your Org-mode document as \"Google Search\",
1666 but really it would remove your entire home directory.
1667 Therefore we advise against setting this variable to nil.
1668 Just change it to `y-or-n-p' if you want to confirm with a
1669 single keystroke rather than having to type \"yes\"."
1670 :group 'org-link-follow
1671 :type '(choice
1672 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1673 (const :tag "with y-or-n (faster)" y-or-n-p)
1674 (const :tag "no confirmation (dangerous)" nil)))
1675 (put 'org-confirm-shell-link-function
1676 'safe-local-variable
1677 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1679 (defcustom org-confirm-shell-link-not-regexp ""
1680 "A regexp to skip confirmation for shell links."
1681 :group 'org-link-follow
1682 :version "24.1"
1683 :type 'regexp)
1685 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1686 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1687 Elisp links can be dangerous: just think about a link
1689 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1691 This link would show up in your Org-mode document as \"Google Search\",
1692 but really it would remove your entire home directory.
1693 Therefore we advise against setting this variable to nil.
1694 Just change it to `y-or-n-p' if you want to confirm with a
1695 single keystroke rather than having to type \"yes\"."
1696 :group 'org-link-follow
1697 :type '(choice
1698 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1699 (const :tag "with y-or-n (faster)" y-or-n-p)
1700 (const :tag "no confirmation (dangerous)" nil)))
1701 (put 'org-confirm-shell-link-function
1702 'safe-local-variable
1703 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1705 (defcustom org-confirm-elisp-link-not-regexp ""
1706 "A regexp to skip confirmation for Elisp links."
1707 :group 'org-link-follow
1708 :version "24.1"
1709 :type 'regexp)
1711 (defconst org-file-apps-defaults-gnu
1712 '((remote . emacs)
1713 (system . mailcap)
1714 (t . mailcap))
1715 "Default file applications on a UNIX or GNU/Linux system.
1716 See `org-file-apps'.")
1718 (defconst org-file-apps-defaults-macosx
1719 '((remote . emacs)
1720 (t . "open %s")
1721 (system . "open %s")
1722 ("ps.gz" . "gv %s")
1723 ("eps.gz" . "gv %s")
1724 ("dvi" . "xdvi %s")
1725 ("fig" . "xfig %s"))
1726 "Default file applications on a MacOS X system.
1727 The system \"open\" is known as a default, but we use X11 applications
1728 for some files for which the OS does not have a good default.
1729 See `org-file-apps'.")
1731 (defconst org-file-apps-defaults-windowsnt
1732 (list
1733 '(remote . emacs)
1734 (cons t
1735 (list (if (featurep 'xemacs)
1736 'mswindows-shell-execute
1737 'w32-shell-execute)
1738 "open" 'file))
1739 (cons 'system
1740 (list (if (featurep 'xemacs)
1741 'mswindows-shell-execute
1742 'w32-shell-execute)
1743 "open" 'file)))
1744 "Default file applications on a Windows NT system.
1745 The system \"open\" is used for most files.
1746 See `org-file-apps'.")
1748 (defcustom org-file-apps
1750 (auto-mode . emacs)
1751 ("\\.mm\\'" . default)
1752 ("\\.x?html?\\'" . default)
1753 ("\\.pdf\\'" . default)
1755 "External applications for opening `file:path' items in a document.
1756 Org-mode uses system defaults for different file types, but
1757 you can use this variable to set the application for a given file
1758 extension. The entries in this list are cons cells where the car identifies
1759 files and the cdr the corresponding command. Possible values for the
1760 file identifier are
1761 \"string\" A string as a file identifier can be interpreted in different
1762 ways, depending on its contents:
1764 - Alphanumeric characters only:
1765 Match links with this file extension.
1766 Example: (\"pdf\" . \"evince %s\")
1767 to open PDFs with evince.
1769 - Regular expression: Match links where the
1770 filename matches the regexp. If you want to
1771 use groups here, use shy groups.
1773 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1774 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1775 to open *.html and *.xhtml with firefox.
1777 - Regular expression which contains (non-shy) groups:
1778 Match links where the whole link, including \"::\", and
1779 anything after that, matches the regexp.
1780 In a custom command string, %1, %2, etc. are replaced with
1781 the parts of the link that were matched by the groups.
1782 For backwards compatibility, if a command string is given
1783 that does not use any of the group matches, this case is
1784 handled identically to the second one (i.e. match against
1785 file name only).
1786 In a custom lisp form, you can access the group matches with
1787 (match-string n link).
1789 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1790 to open [[file:document.pdf::5]] with evince at page 5.
1792 `directory' Matches a directory
1793 `remote' Matches a remote file, accessible through tramp or efs.
1794 Remote files most likely should be visited through Emacs
1795 because external applications cannot handle such paths.
1796 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1797 so all files Emacs knows how to handle. Using this with
1798 command `emacs' will open most files in Emacs. Beware that this
1799 will also open html files inside Emacs, unless you add
1800 (\"html\" . default) to the list as well.
1801 t Default for files not matched by any of the other options.
1802 `system' The system command to open files, like `open' on Windows
1803 and Mac OS X, and mailcap under GNU/Linux. This is the command
1804 that will be selected if you call `C-c C-o' with a double
1805 \\[universal-argument] \\[universal-argument] prefix.
1807 Possible values for the command are:
1808 `emacs' The file will be visited by the current Emacs process.
1809 `default' Use the default application for this file type, which is the
1810 association for t in the list, most likely in the system-specific
1811 part.
1812 This can be used to overrule an unwanted setting in the
1813 system-specific variable.
1814 `system' Use the system command for opening files, like \"open\".
1815 This command is specified by the entry whose car is `system'.
1816 Most likely, the system-specific version of this variable
1817 does define this command, but you can overrule/replace it
1818 here.
1819 string A command to be executed by a shell; %s will be replaced
1820 by the path to the file.
1821 sexp A Lisp form which will be evaluated. The file path will
1822 be available in the Lisp variable `file'.
1823 For more examples, see the system specific constants
1824 `org-file-apps-defaults-macosx'
1825 `org-file-apps-defaults-windowsnt'
1826 `org-file-apps-defaults-gnu'."
1827 :group 'org-link-follow
1828 :type '(repeat
1829 (cons (choice :value ""
1830 (string :tag "Extension")
1831 (const :tag "System command to open files" system)
1832 (const :tag "Default for unrecognized files" t)
1833 (const :tag "Remote file" remote)
1834 (const :tag "Links to a directory" directory)
1835 (const :tag "Any files that have Emacs modes"
1836 auto-mode))
1837 (choice :value ""
1838 (const :tag "Visit with Emacs" emacs)
1839 (const :tag "Use default" default)
1840 (const :tag "Use the system command" system)
1841 (string :tag "Command")
1842 (sexp :tag "Lisp form")))))
1844 (defcustom org-doi-server-url "http://dx.doi.org/"
1845 "The URL of the DOI server."
1846 :type 'string
1847 :version "24.3"
1848 :group 'org-link-follow)
1850 (defgroup org-refile nil
1851 "Options concerning refiling entries in Org-mode."
1852 :tag "Org Refile"
1853 :group 'org)
1855 (defcustom org-directory "~/org"
1856 "Directory with org files.
1857 This is just a default location to look for Org files. There is no need
1858 at all to put your files into this directory. It is only used in the
1859 following situations:
1861 1. When a capture template specifies a target file that is not an
1862 absolute path. The path will then be interpreted relative to
1863 `org-directory'
1864 2. When a capture note is filed away in an interactive way (when exiting the
1865 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1866 with `org-directory' as the default path."
1867 :group 'org-refile
1868 :group 'org-remember
1869 :group 'org-capture
1870 :type 'directory)
1872 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1873 "Default target for storing notes.
1874 Used as a fall back file for org-remember.el and org-capture.el, for
1875 templates that do not specify a target file."
1876 :group 'org-refile
1877 :group 'org-remember
1878 :group 'org-capture
1879 :type '(choice
1880 (const :tag "Default from remember-data-file" nil)
1881 file))
1883 (defcustom org-goto-interface 'outline
1884 "The default interface to be used for `org-goto'.
1885 Allowed values are:
1886 outline The interface shows an outline of the relevant file
1887 and the correct heading is found by moving through
1888 the outline or by searching with incremental search.
1889 outline-path-completion Headlines in the current buffer are offered via
1890 completion. This is the interface also used by
1891 the refile command."
1892 :group 'org-refile
1893 :type '(choice
1894 (const :tag "Outline" outline)
1895 (const :tag "Outline-path-completion" outline-path-completion)))
1897 (defcustom org-goto-max-level 5
1898 "Maximum target level when running `org-goto' with refile interface."
1899 :group 'org-refile
1900 :type 'integer)
1902 (defcustom org-reverse-note-order nil
1903 "Non-nil means store new notes at the beginning of a file or entry.
1904 When nil, new notes will be filed to the end of a file or entry.
1905 This can also be a list with cons cells of regular expressions that
1906 are matched against file names, and values."
1907 :group 'org-remember
1908 :group 'org-capture
1909 :group 'org-refile
1910 :type '(choice
1911 (const :tag "Reverse always" t)
1912 (const :tag "Reverse never" nil)
1913 (repeat :tag "By file name regexp"
1914 (cons regexp boolean))))
1916 (defcustom org-log-refile nil
1917 "Information to record when a task is refiled.
1919 Possible values are:
1921 nil Don't add anything
1922 time Add a time stamp to the task
1923 note Prompt for a note and add it with template `org-log-note-headings'
1925 This option can also be set with on a per-file-basis with
1927 #+STARTUP: nologrefile
1928 #+STARTUP: logrefile
1929 #+STARTUP: lognoterefile
1931 You can have local logging settings for a subtree by setting the LOGGING
1932 property to one or more of these keywords.
1934 When bulk-refiling from the agenda, the value `note' is forbidden and
1935 will temporarily be changed to `time'."
1936 :group 'org-refile
1937 :group 'org-progress
1938 :version "24.1"
1939 :type '(choice
1940 (const :tag "No logging" nil)
1941 (const :tag "Record timestamp" time)
1942 (const :tag "Record timestamp with note." note)))
1944 (defcustom org-refile-targets nil
1945 "Targets for refiling entries with \\[org-refile].
1946 This is a list of cons cells. Each cell contains:
1947 - a specification of the files to be considered, either a list of files,
1948 or a symbol whose function or variable value will be used to retrieve
1949 a file name or a list of file names. If you use `org-agenda-files' for
1950 that, all agenda files will be scanned for targets. Nil means consider
1951 headings in the current buffer.
1952 - A specification of how to find candidate refile targets. This may be
1953 any of:
1954 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1955 This tag has to be present in all target headlines, inheritance will
1956 not be considered.
1957 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1958 todo keyword.
1959 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1960 headlines that are refiling targets.
1961 - a cons cell (:level . N). Any headline of level N is considered a target.
1962 Note that, when `org-odd-levels-only' is set, level corresponds to
1963 order in hierarchy, not to the number of stars.
1964 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1965 Note that, when `org-odd-levels-only' is set, level corresponds to
1966 order in hierarchy, not to the number of stars.
1968 Each element of this list generates a set of possible targets.
1969 The union of these sets is presented (with completion) to
1970 the user by `org-refile'.
1972 You can set the variable `org-refile-target-verify-function' to a function
1973 to verify each headline found by the simple criteria above.
1975 When this variable is nil, all top-level headlines in the current buffer
1976 are used, equivalent to the value `((nil . (:level . 1))'."
1977 :group 'org-refile
1978 :type '(repeat
1979 (cons
1980 (choice :value org-agenda-files
1981 (const :tag "All agenda files" org-agenda-files)
1982 (const :tag "Current buffer" nil)
1983 (function) (variable) (file))
1984 (choice :tag "Identify target headline by"
1985 (cons :tag "Specific tag" (const :value :tag) (string))
1986 (cons :tag "TODO keyword" (const :value :todo) (string))
1987 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1988 (cons :tag "Level number" (const :value :level) (integer))
1989 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1991 (defcustom org-refile-target-verify-function nil
1992 "Function to verify if the headline at point should be a refile target.
1993 The function will be called without arguments, with point at the
1994 beginning of the headline. It should return t and leave point
1995 where it is if the headline is a valid target for refiling.
1997 If the target should not be selected, the function must return nil.
1998 In addition to this, it may move point to a place from where the search
1999 should be continued. For example, the function may decide that the entire
2000 subtree of the current entry should be excluded and move point to the end
2001 of the subtree."
2002 :group 'org-refile
2003 :type 'function)
2005 (defcustom org-refile-use-cache nil
2006 "Non-nil means cache refile targets to speed up the process.
2007 The cache for a particular file will be updated automatically when
2008 the buffer has been killed, or when any of the marker used for flagging
2009 refile targets no longer points at a live buffer.
2010 If you have added new entries to a buffer that might themselves be targets,
2011 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2012 find that easier, `C-u C-u C-u C-c C-w'."
2013 :group 'org-refile
2014 :version "24.1"
2015 :type 'boolean)
2017 (defcustom org-refile-use-outline-path nil
2018 "Non-nil means provide refile targets as paths.
2019 So a level 3 headline will be available as level1/level2/level3.
2021 When the value is `file', also include the file name (without directory)
2022 into the path. In this case, you can also stop the completion after
2023 the file name, to get entries inserted as top level in the file.
2025 When `full-file-path', include the full file path."
2026 :group 'org-refile
2027 :type '(choice
2028 (const :tag "Not" nil)
2029 (const :tag "Yes" t)
2030 (const :tag "Start with file name" file)
2031 (const :tag "Start with full file path" full-file-path)))
2033 (defcustom org-outline-path-complete-in-steps t
2034 "Non-nil means complete the outline path in hierarchical steps.
2035 When Org-mode uses the refile interface to select an outline path
2036 \(see variable `org-refile-use-outline-path'), the completion of
2037 the path can be done is a single go, or if can be done in steps down
2038 the headline hierarchy. Going in steps is probably the best if you
2039 do not use a special completion package like `ido' or `icicles'.
2040 However, when using these packages, going in one step can be very
2041 fast, while still showing the whole path to the entry."
2042 :group 'org-refile
2043 :type 'boolean)
2045 (defcustom org-refile-allow-creating-parent-nodes nil
2046 "Non-nil means allow to create new nodes as refile targets.
2047 New nodes are then created by adding \"/new node name\" to the completion
2048 of an existing node. When the value of this variable is `confirm',
2049 new node creation must be confirmed by the user (recommended)
2050 When nil, the completion must match an existing entry.
2052 Note that, if the new heading is not seen by the criteria
2053 listed in `org-refile-targets', multiple instances of the same
2054 heading would be created by trying again to file under the new
2055 heading."
2056 :group 'org-refile
2057 :type '(choice
2058 (const :tag "Never" nil)
2059 (const :tag "Always" t)
2060 (const :tag "Prompt for confirmation" confirm)))
2062 (defcustom org-refile-active-region-within-subtree nil
2063 "Non-nil means also refile active region within a subtree.
2065 By default `org-refile' doesn't allow refiling regions if they
2066 don't contain a set of subtrees, but it might be convenient to
2067 do so sometimes: in that case, the first line of the region is
2068 converted to a headline before refiling."
2069 :group 'org-refile
2070 :version "24.1"
2071 :type 'boolean)
2073 (defgroup org-todo nil
2074 "Options concerning TODO items in Org-mode."
2075 :tag "Org TODO"
2076 :group 'org)
2078 (defgroup org-progress nil
2079 "Options concerning Progress logging in Org-mode."
2080 :tag "Org Progress"
2081 :group 'org-time)
2083 (defvar org-todo-interpretation-widgets
2084 '((:tag "Sequence (cycling hits every state)" sequence)
2085 (:tag "Type (cycling directly to DONE)" type))
2086 "The available interpretation symbols for customizing `org-todo-keywords'.
2087 Interested libraries should add to this list.")
2089 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2090 "List of TODO entry keyword sequences and their interpretation.
2091 \\<org-mode-map>This is a list of sequences.
2093 Each sequence starts with a symbol, either `sequence' or `type',
2094 indicating if the keywords should be interpreted as a sequence of
2095 action steps, or as different types of TODO items. The first
2096 keywords are states requiring action - these states will select a headline
2097 for inclusion into the global TODO list Org-mode produces. If one of
2098 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2099 signify that no further action is necessary. If \"|\" is not found,
2100 the last keyword is treated as the only DONE state of the sequence.
2102 The command \\[org-todo] cycles an entry through these states, and one
2103 additional state where no keyword is present. For details about this
2104 cycling, see the manual.
2106 TODO keywords and interpretation can also be set on a per-file basis with
2107 the special #+SEQ_TODO and #+TYP_TODO lines.
2109 Each keyword can optionally specify a character for fast state selection
2110 \(in combination with the variable `org-use-fast-todo-selection')
2111 and specifiers for state change logging, using the same syntax that
2112 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2113 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2114 indicates to record a time stamp each time this state is selected.
2116 Each keyword may also specify if a timestamp or a note should be
2117 recorded when entering or leaving the state, by adding additional
2118 characters in the parenthesis after the keyword. This looks like this:
2119 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2120 record only the time of the state change. With X and Y being either
2121 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2122 Y when leaving the state if and only if the *target* state does not
2123 define X. You may omit any of the fast-selection key or X or /Y,
2124 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2126 For backward compatibility, this variable may also be just a list
2127 of keywords. In this case the interpretation (sequence or type) will be
2128 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2129 :group 'org-todo
2130 :group 'org-keywords
2131 :type '(choice
2132 (repeat :tag "Old syntax, just keywords"
2133 (string :tag "Keyword"))
2134 (repeat :tag "New syntax"
2135 (cons
2136 (choice
2137 :tag "Interpretation"
2138 ;;Quick and dirty way to see
2139 ;;`org-todo-interpretations'. This takes the
2140 ;;place of item arguments
2141 :convert-widget
2142 (lambda (widget)
2143 (widget-put widget
2144 :args (mapcar
2145 #'(lambda (x)
2146 (widget-convert
2147 (cons 'const x)))
2148 org-todo-interpretation-widgets))
2149 widget))
2150 (repeat
2151 (string :tag "Keyword"))))))
2153 (defvar org-todo-keywords-1 nil
2154 "All TODO and DONE keywords active in a buffer.")
2155 (make-variable-buffer-local 'org-todo-keywords-1)
2156 (defvar org-todo-keywords-for-agenda nil)
2157 (defvar org-done-keywords-for-agenda nil)
2158 (defvar org-drawers-for-agenda nil)
2159 (defvar org-todo-keyword-alist-for-agenda nil)
2160 (defvar org-tag-alist-for-agenda nil)
2161 (defvar org-agenda-contributing-files nil)
2162 (defvar org-not-done-keywords nil)
2163 (make-variable-buffer-local 'org-not-done-keywords)
2164 (defvar org-done-keywords nil)
2165 (make-variable-buffer-local 'org-done-keywords)
2166 (defvar org-todo-heads nil)
2167 (make-variable-buffer-local 'org-todo-heads)
2168 (defvar org-todo-sets nil)
2169 (make-variable-buffer-local 'org-todo-sets)
2170 (defvar org-todo-log-states nil)
2171 (make-variable-buffer-local 'org-todo-log-states)
2172 (defvar org-todo-kwd-alist nil)
2173 (make-variable-buffer-local 'org-todo-kwd-alist)
2174 (defvar org-todo-key-alist nil)
2175 (make-variable-buffer-local 'org-todo-key-alist)
2176 (defvar org-todo-key-trigger nil)
2177 (make-variable-buffer-local 'org-todo-key-trigger)
2179 (defcustom org-todo-interpretation 'sequence
2180 "Controls how TODO keywords are interpreted.
2181 This variable is in principle obsolete and is only used for
2182 backward compatibility, if the interpretation of todo keywords is
2183 not given already in `org-todo-keywords'. See that variable for
2184 more information."
2185 :group 'org-todo
2186 :group 'org-keywords
2187 :type '(choice (const sequence)
2188 (const type)))
2190 (defcustom org-use-fast-todo-selection t
2191 "Non-nil means use the fast todo selection scheme with C-c C-t.
2192 This variable describes if and under what circumstances the cycling
2193 mechanism for TODO keywords will be replaced by a single-key, direct
2194 selection scheme.
2196 When nil, fast selection is never used.
2198 When the symbol `prefix', it will be used when `org-todo' is called
2199 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2200 `C-u t' in an agenda buffer.
2202 When t, fast selection is used by default. In this case, the prefix
2203 argument forces cycling instead.
2205 In all cases, the special interface is only used if access keys have
2206 actually been assigned by the user, i.e. if keywords in the configuration
2207 are followed by a letter in parenthesis, like TODO(t)."
2208 :group 'org-todo
2209 :type '(choice
2210 (const :tag "Never" nil)
2211 (const :tag "By default" t)
2212 (const :tag "Only with C-u C-c C-t" prefix)))
2214 (defcustom org-provide-todo-statistics t
2215 "Non-nil means update todo statistics after insert and toggle.
2216 ALL-HEADLINES means update todo statistics by including headlines
2217 with no TODO keyword as well, counting them as not done.
2218 A list of TODO keywords means the same, but skip keywords that are
2219 not in this list.
2221 When this is set, todo statistics is updated in the parent of the
2222 current entry each time a todo state is changed."
2223 :group 'org-todo
2224 :type '(choice
2225 (const :tag "Yes, only for TODO entries" t)
2226 (const :tag "Yes, including all entries" 'all-headlines)
2227 (repeat :tag "Yes, for TODOs in this list"
2228 (string :tag "TODO keyword"))
2229 (other :tag "No TODO statistics" nil)))
2231 (defcustom org-hierarchical-todo-statistics t
2232 "Non-nil means TODO statistics covers just direct children.
2233 When nil, all entries in the subtree are considered.
2234 This has only an effect if `org-provide-todo-statistics' is set.
2235 To set this to nil for only a single subtree, use a COOKIE_DATA
2236 property and include the word \"recursive\" into the value."
2237 :group 'org-todo
2238 :type 'boolean)
2240 (defcustom org-after-todo-state-change-hook nil
2241 "Hook which is run after the state of a TODO item was changed.
2242 The new state (a string with a TODO keyword, or nil) is available in the
2243 Lisp variable `org-state'."
2244 :group 'org-todo
2245 :type 'hook)
2247 (defvar org-blocker-hook nil
2248 "Hook for functions that are allowed to block a state change.
2250 Functions in this hook should not modify the buffer.
2251 Each function gets as its single argument a property list,
2252 see `org-trigger-hook' for more information about this list.
2254 If any of the functions in this hook returns nil, the state change
2255 is blocked.")
2257 (defvar org-trigger-hook nil
2258 "Hook for functions that are triggered by a state change.
2260 Each function gets as its single argument a property list with at
2261 least the following elements:
2263 (:type type-of-change :position pos-at-entry-start
2264 :from old-state :to new-state)
2266 Depending on the type, more properties may be present.
2268 This mechanism is currently implemented for:
2270 TODO state changes
2271 ------------------
2272 :type todo-state-change
2273 :from previous state (keyword as a string), or nil, or a symbol
2274 'todo' or 'done', to indicate the general type of state.
2275 :to new state, like in :from")
2277 (defcustom org-enforce-todo-dependencies nil
2278 "Non-nil means undone TODO entries will block switching the parent to DONE.
2279 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2280 be blocked if any prior sibling is not yet done.
2281 Finally, if the parent is blocked because of ordered siblings of its own,
2282 the child will also be blocked."
2283 :set (lambda (var val)
2284 (set var val)
2285 (if val
2286 (add-hook 'org-blocker-hook
2287 'org-block-todo-from-children-or-siblings-or-parent)
2288 (remove-hook 'org-blocker-hook
2289 'org-block-todo-from-children-or-siblings-or-parent)))
2290 :group 'org-todo
2291 :type 'boolean)
2293 (defcustom org-enforce-todo-checkbox-dependencies nil
2294 "Non-nil means unchecked boxes will block switching the parent to DONE.
2295 When this is nil, checkboxes have no influence on switching TODO states.
2296 When non-nil, you first need to check off all check boxes before the TODO
2297 entry can be switched to DONE.
2298 This variable needs to be set before org.el is loaded, and you need to
2299 restart Emacs after a change to make the change effective. The only way
2300 to change is while Emacs is running is through the customize interface."
2301 :set (lambda (var val)
2302 (set var val)
2303 (if val
2304 (add-hook 'org-blocker-hook
2305 'org-block-todo-from-checkboxes)
2306 (remove-hook 'org-blocker-hook
2307 'org-block-todo-from-checkboxes)))
2308 :group 'org-todo
2309 :type 'boolean)
2311 (defcustom org-treat-insert-todo-heading-as-state-change nil
2312 "Non-nil means inserting a TODO heading is treated as state change.
2313 So when the command \\[org-insert-todo-heading] is used, state change
2314 logging will apply if appropriate. When nil, the new TODO item will
2315 be inserted directly, and no logging will take place."
2316 :group 'org-todo
2317 :type 'boolean)
2319 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2320 "Non-nil means switching TODO states with S-cursor counts as state change.
2321 This is the default behavior. However, setting this to nil allows a
2322 convenient way to select a TODO state and bypass any logging associated
2323 with that."
2324 :group 'org-todo
2325 :type 'boolean)
2327 (defcustom org-todo-state-tags-triggers nil
2328 "Tag changes that should be triggered by TODO state changes.
2329 This is a list. Each entry is
2331 (state-change (tag . flag) .......)
2333 State-change can be a string with a state, and empty string to indicate the
2334 state that has no TODO keyword, or it can be one of the symbols `todo'
2335 or `done', meaning any not-done or done state, respectively."
2336 :group 'org-todo
2337 :group 'org-tags
2338 :type '(repeat
2339 (cons (choice :tag "When changing to"
2340 (const :tag "Not-done state" todo)
2341 (const :tag "Done state" done)
2342 (string :tag "State"))
2343 (repeat
2344 (cons :tag "Tag action"
2345 (string :tag "Tag")
2346 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2348 (defcustom org-log-done nil
2349 "Information to record when a task moves to the DONE state.
2351 Possible values are:
2353 nil Don't add anything, just change the keyword
2354 time Add a time stamp to the task
2355 note Prompt for a note and add it with template `org-log-note-headings'
2357 This option can also be set with on a per-file-basis with
2359 #+STARTUP: nologdone
2360 #+STARTUP: logdone
2361 #+STARTUP: lognotedone
2363 You can have local logging settings for a subtree by setting the LOGGING
2364 property to one or more of these keywords."
2365 :group 'org-todo
2366 :group 'org-progress
2367 :type '(choice
2368 (const :tag "No logging" nil)
2369 (const :tag "Record CLOSED timestamp" time)
2370 (const :tag "Record CLOSED timestamp with note." note)))
2372 ;; Normalize old uses of org-log-done.
2373 (cond
2374 ((eq org-log-done t) (setq org-log-done 'time))
2375 ((and (listp org-log-done) (memq 'done org-log-done))
2376 (setq org-log-done 'note)))
2378 (defcustom org-log-reschedule nil
2379 "Information to record when the scheduling date of a tasks is modified.
2381 Possible values are:
2383 nil Don't add anything, just change the date
2384 time Add a time stamp to the task
2385 note Prompt for a note and add it with template `org-log-note-headings'
2387 This option can also be set with on a per-file-basis with
2389 #+STARTUP: nologreschedule
2390 #+STARTUP: logreschedule
2391 #+STARTUP: lognotereschedule"
2392 :group 'org-todo
2393 :group 'org-progress
2394 :type '(choice
2395 (const :tag "No logging" nil)
2396 (const :tag "Record timestamp" time)
2397 (const :tag "Record timestamp with note." note)))
2399 (defcustom org-log-redeadline nil
2400 "Information to record when the deadline date of a tasks is modified.
2402 Possible values are:
2404 nil Don't add anything, just change the date
2405 time Add a time stamp to the task
2406 note Prompt for a note and add it with template `org-log-note-headings'
2408 This option can also be set with on a per-file-basis with
2410 #+STARTUP: nologredeadline
2411 #+STARTUP: logredeadline
2412 #+STARTUP: lognoteredeadline
2414 You can have local logging settings for a subtree by setting the LOGGING
2415 property to one or more of these keywords."
2416 :group 'org-todo
2417 :group 'org-progress
2418 :type '(choice
2419 (const :tag "No logging" nil)
2420 (const :tag "Record timestamp" time)
2421 (const :tag "Record timestamp with note." note)))
2423 (defcustom org-log-note-clock-out nil
2424 "Non-nil means record a note when clocking out of an item.
2425 This can also be configured on a per-file basis by adding one of
2426 the following lines anywhere in the buffer:
2428 #+STARTUP: lognoteclock-out
2429 #+STARTUP: nolognoteclock-out"
2430 :group 'org-todo
2431 :group 'org-progress
2432 :type 'boolean)
2434 (defcustom org-log-done-with-time t
2435 "Non-nil means the CLOSED time stamp will contain date and time.
2436 When nil, only the date will be recorded."
2437 :group 'org-progress
2438 :type 'boolean)
2440 (defcustom org-log-note-headings
2441 '((done . "CLOSING NOTE %t")
2442 (state . "State %-12s from %-12S %t")
2443 (note . "Note taken on %t")
2444 (reschedule . "Rescheduled from %S on %t")
2445 (delschedule . "Not scheduled, was %S on %t")
2446 (redeadline . "New deadline from %S on %t")
2447 (deldeadline . "Removed deadline, was %S on %t")
2448 (refile . "Refiled on %t")
2449 (clock-out . ""))
2450 "Headings for notes added to entries.
2451 The value is an alist, with the car being a symbol indicating the note
2452 context, and the cdr is the heading to be used. The heading may also be the
2453 empty string.
2454 %t in the heading will be replaced by a time stamp.
2455 %T will be an active time stamp instead the default inactive one
2456 %d will be replaced by a short-format time stamp.
2457 %D will be replaced by an active short-format time stamp.
2458 %s will be replaced by the new TODO state, in double quotes.
2459 %S will be replaced by the old TODO state, in double quotes.
2460 %u will be replaced by the user name.
2461 %U will be replaced by the full user name.
2463 In fact, it is not a good idea to change the `state' entry, because
2464 agenda log mode depends on the format of these entries."
2465 :group 'org-todo
2466 :group 'org-progress
2467 :type '(list :greedy t
2468 (cons (const :tag "Heading when closing an item" done) string)
2469 (cons (const :tag
2470 "Heading when changing todo state (todo sequence only)"
2471 state) string)
2472 (cons (const :tag "Heading when just taking a note" note) string)
2473 (cons (const :tag "Heading when clocking out" clock-out) string)
2474 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2475 (cons (const :tag "Heading when rescheduling" reschedule) string)
2476 (cons (const :tag "Heading when changing deadline" redeadline) string)
2477 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2478 (cons (const :tag "Heading when refiling" refile) string)))
2480 (unless (assq 'note org-log-note-headings)
2481 (push '(note . "%t") org-log-note-headings))
2483 (defcustom org-log-into-drawer nil
2484 "Non-nil means insert state change notes and time stamps into a drawer.
2485 When nil, state changes notes will be inserted after the headline and
2486 any scheduling and clock lines, but not inside a drawer.
2488 The value of this variable should be the name of the drawer to use.
2489 LOGBOOK is proposed as the default drawer for this purpose, you can
2490 also set this to a string to define the drawer of your choice.
2492 A value of t is also allowed, representing \"LOGBOOK\".
2494 If this variable is set, `org-log-state-notes-insert-after-drawers'
2495 will be ignored.
2497 You can set the property LOG_INTO_DRAWER to overrule this setting for
2498 a subtree."
2499 :group 'org-todo
2500 :group 'org-progress
2501 :type '(choice
2502 (const :tag "Not into a drawer" nil)
2503 (const :tag "LOGBOOK" t)
2504 (string :tag "Other")))
2506 (if (fboundp 'defvaralias)
2507 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2509 (defun org-log-into-drawer ()
2510 "Return the value of `org-log-into-drawer', but let properties overrule.
2511 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2512 used instead of the default value."
2513 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2514 (cond
2515 ((not p) org-log-into-drawer)
2516 ((equal p "nil") nil)
2517 ((equal p "t") "LOGBOOK")
2518 (t p))))
2520 (defcustom org-log-state-notes-insert-after-drawers nil
2521 "Non-nil means insert state change notes after any drawers in entry.
2522 Only the drawers that *immediately* follow the headline and the
2523 deadline/scheduled line are skipped.
2524 When nil, insert notes right after the heading and perhaps the line
2525 with deadline/scheduling if present.
2527 This variable will have no effect if `org-log-into-drawer' is
2528 set."
2529 :group 'org-todo
2530 :group 'org-progress
2531 :type 'boolean)
2533 (defcustom org-log-states-order-reversed t
2534 "Non-nil means the latest state note will be directly after heading.
2535 When nil, the state change notes will be ordered according to time."
2536 :group 'org-todo
2537 :group 'org-progress
2538 :type 'boolean)
2540 (defcustom org-todo-repeat-to-state nil
2541 "The TODO state to which a repeater should return the repeating task.
2542 By default this is the first task in a TODO sequence, or the previous state
2543 in a TODO_TYP set. But you can specify another task here.
2544 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2545 :group 'org-todo
2546 :version "24.1"
2547 :type '(choice (const :tag "Head of sequence" nil)
2548 (string :tag "Specific state")))
2550 (defcustom org-log-repeat 'time
2551 "Non-nil means record moving through the DONE state when triggering repeat.
2552 An auto-repeating task is immediately switched back to TODO when
2553 marked DONE. If you are not logging state changes (by adding \"@\"
2554 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2555 record a closing note, there will be no record of the task moving
2556 through DONE. This variable forces taking a note anyway.
2558 nil Don't force a record
2559 time Record a time stamp
2560 note Prompt for a note and add it with template `org-log-note-headings'
2562 This option can also be set with on a per-file-basis with
2564 #+STARTUP: nologrepeat
2565 #+STARTUP: logrepeat
2566 #+STARTUP: lognoterepeat
2568 You can have local logging settings for a subtree by setting the LOGGING
2569 property to one or more of these keywords."
2570 :group 'org-todo
2571 :group 'org-progress
2572 :type '(choice
2573 (const :tag "Don't force a record" nil)
2574 (const :tag "Force recording the DONE state" time)
2575 (const :tag "Force recording a note with the DONE state" note)))
2578 (defgroup org-priorities nil
2579 "Priorities in Org-mode."
2580 :tag "Org Priorities"
2581 :group 'org-todo)
2583 (defcustom org-enable-priority-commands t
2584 "Non-nil means priority commands are active.
2585 When nil, these commands will be disabled, so that you never accidentally
2586 set a priority."
2587 :group 'org-priorities
2588 :type 'boolean)
2590 (defcustom org-highest-priority ?A
2591 "The highest priority of TODO items. A character like ?A, ?B etc.
2592 Must have a smaller ASCII number than `org-lowest-priority'."
2593 :group 'org-priorities
2594 :type 'character)
2596 (defcustom org-lowest-priority ?C
2597 "The lowest priority of TODO items. A character like ?A, ?B etc.
2598 Must have a larger ASCII number than `org-highest-priority'."
2599 :group 'org-priorities
2600 :type 'character)
2602 (defcustom org-default-priority ?B
2603 "The default priority of TODO items.
2604 This is the priority an item gets if no explicit priority is given.
2605 When starting to cycle on an empty priority the first step in the cycle
2606 depends on `org-priority-start-cycle-with-default'. The resulting first
2607 step priority must not exceed the range from `org-highest-priority' to
2608 `org-lowest-priority' which means that `org-default-priority' has to be
2609 in this range exclusive or inclusive the range boundaries. Else the
2610 first step refuses to set the default and the second will fall back
2611 to (depending on the command used) the highest or lowest priority."
2612 :group 'org-priorities
2613 :type 'character)
2615 (defcustom org-priority-start-cycle-with-default t
2616 "Non-nil means start with default priority when starting to cycle.
2617 When this is nil, the first step in the cycle will be (depending on the
2618 command used) one higher or lower than the default priority.
2619 See also `org-default-priority'."
2620 :group 'org-priorities
2621 :type 'boolean)
2623 (defcustom org-get-priority-function nil
2624 "Function to extract the priority from a string.
2625 The string is normally the headline. If this is nil Org computes the
2626 priority from the priority cookie like [#A] in the headline. It returns
2627 an integer, increasing by 1000 for each priority level.
2628 The user can set a different function here, which should take a string
2629 as an argument and return the numeric priority."
2630 :group 'org-priorities
2631 :version "24.1"
2632 :type 'function)
2634 (defgroup org-time nil
2635 "Options concerning time stamps and deadlines in Org-mode."
2636 :tag "Org Time"
2637 :group 'org)
2639 (defcustom org-insert-labeled-timestamps-at-point nil
2640 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2641 When nil, these labeled time stamps are forces into the second line of an
2642 entry, just after the headline. When scheduling from the global TODO list,
2643 the time stamp will always be forced into the second line."
2644 :group 'org-time
2645 :type 'boolean)
2647 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2648 "Formats for `format-time-string' which are used for time stamps.
2649 It is not recommended to change this constant.")
2651 (defcustom org-time-stamp-rounding-minutes '(0 5)
2652 "Number of minutes to round time stamps to.
2653 These are two values, the first applies when first creating a time stamp.
2654 The second applies when changing it with the commands `S-up' and `S-down'.
2655 When changing the time stamp, this means that it will change in steps
2656 of N minutes, as given by the second value.
2658 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2659 numbers should be factors of 60, so for example 5, 10, 15.
2661 When this is larger than 1, you can still force an exact time stamp by using
2662 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2663 and by using a prefix arg to `S-up/down' to specify the exact number
2664 of minutes to shift."
2665 :group 'org-time
2666 :get #'(lambda (var) ; Make sure both elements are there
2667 (if (integerp (default-value var))
2668 (list (default-value var) 5)
2669 (default-value var)))
2670 :type '(list
2671 (integer :tag "when inserting times")
2672 (integer :tag "when modifying times")))
2674 ;; Normalize old customizations of this variable.
2675 (when (integerp org-time-stamp-rounding-minutes)
2676 (setq org-time-stamp-rounding-minutes
2677 (list org-time-stamp-rounding-minutes
2678 org-time-stamp-rounding-minutes)))
2680 (defcustom org-display-custom-times nil
2681 "Non-nil means overlay custom formats over all time stamps.
2682 The formats are defined through the variable `org-time-stamp-custom-formats'.
2683 To turn this on on a per-file basis, insert anywhere in the file:
2684 #+STARTUP: customtime"
2685 :group 'org-time
2686 :set 'set-default
2687 :type 'sexp)
2688 (make-variable-buffer-local 'org-display-custom-times)
2690 (defcustom org-time-stamp-custom-formats
2691 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2692 "Custom formats for time stamps. See `format-time-string' for the syntax.
2693 These are overlaid over the default ISO format if the variable
2694 `org-display-custom-times' is set. Time like %H:%M should be at the
2695 end of the second format. The custom formats are also honored by export
2696 commands, if custom time display is turned on at the time of export."
2697 :group 'org-time
2698 :type 'sexp)
2700 (defun org-time-stamp-format (&optional long inactive)
2701 "Get the right format for a time string."
2702 (let ((f (if long (cdr org-time-stamp-formats)
2703 (car org-time-stamp-formats))))
2704 (if inactive
2705 (concat "[" (substring f 1 -1) "]")
2706 f)))
2708 (defcustom org-time-clocksum-format "%d:%02d"
2709 "The format string used when creating CLOCKSUM lines.
2710 This is also used when org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'string)
2714 (defcustom org-time-clocksum-use-fractional nil
2715 "If non-nil, \\[org-clock-display] uses fractional times.
2716 org-mode generates a time duration."
2717 :group 'org-time
2718 :type 'boolean)
2720 (defcustom org-time-clocksum-fractional-format "%.2f"
2721 "The format string used when creating CLOCKSUM lines, or when
2722 org-mode generates a time duration."
2723 :group 'org-time
2724 :type 'string)
2726 (defcustom org-deadline-warning-days 14
2727 "No. of days before expiration during which a deadline becomes active.
2728 This variable governs the display in sparse trees and in the agenda.
2729 When 0 or negative, it means use this number (the absolute value of it)
2730 even if a deadline has a different individual lead time specified.
2732 Custom commands can set this variable in the options section."
2733 :group 'org-time
2734 :group 'org-agenda-daily/weekly
2735 :type 'integer)
2737 (defcustom org-read-date-prefer-future t
2738 "Non-nil means assume future for incomplete date input from user.
2739 This affects the following situations:
2740 1. The user gives a month but not a year.
2741 For example, if it is April and you enter \"feb 2\", this will be read
2742 as Feb 2, *next* year. \"May 5\", however, will be this year.
2743 2. The user gives a day, but no month.
2744 For example, if today is the 15th, and you enter \"3\", Org-mode will
2745 read this as the third of *next* month. However, if you enter \"17\",
2746 it will be considered as *this* month.
2748 If you set this variable to the symbol `time', then also the following
2749 will work:
2751 3. If the user gives a time.
2752 If the time is before now, it will be interpreted as tomorrow.
2754 Currently none of this works for ISO week specifications.
2756 When this option is nil, the current day, month and year will always be
2757 used as defaults.
2759 See also `org-agenda-jump-prefer-future'."
2760 :group 'org-time
2761 :type '(choice
2762 (const :tag "Never" nil)
2763 (const :tag "Check month and day" t)
2764 (const :tag "Check month, day, and time" time)))
2766 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2767 "Should the agenda jump command prefer the future for incomplete dates?
2768 The default is to do the same as configured in `org-read-date-prefer-future'.
2769 But you can also set a deviating value here.
2770 This may t or nil, or the symbol `org-read-date-prefer-future'."
2771 :group 'org-agenda
2772 :group 'org-time
2773 :version "24.1"
2774 :type '(choice
2775 (const :tag "Use org-read-date-prefer-future"
2776 org-read-date-prefer-future)
2777 (const :tag "Never" nil)
2778 (const :tag "Always" t)))
2780 (defcustom org-read-date-force-compatible-dates t
2781 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2783 Depending on the system Emacs is running on, certain dates cannot
2784 be represented with the type used internally to represent time.
2785 Dates between 1970-1-1 and 2038-1-1 can always be represented
2786 correctly. Some systems allow for earlier dates, some for later,
2787 some for both. One way to find out it to insert any date into an
2788 Org buffer, putting the cursor on the year and hitting S-up and
2789 S-down to test the range.
2791 When this variable is set to t, the date/time prompt will not let
2792 you specify dates outside the 1970-2037 range, so it is certain that
2793 these dates will work in whatever version of Emacs you are
2794 running, and also that you can move a file from one Emacs implementation
2795 to another. WHenever Org is forcing the year for you, it will display
2796 a message and beep.
2798 When this variable is nil, Org will check if the date is
2799 representable in the specific Emacs implementation you are using.
2800 If not, it will force a year, usually the current year, and beep
2801 to remind you. Currently this setting is not recommended because
2802 the likelihood that you will open your Org files in an Emacs that
2803 has limited date range is not negligible.
2805 A workaround for this problem is to use diary sexp dates for time
2806 stamps outside of this range."
2807 :group 'org-time
2808 :version "24.1"
2809 :type 'boolean)
2811 (defcustom org-read-date-display-live t
2812 "Non-nil means display current interpretation of date prompt live.
2813 This display will be in an overlay, in the minibuffer."
2814 :group 'org-time
2815 :type 'boolean)
2817 (defcustom org-read-date-popup-calendar t
2818 "Non-nil means pop up a calendar when prompting for a date.
2819 In the calendar, the date can be selected with mouse-1. However, the
2820 minibuffer will also be active, and you can simply enter the date as well.
2821 When nil, only the minibuffer will be available."
2822 :group 'org-time
2823 :type 'boolean)
2824 (if (fboundp 'defvaralias)
2825 (defvaralias 'org-popup-calendar-for-date-prompt
2826 'org-read-date-popup-calendar))
2828 (defcustom org-read-date-minibuffer-setup-hook nil
2829 "Hook to be used to set up keys for the date/time interface.
2830 Add key definitions to `minibuffer-local-map', which will be a temporary
2831 copy."
2832 :group 'org-time
2833 :type 'hook)
2835 (defcustom org-extend-today-until 0
2836 "The hour when your day really ends. Must be an integer.
2837 This has influence for the following applications:
2838 - When switching the agenda to \"today\". It it is still earlier than
2839 the time given here, the day recognized as TODAY is actually yesterday.
2840 - When a date is read from the user and it is still before the time given
2841 here, the current date and time will be assumed to be yesterday, 23:59.
2842 Also, timestamps inserted in capture templates follow this rule.
2844 IMPORTANT: This is a feature whose implementation is and likely will
2845 remain incomplete. Really, it is only here because past midnight seems to
2846 be the favorite working time of John Wiegley :-)"
2847 :group 'org-time
2848 :type 'integer)
2850 (defcustom org-use-effective-time nil
2851 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2852 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2853 \"effective time\" of any timestamps between midnight and 8am will be
2854 23:59 of the previous day."
2855 :group 'org-time
2856 :version "24.1"
2857 :type 'boolean)
2859 (defcustom org-edit-timestamp-down-means-later nil
2860 "Non-nil means S-down will increase the time in a time stamp.
2861 When nil, S-up will increase."
2862 :group 'org-time
2863 :type 'boolean)
2865 (defcustom org-calendar-follow-timestamp-change t
2866 "Non-nil means make the calendar window follow timestamp changes.
2867 When a timestamp is modified and the calendar window is visible, it will be
2868 moved to the new date."
2869 :group 'org-time
2870 :type 'boolean)
2872 (defgroup org-tags nil
2873 "Options concerning tags in Org-mode."
2874 :tag "Org Tags"
2875 :group 'org)
2877 (defcustom org-tag-alist nil
2878 "List of tags allowed in Org-mode files.
2879 When this list is nil, Org-mode will base TAG input on what is already in the
2880 buffer.
2881 The value of this variable is an alist, the car of each entry must be a
2882 keyword as a string, the cdr may be a character that is used to select
2883 that tag through the fast-tag-selection interface.
2884 See the manual for details."
2885 :group 'org-tags
2886 :type '(repeat
2887 (choice
2888 (cons (string :tag "Tag name")
2889 (character :tag "Access char"))
2890 (list :tag "Start radio group"
2891 (const :startgroup)
2892 (option (string :tag "Group description")))
2893 (list :tag "End radio group"
2894 (const :endgroup)
2895 (option (string :tag "Group description")))
2896 (const :tag "New line" (:newline)))))
2898 (defcustom org-tag-persistent-alist nil
2899 "List of tags that will always appear in all Org-mode files.
2900 This is in addition to any in buffer settings or customizations
2901 of `org-tag-alist'.
2902 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2903 The value of this variable is an alist, the car of each entry must be a
2904 keyword as a string, the cdr may be a character that is used to select
2905 that tag through the fast-tag-selection interface.
2906 See the manual for details.
2907 To disable these tags on a per-file basis, insert anywhere in the file:
2908 #+STARTUP: noptag"
2909 :group 'org-tags
2910 :type '(repeat
2911 (choice
2912 (cons (string :tag "Tag name")
2913 (character :tag "Access char"))
2914 (const :tag "Start radio group" (:startgroup))
2915 (const :tag "End radio group" (:endgroup))
2916 (const :tag "New line" (:newline)))))
2918 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2919 "If non-nil, always offer completion for all tags of all agenda files.
2920 Instead of customizing this variable directly, you might want to
2921 set it locally for capture buffers, because there no list of
2922 tags in that file can be created dynamically (there are none).
2924 (add-hook 'org-capture-mode-hook
2925 (lambda ()
2926 (set (make-local-variable
2927 'org-complete-tags-always-offer-all-agenda-tags)
2928 t)))"
2929 :group 'org-tags
2930 :version "24.1"
2931 :type 'boolean)
2933 (defvar org-file-tags nil
2934 "List of tags that can be inherited by all entries in the file.
2935 The tags will be inherited if the variable `org-use-tag-inheritance'
2936 says they should be.
2937 This variable is populated from #+FILETAGS lines.")
2939 (defcustom org-use-fast-tag-selection 'auto
2940 "Non-nil means use fast tag selection scheme.
2941 This is a special interface to select and deselect tags with single keys.
2942 When nil, fast selection is never used.
2943 When the symbol `auto', fast selection is used if and only if selection
2944 characters for tags have been configured, either through the variable
2945 `org-tag-alist' or through a #+TAGS line in the buffer.
2946 When t, fast selection is always used and selection keys are assigned
2947 automatically if necessary."
2948 :group 'org-tags
2949 :type '(choice
2950 (const :tag "Always" t)
2951 (const :tag "Never" nil)
2952 (const :tag "When selection characters are configured" 'auto)))
2954 (defcustom org-fast-tag-selection-single-key nil
2955 "Non-nil means fast tag selection exits after first change.
2956 When nil, you have to press RET to exit it.
2957 During fast tag selection, you can toggle this flag with `C-c'.
2958 This variable can also have the value `expert'. In this case, the window
2959 displaying the tags menu is not even shown, until you press C-c again."
2960 :group 'org-tags
2961 :type '(choice
2962 (const :tag "No" nil)
2963 (const :tag "Yes" t)
2964 (const :tag "Expert" expert)))
2966 (defvar org-fast-tag-selection-include-todo nil
2967 "Non-nil means fast tags selection interface will also offer TODO states.
2968 This is an undocumented feature, you should not rely on it.")
2970 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2971 "The column to which tags should be indented in a headline.
2972 If this number is positive, it specifies the column. If it is negative,
2973 it means that the tags should be flushright to that column. For example,
2974 -80 works well for a normal 80 character screen.
2975 When 0, place tags directly after headline text, with only one space in
2976 between."
2977 :group 'org-tags
2978 :type 'integer)
2980 (defcustom org-auto-align-tags t
2981 "Non-nil keeps tags aligned when modifying headlines.
2982 Some operations (i.e. demoting) change the length of a headline and
2983 therefore shift the tags around. With this option turned on, after
2984 each such operation the tags are again aligned to `org-tags-column'."
2985 :group 'org-tags
2986 :type 'boolean)
2988 (defcustom org-use-tag-inheritance t
2989 "Non-nil means tags in levels apply also for sublevels.
2990 When nil, only the tags directly given in a specific line apply there.
2991 This may also be a list of tags that should be inherited, or a regexp that
2992 matches tags that should be inherited. Additional control is possible
2993 with the variable `org-tags-exclude-from-inheritance' which gives an
2994 explicit list of tags to be excluded from inheritance, even if the value of
2995 `org-use-tag-inheritance' would select it for inheritance.
2997 If this option is t, a match early-on in a tree can lead to a large
2998 number of matches in the subtree when constructing the agenda or creating
2999 a sparse tree. If you only want to see the first match in a tree during
3000 a search, check out the variable `org-tags-match-list-sublevels'."
3001 :group 'org-tags
3002 :type '(choice
3003 (const :tag "Not" nil)
3004 (const :tag "Always" t)
3005 (repeat :tag "Specific tags" (string :tag "Tag"))
3006 (regexp :tag "Tags matched by regexp")))
3008 (defcustom org-tags-exclude-from-inheritance nil
3009 "List of tags that should never be inherited.
3010 This is a way to exclude a few tags from inheritance. For way to do
3011 the opposite, to actively allow inheritance for selected tags,
3012 see the variable `org-use-tag-inheritance'."
3013 :group 'org-tags
3014 :type '(repeat (string :tag "Tag")))
3016 (defun org-tag-inherit-p (tag)
3017 "Check if TAG is one that should be inherited."
3018 (cond
3019 ((member tag org-tags-exclude-from-inheritance) nil)
3020 ((eq org-use-tag-inheritance t) t)
3021 ((not org-use-tag-inheritance) nil)
3022 ((stringp org-use-tag-inheritance)
3023 (string-match org-use-tag-inheritance tag))
3024 ((listp org-use-tag-inheritance)
3025 (member tag org-use-tag-inheritance))
3026 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3028 (defcustom org-tags-match-list-sublevels t
3029 "Non-nil means list also sublevels of headlines matching a search.
3030 This variable applies to tags/property searches, and also to stuck
3031 projects because this search is based on a tags match as well.
3033 When set to the symbol `indented', sublevels are indented with
3034 leading dots.
3036 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3037 the sublevels of a headline matching a tag search often also match
3038 the same search. Listing all of them can create very long lists.
3039 Setting this variable to nil causes subtrees of a match to be skipped.
3041 This variable is semi-obsolete and probably should always be true. It
3042 is better to limit inheritance to certain tags using the variables
3043 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3044 :group 'org-tags
3045 :type '(choice
3046 (const :tag "No, don't list them" nil)
3047 (const :tag "Yes, do list them" t)
3048 (const :tag "List them, indented with leading dots" indented)))
3050 (defcustom org-tags-sort-function nil
3051 "When set, tags are sorted using this function as a comparator."
3052 :group 'org-tags
3053 :type '(choice
3054 (const :tag "No sorting" nil)
3055 (const :tag "Alphabetical" string<)
3056 (const :tag "Reverse alphabetical" string>)
3057 (function :tag "Custom function" nil)))
3059 (defvar org-tags-history nil
3060 "History of minibuffer reads for tags.")
3061 (defvar org-last-tags-completion-table nil
3062 "The last used completion table for tags.")
3063 (defvar org-after-tags-change-hook nil
3064 "Hook that is run after the tags in a line have changed.")
3066 (defgroup org-properties nil
3067 "Options concerning properties in Org-mode."
3068 :tag "Org Properties"
3069 :group 'org)
3071 (defcustom org-property-format "%-10s %s"
3072 "How property key/value pairs should be formatted by `indent-line'.
3073 When `indent-line' hits a property definition, it will format the line
3074 according to this format, mainly to make sure that the values are
3075 lined-up with respect to each other."
3076 :group 'org-properties
3077 :type 'string)
3079 (defcustom org-properties-postprocess-alist nil
3080 "Alist of properties and functions to adjust inserted values.
3081 Elements of this alist must be of the form
3083 ([string] [function])
3085 where [string] must be a property name and [function] must be a
3086 lambda expression: this lambda expression must take one argument,
3087 the value to adjust, and return the new value as a string.
3089 For example, this element will allow the property \"Remaining\"
3090 to be updated wrt the relation between the \"Effort\" property
3091 and the clock summary:
3093 ((\"Remaining\" (lambda(value)
3094 (let ((clocksum (org-clock-sum-current-item))
3095 (effort (org-duration-string-to-minutes
3096 (org-entry-get (point) \"Effort\"))))
3097 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3098 :group 'org-properties
3099 :version "24.1"
3100 :type '(alist :key-type (string :tag "Property")
3101 :value-type (function :tag "Function")))
3103 (defcustom org-use-property-inheritance nil
3104 "Non-nil means properties apply also for sublevels.
3106 This setting is chiefly used during property searches. Turning it on can
3107 cause significant overhead when doing a search, which is why it is not
3108 on by default.
3110 When nil, only the properties directly given in the current entry count.
3111 When t, every property is inherited. The value may also be a list of
3112 properties that should have inheritance, or a regular expression matching
3113 properties that should be inherited.
3115 However, note that some special properties use inheritance under special
3116 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3117 and the properties ending in \"_ALL\" when they are used as descriptor
3118 for valid values of a property.
3120 Note for programmers:
3121 When querying an entry with `org-entry-get', you can control if inheritance
3122 should be used. By default, `org-entry-get' looks only at the local
3123 properties. You can request inheritance by setting the inherit argument
3124 to t (to force inheritance) or to `selective' (to respect the setting
3125 in this variable)."
3126 :group 'org-properties
3127 :type '(choice
3128 (const :tag "Not" nil)
3129 (const :tag "Always" t)
3130 (repeat :tag "Specific properties" (string :tag "Property"))
3131 (regexp :tag "Properties matched by regexp")))
3133 (defun org-property-inherit-p (property)
3134 "Check if PROPERTY is one that should be inherited."
3135 (cond
3136 ((eq org-use-property-inheritance t) t)
3137 ((not org-use-property-inheritance) nil)
3138 ((stringp org-use-property-inheritance)
3139 (string-match org-use-property-inheritance property))
3140 ((listp org-use-property-inheritance)
3141 (member property org-use-property-inheritance))
3142 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3144 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3145 "The default column format, if no other format has been defined.
3146 This variable can be set on the per-file basis by inserting a line
3148 #+COLUMNS: %25ITEM ....."
3149 :group 'org-properties
3150 :type 'string)
3152 (defcustom org-columns-ellipses ".."
3153 "The ellipses to be used when a field in column view is truncated.
3154 When this is the empty string, as many characters as possible are shown,
3155 but then there will be no visual indication that the field has been truncated.
3156 When this is a string of length N, the last N characters of a truncated
3157 field are replaced by this string. If the column is narrower than the
3158 ellipses string, only part of the ellipses string will be shown."
3159 :group 'org-properties
3160 :type 'string)
3162 (defcustom org-columns-modify-value-for-display-function nil
3163 "Function that modifies values for display in column view.
3164 For example, it can be used to cut out a certain part from a time stamp.
3165 The function must take 2 arguments:
3167 column-title The title of the column (*not* the property name)
3168 value The value that should be modified.
3170 The function should return the value that should be displayed,
3171 or nil if the normal value should be used."
3172 :group 'org-properties
3173 :type 'function)
3175 (defcustom org-effort-property "Effort"
3176 "The property that is being used to keep track of effort estimates.
3177 Effort estimates given in this property need to have the format H:MM."
3178 :group 'org-properties
3179 :group 'org-progress
3180 :type '(string :tag "Property"))
3182 (defconst org-global-properties-fixed
3183 '(("VISIBILITY_ALL" . "folded children content all")
3184 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3185 "List of property/value pairs that can be inherited by any entry.
3187 These are fixed values, for the preset properties. The user variable
3188 that can be used to add to this list is `org-global-properties'.
3190 The entries in this list are cons cells where the car is a property
3191 name and cdr is a string with the value. If the value represents
3192 multiple items like an \"_ALL\" property, separate the items by
3193 spaces.")
3195 (defcustom org-global-properties nil
3196 "List of property/value pairs that can be inherited by any entry.
3198 This list will be combined with the constant `org-global-properties-fixed'.
3200 The entries in this list are cons cells where the car is a property
3201 name and cdr is a string with the value.
3203 You can set buffer-local values for the same purpose in the variable
3204 `org-file-properties' this by adding lines like
3206 #+PROPERTY: NAME VALUE"
3207 :group 'org-properties
3208 :type '(repeat
3209 (cons (string :tag "Property")
3210 (string :tag "Value"))))
3212 (defvar org-file-properties nil
3213 "List of property/value pairs that can be inherited by any entry.
3214 Valid for the current buffer.
3215 This variable is populated from #+PROPERTY lines.")
3216 (make-variable-buffer-local 'org-file-properties)
3218 (defgroup org-agenda nil
3219 "Options concerning agenda views in Org-mode."
3220 :tag "Org Agenda"
3221 :group 'org)
3223 (defvar org-category nil
3224 "Variable used by org files to set a category for agenda display.
3225 Such files should use a file variable to set it, for example
3227 # -*- mode: org; org-category: \"ELisp\"
3229 or contain a special line
3231 #+CATEGORY: ELisp
3233 If the file does not specify a category, then file's base name
3234 is used instead.")
3235 (make-variable-buffer-local 'org-category)
3236 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3238 (defcustom org-agenda-files nil
3239 "The files to be used for agenda display.
3240 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3241 \\[org-remove-file]. You can also use customize to edit the list.
3243 If an entry is a directory, all files in that directory that are matched by
3244 `org-agenda-file-regexp' will be part of the file list.
3246 If the value of the variable is not a list but a single file name, then
3247 the list of agenda files is actually stored and maintained in that file, one
3248 agenda file per line. In this file paths can be given relative to
3249 `org-directory'. Tilde expansion and environment variable substitution
3250 are also made."
3251 :group 'org-agenda
3252 :type '(choice
3253 (repeat :tag "List of files and directories" file)
3254 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3256 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3257 "Regular expression to match files for `org-agenda-files'.
3258 If any element in the list in that variable contains a directory instead
3259 of a normal file, all files in that directory that are matched by this
3260 regular expression will be included."
3261 :group 'org-agenda
3262 :type 'regexp)
3264 (defcustom org-agenda-text-search-extra-files nil
3265 "List of extra files to be searched by text search commands.
3266 These files will be search in addition to the agenda files by the
3267 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3268 Note that these files will only be searched for text search commands,
3269 not for the other agenda views like todo lists, tag searches or the weekly
3270 agenda. This variable is intended to list notes and possibly archive files
3271 that should also be searched by these two commands.
3272 In fact, if the first element in the list is the symbol `agenda-archives',
3273 than all archive files of all agenda files will be added to the search
3274 scope."
3275 :group 'org-agenda
3276 :type '(set :greedy t
3277 (const :tag "Agenda Archives" agenda-archives)
3278 (repeat :inline t (file))))
3280 (if (fboundp 'defvaralias)
3281 (defvaralias 'org-agenda-multi-occur-extra-files
3282 'org-agenda-text-search-extra-files))
3284 (defcustom org-agenda-skip-unavailable-files nil
3285 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3286 A nil value means to remove them, after a query, from the list."
3287 :group 'org-agenda
3288 :type 'boolean)
3290 (defcustom org-calendar-to-agenda-key [?c]
3291 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3292 The command `org-calendar-goto-agenda' will be bound to this key. The
3293 default is the character `c' because then `c' can be used to switch back and
3294 forth between agenda and calendar."
3295 :group 'org-agenda
3296 :type 'sexp)
3298 (defcustom org-calendar-insert-diary-entry-key [?i]
3299 "The key to be installed in `calendar-mode-map' for adding diary entries.
3300 This option is irrelevant until `org-agenda-diary-file' has been configured
3301 to point to an Org-mode file. When that is the case, the command
3302 `org-agenda-diary-entry' will be bound to the key given here, by default
3303 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3304 if you want to continue doing this, you need to change this to a different
3305 key."
3306 :group 'org-agenda
3307 :type 'sexp)
3309 (defcustom org-agenda-diary-file 'diary-file
3310 "File to which to add new entries with the `i' key in agenda and calendar.
3311 When this is the symbol `diary-file', the functionality in the Emacs
3312 calendar will be used to add entries to the `diary-file'. But when this
3313 points to a file, `org-agenda-diary-entry' will be used instead."
3314 :group 'org-agenda
3315 :type '(choice
3316 (const :tag "The standard Emacs diary file" diary-file)
3317 (file :tag "Special Org file diary entries")))
3319 (eval-after-load "calendar"
3320 '(progn
3321 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3322 'org-calendar-goto-agenda)
3323 (add-hook 'calendar-mode-hook
3324 (lambda ()
3325 (unless (eq org-agenda-diary-file 'diary-file)
3326 (define-key calendar-mode-map
3327 org-calendar-insert-diary-entry-key
3328 'org-agenda-diary-entry))))))
3330 (defgroup org-latex nil
3331 "Options for embedding LaTeX code into Org-mode."
3332 :tag "Org LaTeX"
3333 :group 'org)
3335 (defcustom org-format-latex-options
3336 '(:foreground default :background default :scale 1.0
3337 :html-foreground "Black" :html-background "Transparent"
3338 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3339 "Options for creating images from LaTeX fragments.
3340 This is a property list with the following properties:
3341 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3342 `default' means use the foreground of the default face.
3343 :background the background color, or \"Transparent\".
3344 `default' means use the background of the default face.
3345 :scale a scaling factor for the size of the images, to get more pixels
3346 :html-foreground, :html-background, :html-scale
3347 the same numbers for HTML export.
3348 :matchers a list indicating which matchers should be used to
3349 find LaTeX fragments. Valid members of this list are:
3350 \"begin\" find environments
3351 \"$1\" find single characters surrounded by $.$
3352 \"$\" find math expressions surrounded by $...$
3353 \"$$\" find math expressions surrounded by $$....$$
3354 \"\\(\" find math expressions surrounded by \\(...\\)
3355 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3356 :group 'org-latex
3357 :type 'plist)
3359 (defcustom org-format-latex-signal-error t
3360 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3361 When nil, just push out a message."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-latex-to-mathml-jar-file nil
3367 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3368 Use this to specify additional executable file say a jar file.
3370 When using MathToWeb as the converter, specify the full-path to
3371 your mathtoweb.jar file."
3372 :group 'org-latex
3373 :version "24.1"
3374 :type '(choice
3375 (const :tag "None" nil)
3376 (file :tag "JAR file" :must-match t)))
3378 (defcustom org-latex-to-mathml-convert-command nil
3379 "Command to convert LaTeX fragments to MathML.
3380 Replace format-specifiers in the command as noted below and use
3381 `shell-command' to convert LaTeX to MathML.
3382 %j: Executable file in fully expanded form as specified by
3383 `org-latex-to-mathml-jar-file'.
3384 %I: Input LaTeX file in fully expanded form
3385 %o: Output MathML file
3386 This command is used by `org-create-math-formula'.
3388 When using MathToWeb as the converter, set this to
3389 \"java -jar %j -unicode -force -df %o %I\"."
3390 :group 'org-latex
3391 :version "24.1"
3392 :type '(choice
3393 (const :tag "None" nil)
3394 (string :tag "\nShell command")))
3396 (defcustom org-latex-create-formula-image-program 'dvipng
3397 "Program to convert LaTeX fragments with.
3399 dvipng Process the LaTeX fragments to dvi file, then convert
3400 dvi files to png files using dvipng.
3401 This will also include processing of non-math environments.
3402 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3403 to convert pdf files to png files"
3404 :group 'org-latex
3405 :version "24.1"
3406 :type '(choice
3407 (const :tag "dvipng" dvipng)
3408 (const :tag "imagemagick" imagemagick)))
3410 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3411 "Path to store latex preview images. A relative path here creates many
3412 directories relative to the processed org files paths. An absolute path
3413 puts all preview images at the same place."
3414 :group 'org-latex
3415 :version "24.3"
3416 :type 'string)
3418 (defun org-format-latex-mathml-available-p ()
3419 "Return t if `org-latex-to-mathml-convert-command' is usable."
3420 (save-match-data
3421 (when (and (boundp 'org-latex-to-mathml-convert-command)
3422 org-latex-to-mathml-convert-command)
3423 (let ((executable (car (split-string
3424 org-latex-to-mathml-convert-command))))
3425 (when (executable-find executable)
3426 (if (string-match
3427 "%j" org-latex-to-mathml-convert-command)
3428 (file-readable-p org-latex-to-mathml-jar-file)
3429 t))))))
3431 (defcustom org-format-latex-header "\\documentclass{article}
3432 \\usepackage[usenames]{color}
3433 \\usepackage{amsmath}
3434 \\usepackage[mathscr]{eucal}
3435 \\pagestyle{empty} % do not remove
3436 \[PACKAGES]
3437 \[DEFAULT-PACKAGES]
3438 % The settings below are copied from fullpage.sty
3439 \\setlength{\\textwidth}{\\paperwidth}
3440 \\addtolength{\\textwidth}{-3cm}
3441 \\setlength{\\oddsidemargin}{1.5cm}
3442 \\addtolength{\\oddsidemargin}{-2.54cm}
3443 \\setlength{\\evensidemargin}{\\oddsidemargin}
3444 \\setlength{\\textheight}{\\paperheight}
3445 \\addtolength{\\textheight}{-\\headheight}
3446 \\addtolength{\\textheight}{-\\headsep}
3447 \\addtolength{\\textheight}{-\\footskip}
3448 \\addtolength{\\textheight}{-3cm}
3449 \\setlength{\\topmargin}{1.5cm}
3450 \\addtolength{\\topmargin}{-2.54cm}"
3451 "The document header used for processing LaTeX fragments.
3452 It is imperative that this header make sure that no page number
3453 appears on the page. The package defined in the variables
3454 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3455 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3456 will be appended."
3457 :group 'org-latex
3458 :type 'string)
3460 (defvar org-format-latex-header-extra nil)
3462 (defun org-set-packages-alist (var val)
3463 "Set the packages alist and make sure it has 3 elements per entry."
3464 (set var (mapcar (lambda (x)
3465 (if (and (consp x) (= (length x) 2))
3466 (list (car x) (nth 1 x) t)
3468 val)))
3470 (defun org-get-packages-alist (var)
3472 "Get the packages alist and make sure it has 3 elements per entry."
3473 (mapcar (lambda (x)
3474 (if (and (consp x) (= (length x) 2))
3475 (list (car x) (nth 1 x) t)
3477 (default-value var)))
3479 ;; The following variables are defined here because is it also used
3480 ;; when formatting latex fragments. Originally it was part of the
3481 ;; LaTeX exporter, which is why the name includes "export".
3482 (defcustom org-export-latex-default-packages-alist
3483 '(("AUTO" "inputenc" t)
3484 ("T1" "fontenc" t)
3485 ("" "fixltx2e" nil)
3486 ("" "graphicx" t)
3487 ("" "longtable" nil)
3488 ("" "float" nil)
3489 ("" "wrapfig" nil)
3490 ("" "soul" t)
3491 ("" "textcomp" t)
3492 ("" "marvosym" t)
3493 ("" "wasysym" t)
3494 ("" "latexsym" t)
3495 ("" "amssymb" t)
3496 ("" "hyperref" nil)
3497 "\\tolerance=1000"
3499 "Alist of default packages to be inserted in the header.
3500 Change this only if one of the packages here causes an incompatibility
3501 with another package you are using.
3502 The packages in this list are needed by one part or another of Org-mode
3503 to function properly.
3505 - inputenc, fontenc: for basic font and character selection
3506 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3507 for interpreting the entities in `org-entities'. You can skip some of these
3508 packages if you don't use any of the symbols in it.
3509 - graphicx: for including images
3510 - float, wrapfig: for figure placement
3511 - longtable: for long tables
3512 - hyperref: for cross references
3514 Therefore you should not modify this variable unless you know what you
3515 are doing. The one reason to change it anyway is that you might be loading
3516 some other package that conflicts with one of the default packages.
3517 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3518 If SNIPPET-FLAG is t, the package also needs to be included when
3519 compiling LaTeX snippets into images for inclusion into HTML."
3520 :group 'org-export-latex
3521 :set 'org-set-packages-alist
3522 :get 'org-get-packages-alist
3523 :version "24.1"
3524 :type '(repeat
3525 (choice
3526 (list :tag "options/package pair"
3527 (string :tag "options")
3528 (string :tag "package")
3529 (boolean :tag "Snippet"))
3530 (string :tag "A line of LaTeX"))))
3532 (defcustom org-export-latex-packages-alist nil
3533 "Alist of packages to be inserted in every LaTeX header.
3534 These will be inserted after `org-export-latex-default-packages-alist'.
3535 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3536 SNIPPET-FLAG, when t, indicates that this package is also needed when
3537 turning LaTeX snippets into images for inclusion into HTML.
3538 Make sure that you only list packages here which:
3539 - you want in every file
3540 - do not conflict with the default packages in
3541 `org-export-latex-default-packages-alist'
3542 - do not conflict with the setup in `org-format-latex-header'."
3543 :group 'org-export-latex
3544 :set 'org-set-packages-alist
3545 :get 'org-get-packages-alist
3546 :type '(repeat
3547 (choice
3548 (list :tag "options/package pair"
3549 (string :tag "options")
3550 (string :tag "package")
3551 (boolean :tag "Snippet"))
3552 (string :tag "A line of LaTeX"))))
3555 (defgroup org-appearance nil
3556 "Settings for Org-mode appearance."
3557 :tag "Org Appearance"
3558 :group 'org)
3560 (defcustom org-level-color-stars-only nil
3561 "Non-nil means fontify only the stars in each headline.
3562 When nil, the entire headline is fontified.
3563 Changing it requires restart of `font-lock-mode' to become effective
3564 also in regions already fontified."
3565 :group 'org-appearance
3566 :type 'boolean)
3568 (defcustom org-hide-leading-stars nil
3569 "Non-nil means hide the first N-1 stars in a headline.
3570 This works by using the face `org-hide' for these stars. This
3571 face is white for a light background, and black for a dark
3572 background. You may have to customize the face `org-hide' to
3573 make this work.
3574 Changing it requires restart of `font-lock-mode' to become effective
3575 also in regions already fontified.
3576 You may also set this on a per-file basis by adding one of the following
3577 lines to the buffer:
3579 #+STARTUP: hidestars
3580 #+STARTUP: showstars"
3581 :group 'org-appearance
3582 :type 'boolean)
3584 (defcustom org-hidden-keywords nil
3585 "List of symbols corresponding to keywords to be hidden the org buffer.
3586 For example, a value '(title) for this list will make the document's title
3587 appear in the buffer without the initial #+TITLE: keyword."
3588 :group 'org-appearance
3589 :version "24.1"
3590 :type '(set (const :tag "#+AUTHOR" author)
3591 (const :tag "#+DATE" date)
3592 (const :tag "#+EMAIL" email)
3593 (const :tag "#+TITLE" title)))
3595 (defcustom org-custom-properties nil
3596 "List of properties (as strings) with a special meaning.
3597 The default use of these custom properties is to let the user
3598 hide them with `org-toggle-custom-properties-visibility'."
3599 :group 'org-properties
3600 :group 'org-appearance
3601 :version "24.3"
3602 :type '(repeat (string :tag "Property Name")))
3604 (defcustom org-fontify-done-headline nil
3605 "Non-nil means change the face of a headline if it is marked DONE.
3606 Normally, only the TODO/DONE keyword indicates the state of a headline.
3607 When this is non-nil, the headline after the keyword is set to the
3608 `org-headline-done' as an additional indication."
3609 :group 'org-appearance
3610 :type 'boolean)
3612 (defcustom org-fontify-emphasized-text t
3613 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3614 Changing this variable requires a restart of Emacs to take effect."
3615 :group 'org-appearance
3616 :type 'boolean)
3618 (defcustom org-fontify-whole-heading-line nil
3619 "Non-nil means fontify the whole line for headings.
3620 This is useful when setting a background color for the
3621 org-level-* faces."
3622 :group 'org-appearance
3623 :type 'boolean)
3625 (defcustom org-highlight-latex-fragments-and-specials nil
3626 "Non-nil means fontify what is treated specially by the exporters."
3627 :group 'org-appearance
3628 :type 'boolean)
3630 (defcustom org-hide-emphasis-markers nil
3631 "Non-nil mean font-lock should hide the emphasis marker characters."
3632 :group 'org-appearance
3633 :type 'boolean)
3635 (defcustom org-pretty-entities nil
3636 "Non-nil means show entities as UTF8 characters.
3637 When nil, the \\name form remains in the buffer."
3638 :group 'org-appearance
3639 :version "24.1"
3640 :type 'boolean)
3642 (defcustom org-pretty-entities-include-sub-superscripts t
3643 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3644 :group 'org-appearance
3645 :version "24.1"
3646 :type 'boolean)
3648 (defvar org-emph-re nil
3649 "Regular expression for matching emphasis.
3650 After a match, the match groups contain these elements:
3651 0 The match of the full regular expression, including the characters
3652 before and after the proper match
3653 1 The character before the proper match, or empty at beginning of line
3654 2 The proper match, including the leading and trailing markers
3655 3 The leading marker like * or /, indicating the type of highlighting
3656 4 The text between the emphasis markers, not including the markers
3657 5 The character after the match, empty at the end of a line")
3658 (defvar org-verbatim-re nil
3659 "Regular expression for matching verbatim text.")
3660 (defvar org-emphasis-regexp-components) ; defined just below
3661 (defvar org-emphasis-alist) ; defined just below
3662 (defun org-set-emph-re (var val)
3663 "Set variable and compute the emphasis regular expression."
3664 (set var val)
3665 (when (and (boundp 'org-emphasis-alist)
3666 (boundp 'org-emphasis-regexp-components)
3667 org-emphasis-alist org-emphasis-regexp-components)
3668 (let* ((e org-emphasis-regexp-components)
3669 (pre (car e))
3670 (post (nth 1 e))
3671 (border (nth 2 e))
3672 (body (nth 3 e))
3673 (nl (nth 4 e))
3674 (body1 (concat body "*?"))
3675 (markers (mapconcat 'car org-emphasis-alist ""))
3676 (vmarkers (mapconcat
3677 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3678 org-emphasis-alist "")))
3679 ;; make sure special characters appear at the right position in the class
3680 (if (string-match "\\^" markers)
3681 (setq markers (concat (replace-match "" t t markers) "^")))
3682 (if (string-match "-" markers)
3683 (setq markers (concat (replace-match "" t t markers) "-")))
3684 (if (string-match "\\^" vmarkers)
3685 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3686 (if (string-match "-" vmarkers)
3687 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3688 (if (> nl 0)
3689 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3690 (int-to-string nl) "\\}")))
3691 ;; Make the regexp
3692 (setq org-emph-re
3693 (concat "\\([" pre "]\\|^\\)"
3694 "\\("
3695 "\\([" markers "]\\)"
3696 "\\("
3697 "[^" border "]\\|"
3698 "[^" border "]"
3699 body1
3700 "[^" border "]"
3701 "\\)"
3702 "\\3\\)"
3703 "\\([" post "]\\|$\\)"))
3704 (setq org-verbatim-re
3705 (concat "\\([" pre "]\\|^\\)"
3706 "\\("
3707 "\\([" vmarkers "]\\)"
3708 "\\("
3709 "[^" border "]\\|"
3710 "[^" border "]"
3711 body1
3712 "[^" border "]"
3713 "\\)"
3714 "\\3\\)"
3715 "\\([" post "]\\|$\\)")))))
3717 (defcustom org-emphasis-regexp-components
3718 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3719 "Components used to build the regular expression for emphasis.
3720 This is a list with five entries. Terminology: In an emphasis string
3721 like \" *strong word* \", we call the initial space PREMATCH, the final
3722 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3723 and \"trong wor\" is the body. The different components in this variable
3724 specify what is allowed/forbidden in each part:
3726 pre Chars allowed as prematch. Beginning of line will be allowed too.
3727 post Chars allowed as postmatch. End of line will be allowed too.
3728 border The chars *forbidden* as border characters.
3729 body-regexp A regexp like \".\" to match a body character. Don't use
3730 non-shy groups here, and don't allow newline here.
3731 newline The maximum number of newlines allowed in an emphasis exp.
3733 Use customize to modify this, or restart Emacs after changing it."
3734 :group 'org-appearance
3735 :set 'org-set-emph-re
3736 :type '(list
3737 (sexp :tag "Allowed chars in pre ")
3738 (sexp :tag "Allowed chars in post ")
3739 (sexp :tag "Forbidden chars in border ")
3740 (sexp :tag "Regexp for body ")
3741 (integer :tag "number of newlines allowed")
3742 (option (boolean :tag "Please ignore this button"))))
3744 (defcustom org-emphasis-alist
3745 `(("*" bold "<b>" "</b>")
3746 ("/" italic "<i>" "</i>")
3747 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3748 ("=" org-code "<code>" "</code>" verbatim)
3749 ("~" org-verbatim "<code>" "</code>" verbatim)
3750 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3751 "<del>" "</del>")
3753 "Special syntax for emphasized text.
3754 Text starting and ending with a special character will be emphasized, for
3755 example *bold*, _underlined_ and /italic/. This variable sets the marker
3756 characters, the face to be used by font-lock for highlighting in Org-mode
3757 Emacs buffers, and the HTML tags to be used for this.
3758 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3759 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3760 Use customize to modify this, or restart Emacs after changing it."
3761 :group 'org-appearance
3762 :set 'org-set-emph-re
3763 :type '(repeat
3764 (list
3765 (string :tag "Marker character")
3766 (choice
3767 (face :tag "Font-lock-face")
3768 (plist :tag "Face property list"))
3769 (string :tag "HTML start tag")
3770 (string :tag "HTML end tag")
3771 (option (const verbatim)))))
3773 (defvar org-protecting-blocks
3774 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3775 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3776 This is needed for font-lock setup.")
3778 ;;; Miscellaneous options
3780 (defgroup org-completion nil
3781 "Completion in Org-mode."
3782 :tag "Org Completion"
3783 :group 'org)
3785 (defcustom org-completion-use-ido nil
3786 "Non-nil means use ido completion wherever possible.
3787 Note that `ido-mode' must be active for this variable to be relevant.
3788 If you decide to turn this variable on, you might well want to turn off
3789 `org-outline-path-complete-in-steps'.
3790 See also `org-completion-use-iswitchb'."
3791 :group 'org-completion
3792 :type 'boolean)
3794 (defcustom org-completion-use-iswitchb nil
3795 "Non-nil means use iswitchb completion wherever possible.
3796 Note that `iswitchb-mode' must be active for this variable to be relevant.
3797 If you decide to turn this variable on, you might well want to turn off
3798 `org-outline-path-complete-in-steps'.
3799 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3800 :group 'org-completion
3801 :type 'boolean)
3803 (defcustom org-completion-fallback-command 'hippie-expand
3804 "The expansion command called by \\[pcomplete] in normal context.
3805 Normal means, no org-mode-specific context."
3806 :group 'org-completion
3807 :type 'function)
3809 ;;; Functions and variables from their packages
3810 ;; Declared here to avoid compiler warnings
3812 ;; XEmacs only
3813 (defvar outline-mode-menu-heading)
3814 (defvar outline-mode-menu-show)
3815 (defvar outline-mode-menu-hide)
3816 (defvar zmacs-regions) ; XEmacs regions
3818 ;; Emacs only
3819 (defvar mark-active)
3821 ;; Various packages
3822 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3823 (declare-function calendar-forward-day "cal-move" (arg))
3824 (declare-function calendar-goto-date "cal-move" (date))
3825 (declare-function calendar-goto-today "cal-move" ())
3826 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3827 (defvar calc-embedded-close-formula)
3828 (defvar calc-embedded-open-formula)
3829 (declare-function cdlatex-tab "ext:cdlatex" ())
3830 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3831 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3832 (defvar font-lock-unfontify-region-function)
3833 (declare-function iswitchb-read-buffer "iswitchb"
3834 (prompt &optional default require-match start matches-set))
3835 (defvar iswitchb-temp-buflist)
3836 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3837 (defvar org-agenda-tags-todo-honor-ignore-options)
3838 (declare-function org-agenda-skip "org-agenda" ())
3839 (declare-function
3840 org-agenda-format-item "org-agenda"
3841 (extra txt &optional category tags dotime noprefix remove-re habitp))
3842 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3843 (declare-function org-agenda-change-all-lines "org-agenda"
3844 (newhead hdmarker &optional fixface just-this))
3845 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3846 (declare-function org-agenda-maybe-redo "org-agenda" ())
3847 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3848 (beg end))
3849 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3850 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3851 "org-agenda" (&optional end))
3852 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3853 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3854 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3855 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3856 (declare-function org-indent-mode "org-indent" (&optional arg))
3857 (declare-function parse-time-string "parse-time" (string))
3858 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3859 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3860 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3861 (defvar remember-data-file)
3862 (defvar texmathp-why)
3863 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3864 (declare-function table--at-cell-p "table" (position &optional object at-column))
3866 (defvar w3m-current-url)
3867 (defvar w3m-current-title)
3869 (defvar org-latex-regexps)
3871 ;;; Autoload and prepare some org modules
3873 ;; Some table stuff that needs to be defined here, because it is used
3874 ;; by the functions setting up org-mode or checking for table context.
3876 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3877 "Detect an org-type or table-type table.")
3878 (defconst org-table-line-regexp "^[ \t]*|"
3879 "Detect an org-type table line.")
3880 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3881 "Detect an org-type table line.")
3882 (defconst org-table-hline-regexp "^[ \t]*|-"
3883 "Detect an org-type table hline.")
3884 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3885 "Detect a table-type table hline.")
3886 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3887 "Detect the first line outside a table when searching from within it.
3888 This works for both table types.")
3890 ;; Autoload the functions in org-table.el that are needed by functions here.
3892 (eval-and-compile
3893 (org-autoload "org-table"
3894 '(org-table-begin org-table-blank-field org-table-end)))
3896 ;;;###autoload
3897 (defun turn-on-orgtbl ()
3898 "Unconditionally turn on `orgtbl-mode'."
3899 (require 'org-table)
3900 (orgtbl-mode 1))
3902 (defun org-at-table-p (&optional table-type)
3903 "Return t if the cursor is inside an org-type table.
3904 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3905 (if org-enable-table-editor
3906 (save-excursion
3907 (beginning-of-line 1)
3908 (looking-at (if table-type org-table-any-line-regexp
3909 org-table-line-regexp)))
3910 nil))
3911 (defsubst org-table-p () (org-at-table-p))
3913 (defun org-at-table.el-p ()
3914 "Return t if and only if we are at a table.el table."
3915 (and (org-at-table-p 'any)
3916 (save-excursion
3917 (goto-char (org-table-begin 'any))
3918 (looking-at org-table1-hline-regexp))))
3920 (defun org-table-recognize-table.el ()
3921 "If there is a table.el table nearby, recognize it and move into it."
3922 (if org-table-tab-recognizes-table.el
3923 (if (org-at-table.el-p)
3924 (progn
3925 (beginning-of-line 1)
3926 (if (looking-at org-table-dataline-regexp)
3928 (if (looking-at org-table1-hline-regexp)
3929 (progn
3930 (beginning-of-line 2)
3931 (if (looking-at org-table-any-border-regexp)
3932 (beginning-of-line -1)))))
3933 (if (re-search-forward "|" (org-table-end t) t)
3934 (progn
3935 (require 'table)
3936 (if (table--at-cell-p (point))
3938 (message "recognizing table.el table...")
3939 (table-recognize-table)
3940 (message "recognizing table.el table...done")))
3941 (error "This should not happen"))
3943 nil)
3944 nil))
3946 (defun org-at-table-hline-p ()
3947 "Return t if the cursor is inside a hline in a table."
3948 (if org-enable-table-editor
3949 (save-excursion
3950 (beginning-of-line 1)
3951 (looking-at org-table-hline-regexp))
3952 nil))
3954 (defvar org-table-clean-did-remove-column nil)
3955 (defun org-table-map-tables (function &optional quietly)
3956 "Apply FUNCTION to the start of all tables in the buffer."
3957 (save-excursion
3958 (save-restriction
3959 (widen)
3960 (goto-char (point-min))
3961 (while (re-search-forward org-table-any-line-regexp nil t)
3962 (unless quietly
3963 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3964 (beginning-of-line 1)
3965 (when (and (looking-at org-table-line-regexp)
3966 ;; Exclude tables in src/example/verbatim/clocktable blocks
3967 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
3968 (save-excursion (funcall function))
3969 (or (looking-at org-table-line-regexp)
3970 (forward-char 1)))
3971 (re-search-forward org-table-any-border-regexp nil 1))))
3972 (unless quietly (message "Mapping tables: done")))
3974 ;; Declare and autoload functions from org-exp.el & Co
3976 (declare-function org-default-export-plist "org-exp")
3977 (declare-function org-infile-export-plist "org-exp")
3978 (declare-function org-get-current-options "org-exp")
3980 ;; Declare and autoload functions from org-agenda.el
3982 (eval-and-compile
3983 (org-autoload "org-agenda"
3984 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3986 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3987 (declare-function org-clock-update-mode-line "org-clock" ())
3988 (declare-function org-resolve-clocks "org-clock"
3989 (&optional also-non-dangling-p prompt last-valid))
3990 (defvar org-clock-start-time)
3991 (defvar org-clock-marker (make-marker)
3992 "Marker recording the last clock-in.")
3993 (defvar org-clock-hd-marker (make-marker)
3994 "Marker recording the last clock-in, but the headline position.")
3995 (defvar org-clock-heading ""
3996 "The heading of the current clock entry.")
3997 (defun org-clock-is-active ()
3998 "Return non-nil if clock is currently running.
3999 The return value is actually the clock marker."
4000 (marker-buffer org-clock-marker))
4002 (eval-and-compile
4003 (org-autoload "org-clock" '(org-clock-remove-overlays
4004 org-clock-update-time-maybe
4005 org-clocktable-shift)))
4007 (defun org-check-running-clock ()
4008 "Check if the current buffer contains the running clock.
4009 If yes, offer to stop it and to save the buffer with the changes."
4010 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4011 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4012 (buffer-name))))
4013 (org-clock-out)
4014 (when (y-or-n-p "Save changed buffer?")
4015 (save-buffer))))
4017 (defun org-clocktable-try-shift (dir n)
4018 "Check if this line starts a clock table, if yes, shift the time block."
4019 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4020 (org-clocktable-shift dir n)))
4022 ;;;###autoload
4023 (defun org-clock-persistence-insinuate ()
4024 "Set up hooks for clock persistence."
4025 (require 'org-clock)
4026 (add-hook 'org-mode-hook 'org-clock-load)
4027 (add-hook 'kill-emacs-hook 'org-clock-save))
4029 ;; Define the variable already here, to make sure we have it.
4030 (defvar org-indent-mode nil
4031 "Non-nil if Org-Indent mode is enabled.
4032 Use the command `org-indent-mode' to change this variable.")
4034 ;; Autoload archiving code
4035 ;; The stuff that is needed for cycling and tags has to be defined here.
4037 (defgroup org-archive nil
4038 "Options concerning archiving in Org-mode."
4039 :tag "Org Archive"
4040 :group 'org-structure)
4042 (defcustom org-archive-location "%s_archive::"
4043 "The location where subtrees should be archived.
4045 The value of this variable is a string, consisting of two parts,
4046 separated by a double-colon. The first part is a filename and
4047 the second part is a headline.
4049 When the filename is omitted, archiving happens in the same file.
4050 %s in the filename will be replaced by the current file
4051 name (without the directory part). Archiving to a different file
4052 is useful to keep archived entries from contributing to the
4053 Org-mode Agenda.
4055 The archived entries will be filed as subtrees of the specified
4056 headline. When the headline is omitted, the subtrees are simply
4057 filed away at the end of the file, as top-level entries. Also in
4058 the heading you can use %s to represent the file name, this can be
4059 useful when using the same archive for a number of different files.
4061 Here are a few examples:
4062 \"%s_archive::\"
4063 If the current file is Projects.org, archive in file
4064 Projects.org_archive, as top-level trees. This is the default.
4066 \"::* Archived Tasks\"
4067 Archive in the current file, under the top-level headline
4068 \"* Archived Tasks\".
4070 \"~/org/archive.org::\"
4071 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4073 \"~/org/archive.org::* From %s\"
4074 Archive in file ~/org/archive.org (absolute path), under headlines
4075 \"From FILENAME\" where file name is the current file name.
4077 \"~/org/datetree.org::datetree/* Finished Tasks\"
4078 The \"datetree/\" string is special, signifying to archive
4079 items to the datetree. Items are placed in either the CLOSED
4080 date of the item, or the current date if there is no CLOSED date.
4081 The heading will be a subentry to the current date. There doesn't
4082 need to be a heading, but there always needs to be a slash after
4083 datetree. For example, to store archived items directly in the
4084 datetree, use \"~/org/datetree.org::datetree/\".
4086 \"basement::** Finished Tasks\"
4087 Archive in file ./basement (relative path), as level 3 trees
4088 below the level 2 heading \"** Finished Tasks\".
4090 You may set this option on a per-file basis by adding to the buffer a
4091 line like
4093 #+ARCHIVE: basement::** Finished Tasks
4095 You may also define it locally for a subtree by setting an ARCHIVE property
4096 in the entry. If such a property is found in an entry, or anywhere up
4097 the hierarchy, it will be used."
4098 :group 'org-archive
4099 :type 'string)
4101 (defcustom org-archive-tag "ARCHIVE"
4102 "The tag that marks a subtree as archived.
4103 An archived subtree does not open during visibility cycling, and does
4104 not contribute to the agenda listings.
4105 After changing this, font-lock must be restarted in the relevant buffers to
4106 get the proper fontification."
4107 :group 'org-archive
4108 :group 'org-keywords
4109 :type 'string)
4111 (defcustom org-agenda-skip-archived-trees t
4112 "Non-nil means the agenda will skip any items located in archived trees.
4113 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4114 variable is no longer recommended, you should leave it at the value t.
4115 Instead, use the key `v' to cycle the archives-mode in the agenda."
4116 :group 'org-archive
4117 :group 'org-agenda-skip
4118 :type 'boolean)
4120 (defcustom org-columns-skip-archived-trees t
4121 "Non-nil means ignore archived trees when creating column view."
4122 :group 'org-archive
4123 :group 'org-properties
4124 :type 'boolean)
4126 (defcustom org-cycle-open-archived-trees nil
4127 "Non-nil means `org-cycle' will open archived trees.
4128 An archived tree is a tree marked with the tag ARCHIVE.
4129 When nil, archived trees will stay folded. You can still open them with
4130 normal outline commands like `show-all', but not with the cycling commands."
4131 :group 'org-archive
4132 :group 'org-cycle
4133 :type 'boolean)
4135 (defcustom org-sparse-tree-open-archived-trees nil
4136 "Non-nil means sparse tree construction shows matches in archived trees.
4137 When nil, matches in these trees are highlighted, but the trees are kept in
4138 collapsed state."
4139 :group 'org-archive
4140 :group 'org-sparse-trees
4141 :type 'boolean)
4143 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4144 "The default date type when building a sparse tree.
4145 When this is nil, a date is a scheduled or a deadline timestamp.
4146 Otherwise, these types are allowed:
4148 all: all timestamps
4149 active: only active timestamps (<...>)
4150 inactive: only inactive timestamps (<...)
4151 scheduled: only scheduled timestamps
4152 deadline: only deadline timestamps"
4153 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4154 (const :tag "All timestamps" all)
4155 (const :tag "Only active timestamps" active)
4156 (const :tag "Only inactive timestamps" inactive)
4157 (const :tag "Only scheduled timestamps" scheduled)
4158 (const :tag "Only deadline timestamps" deadline))
4159 :version "24.3"
4160 :group 'org-sparse-trees)
4162 (defun org-cycle-hide-archived-subtrees (state)
4163 "Re-hide all archived subtrees after a visibility state change."
4164 (when (and (not org-cycle-open-archived-trees)
4165 (not (memq state '(overview folded))))
4166 (save-excursion
4167 (let* ((globalp (memq state '(contents all)))
4168 (beg (if globalp (point-min) (point)))
4169 (end (if globalp (point-max) (org-end-of-subtree t))))
4170 (org-hide-archived-subtrees beg end)
4171 (goto-char beg)
4172 (if (looking-at (concat ".*:" org-archive-tag ":"))
4173 (message "%s" (substitute-command-keys
4174 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4176 (defun org-force-cycle-archived ()
4177 "Cycle subtree even if it is archived."
4178 (interactive)
4179 (setq this-command 'org-cycle)
4180 (let ((org-cycle-open-archived-trees t))
4181 (call-interactively 'org-cycle)))
4183 (defun org-hide-archived-subtrees (beg end)
4184 "Re-hide all archived subtrees after a visibility state change."
4185 (save-excursion
4186 (let* ((re (concat ":" org-archive-tag ":")))
4187 (goto-char beg)
4188 (while (re-search-forward re end t)
4189 (when (org-at-heading-p)
4190 (org-flag-subtree t)
4191 (org-end-of-subtree t))))))
4193 (declare-function outline-end-of-heading "outline" ())
4194 (declare-function outline-flag-region "outline" (from to flag))
4195 (defun org-flag-subtree (flag)
4196 (save-excursion
4197 (org-back-to-heading t)
4198 (outline-end-of-heading)
4199 (outline-flag-region (point)
4200 (progn (org-end-of-subtree t) (point))
4201 flag)))
4203 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4205 (eval-and-compile
4206 (org-autoload "org-archive"
4207 '(org-add-archive-files)))
4209 ;; Autoload Column View Code
4211 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4212 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4213 (declare-function org-columns-compute "org-colview" (property))
4215 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4216 '(org-columns-number-to-string
4217 org-columns-get-format-and-top-level
4218 org-columns-compute
4219 org-columns-remove-overlays))
4221 ;; Autoload ID code
4223 (declare-function org-id-store-link "org-id")
4224 (declare-function org-id-locations-load "org-id")
4225 (declare-function org-id-locations-save "org-id")
4226 (defvar org-id-track-globally)
4227 (org-autoload "org-id"
4228 '(org-id-new
4229 org-id-copy
4230 org-id-get-with-outline-path-completion
4231 org-id-get-with-outline-drilling))
4233 ;;; Variables for pre-computed regular expressions, all buffer local
4235 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4236 "Matches first line of a hidden block.")
4237 (make-variable-buffer-local 'org-drawer-regexp)
4238 (defvar org-todo-regexp nil
4239 "Matches any of the TODO state keywords.")
4240 (make-variable-buffer-local 'org-todo-regexp)
4241 (defvar org-not-done-regexp nil
4242 "Matches any of the TODO state keywords except the last one.")
4243 (make-variable-buffer-local 'org-not-done-regexp)
4244 (defvar org-not-done-heading-regexp nil
4245 "Matches a TODO headline that is not done.")
4246 (make-variable-buffer-local 'org-not-done-regexp)
4247 (defvar org-todo-line-regexp nil
4248 "Matches a headline and puts TODO state into group 2 if present.")
4249 (make-variable-buffer-local 'org-todo-line-regexp)
4250 (defvar org-complex-heading-regexp nil
4251 "Matches a headline and puts everything into groups:
4252 group 1: the stars
4253 group 2: The todo keyword, maybe
4254 group 3: Priority cookie
4255 group 4: True headline
4256 group 5: Tags")
4257 (make-variable-buffer-local 'org-complex-heading-regexp)
4258 (defvar org-complex-heading-regexp-format nil
4259 "Printf format to make regexp to match an exact headline.
4260 This regexp will match the headline of any node which has the
4261 exact headline text that is put into the format, but may have any
4262 TODO state, priority and tags.")
4263 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4264 (defvar org-todo-line-tags-regexp nil
4265 "Matches a headline and puts TODO state into group 2 if present.
4266 Also put tags into group 4 if tags are present.")
4267 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4268 (defvar org-ds-keyword-length 12
4269 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4270 (make-variable-buffer-local 'org-ds-keyword-length)
4271 (defvar org-deadline-regexp nil
4272 "Matches the DEADLINE keyword.")
4273 (make-variable-buffer-local 'org-deadline-regexp)
4274 (defvar org-deadline-time-regexp nil
4275 "Matches the DEADLINE keyword together with a time stamp.")
4276 (make-variable-buffer-local 'org-deadline-time-regexp)
4277 (defvar org-deadline-line-regexp nil
4278 "Matches the DEADLINE keyword and the rest of the line.")
4279 (make-variable-buffer-local 'org-deadline-line-regexp)
4280 (defvar org-scheduled-regexp nil
4281 "Matches the SCHEDULED keyword.")
4282 (make-variable-buffer-local 'org-scheduled-regexp)
4283 (defvar org-scheduled-time-regexp nil
4284 "Matches the SCHEDULED keyword together with a time stamp.")
4285 (make-variable-buffer-local 'org-scheduled-time-regexp)
4286 (defvar org-closed-time-regexp nil
4287 "Matches the CLOSED keyword together with a time stamp.")
4288 (make-variable-buffer-local 'org-closed-time-regexp)
4290 (defvar org-keyword-time-regexp nil
4291 "Matches any of the 4 keywords, together with the time stamp.")
4292 (make-variable-buffer-local 'org-keyword-time-regexp)
4293 (defvar org-keyword-time-not-clock-regexp nil
4294 "Matches any of the 3 keywords, together with the time stamp.")
4295 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4296 (defvar org-maybe-keyword-time-regexp nil
4297 "Matches a timestamp, possibly preceded by a keyword.")
4298 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4299 (defvar org-all-time-keywords nil
4300 "List of time keywords.")
4301 (make-variable-buffer-local 'org-all-time-keywords)
4303 (defconst org-plain-time-of-day-regexp
4304 (concat
4305 "\\(\\<[012]?[0-9]"
4306 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4307 "\\(--?"
4308 "\\(\\<[012]?[0-9]"
4309 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4310 "\\)?")
4311 "Regular expression to match a plain time or time range.
4312 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4313 groups carry important information:
4314 0 the full match
4315 1 the first time, range or not
4316 8 the second time, if it is a range.")
4318 (defconst org-plain-time-extension-regexp
4319 (concat
4320 "\\(\\<[012]?[0-9]"
4321 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4322 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4323 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4324 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4325 groups carry important information:
4326 0 the full match
4327 7 hours of duration
4328 9 minutes of duration")
4330 (defconst org-stamp-time-of-day-regexp
4331 (concat
4332 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4333 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4334 "\\(--?"
4335 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4336 "Regular expression to match a timestamp time or time range.
4337 After a match, the following groups carry important information:
4338 0 the full match
4339 1 date plus weekday, for back referencing to make sure both times are on the same day
4340 2 the first time, range or not
4341 4 the second time, if it is a range.")
4343 (defconst org-startup-options
4344 '(("fold" org-startup-folded t)
4345 ("overview" org-startup-folded t)
4346 ("nofold" org-startup-folded nil)
4347 ("showall" org-startup-folded nil)
4348 ("showeverything" org-startup-folded showeverything)
4349 ("content" org-startup-folded content)
4350 ("indent" org-startup-indented t)
4351 ("noindent" org-startup-indented nil)
4352 ("hidestars" org-hide-leading-stars t)
4353 ("showstars" org-hide-leading-stars nil)
4354 ("odd" org-odd-levels-only t)
4355 ("oddeven" org-odd-levels-only nil)
4356 ("align" org-startup-align-all-tables t)
4357 ("noalign" org-startup-align-all-tables nil)
4358 ("inlineimages" org-startup-with-inline-images t)
4359 ("noinlineimages" org-startup-with-inline-images nil)
4360 ("customtime" org-display-custom-times t)
4361 ("logdone" org-log-done time)
4362 ("lognotedone" org-log-done note)
4363 ("nologdone" org-log-done nil)
4364 ("lognoteclock-out" org-log-note-clock-out t)
4365 ("nolognoteclock-out" org-log-note-clock-out nil)
4366 ("logrepeat" org-log-repeat state)
4367 ("lognoterepeat" org-log-repeat note)
4368 ("nologrepeat" org-log-repeat nil)
4369 ("logreschedule" org-log-reschedule time)
4370 ("lognotereschedule" org-log-reschedule note)
4371 ("nologreschedule" org-log-reschedule nil)
4372 ("logredeadline" org-log-redeadline time)
4373 ("lognoteredeadline" org-log-redeadline note)
4374 ("nologredeadline" org-log-redeadline nil)
4375 ("logrefile" org-log-refile time)
4376 ("lognoterefile" org-log-refile note)
4377 ("nologrefile" org-log-refile nil)
4378 ("fninline" org-footnote-define-inline t)
4379 ("nofninline" org-footnote-define-inline nil)
4380 ("fnlocal" org-footnote-section nil)
4381 ("fnauto" org-footnote-auto-label t)
4382 ("fnprompt" org-footnote-auto-label nil)
4383 ("fnconfirm" org-footnote-auto-label confirm)
4384 ("fnplain" org-footnote-auto-label plain)
4385 ("fnadjust" org-footnote-auto-adjust t)
4386 ("nofnadjust" org-footnote-auto-adjust nil)
4387 ("constcgs" constants-unit-system cgs)
4388 ("constSI" constants-unit-system SI)
4389 ("noptag" org-tag-persistent-alist nil)
4390 ("hideblocks" org-hide-block-startup t)
4391 ("nohideblocks" org-hide-block-startup nil)
4392 ("beamer" org-startup-with-beamer-mode t)
4393 ("entitiespretty" org-pretty-entities t)
4394 ("entitiesplain" org-pretty-entities nil))
4395 "Variable associated with STARTUP options for org-mode.
4396 Each element is a list of three items: the startup options (as written
4397 in the #+STARTUP line), the corresponding variable, and the value to set
4398 this variable to if the option is found. An optional forth element PUSH
4399 means to push this value onto the list in the variable.")
4401 (defun org-update-property-plist (key val props)
4402 "Update PROPS with KEY and VAL."
4403 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4404 (key (if appending (substring key 0 (- (length key) 1)) key))
4405 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4406 (previous (cdr (assoc key props))))
4407 (if appending
4408 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4409 (cons (cons key val) remainder))))
4411 (defconst org-block-regexp
4412 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4413 "Regular expression for hiding blocks.")
4414 (defconst org-heading-keyword-regexp-format
4415 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4416 "Printf format for a regexp matching an headline with some keyword.
4417 This regexp will match the headline of any node which has the
4418 exact keyword that is put into the format. The keyword isn't in
4419 any group by default, but the stars and the body are.")
4420 (defconst org-heading-keyword-maybe-regexp-format
4421 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4422 "Printf format for a regexp matching an headline, possibly with some keyword.
4423 This regexp can match any headline with the specified keyword, or
4424 without a keyword. The keyword isn't in any group by default,
4425 but the stars and the body are.")
4427 (defun org-set-regexps-and-options ()
4428 "Precompute regular expressions for current buffer."
4429 (when (derived-mode-p 'org-mode)
4430 (org-set-local 'org-todo-kwd-alist nil)
4431 (org-set-local 'org-todo-key-alist nil)
4432 (org-set-local 'org-todo-key-trigger nil)
4433 (org-set-local 'org-todo-keywords-1 nil)
4434 (org-set-local 'org-done-keywords nil)
4435 (org-set-local 'org-todo-heads nil)
4436 (org-set-local 'org-todo-sets nil)
4437 (org-set-local 'org-todo-log-states nil)
4438 (org-set-local 'org-file-properties nil)
4439 (org-set-local 'org-file-tags nil)
4440 (let ((re (org-make-options-regexp
4441 '("CATEGORY" "TODO" "COLUMNS"
4442 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4443 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4444 "OPTIONS")
4445 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4446 (splitre "[ \t]+")
4447 (scripts org-use-sub-superscripts)
4448 kwds kws0 kwsa key log value cat arch tags const links hw dws
4449 tail sep kws1 prio props ftags drawers beamer-p
4450 ext-setup-or-nil setup-contents (start 0))
4451 (save-excursion
4452 (save-restriction
4453 (widen)
4454 (goto-char (point-min))
4455 (while (or (and ext-setup-or-nil
4456 (string-match re ext-setup-or-nil start)
4457 (setq start (match-end 0)))
4458 (and (setq ext-setup-or-nil nil start 0)
4459 (re-search-forward re nil t)))
4460 (setq key (upcase (match-string 1 ext-setup-or-nil))
4461 value (org-match-string-no-properties 2 ext-setup-or-nil))
4462 (if (stringp value) (setq value (org-trim value)))
4463 (cond
4464 ((equal key "CATEGORY")
4465 (setq cat value))
4466 ((member key '("SEQ_TODO" "TODO"))
4467 (push (cons 'sequence (org-split-string value splitre)) kwds))
4468 ((equal key "TYP_TODO")
4469 (push (cons 'type (org-split-string value splitre)) kwds))
4470 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4471 ;; general TODO-like setup
4472 (push (cons (intern (downcase (match-string 1 key)))
4473 (org-split-string value splitre)) kwds))
4474 ((equal key "TAGS")
4475 (setq tags (append tags (if tags '("\\n") nil)
4476 (org-split-string value splitre))))
4477 ((equal key "COLUMNS")
4478 (org-set-local 'org-columns-default-format value))
4479 ((equal key "LINK")
4480 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4481 (push (cons (match-string 1 value)
4482 (org-trim (match-string 2 value)))
4483 links)))
4484 ((equal key "PRIORITIES")
4485 (setq prio (org-split-string value " +")))
4486 ((equal key "PROPERTY")
4487 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4488 (setq props (org-update-property-plist (match-string 1 value)
4489 (match-string 2 value)
4490 props))))
4491 ((equal key "FILETAGS")
4492 (when (string-match "\\S-" value)
4493 (setq ftags
4494 (append
4495 ftags
4496 (apply 'append
4497 (mapcar (lambda (x) (org-split-string x ":"))
4498 (org-split-string value)))))))
4499 ((equal key "DRAWERS")
4500 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4501 ((equal key "CONSTANTS")
4502 (setq const (append const (org-split-string value splitre))))
4503 ((equal key "STARTUP")
4504 (let ((opts (org-split-string value splitre))
4505 l var val)
4506 (while (setq l (pop opts))
4507 (when (setq l (assoc l org-startup-options))
4508 (setq var (nth 1 l) val (nth 2 l))
4509 (if (not (nth 3 l))
4510 (set (make-local-variable var) val)
4511 (if (not (listp (symbol-value var)))
4512 (set (make-local-variable var) nil))
4513 (set (make-local-variable var) (symbol-value var))
4514 (add-to-list var val))))))
4515 ((equal key "ARCHIVE")
4516 (setq arch value)
4517 (remove-text-properties 0 (length arch)
4518 '(face t fontified t) arch))
4519 ((equal key "LATEX_CLASS")
4520 (setq beamer-p (equal value "beamer")))
4521 ((equal key "OPTIONS")
4522 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4523 (setq scripts (read (match-string 2 value)))))
4524 ((equal key "SETUPFILE")
4525 (setq setup-contents (org-file-contents
4526 (expand-file-name
4527 (org-remove-double-quotes value))
4528 'noerror))
4529 (if (not ext-setup-or-nil)
4530 (setq ext-setup-or-nil setup-contents start 0)
4531 (setq ext-setup-or-nil
4532 (concat (substring ext-setup-or-nil 0 start)
4533 "\n" setup-contents "\n"
4534 (substring ext-setup-or-nil start)))))))
4535 ;; search for property blocks
4536 (goto-char (point-min))
4537 (while (re-search-forward org-block-regexp nil t)
4538 (when (equal "PROPERTY" (upcase (match-string 1)))
4539 (setq value (replace-regexp-in-string
4540 "[\n\r]" " " (match-string 4)))
4541 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4542 (setq props (org-update-property-plist (match-string 1 value)
4543 (match-string 2 value)
4544 props)))))))
4545 (org-set-local 'org-use-sub-superscripts scripts)
4546 (when cat
4547 (org-set-local 'org-category (intern cat))
4548 (push (cons "CATEGORY" cat) props))
4549 (when prio
4550 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4551 (setq prio (mapcar 'string-to-char prio))
4552 (org-set-local 'org-highest-priority (nth 0 prio))
4553 (org-set-local 'org-lowest-priority (nth 1 prio))
4554 (org-set-local 'org-default-priority (nth 2 prio)))
4555 (and props (org-set-local 'org-file-properties (nreverse props)))
4556 (and ftags (org-set-local 'org-file-tags
4557 (mapcar 'org-add-prop-inherited ftags)))
4558 (and drawers (org-set-local 'org-drawers drawers))
4559 (and arch (org-set-local 'org-archive-location arch))
4560 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4561 ;; Process the TODO keywords
4562 (unless kwds
4563 ;; Use the global values as if they had been given locally.
4564 (setq kwds (default-value 'org-todo-keywords))
4565 (if (stringp (car kwds))
4566 (setq kwds (list (cons org-todo-interpretation
4567 (default-value 'org-todo-keywords)))))
4568 (setq kwds (reverse kwds)))
4569 (setq kwds (nreverse kwds))
4570 (let (inter kws kw)
4571 (while (setq kws (pop kwds))
4572 (let ((kws (or
4573 (run-hook-with-args-until-success
4574 'org-todo-setup-filter-hook kws)
4575 kws)))
4576 (setq inter (pop kws) sep (member "|" kws)
4577 kws0 (delete "|" (copy-sequence kws))
4578 kwsa nil
4579 kws1 (mapcar
4580 (lambda (x)
4581 ;; 1 2
4582 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4583 (progn
4584 (setq kw (match-string 1 x)
4585 key (and (match-end 2) (match-string 2 x))
4586 log (org-extract-log-state-settings x))
4587 (push (cons kw (and key (string-to-char key))) kwsa)
4588 (and log (push log org-todo-log-states))
4590 (error "Invalid TODO keyword %s" x)))
4591 kws0)
4592 kwsa (if kwsa (append '((:startgroup))
4593 (nreverse kwsa)
4594 '((:endgroup))))
4595 hw (car kws1)
4596 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4597 tail (list inter hw (car dws) (org-last dws))))
4598 (add-to-list 'org-todo-heads hw 'append)
4599 (push kws1 org-todo-sets)
4600 (setq org-done-keywords (append org-done-keywords dws nil))
4601 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4602 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4603 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4604 (setq org-todo-sets (nreverse org-todo-sets)
4605 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4606 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4607 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4608 ;; Process the constants
4609 (when const
4610 (let (e cst)
4611 (while (setq e (pop const))
4612 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4613 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4614 (setq org-table-formula-constants-local cst)))
4616 ;; Process the tags.
4617 (when tags
4618 (let (e tgs)
4619 (while (setq e (pop tags))
4620 (cond
4621 ((equal e "{") (push '(:startgroup) tgs))
4622 ((equal e "}") (push '(:endgroup) tgs))
4623 ((equal e "\\n") (push '(:newline) tgs))
4624 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4625 (push (cons (match-string 1 e)
4626 (string-to-char (match-string 2 e)))
4627 tgs))
4628 (t (push (list e) tgs))))
4629 (org-set-local 'org-tag-alist nil)
4630 (while (setq e (pop tgs))
4631 (or (and (stringp (car e))
4632 (assoc (car e) org-tag-alist))
4633 (push e org-tag-alist)))))
4635 ;; Compute the regular expressions and other local variables.
4636 ;; Using `org-outline-regexp-bol' would complicate them much,
4637 ;; because of the fixed white space at the end of that string.
4638 (if (not org-done-keywords)
4639 (setq org-done-keywords (and org-todo-keywords-1
4640 (list (org-last org-todo-keywords-1)))))
4641 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4642 (length org-scheduled-string)
4643 (length org-clock-string)
4644 (length org-closed-string)))
4645 org-drawer-regexp
4646 (concat "^[ \t]*:\\("
4647 (mapconcat 'regexp-quote org-drawers "\\|")
4648 "\\):[ \t]*$")
4649 org-not-done-keywords
4650 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4651 org-todo-regexp
4652 (concat "\\("
4653 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4654 "\\)")
4655 org-not-done-regexp
4656 (concat "\\("
4657 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4658 "\\)")
4659 org-not-done-heading-regexp
4660 (format org-heading-keyword-regexp-format org-not-done-regexp)
4661 org-todo-line-regexp
4662 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4663 org-complex-heading-regexp
4664 (concat "^\\(\\*+\\)"
4665 "\\(?: +" org-todo-regexp "\\)?"
4666 "\\(?: +\\(\\[#.\\]\\)\\)?"
4667 "\\(?: +\\(.*?\\)\\)??"
4668 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4669 "[ \t]*$")
4670 org-complex-heading-regexp-format
4671 (concat "^\\(\\*+\\)"
4672 "\\(?: +" org-todo-regexp "\\)?"
4673 "\\(?: +\\(\\[#.\\]\\)\\)?"
4674 "\\(?: +"
4675 ;; Stats cookies can be stuck to body.
4676 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4677 "\\(%s\\)"
4678 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4679 "\\)"
4680 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4681 "[ \t]*$")
4682 org-todo-line-tags-regexp
4683 (concat "^\\(\\*+\\)"
4684 "\\(?: +" org-todo-regexp "\\)?"
4685 "\\(?: +\\(.*?\\)\\)??"
4686 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4687 "[ \t]*$")
4688 org-deadline-regexp (concat "\\<" org-deadline-string)
4689 org-deadline-time-regexp
4690 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4691 org-deadline-line-regexp
4692 (concat "\\<\\(" org-deadline-string "\\).*")
4693 org-scheduled-regexp
4694 (concat "\\<" org-scheduled-string)
4695 org-scheduled-time-regexp
4696 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4697 org-closed-time-regexp
4698 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4699 org-keyword-time-regexp
4700 (concat "\\<\\(" org-scheduled-string
4701 "\\|" org-deadline-string
4702 "\\|" org-closed-string
4703 "\\|" org-clock-string "\\)"
4704 " *[[<]\\([^]>]+\\)[]>]")
4705 org-keyword-time-not-clock-regexp
4706 (concat "\\<\\(" org-scheduled-string
4707 "\\|" org-deadline-string
4708 "\\|" org-closed-string
4709 "\\)"
4710 " *[[<]\\([^]>]+\\)[]>]")
4711 org-maybe-keyword-time-regexp
4712 (concat "\\(\\<\\(" org-scheduled-string
4713 "\\|" org-deadline-string
4714 "\\|" org-closed-string
4715 "\\|" org-clock-string "\\)\\)?"
4716 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4717 org-all-time-keywords
4718 (mapcar (lambda (w) (substring w 0 -1))
4719 (list org-scheduled-string org-deadline-string
4720 org-clock-string org-closed-string))
4722 (org-compute-latex-and-specials-regexp)
4723 (org-set-font-lock-defaults))))
4725 (defun org-file-contents (file &optional noerror)
4726 "Return the contents of FILE, as a string."
4727 (if (or (not file)
4728 (not (file-readable-p file)))
4729 (if noerror
4730 (progn
4731 (message "Cannot read file \"%s\"" file)
4732 (ding) (sit-for 2)
4734 (error "Cannot read file \"%s\"" file))
4735 (with-temp-buffer
4736 (insert-file-contents file)
4737 (buffer-string))))
4739 (defun org-extract-log-state-settings (x)
4740 "Extract the log state setting from a TODO keyword string.
4741 This will extract info from a string like \"WAIT(w@/!)\"."
4742 (let (kw key log1 log2)
4743 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4744 (setq kw (match-string 1 x)
4745 key (and (match-end 2) (match-string 2 x))
4746 log1 (and (match-end 3) (match-string 3 x))
4747 log2 (and (match-end 4) (match-string 4 x)))
4748 (and (or log1 log2)
4749 (list kw
4750 (and log1 (if (equal log1 "!") 'time 'note))
4751 (and log2 (if (equal log2 "!") 'time 'note)))))))
4753 (defun org-remove-keyword-keys (list)
4754 "Remove a pair of parenthesis at the end of each string in LIST."
4755 (mapcar (lambda (x)
4756 (if (string-match "(.*)$" x)
4757 (substring x 0 (match-beginning 0))
4759 list))
4761 (defun org-assign-fast-keys (alist)
4762 "Assign fast keys to a keyword-key alist.
4763 Respect keys that are already there."
4764 (let (new e (alt ?0))
4765 (while (setq e (pop alist))
4766 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4767 (cdr e)) ;; Key already assigned.
4768 (push e new)
4769 (let ((clist (string-to-list (downcase (car e))))
4770 (used (append new alist)))
4771 (when (= (car clist) ?@)
4772 (pop clist))
4773 (while (and clist (rassoc (car clist) used))
4774 (pop clist))
4775 (unless clist
4776 (while (rassoc alt used)
4777 (incf alt)))
4778 (push (cons (car e) (or (car clist) alt)) new))))
4779 (nreverse new)))
4781 ;;; Some variables used in various places
4783 (defvar org-window-configuration nil
4784 "Used in various places to store a window configuration.")
4785 (defvar org-selected-window nil
4786 "Used in various places to store a window configuration.")
4787 (defvar org-finish-function nil
4788 "Function to be called when `C-c C-c' is used.
4789 This is for getting out of special buffers like capture.")
4792 ;; FIXME: Occasionally check by commenting these, to make sure
4793 ;; no other functions uses these, forgetting to let-bind them.
4794 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4795 (defvar org-last-state)
4796 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4798 ;; Defined somewhere in this file, but used before definition.
4799 (defvar org-entities) ;; defined in org-entities.el
4800 (defvar org-struct-menu)
4801 (defvar org-org-menu)
4802 (defvar org-tbl-menu)
4804 ;;;; Define the Org-mode
4806 ;; We use a before-change function to check if a table might need
4807 ;; an update.
4808 (defvar org-table-may-need-update t
4809 "Indicates that a table might need an update.
4810 This variable is set by `org-before-change-function'.
4811 `org-table-align' sets it back to nil.")
4812 (defun org-before-change-function (beg end)
4813 "Every change indicates that a table might need an update."
4814 (setq org-table-may-need-update t))
4815 (defvar org-mode-map)
4816 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4817 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4818 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4819 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4820 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4821 (defvar org-table-buffer-is-an nil)
4823 (defvar bidi-paragraph-direction)
4824 (defvar buffer-face-mode-face)
4826 (require 'outline)
4827 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4828 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4829 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4831 ;; Other stuff we need.
4832 (require 'time-date)
4833 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4834 (require 'easymenu)
4835 (require 'overlay)
4837 (require 'org-macs)
4838 (require 'org-entities)
4839 ;; (require 'org-compat) moved higher up in the file before it is first used
4840 (require 'org-faces)
4841 (require 'org-list)
4842 (require 'org-pcomplete)
4843 (require 'org-src)
4844 (require 'org-footnote)
4846 ;; babel
4847 (require 'ob)
4848 (require 'ob-table)
4849 (require 'ob-lob)
4850 (require 'ob-ref)
4851 (require 'ob-tangle)
4852 (require 'ob-comint)
4853 (require 'ob-keys)
4855 ;;;###autoload
4856 (define-derived-mode org-mode outline-mode "Org"
4857 "Outline-based notes management and organizer, alias
4858 \"Carsten's outline-mode for keeping track of everything.\"
4860 Org-mode develops organizational tasks around a NOTES file which
4861 contains information about projects as plain text. Org-mode is
4862 implemented on top of outline-mode, which is ideal to keep the content
4863 of large files well structured. It supports ToDo items, deadlines and
4864 time stamps, which magically appear in the diary listing of the Emacs
4865 calendar. Tables are easily created with a built-in table editor.
4866 Plain text URL-like links connect to websites, emails (VM), Usenet
4867 messages (Gnus), BBDB entries, and any files related to the project.
4868 For printing and sharing of notes, an Org-mode file (or a part of it)
4869 can be exported as a structured ASCII or HTML file.
4871 The following commands are available:
4873 \\{org-mode-map}"
4875 ;; Get rid of Outline menus, they are not needed
4876 ;; Need to do this here because define-derived-mode sets up
4877 ;; the keymap so late. Still, it is a waste to call this each time
4878 ;; we switch another buffer into org-mode.
4879 (if (featurep 'xemacs)
4880 (when (boundp 'outline-mode-menu-heading)
4881 ;; Assume this is Greg's port, it uses easymenu
4882 (easy-menu-remove outline-mode-menu-heading)
4883 (easy-menu-remove outline-mode-menu-show)
4884 (easy-menu-remove outline-mode-menu-hide))
4885 (define-key org-mode-map [menu-bar headings] 'undefined)
4886 (define-key org-mode-map [menu-bar hide] 'undefined)
4887 (define-key org-mode-map [menu-bar show] 'undefined))
4889 (org-load-modules-maybe)
4890 (easy-menu-add org-org-menu)
4891 (easy-menu-add org-tbl-menu)
4892 (org-install-agenda-files-menu)
4893 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4894 (add-to-invisibility-spec '(org-cwidth))
4895 (add-to-invisibility-spec '(org-hide-block . t))
4896 (when (featurep 'xemacs)
4897 (org-set-local 'line-move-ignore-invisible t))
4898 (org-set-local 'outline-regexp org-outline-regexp)
4899 (org-set-local 'outline-level 'org-outline-level)
4900 (setq bidi-paragraph-direction 'left-to-right)
4901 (when (and org-ellipsis
4902 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4903 (fboundp 'make-glyph-code))
4904 (unless org-display-table
4905 (setq org-display-table (make-display-table)))
4906 (set-display-table-slot
4907 org-display-table 4
4908 (vconcat (mapcar
4909 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4910 org-ellipsis)))
4911 (if (stringp org-ellipsis) org-ellipsis "..."))))
4912 (setq buffer-display-table org-display-table))
4913 (org-set-regexps-and-options)
4914 (when (and org-tag-faces (not org-tags-special-faces-re))
4915 ;; tag faces set outside customize.... force initialization.
4916 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4917 ;; Calc embedded
4918 (org-set-local 'calc-embedded-open-mode "# ")
4919 (modify-syntax-entry ?@ "w")
4920 (if org-startup-truncated (setq truncate-lines t))
4921 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
4922 (org-set-local 'font-lock-unfontify-region-function
4923 'org-unfontify-region)
4924 ;; Activate before-change-function
4925 (org-set-local 'org-table-may-need-update t)
4926 (org-add-hook 'before-change-functions 'org-before-change-function nil
4927 'local)
4928 ;; Check for running clock before killing a buffer
4929 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4930 ;; Indentation.
4931 (org-set-local 'indent-line-function 'org-indent-line)
4932 (org-set-local 'indent-region-function 'org-indent-region)
4933 ;; Initialize radio targets.
4934 (org-update-radio-target-regexp)
4935 ;; Filling and auto-filling.
4936 (org-setup-filling)
4937 ;; Comments.
4938 (org-setup-comments-handling)
4939 ;; Beginning/end of defun
4940 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4941 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4942 ;; Next error for sparse trees
4943 (org-set-local 'next-error-function 'org-occur-next-match)
4944 ;; Make sure dependence stuff works reliably, even for users who set it
4945 ;; too late :-(
4946 (if org-enforce-todo-dependencies
4947 (add-hook 'org-blocker-hook
4948 'org-block-todo-from-children-or-siblings-or-parent)
4949 (remove-hook 'org-blocker-hook
4950 'org-block-todo-from-children-or-siblings-or-parent))
4951 (if org-enforce-todo-checkbox-dependencies
4952 (add-hook 'org-blocker-hook
4953 'org-block-todo-from-checkboxes)
4954 (remove-hook 'org-blocker-hook
4955 'org-block-todo-from-checkboxes))
4957 ;; Align options lines
4958 (org-set-local
4959 'align-mode-rules-list
4960 '((org-in-buffer-settings
4961 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4962 (modes . '(org-mode)))))
4964 ;; Imenu
4965 (org-set-local 'imenu-create-index-function
4966 'org-imenu-get-tree)
4968 ;; Make isearch reveal context
4969 (if (or (featurep 'xemacs)
4970 (not (boundp 'outline-isearch-open-invisible-function)))
4971 ;; Emacs 21 and XEmacs make use of the hook
4972 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4973 ;; Emacs 22 deals with this through a special variable
4974 (org-set-local 'outline-isearch-open-invisible-function
4975 (lambda (&rest ignore) (org-show-context 'isearch)))
4976 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
4978 ;; Setup the pcomplete hooks
4979 (set (make-local-variable 'pcomplete-command-completion-function)
4980 'org-pcomplete-initial)
4981 (set (make-local-variable 'pcomplete-command-name-function)
4982 'org-command-at-point)
4983 (set (make-local-variable 'pcomplete-default-completion-function)
4984 'ignore)
4985 (set (make-local-variable 'pcomplete-parse-arguments-function)
4986 'org-parse-arguments)
4987 (set (make-local-variable 'pcomplete-termination-string) "")
4988 (when (>= emacs-major-version 23)
4989 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4991 ;; If empty file that did not turn on org-mode automatically, make it to.
4992 (if (and org-insert-mode-line-in-empty-file
4993 (org-called-interactively-p 'any)
4994 (= (point-min) (point-max)))
4995 (insert "# -*- mode: org -*-\n\n"))
4996 (unless org-inhibit-startup
4997 (and org-startup-with-beamer-mode (org-beamer-mode))
4998 (when org-startup-align-all-tables
4999 (let ((bmp (buffer-modified-p)))
5000 (org-table-map-tables 'org-table-align 'quietly)
5001 (set-buffer-modified-p bmp)))
5002 (when org-startup-with-inline-images
5003 (org-display-inline-images))
5004 (unless org-inhibit-startup-visibility-stuff
5005 (org-set-startup-visibility)))
5006 ;; Try to set org-hide correctly
5007 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5009 (when (fboundp 'abbrev-table-put)
5010 (abbrev-table-put org-mode-abbrev-table
5011 :parents (list text-mode-abbrev-table)))
5013 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5015 (defsubst org-fix-ellipsis-at-bol ()
5016 (save-excursion (goto-char (window-start)) (recenter 0)))
5018 (defun org-find-invisible-foreground ()
5019 (let ((candidates (remove
5020 "unspecified-bg"
5021 (nconc
5022 (list (face-background 'default)
5023 (face-background 'org-default))
5024 (mapcar
5025 (lambda (alist)
5026 (when (boundp alist)
5027 (cdr (assoc 'background-color (symbol-value alist)))))
5028 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5029 (list (face-foreground 'org-hide))))))
5030 (car (remove nil candidates))))
5032 (defun org-current-time ()
5033 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5034 (if (> (car org-time-stamp-rounding-minutes) 1)
5035 (let ((r (car org-time-stamp-rounding-minutes))
5036 (time (decode-time)))
5037 (apply 'encode-time
5038 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5039 (nthcdr 2 time))))
5040 (current-time)))
5042 (defun org-today ()
5043 "Return today date, considering `org-extend-today-until'."
5044 (time-to-days
5045 (time-subtract (current-time)
5046 (list 0 (* 3600 org-extend-today-until) 0))))
5048 ;;;; Font-Lock stuff, including the activators
5050 (defvar org-mouse-map (make-sparse-keymap))
5051 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5052 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5053 (when org-mouse-1-follows-link
5054 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5055 (when org-tab-follows-link
5056 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5057 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5059 (require 'font-lock)
5061 (defconst org-non-link-chars "]\t\n\r<>")
5062 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5063 "shell" "elisp" "doi" "message"))
5064 (defvar org-link-types-re nil
5065 "Matches a link that has a url-like prefix like \"http:\"")
5066 (defvar org-link-re-with-space nil
5067 "Matches a link with spaces, optional angular brackets around it.")
5068 (defvar org-link-re-with-space2 nil
5069 "Matches a link with spaces, optional angular brackets around it.")
5070 (defvar org-link-re-with-space3 nil
5071 "Matches a link with spaces, only for internal part in bracket links.")
5072 (defvar org-angle-link-re nil
5073 "Matches link with angular brackets, spaces are allowed.")
5074 (defvar org-plain-link-re nil
5075 "Matches plain link, without spaces.")
5076 (defvar org-bracket-link-regexp nil
5077 "Matches a link in double brackets.")
5078 (defvar org-bracket-link-analytic-regexp nil
5079 "Regular expression used to analyze links.
5080 Here is what the match groups contain after a match:
5081 1: http:
5082 2: http
5083 3: path
5084 4: [desc]
5085 5: desc")
5086 (defvar org-bracket-link-analytic-regexp++ nil
5087 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5088 (defvar org-any-link-re nil
5089 "Regular expression matching any link.")
5091 (defcustom org-match-sexp-depth 3
5092 "Number of stacked braces for sub/superscript matching.
5093 This has to be set before loading org.el to be effective."
5094 :group 'org-export-translation ; ??????????????????????????/
5095 :type 'integer)
5097 (defun org-create-multibrace-regexp (left right n)
5098 "Create a regular expression which will match a balanced sexp.
5099 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5100 as single character strings.
5101 The regexp returned will match the entire expression including the
5102 delimiters. It will also define a single group which contains the
5103 match except for the outermost delimiters. The maximum depth of
5104 stacked delimiters is N. Escaping delimiters is not possible."
5105 (let* ((nothing (concat "[^" left right "]*?"))
5106 (or "\\|")
5107 (re nothing)
5108 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5109 (while (> n 1)
5110 (setq n (1- n)
5111 re (concat re or next)
5112 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5113 (concat left "\\(" re "\\)" right)))
5115 (defvar org-match-substring-regexp
5116 (concat
5117 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5118 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5119 "\\|"
5120 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5121 "\\|"
5122 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5123 "The regular expression matching a sub- or superscript.")
5125 (defvar org-match-substring-with-braces-regexp
5126 (concat
5127 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5128 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5129 "\\)")
5130 "The regular expression matching a sub- or superscript, forcing braces.")
5132 (defun org-make-link-regexps ()
5133 "Update the link regular expressions.
5134 This should be called after the variable `org-link-types' has changed."
5135 (setq org-link-types-re
5136 (concat
5137 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5138 org-link-re-with-space
5139 (concat
5140 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5141 "\\([^" org-non-link-chars " ]"
5142 "[^" org-non-link-chars "]*"
5143 "[^" org-non-link-chars " ]\\)>?")
5144 org-link-re-with-space2
5145 (concat
5146 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5147 "\\([^" org-non-link-chars " ]"
5148 "[^\t\n\r]*"
5149 "[^" org-non-link-chars " ]\\)>?")
5150 org-link-re-with-space3
5151 (concat
5152 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5153 "\\([^" org-non-link-chars " ]"
5154 "[^\t\n\r]*\\)")
5155 org-angle-link-re
5156 (concat
5157 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5158 "\\([^" org-non-link-chars " ]"
5159 "[^" org-non-link-chars "]*"
5160 "\\)>")
5161 org-plain-link-re
5162 (concat
5163 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5164 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5165 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5166 org-bracket-link-regexp
5167 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5168 org-bracket-link-analytic-regexp
5169 (concat
5170 "\\[\\["
5171 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5172 "\\([^]]+\\)"
5173 "\\]"
5174 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5175 "\\]")
5176 org-bracket-link-analytic-regexp++
5177 (concat
5178 "\\[\\["
5179 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5180 "\\([^]]+\\)"
5181 "\\]"
5182 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5183 "\\]")
5184 org-any-link-re
5185 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5186 org-angle-link-re "\\)\\|\\("
5187 org-plain-link-re "\\)")))
5189 (org-make-link-regexps)
5191 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5192 "Regular expression for fast time stamp matching.")
5193 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5194 "Regular expression for fast time stamp matching.")
5195 (defconst org-ts-regexp0
5196 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5197 "Regular expression matching time strings for analysis.
5198 This one does not require the space after the date, so it can be used
5199 on a string that terminates immediately after the date.")
5200 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5201 "Regular expression matching time strings for analysis.")
5202 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5203 "Regular expression matching time stamps, with groups.")
5204 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5205 "Regular expression matching time stamps (also [..]), with groups.")
5206 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5207 "Regular expression matching a time stamp range.")
5208 (defconst org-tr-regexp-both
5209 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5210 "Regular expression matching a time stamp range.")
5211 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5212 org-ts-regexp "\\)?")
5213 "Regular expression matching a time stamp or time stamp range.")
5214 (defconst org-tsr-regexp-both
5215 (concat org-ts-regexp-both "\\(--?-?"
5216 org-ts-regexp-both "\\)?")
5217 "Regular expression matching a time stamp or time stamp range.
5218 The time stamps may be either active or inactive.")
5220 (defvar org-emph-face nil)
5222 (defun org-do-emphasis-faces (limit)
5223 "Run through the buffer and add overlays to emphasized strings."
5224 (let (rtn a)
5225 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5226 (if (not (= (char-after (match-beginning 3))
5227 (char-after (match-beginning 4))))
5228 (progn
5229 (setq rtn t)
5230 (setq a (assoc (match-string 3) org-emphasis-alist))
5231 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5232 'face
5233 (nth 1 a))
5234 (and (nth 4 a)
5235 (org-remove-flyspell-overlays-in
5236 (match-beginning 0) (match-end 0)))
5237 (add-text-properties (match-beginning 2) (match-end 2)
5238 '(font-lock-multiline t org-emphasis t))
5239 (when org-hide-emphasis-markers
5240 (add-text-properties (match-end 4) (match-beginning 5)
5241 '(invisible org-link))
5242 (add-text-properties (match-beginning 3) (match-end 3)
5243 '(invisible org-link)))))
5244 (backward-char 1))
5245 rtn))
5247 (defun org-emphasize (&optional char)
5248 "Insert or change an emphasis, i.e. a font like bold or italic.
5249 If there is an active region, change that region to a new emphasis.
5250 If there is no region, just insert the marker characters and position
5251 the cursor between them.
5252 CHAR should be either the marker character, or the first character of the
5253 HTML tag associated with that emphasis. If CHAR is a space, the means
5254 to remove the emphasis of the selected region.
5255 If char is not given (for example in an interactive call) it
5256 will be prompted for."
5257 (interactive)
5258 (let ((eal org-emphasis-alist) e det
5259 (erc org-emphasis-regexp-components)
5260 (prompt "")
5261 (string "") beg end move tag c s)
5262 (if (org-region-active-p)
5263 (setq beg (region-beginning) end (region-end)
5264 string (buffer-substring beg end))
5265 (setq move t))
5267 (while (setq e (pop eal))
5268 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5269 c (aref tag 0))
5270 (push (cons c (string-to-char (car e))) det)
5271 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5272 (substring tag 1)))))
5273 (setq det (nreverse det))
5274 (unless char
5275 (message "%s" (concat "Emphasis marker or tag:" prompt))
5276 (setq char (read-char-exclusive)))
5277 (setq char (or (cdr (assoc char det)) char))
5278 (if (equal char ?\ )
5279 (setq s "" move nil)
5280 (unless (assoc (char-to-string char) org-emphasis-alist)
5281 (error "No such emphasis marker: \"%c\"" char))
5282 (setq s (char-to-string char)))
5283 (while (and (> (length string) 1)
5284 (equal (substring string 0 1) (substring string -1))
5285 (assoc (substring string 0 1) org-emphasis-alist))
5286 (setq string (substring string 1 -1)))
5287 (setq string (concat s string s))
5288 (if beg (delete-region beg end))
5289 (unless (or (bolp)
5290 (string-match (concat "[" (nth 0 erc) "\n]")
5291 (char-to-string (char-before (point)))))
5292 (insert " "))
5293 (unless (or (eobp)
5294 (string-match (concat "[" (nth 1 erc) "\n]")
5295 (char-to-string (char-after (point)))))
5296 (insert " ") (backward-char 1))
5297 (insert string)
5298 (and move (backward-char 1))))
5300 (defconst org-nonsticky-props
5301 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5303 (defsubst org-rear-nonsticky-at (pos)
5304 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5306 (defun org-activate-plain-links (limit)
5307 "Run through the buffer and add overlays to links."
5308 (let (f)
5309 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5310 (not (org-in-src-block-p)))
5311 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5312 (setq f (get-text-property (match-beginning 0) 'face))
5313 (unless (or (org-in-src-block-p)
5314 (eq f 'org-tag)
5315 (and (listp f) (memq 'org-tag f)))
5316 (add-text-properties (match-beginning 0) (match-end 0)
5317 (list 'mouse-face 'highlight
5318 'face 'org-link
5319 'keymap org-mouse-map))
5320 (org-rear-nonsticky-at (match-end 0)))
5321 t)))
5323 (defun org-activate-code (limit)
5324 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5325 (progn
5326 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5327 (remove-text-properties (match-beginning 0) (match-end 0)
5328 '(display t invisible t intangible t))
5329 t)))
5331 (defcustom org-src-fontify-natively nil
5332 "When non-nil, fontify code in code blocks."
5333 :type 'boolean
5334 :version "24.1"
5335 :group 'org-appearance
5336 :group 'org-babel)
5338 (defcustom org-allow-promoting-top-level-subtree nil
5339 "When non-nil, allow promoting a top level subtree.
5340 The leading star of the top level headline will be replaced
5341 by a #."
5342 :type 'boolean
5343 :version "24.1"
5344 :group 'org-appearance)
5346 (defun org-fontify-meta-lines-and-blocks (limit)
5347 (condition-case nil
5348 (org-fontify-meta-lines-and-blocks-1 limit)
5349 (error (message "org-mode fontification error"))))
5351 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5352 "Fontify #+ lines and blocks, in the correct ways."
5353 (let ((case-fold-search t))
5354 (if (re-search-forward
5355 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5356 limit t)
5357 (let ((beg (match-beginning 0))
5358 (block-start (match-end 0))
5359 (block-end nil)
5360 (lang (match-string 7))
5361 (beg1 (line-beginning-position 2))
5362 (dc1 (downcase (match-string 2)))
5363 (dc3 (downcase (match-string 3)))
5364 end end1 quoting block-type ovl)
5365 (cond
5366 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5367 ;; a single line of backend-specific content
5368 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5369 (remove-text-properties (match-beginning 0) (match-end 0)
5370 '(display t invisible t intangible t))
5371 (add-text-properties (match-beginning 1) (match-end 3)
5372 '(font-lock-fontified t face org-meta-line))
5373 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5374 '(font-lock-fontified t face org-block))
5375 ; for backend-specific code
5377 ((and (match-end 4) (equal dc3 "+begin"))
5378 ;; Truly a block
5379 (setq block-type (downcase (match-string 5))
5380 quoting (member block-type org-protecting-blocks))
5381 (when (re-search-forward
5382 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5383 nil t) ;; on purpose, we look further than LIMIT
5384 (setq end (min (point-max) (match-end 0))
5385 end1 (min (point-max) (1- (match-beginning 0))))
5386 (setq block-end (match-beginning 0))
5387 (when quoting
5388 (remove-text-properties beg end
5389 '(display t invisible t intangible t)))
5390 (add-text-properties
5391 beg end
5392 '(font-lock-fontified t font-lock-multiline t))
5393 (add-text-properties beg beg1 '(face org-meta-line))
5394 (add-text-properties end1 (min (point-max) (1+ end))
5395 '(face org-meta-line)) ; for end_src
5396 (cond
5397 ((and lang (not (string= lang "")) org-src-fontify-natively)
5398 (org-src-font-lock-fontify-block lang block-start block-end)
5399 ;; remove old background overlays
5400 (mapc (lambda (ov)
5401 (if (eq (overlay-get ov 'face) 'org-block-background)
5402 (delete-overlay ov)))
5403 (overlays-at (/ (+ beg1 block-end) 2)))
5404 ;; add a background overlay
5405 (setq ovl (make-overlay beg1 block-end))
5406 (overlay-put ovl 'face 'org-block-background)
5407 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5408 (quoting
5409 (add-text-properties beg1 (min (point-max) (1+ end1))
5410 '(face org-block))) ; end of source block
5411 ((not org-fontify-quote-and-verse-blocks))
5412 ((string= block-type "quote")
5413 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5414 ((string= block-type "verse")
5415 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5416 (add-text-properties beg beg1 '(face org-block-begin-line))
5417 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5418 '(face org-block-end-line))
5420 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5421 (add-text-properties
5422 beg (match-end 3)
5423 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5424 '(font-lock-fontified t invisible t)
5425 '(font-lock-fontified t face org-document-info-keyword)))
5426 (add-text-properties
5427 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5428 (if (string-equal dc1 "+title:")
5429 '(font-lock-fontified t face org-document-title)
5430 '(font-lock-fontified t face org-document-info))))
5431 ((or (equal dc1 "+results")
5432 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5433 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5434 "+call:" "+header:" "+headers:" "+name:"))
5435 (and (match-end 4) (equal dc3 "+attr")))
5436 (add-text-properties
5437 beg (match-end 0)
5438 '(font-lock-fontified t face org-meta-line))
5440 ((member dc3 '(" " ""))
5441 (add-text-properties
5442 beg (match-end 0)
5443 '(font-lock-fontified t face font-lock-comment-face)))
5444 ((not (member (char-after beg) '(?\ ?\t)))
5445 ;; just any other in-buffer setting, but not indented
5446 (add-text-properties
5447 beg (match-end 0)
5448 '(font-lock-fontified t face org-meta-line))
5450 (t nil))))))
5452 (defun org-activate-angle-links (limit)
5453 "Run through the buffer and add overlays to links."
5454 (if (and (re-search-forward org-angle-link-re limit t)
5455 (not (org-in-src-block-p)))
5456 (progn
5457 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5458 (add-text-properties (match-beginning 0) (match-end 0)
5459 (list 'mouse-face 'highlight
5460 'keymap org-mouse-map))
5461 (org-rear-nonsticky-at (match-end 0))
5462 t)))
5464 (defun org-activate-footnote-links (limit)
5465 "Run through the buffer and add overlays to footnotes."
5466 (let ((fn (org-footnote-next-reference-or-definition limit)))
5467 (when fn
5468 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5469 (org-remove-flyspell-overlays-in beg end)
5470 (add-text-properties beg end
5471 (list 'mouse-face 'highlight
5472 'keymap org-mouse-map
5473 'help-echo
5474 (if (= (point-at-bol) beg)
5475 "Footnote definition"
5476 "Footnote reference")
5477 'font-lock-fontified t
5478 'font-lock-multiline t
5479 'face 'org-footnote))))))
5481 (defun org-activate-bracket-links (limit)
5482 "Run through the buffer and add overlays to bracketed links."
5483 (if (and (re-search-forward org-bracket-link-regexp limit t)
5484 (not (org-in-src-block-p)))
5485 (let* ((help (concat "LINK: "
5486 (org-match-string-no-properties 1)))
5487 ;; FIXME: above we should remove the escapes.
5488 ;; but that requires another match, protecting match data,
5489 ;; a lot of overhead for font-lock.
5490 (ip (org-maybe-intangible
5491 (list 'invisible 'org-link
5492 'keymap org-mouse-map 'mouse-face 'highlight
5493 'font-lock-multiline t 'help-echo help)))
5494 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5495 'font-lock-multiline t 'help-echo help)))
5496 ;; We need to remove the invisible property here. Table narrowing
5497 ;; may have made some of this invisible.
5498 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5499 (remove-text-properties (match-beginning 0) (match-end 0)
5500 '(invisible nil))
5501 (if (match-end 3)
5502 (progn
5503 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5504 (org-rear-nonsticky-at (match-beginning 3))
5505 (add-text-properties (match-beginning 3) (match-end 3) vp)
5506 (org-rear-nonsticky-at (match-end 3))
5507 (add-text-properties (match-end 3) (match-end 0) ip)
5508 (org-rear-nonsticky-at (match-end 0)))
5509 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5510 (org-rear-nonsticky-at (match-beginning 1))
5511 (add-text-properties (match-beginning 1) (match-end 1) vp)
5512 (org-rear-nonsticky-at (match-end 1))
5513 (add-text-properties (match-end 1) (match-end 0) ip)
5514 (org-rear-nonsticky-at (match-end 0)))
5515 t)))
5517 (defun org-activate-dates (limit)
5518 "Run through the buffer and add overlays to dates."
5519 (if (and (re-search-forward org-tsr-regexp-both limit t)
5520 (not (equal (char-before (match-beginning 0)) 91)))
5521 (progn
5522 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5523 (add-text-properties (match-beginning 0) (match-end 0)
5524 (list 'mouse-face 'highlight
5525 'keymap org-mouse-map))
5526 (org-rear-nonsticky-at (match-end 0))
5527 (when org-display-custom-times
5528 (if (match-end 3)
5529 (org-display-custom-time (match-beginning 3) (match-end 3)))
5530 (org-display-custom-time (match-beginning 1) (match-end 1)))
5531 t)))
5533 (defvar org-target-link-regexp nil
5534 "Regular expression matching radio targets in plain text.")
5535 (make-variable-buffer-local 'org-target-link-regexp)
5536 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5537 "Regular expression matching a link target.")
5538 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5539 "Regular expression matching a radio target.")
5540 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5541 "Regular expression matching any target.")
5543 (defun org-activate-target-links (limit)
5544 "Run through the buffer and add overlays to target matches."
5545 (when org-target-link-regexp
5546 (let ((case-fold-search t))
5547 (if (re-search-forward org-target-link-regexp limit t)
5548 (progn
5549 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5550 (add-text-properties (match-beginning 0) (match-end 0)
5551 (list 'mouse-face 'highlight
5552 'keymap org-mouse-map
5553 'help-echo "Radio target link"
5554 'org-linked-text t))
5555 (org-rear-nonsticky-at (match-end 0))
5556 t)))))
5558 (defun org-update-radio-target-regexp ()
5559 "Find all radio targets in this file and update the regular expression."
5560 (interactive)
5561 (when (memq 'radio org-activate-links)
5562 (setq org-target-link-regexp
5563 (org-make-target-link-regexp (org-all-targets 'radio)))
5564 (org-restart-font-lock)))
5566 (defun org-hide-wide-columns (limit)
5567 (let (s e)
5568 (setq s (text-property-any (point) (or limit (point-max))
5569 'org-cwidth t))
5570 (when s
5571 (setq e (next-single-property-change s 'org-cwidth))
5572 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5573 (goto-char e)
5574 t)))
5576 (defvar org-latex-and-specials-regexp nil
5577 "Regular expression for highlighting export special stuff.")
5578 (defvar org-match-substring-regexp)
5579 (defvar org-match-substring-with-braces-regexp)
5581 ;; This should be with the exporter code, but we also use if for font-locking
5582 (defconst org-export-html-special-string-regexps
5583 '(("\\\\-" . "&shy;")
5584 ("---\\([^-]\\)" . "&mdash;\\1")
5585 ("--\\([^-]\\)" . "&ndash;\\1")
5586 ("\\.\\.\\." . "&hellip;"))
5587 "Regular expressions for special string conversion.")
5590 (defun org-compute-latex-and-specials-regexp ()
5591 "Compute regular expression for stuff treated specially by exporters."
5592 (if (not org-highlight-latex-fragments-and-specials)
5593 (org-set-local 'org-latex-and-specials-regexp nil)
5594 (require 'org-exp)
5595 (let*
5596 ((matchers (plist-get org-format-latex-options :matchers))
5597 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5598 org-latex-regexps)))
5599 (org-export-allow-BIND nil)
5600 (options (org-combine-plists (org-default-export-plist)
5601 (org-infile-export-plist)))
5602 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5603 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5604 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5605 (org-export-html-expand (plist-get options :expand-quoted-html))
5606 (org-export-with-special-strings (plist-get options :special-strings))
5607 (re-sub
5608 (cond
5609 ((equal org-export-with-sub-superscripts '{})
5610 (list org-match-substring-with-braces-regexp))
5611 (org-export-with-sub-superscripts
5612 (list org-match-substring-regexp))))
5613 (re-latex
5614 (if org-export-with-LaTeX-fragments
5615 (mapcar (lambda (x) (nth 1 x)) latexs)))
5616 (re-macros
5617 (if org-export-with-TeX-macros
5618 (list (concat "\\\\"
5619 (regexp-opt
5620 (append
5622 (delq nil
5623 (mapcar 'car-safe
5624 (append org-entities-user
5625 org-entities)))
5626 (if (boundp 'org-latex-entities)
5627 (mapcar (lambda (x)
5628 (or (car-safe x) x))
5629 org-latex-entities)
5630 nil))
5631 'words))) ; FIXME
5633 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5634 (re-special (if org-export-with-special-strings
5635 (mapcar (lambda (x) (car x))
5636 org-export-html-special-string-regexps)))
5637 (re-rest
5638 (delq nil
5639 (list
5640 (if org-export-html-expand "@<[^>\n]+>")
5641 ))))
5642 (org-set-local
5643 'org-latex-and-specials-regexp
5644 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5645 re-rest) "\\|")))))
5647 (defun org-do-latex-and-special-faces (limit)
5648 "Run through the buffer and add overlays to links."
5649 (when org-latex-and-specials-regexp
5650 (let (rtn d)
5651 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5652 limit t))
5653 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5654 'face))
5655 '(org-code org-verbatim underline)))
5656 (progn
5657 (setq rtn t
5658 d (cond ((member (char-after (1+ (match-beginning 0)))
5659 '(?_ ?^)) 1)
5660 (t 0)))
5661 (font-lock-prepend-text-property
5662 (+ d (match-beginning 0)) (match-end 0)
5663 'face 'org-latex-and-export-specials)
5664 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5665 '(font-lock-multiline t)))))
5666 rtn)))
5668 (defun org-restart-font-lock ()
5669 "Restart `font-lock-mode', to force refontification."
5670 (when (and (boundp 'font-lock-mode) font-lock-mode)
5671 (font-lock-mode -1)
5672 (font-lock-mode 1)))
5674 (defun org-all-targets (&optional radio)
5675 "Return a list of all targets in this file.
5676 With optional argument RADIO, only find radio targets."
5677 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5678 rtn)
5679 (save-excursion
5680 (goto-char (point-min))
5681 (while (re-search-forward re nil t)
5682 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5683 rtn)))
5685 (defun org-make-target-link-regexp (targets)
5686 "Make regular expression matching all strings in TARGETS.
5687 The regular expression finds the targets also if there is a line break
5688 between words."
5689 (and targets
5690 (concat
5691 "\\<\\("
5692 (mapconcat
5693 (lambda (x)
5694 (setq x (regexp-quote x))
5695 (while (string-match " +" x)
5696 (setq x (replace-match "\\s-+" t t x)))
5698 targets
5699 "\\|")
5700 "\\)\\>")))
5702 (defun org-activate-tags (limit)
5703 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5704 (progn
5705 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5706 (add-text-properties (match-beginning 1) (match-end 1)
5707 (list 'mouse-face 'highlight
5708 'keymap org-mouse-map))
5709 (org-rear-nonsticky-at (match-end 1))
5710 t)))
5712 (defun org-outline-level ()
5713 "Compute the outline level of the heading at point.
5714 This function assumes that the cursor is at the beginning of a line matched
5715 by `outline-regexp'. Otherwise it returns garbage.
5716 If this is called at a normal headline, the level is the number of stars.
5717 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5718 (save-excursion
5719 (looking-at org-outline-regexp)
5720 (1- (- (match-end 0) (match-beginning 0)))))
5722 (defvar org-font-lock-keywords nil)
5724 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5725 "Regular expression matching a property line.")
5727 (defvar org-font-lock-hook nil
5728 "Functions to be called for special font lock stuff.")
5730 (defvar org-font-lock-set-keywords-hook nil
5731 "Functions that can manipulate `org-font-lock-extra-keywords'.
5732 This is called after `org-font-lock-extra-keywords' is defined, but before
5733 it is installed to be used by font lock. This can be useful if something
5734 needs to be inserted at a specific position in the font-lock sequence.")
5736 (defun org-font-lock-hook (limit)
5737 "Run `org-font-lock-hook' within LIMIT."
5738 (run-hook-with-args 'org-font-lock-hook limit))
5740 (defun org-set-font-lock-defaults ()
5741 "Set font lock defaults for the current buffer."
5742 (let* ((em org-fontify-emphasized-text)
5743 (lk org-activate-links)
5744 (org-font-lock-extra-keywords
5745 (list
5746 ;; Call the hook
5747 '(org-font-lock-hook)
5748 ;; Headlines
5749 `(,(if org-fontify-whole-heading-line
5750 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5751 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5752 (1 (org-get-level-face 1))
5753 (2 (org-get-level-face 2))
5754 (3 (org-get-level-face 3)))
5755 ;; Table lines
5756 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5757 (1 'org-table t))
5758 ;; Table internals
5759 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5760 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5761 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5762 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5763 ;; Drawers
5764 (list org-drawer-regexp '(0 'org-special-keyword t))
5765 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5766 ;; Properties
5767 (list org-property-re
5768 '(1 'org-special-keyword t)
5769 '(3 'org-property-value t))
5770 ;; Links
5771 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5772 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5773 (if (memq 'plain lk) '(org-activate-plain-links))
5774 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5775 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5776 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5777 (if (memq 'footnote lk) '(org-activate-footnote-links))
5778 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5779 '(org-hide-wide-columns (0 nil append))
5780 ;; TODO keyword
5781 (list (format org-heading-keyword-regexp-format
5782 org-todo-regexp)
5783 '(2 (org-get-todo-face 2) t))
5784 ;; DONE
5785 (if org-fontify-done-headline
5786 (list (format org-heading-keyword-regexp-format
5787 (concat
5788 "\\(?:"
5789 (mapconcat 'regexp-quote org-done-keywords "\\|")
5790 "\\)"))
5791 '(2 'org-headline-done t))
5792 nil)
5793 ;; Priorities
5794 '(org-font-lock-add-priority-faces)
5795 ;; Tags
5796 '(org-font-lock-add-tag-faces)
5797 ;; Special keywords
5798 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5799 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5800 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5801 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5802 ;; Emphasis
5803 (if em
5804 (if (featurep 'xemacs)
5805 '(org-do-emphasis-faces (0 nil append))
5806 '(org-do-emphasis-faces)))
5807 ;; Checkboxes
5808 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5809 1 'org-checkbox prepend)
5810 (if (cdr (assq 'checkbox org-list-automatic-rules))
5811 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5812 (0 (org-get-checkbox-statistics-face) t)))
5813 ;; Description list items
5814 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5815 1 'org-list-dt prepend)
5816 ;; ARCHIVEd headings
5817 (list (concat
5818 org-outline-regexp-bol
5819 "\\(.*:" org-archive-tag ":.*\\)")
5820 '(1 'org-archived prepend))
5821 ;; Specials
5822 '(org-do-latex-and-special-faces)
5823 '(org-fontify-entities)
5824 '(org-raise-scripts)
5825 ;; Code
5826 '(org-activate-code (1 'org-code t))
5827 ;; COMMENT
5828 (list (format org-heading-keyword-regexp-format
5829 (concat "\\("
5830 org-comment-string "\\|" org-quote-string
5831 "\\)"))
5832 '(2 'org-special-keyword t))
5833 ;; Blocks and meta lines
5834 '(org-fontify-meta-lines-and-blocks)
5836 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5837 (run-hooks 'org-font-lock-set-keywords-hook)
5838 ;; Now set the full font-lock-keywords
5839 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5840 (org-set-local 'font-lock-defaults
5841 '(org-font-lock-keywords t nil nil backward-paragraph))
5842 (kill-local-variable 'font-lock-keywords) nil))
5844 (defun org-toggle-pretty-entities ()
5845 "Toggle the composition display of entities as UTF8 characters."
5846 (interactive)
5847 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5848 (org-restart-font-lock)
5849 (if org-pretty-entities
5850 (message "Entities are displayed as UTF8 characters")
5851 (save-restriction
5852 (widen)
5853 (org-decompose-region (point-min) (point-max))
5854 (message "Entities are displayed plain"))))
5856 (defvar org-custom-properties-overlays nil
5857 "List of overlays used for custom properties.")
5858 (make-variable-buffer-local 'org-custom-properties-overlays)
5860 (defun org-toggle-custom-properties-visibility ()
5861 "Display or hide properties in `org-custom-properties'."
5862 (interactive)
5863 (if org-custom-properties-overlays
5864 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5865 (setq org-custom-properties-overlays nil))
5866 (unless (not org-custom-properties)
5867 (save-excursion
5868 (save-restriction
5869 (widen)
5870 (goto-char (point-min))
5871 (while (re-search-forward org-property-re nil t)
5872 (mapc (lambda(p)
5873 (when (equal p (substring (match-string 1) 1 -1))
5874 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5875 (overlay-put o 'invisible t)
5876 (overlay-put o 'org-custom-property t)
5877 (push o org-custom-properties-overlays))))
5878 org-custom-properties)))))))
5880 (defun org-fontify-entities (limit)
5881 "Find an entity to fontify."
5882 (let (ee)
5883 (when org-pretty-entities
5884 (catch 'match
5885 (while (re-search-forward
5886 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5887 limit t)
5888 (if (and (not (org-in-indented-comment-line))
5889 (setq ee (org-entity-get (match-string 1)))
5890 (= (length (nth 6 ee)) 1))
5891 (let*
5892 ((end (if (equal (match-string 2) "{}")
5893 (match-end 2)
5894 (match-end 1))))
5895 (add-text-properties
5896 (match-beginning 0) end
5897 (list 'font-lock-fontified t))
5898 (compose-region (match-beginning 0) end
5899 (nth 6 ee) nil)
5900 (backward-char 1)
5901 (throw 'match t))))
5902 nil))))
5904 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5905 "Fontify string S like in Org-mode."
5906 (with-temp-buffer
5907 (insert s)
5908 (let ((org-odd-levels-only odd-levels))
5909 (org-mode)
5910 (font-lock-fontify-buffer)
5911 (buffer-string))))
5913 (defvar org-m nil)
5914 (defvar org-l nil)
5915 (defvar org-f nil)
5916 (defun org-get-level-face (n)
5917 "Get the right face for match N in font-lock matching of headlines."
5918 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5919 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5920 (if org-cycle-level-faces
5921 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5922 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5923 (cond
5924 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5925 ((eq n 2) org-f)
5926 (t (if org-level-color-stars-only nil org-f))))
5929 (defun org-get-todo-face (kwd)
5930 "Get the right face for a TODO keyword KWD.
5931 If KWD is a number, get the corresponding match group."
5932 (if (numberp kwd) (setq kwd (match-string kwd)))
5933 (or (org-face-from-face-or-color
5934 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5935 (and (member kwd org-done-keywords) 'org-done)
5936 'org-todo))
5938 (defun org-face-from-face-or-color (context inherit face-or-color)
5939 "Create a face list that inherits INHERIT, but sets the foreground color.
5940 When FACE-OR-COLOR is not a string, just return it."
5941 (if (stringp face-or-color)
5942 (list :inherit inherit
5943 (cdr (assoc context org-faces-easy-properties))
5944 face-or-color)
5945 face-or-color))
5947 (defun org-font-lock-add-tag-faces (limit)
5948 "Add the special tag faces."
5949 (when (and org-tag-faces org-tags-special-faces-re)
5950 (while (re-search-forward org-tags-special-faces-re limit t)
5951 (add-text-properties (match-beginning 1) (match-end 1)
5952 (list 'face (org-get-tag-face 1)
5953 'font-lock-fontified t))
5954 (backward-char 1))))
5956 (defun org-font-lock-add-priority-faces (limit)
5957 "Add the special priority faces."
5958 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5959 (when (save-match-data (org-at-heading-p))
5960 (add-text-properties
5961 (match-beginning 0) (match-end 0)
5962 (list 'face (or (org-face-from-face-or-color
5963 'priority 'org-special-keyword
5964 (cdr (assoc (char-after (match-beginning 1))
5965 org-priority-faces)))
5966 'org-special-keyword)
5967 'font-lock-fontified t)))))
5969 (defun org-get-tag-face (kwd)
5970 "Get the right face for a TODO keyword KWD.
5971 If KWD is a number, get the corresponding match group."
5972 (if (numberp kwd) (setq kwd (match-string kwd)))
5973 (or (org-face-from-face-or-color
5974 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5975 'org-tag))
5977 (defun org-unfontify-region (beg end &optional maybe_loudly)
5978 "Remove fontification and activation overlays from links."
5979 (font-lock-default-unfontify-region beg end)
5980 (let* ((buffer-undo-list t)
5981 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5982 (inhibit-modification-hooks t)
5983 deactivate-mark buffer-file-name buffer-file-truename)
5984 (org-decompose-region beg end)
5985 (remove-text-properties beg end
5986 '(mouse-face t keymap t org-linked-text t
5987 invisible t intangible t
5988 org-no-flyspell t org-emphasis t))
5989 (org-remove-font-lock-display-properties beg end)))
5991 (defconst org-script-display '(((raise -0.3) (height 0.7))
5992 ((raise 0.3) (height 0.7))
5993 ((raise -0.5))
5994 ((raise 0.5)))
5995 "Display properties for showing superscripts and subscripts.")
5997 (defun org-remove-font-lock-display-properties (beg end)
5998 "Remove specific display properties that have been added by font lock.
5999 The will remove the raise properties that are used to show superscripts
6000 and subscripts."
6001 (let (next prop)
6002 (while (< beg end)
6003 (setq next (next-single-property-change beg 'display nil end)
6004 prop (get-text-property beg 'display))
6005 (if (member prop org-script-display)
6006 (put-text-property beg next 'display nil))
6007 (setq beg next))))
6009 (defun org-raise-scripts (limit)
6010 "Add raise properties to sub/superscripts."
6011 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6012 (if (re-search-forward
6013 (if (eq org-use-sub-superscripts t)
6014 org-match-substring-regexp
6015 org-match-substring-with-braces-regexp)
6016 limit t)
6017 (let* ((pos (point)) table-p comment-p
6018 (mpos (match-beginning 3))
6019 (emph-p (get-text-property mpos 'org-emphasis))
6020 (link-p (get-text-property mpos 'mouse-face))
6021 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6022 (goto-char (point-at-bol))
6023 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6024 comment-p (org-looking-at-p "[ \t]*#"))
6025 (goto-char pos)
6026 ;; FIXME: Should we go back one character here, for a_b^c
6027 ;; (goto-char (1- pos)) ;????????????????????
6028 (if (or comment-p emph-p link-p keyw-p)
6030 (put-text-property (match-beginning 3) (match-end 0)
6031 'display
6032 (if (equal (char-after (match-beginning 2)) ?^)
6033 (nth (if table-p 3 1) org-script-display)
6034 (nth (if table-p 2 0) org-script-display)))
6035 (add-text-properties (match-beginning 2) (match-end 2)
6036 (list 'invisible t
6037 'org-dwidth t 'org-dwidth-n 1))
6038 (if (and (eq (char-after (match-beginning 3)) ?{)
6039 (eq (char-before (match-end 3)) ?}))
6040 (progn
6041 (add-text-properties
6042 (match-beginning 3) (1+ (match-beginning 3))
6043 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6044 (add-text-properties
6045 (1- (match-end 3)) (match-end 3)
6046 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6047 t)))))
6049 ;;;; Visibility cycling, including org-goto and indirect buffer
6051 ;;; Cycling
6053 (defvar org-cycle-global-status nil)
6054 (make-variable-buffer-local 'org-cycle-global-status)
6055 (defvar org-cycle-subtree-status nil)
6056 (make-variable-buffer-local 'org-cycle-subtree-status)
6058 (defvar org-inlinetask-min-level)
6060 ;;;###autoload
6061 (defun org-cycle (&optional arg)
6062 "TAB-action and visibility cycling for Org-mode.
6064 This is the command invoked in Org-mode by the TAB key. Its main purpose
6065 is outline visibility cycling, but it also invokes other actions
6066 in special contexts.
6068 - When this function is called with a prefix argument, rotate the entire
6069 buffer through 3 states (global cycling)
6070 1. OVERVIEW: Show only top-level headlines.
6071 2. CONTENTS: Show all headlines of all levels, but no body text.
6072 3. SHOW ALL: Show everything.
6073 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6074 determined by the variable `org-startup-folded', and by any VISIBILITY
6075 properties in the buffer.
6076 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6077 including any drawers.
6079 - When inside a table, re-align the table and move to the next field.
6081 - When point is at the beginning of a headline, rotate the subtree started
6082 by this line through 3 different states (local cycling)
6083 1. FOLDED: Only the main headline is shown.
6084 2. CHILDREN: The main headline and the direct children are shown.
6085 From this state, you can move to one of the children
6086 and zoom in further.
6087 3. SUBTREE: Show the entire subtree, including body text.
6088 If there is no subtree, switch directly from CHILDREN to FOLDED.
6090 - When point is at the beginning of an empty headline and the variable
6091 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6092 of the headline by demoting and promoting it to likely levels. This
6093 speeds up creation document structure by pressing TAB once or several
6094 times right after creating a new headline.
6096 - When there is a numeric prefix, go up to a heading with level ARG, do
6097 a `show-subtree' and return to the previous cursor position. If ARG
6098 is negative, go up that many levels.
6100 - When point is not at the beginning of a headline, execute the global
6101 binding for TAB, which is re-indenting the line. See the option
6102 `org-cycle-emulate-tab' for details.
6104 - Special case: if point is at the beginning of the buffer and there is
6105 no headline in line 1, this function will act as if called with prefix arg
6106 (C-u TAB, same as S-TAB) also when called without prefix arg.
6107 But only if also the variable `org-cycle-global-at-bob' is t."
6108 (interactive "P")
6109 (org-load-modules-maybe)
6110 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6111 (and org-cycle-level-after-item/entry-creation
6112 (or (org-cycle-level)
6113 (org-cycle-item-indentation))))
6114 (let* ((limit-level
6115 (or org-cycle-max-level
6116 (and (boundp 'org-inlinetask-min-level)
6117 org-inlinetask-min-level
6118 (1- org-inlinetask-min-level))))
6119 (nstars (and limit-level
6120 (if org-odd-levels-only
6121 (and limit-level (1- (* limit-level 2)))
6122 limit-level)))
6123 (org-outline-regexp
6124 (if (not (derived-mode-p 'org-mode))
6125 outline-regexp
6126 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6127 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6128 (not (looking-at org-outline-regexp))))
6129 (org-cycle-hook
6130 (if bob-special
6131 (delq 'org-optimize-window-after-visibility-change
6132 (copy-sequence org-cycle-hook))
6133 org-cycle-hook))
6134 (pos (point)))
6136 (if (or bob-special (equal arg '(4)))
6137 ;; special case: use global cycling
6138 (setq arg t))
6140 (cond
6142 ((equal arg '(16))
6143 (setq last-command 'dummy)
6144 (org-set-startup-visibility)
6145 (message "Startup visibility, plus VISIBILITY properties"))
6147 ((equal arg '(64))
6148 (show-all)
6149 (message "Entire buffer visible, including drawers"))
6151 ;; Table: enter it or move to the next field.
6152 ((org-at-table-p 'any)
6153 (if (org-at-table.el-p)
6154 (message "Use C-c ' to edit table.el tables")
6155 (if arg (org-table-edit-field t)
6156 (org-table-justify-field-maybe)
6157 (call-interactively 'org-table-next-field))))
6159 ((run-hook-with-args-until-success
6160 'org-tab-after-check-for-table-hook))
6162 ;; Global cycling: delegate to `org-cycle-internal-global'.
6163 ((eq arg t) (org-cycle-internal-global))
6165 ;; Drawers: delegate to `org-flag-drawer'.
6166 ((and org-drawers org-drawer-regexp
6167 (save-excursion
6168 (beginning-of-line 1)
6169 (looking-at org-drawer-regexp)))
6170 (org-flag-drawer ; toggle block visibility
6171 (not (get-char-property (match-end 0) 'invisible))))
6173 ;; Show-subtree, ARG levels up from here.
6174 ((integerp arg)
6175 (save-excursion
6176 (org-back-to-heading)
6177 (outline-up-heading (if (< arg 0) (- arg)
6178 (- (funcall outline-level) arg)))
6179 (org-show-subtree)))
6181 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6182 ((and (featurep 'org-inlinetask)
6183 (org-inlinetask-at-task-p)
6184 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6185 (org-inlinetask-toggle-visibility))
6187 ((org-try-cdlatex-tab))
6189 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6190 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6191 (save-excursion (beginning-of-line 1)
6192 (looking-at org-outline-regexp)))
6193 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6194 (org-cycle-internal-local))
6196 ;; From there: TAB emulation and template completion.
6197 (buffer-read-only (org-back-to-heading))
6199 ((run-hook-with-args-until-success
6200 'org-tab-after-check-for-cycling-hook))
6202 ((org-try-structure-completion))
6204 ((run-hook-with-args-until-success
6205 'org-tab-before-tab-emulation-hook))
6207 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6208 (or (not (bolp))
6209 (not (looking-at org-outline-regexp))))
6210 (call-interactively (global-key-binding "\t")))
6212 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6213 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6214 (or (and (eq org-cycle-emulate-tab 'white)
6215 (= (match-end 0) (point-at-eol)))
6216 (and (eq org-cycle-emulate-tab 'whitestart)
6217 (>= (match-end 0) pos))))
6219 (eq org-cycle-emulate-tab t))
6220 (call-interactively (global-key-binding "\t")))
6222 (t (save-excursion
6223 (org-back-to-heading)
6224 (org-cycle)))))))
6226 (defun org-cycle-internal-global ()
6227 "Do the global cycling action."
6228 ;; Hack to avoid display of messages for .org attachments in Gnus
6229 (let ((ga (string-match "\\*fontification" (buffer-name))))
6230 (cond
6231 ((and (eq last-command this-command)
6232 (eq org-cycle-global-status 'overview))
6233 ;; We just created the overview - now do table of contents
6234 ;; This can be slow in very large buffers, so indicate action
6235 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6236 (unless ga (message "CONTENTS..."))
6237 (org-content)
6238 (unless ga (message "CONTENTS...done"))
6239 (setq org-cycle-global-status 'contents)
6240 (run-hook-with-args 'org-cycle-hook 'contents))
6242 ((and (eq last-command this-command)
6243 (eq org-cycle-global-status 'contents))
6244 ;; We just showed the table of contents - now show everything
6245 (run-hook-with-args 'org-pre-cycle-hook 'all)
6246 (show-all)
6247 (unless ga (message "SHOW ALL"))
6248 (setq org-cycle-global-status 'all)
6249 (run-hook-with-args 'org-cycle-hook 'all))
6252 ;; Default action: go to overview
6253 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6254 (org-overview)
6255 (unless ga (message "OVERVIEW"))
6256 (setq org-cycle-global-status 'overview)
6257 (run-hook-with-args 'org-cycle-hook 'overview)))))
6259 (defun org-cycle-internal-local ()
6260 "Do the local cycling action."
6261 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6262 ;; First, determine end of headline (EOH), end of subtree or item
6263 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6264 (save-excursion
6265 (if (org-at-item-p)
6266 (progn
6267 (beginning-of-line)
6268 (setq struct (org-list-struct))
6269 (setq eoh (point-at-eol))
6270 (setq eos (org-list-get-item-end-before-blank (point) struct))
6271 (setq has-children (org-list-has-child-p (point) struct)))
6272 (org-back-to-heading)
6273 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6274 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6275 (setq has-children
6276 (or (save-excursion
6277 (let ((level (funcall outline-level)))
6278 (outline-next-heading)
6279 (and (org-at-heading-p t)
6280 (> (funcall outline-level) level))))
6281 (save-excursion
6282 (org-list-search-forward (org-item-beginning-re) eos t)))))
6283 ;; Determine end invisible part of buffer (EOL)
6284 (beginning-of-line 2)
6285 ;; XEmacs doesn't have `next-single-char-property-change'
6286 (if (featurep 'xemacs)
6287 (while (and (not (eobp)) ;; this is like `next-line'
6288 (get-char-property (1- (point)) 'invisible))
6289 (beginning-of-line 2))
6290 (while (and (not (eobp)) ;; this is like `next-line'
6291 (get-char-property (1- (point)) 'invisible))
6292 (goto-char (next-single-char-property-change (point) 'invisible))
6293 (and (eolp) (beginning-of-line 2))))
6294 (setq eol (point)))
6295 ;; Find out what to do next and set `this-command'
6296 (cond
6297 ((= eos eoh)
6298 ;; Nothing is hidden behind this heading
6299 (unless (org-before-first-heading-p)
6300 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6301 (message "EMPTY ENTRY")
6302 (setq org-cycle-subtree-status nil)
6303 (save-excursion
6304 (goto-char eos)
6305 (outline-next-heading)
6306 (if (outline-invisible-p) (org-flag-heading nil))))
6307 ((and (or (>= eol eos)
6308 (not (string-match "\\S-" (buffer-substring eol eos))))
6309 (or has-children
6310 (not (setq children-skipped
6311 org-cycle-skip-children-state-if-no-children))))
6312 ;; Entire subtree is hidden in one line: children view
6313 (unless (org-before-first-heading-p)
6314 (run-hook-with-args 'org-pre-cycle-hook 'children))
6315 (if (org-at-item-p)
6316 (org-list-set-item-visibility (point-at-bol) struct 'children)
6317 (org-show-entry)
6318 (org-with-limited-levels (show-children))
6319 ;; FIXME: This slows down the func way too much.
6320 ;; How keep drawers hidden in subtree anyway?
6321 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6322 ;; (org-cycle-hide-drawers 'subtree))
6324 ;; Fold every list in subtree to top-level items.
6325 (when (eq org-cycle-include-plain-lists 'integrate)
6326 (save-excursion
6327 (org-back-to-heading)
6328 (while (org-list-search-forward (org-item-beginning-re) eos t)
6329 (beginning-of-line 1)
6330 (let* ((struct (org-list-struct))
6331 (prevs (org-list-prevs-alist struct))
6332 (end (org-list-get-bottom-point struct)))
6333 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6334 (org-list-get-all-items (point) struct prevs))
6335 (goto-char end))))))
6336 (message "CHILDREN")
6337 (save-excursion
6338 (goto-char eos)
6339 (outline-next-heading)
6340 (if (outline-invisible-p) (org-flag-heading nil)))
6341 (setq org-cycle-subtree-status 'children)
6342 (unless (org-before-first-heading-p)
6343 (run-hook-with-args 'org-cycle-hook 'children)))
6344 ((or children-skipped
6345 (and (eq last-command this-command)
6346 (eq org-cycle-subtree-status 'children)))
6347 ;; We just showed the children, or no children are there,
6348 ;; now show everything.
6349 (unless (org-before-first-heading-p)
6350 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6351 (outline-flag-region eoh eos nil)
6352 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6353 (setq org-cycle-subtree-status 'subtree)
6354 (unless (org-before-first-heading-p)
6355 (run-hook-with-args 'org-cycle-hook 'subtree)))
6357 ;; Default action: hide the subtree.
6358 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6359 (outline-flag-region eoh eos t)
6360 (message "FOLDED")
6361 (setq org-cycle-subtree-status 'folded)
6362 (unless (org-before-first-heading-p)
6363 (run-hook-with-args 'org-cycle-hook 'folded))))))
6365 ;;;###autoload
6366 (defun org-global-cycle (&optional arg)
6367 "Cycle the global visibility. For details see `org-cycle'.
6368 With \\[universal-argument] prefix arg, switch to startup visibility.
6369 With a numeric prefix, show all headlines up to that level."
6370 (interactive "P")
6371 (let ((org-cycle-include-plain-lists
6372 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6373 (cond
6374 ((integerp arg)
6375 (show-all)
6376 (hide-sublevels arg)
6377 (setq org-cycle-global-status 'contents))
6378 ((equal arg '(4))
6379 (org-set-startup-visibility)
6380 (message "Startup visibility, plus VISIBILITY properties."))
6382 (org-cycle '(4))))))
6384 (defun org-set-startup-visibility ()
6385 "Set the visibility required by startup options and properties."
6386 (cond
6387 ((eq org-startup-folded t)
6388 (org-cycle '(4)))
6389 ((eq org-startup-folded 'content)
6390 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6391 (org-cycle '(4)) (org-cycle '(4)))))
6392 (unless (eq org-startup-folded 'showeverything)
6393 (if org-hide-block-startup (org-hide-block-all))
6394 (org-set-visibility-according-to-property 'no-cleanup)
6395 (org-cycle-hide-archived-subtrees 'all)
6396 (org-cycle-hide-drawers 'all)
6397 (org-cycle-show-empty-lines t)))
6399 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6400 "Switch subtree visibilities according to :VISIBILITY: property."
6401 (interactive)
6402 (let (org-show-entry-below state)
6403 (save-excursion
6404 (goto-char (point-min))
6405 (while (re-search-forward
6406 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6407 nil t)
6408 (setq state (match-string 1))
6409 (save-excursion
6410 (org-back-to-heading t)
6411 (hide-subtree)
6412 (org-reveal)
6413 (cond
6414 ((equal state '("fold" "folded"))
6415 (hide-subtree))
6416 ((equal state "children")
6417 (org-show-hidden-entry)
6418 (show-children))
6419 ((equal state "content")
6420 (save-excursion
6421 (save-restriction
6422 (org-narrow-to-subtree)
6423 (org-content))))
6424 ((member state '("all" "showall"))
6425 (show-subtree)))))
6426 (unless no-cleanup
6427 (org-cycle-hide-archived-subtrees 'all)
6428 (org-cycle-hide-drawers 'all)
6429 (org-cycle-show-empty-lines 'all)))))
6431 ;; This function uses outline-regexp instead of the more fundamental
6432 ;; org-outline-regexp so that org-cycle-global works outside of Org
6433 ;; buffers, where outline-regexp is needed.
6434 (defun org-overview ()
6435 "Switch to overview mode, showing only top-level headlines.
6436 Really, this shows all headlines with level equal or greater than the level
6437 of the first headline in the buffer. This is important, because if the
6438 first headline is not level one, then (hide-sublevels 1) gives confusing
6439 results."
6440 (interactive)
6441 (let ((l (org-current-line))
6442 (level (save-excursion
6443 (goto-char (point-min))
6444 (if (re-search-forward (concat "^" outline-regexp) nil t)
6445 (progn
6446 (goto-char (match-beginning 0))
6447 (funcall outline-level))))))
6448 (and level (hide-sublevels level))
6449 (recenter '(4))
6450 (org-goto-line l)))
6452 (defun org-content (&optional arg)
6453 "Show all headlines in the buffer, like a table of contents.
6454 With numerical argument N, show content up to level N."
6455 (interactive "P")
6456 (save-excursion
6457 ;; Visit all headings and show their offspring
6458 (and (integerp arg) (org-overview))
6459 (goto-char (point-max))
6460 (catch 'exit
6461 (while (and (progn (condition-case nil
6462 (outline-previous-visible-heading 1)
6463 (error (goto-char (point-min))))
6465 (looking-at org-outline-regexp))
6466 (if (integerp arg)
6467 (show-children (1- arg))
6468 (show-branches))
6469 (if (bobp) (throw 'exit nil))))))
6472 (defun org-optimize-window-after-visibility-change (state)
6473 "Adjust the window after a change in outline visibility.
6474 This function is the default value of the hook `org-cycle-hook'."
6475 (when (get-buffer-window (current-buffer))
6476 (cond
6477 ((eq state 'content) nil)
6478 ((eq state 'all) nil)
6479 ((eq state 'folded) nil)
6480 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6481 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6483 (defun org-remove-empty-overlays-at (pos)
6484 "Remove outline overlays that do not contain non-white stuff."
6485 (mapc
6486 (lambda (o)
6487 (and (eq 'outline (overlay-get o 'invisible))
6488 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6489 (overlay-end o))))
6490 (delete-overlay o)))
6491 (overlays-at pos)))
6493 (defun org-clean-visibility-after-subtree-move ()
6494 "Fix visibility issues after moving a subtree."
6495 ;; First, find a reasonable region to look at:
6496 ;; Start two siblings above, end three below
6497 (let* ((beg (save-excursion
6498 (and (org-get-last-sibling)
6499 (org-get-last-sibling))
6500 (point)))
6501 (end (save-excursion
6502 (and (org-get-next-sibling)
6503 (org-get-next-sibling)
6504 (org-get-next-sibling))
6505 (if (org-at-heading-p)
6506 (point-at-eol)
6507 (point))))
6508 (level (looking-at "\\*+"))
6509 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6510 (save-excursion
6511 (save-restriction
6512 (narrow-to-region beg end)
6513 (when re
6514 ;; Properly fold already folded siblings
6515 (goto-char (point-min))
6516 (while (re-search-forward re nil t)
6517 (if (and (not (outline-invisible-p))
6518 (save-excursion
6519 (goto-char (point-at-eol)) (outline-invisible-p)))
6520 (hide-entry))))
6521 (org-cycle-show-empty-lines 'overview)
6522 (org-cycle-hide-drawers 'overview)))))
6524 (defun org-cycle-show-empty-lines (state)
6525 "Show empty lines above all visible headlines.
6526 The region to be covered depends on STATE when called through
6527 `org-cycle-hook'. Lisp program can use t for STATE to get the
6528 entire buffer covered. Note that an empty line is only shown if there
6529 are at least `org-cycle-separator-lines' empty lines before the headline."
6530 (when (not (= org-cycle-separator-lines 0))
6531 (save-excursion
6532 (let* ((n (abs org-cycle-separator-lines))
6533 (re (cond
6534 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6535 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6536 (t (let ((ns (number-to-string (- n 2))))
6537 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6538 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6539 beg end b e)
6540 (cond
6541 ((memq state '(overview contents t))
6542 (setq beg (point-min) end (point-max)))
6543 ((memq state '(children folded))
6544 (setq beg (point) end (progn (org-end-of-subtree t t)
6545 (beginning-of-line 2)
6546 (point)))))
6547 (when beg
6548 (goto-char beg)
6549 (while (re-search-forward re end t)
6550 (unless (get-char-property (match-end 1) 'invisible)
6551 (setq e (match-end 1))
6552 (if (< org-cycle-separator-lines 0)
6553 (setq b (save-excursion
6554 (goto-char (match-beginning 0))
6555 (org-back-over-empty-lines)
6556 (if (save-excursion
6557 (goto-char (max (point-min) (1- (point))))
6558 (org-at-heading-p))
6559 (1- (point))
6560 (point))))
6561 (setq b (match-beginning 1)))
6562 (outline-flag-region b e nil)))))))
6563 ;; Never hide empty lines at the end of the file.
6564 (save-excursion
6565 (goto-char (point-max))
6566 (outline-previous-heading)
6567 (outline-end-of-heading)
6568 (if (and (looking-at "[ \t\n]+")
6569 (= (match-end 0) (point-max)))
6570 (outline-flag-region (point) (match-end 0) nil))))
6572 (defun org-show-empty-lines-in-parent ()
6573 "Move to the parent and re-show empty lines before visible headlines."
6574 (save-excursion
6575 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6576 (org-cycle-show-empty-lines context))))
6578 (defun org-files-list ()
6579 "Return `org-agenda-files' list, plus all open org-mode files.
6580 This is useful for operations that need to scan all of a user's
6581 open and agenda-wise Org files."
6582 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6583 (dolist (buf (buffer-list))
6584 (with-current-buffer buf
6585 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6586 (let ((file (expand-file-name (buffer-file-name))))
6587 (unless (member file files)
6588 (push file files))))))
6589 files))
6591 (defsubst org-entry-beginning-position ()
6592 "Return the beginning position of the current entry."
6593 (save-excursion (outline-back-to-heading t) (point)))
6595 (defsubst org-entry-end-position ()
6596 "Return the end position of the current entry."
6597 (save-excursion (outline-next-heading) (point)))
6599 (defun org-cycle-hide-drawers (state)
6600 "Re-hide all drawers after a visibility state change."
6601 (when (and (derived-mode-p 'org-mode)
6602 (not (memq state '(overview folded contents))))
6603 (save-excursion
6604 (let* ((globalp (memq state '(contents all)))
6605 (beg (if globalp (point-min) (point)))
6606 (end (if globalp (point-max)
6607 (if (eq state 'children)
6608 (save-excursion (outline-next-heading) (point))
6609 (org-end-of-subtree t)))))
6610 (goto-char beg)
6611 (while (re-search-forward org-drawer-regexp end t)
6612 (org-flag-drawer t))))))
6614 (defun org-flag-drawer (flag)
6615 "When FLAG is non-nil, hide the drawer we are within.
6616 Otherwise make it visible."
6617 (save-excursion
6618 (beginning-of-line 1)
6619 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6620 (let ((b (match-end 0)))
6621 (if (re-search-forward
6622 "^[ \t]*:END:"
6623 (save-excursion (outline-next-heading) (point)) t)
6624 (outline-flag-region b (point-at-eol) flag)
6625 (error ":END: line missing at position %s" b))))))
6627 (defun org-subtree-end-visible-p ()
6628 "Is the end of the current subtree visible?"
6629 (pos-visible-in-window-p
6630 (save-excursion (org-end-of-subtree t) (point))))
6632 (defun org-first-headline-recenter (&optional N)
6633 "Move cursor to the first headline and recenter the headline.
6634 Optional argument N means put the headline into the Nth line of the window."
6635 (goto-char (point-min))
6636 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6637 (beginning-of-line)
6638 (recenter (prefix-numeric-value N))))
6640 ;;; Saving and restoring visibility
6642 (defun org-outline-overlay-data (&optional use-markers)
6643 "Return a list of the locations of all outline overlays.
6644 These are overlays with the `invisible' property value `outline'.
6645 The return value is a list of cons cells, with start and stop
6646 positions for each overlay.
6647 If USE-MARKERS is set, return the positions as markers."
6648 (let (beg end)
6649 (save-excursion
6650 (save-restriction
6651 (widen)
6652 (delq nil
6653 (mapcar (lambda (o)
6654 (when (eq (overlay-get o 'invisible) 'outline)
6655 (setq beg (overlay-start o)
6656 end (overlay-end o))
6657 (and beg end (> end beg)
6658 (if use-markers
6659 (cons (move-marker (make-marker) beg)
6660 (move-marker (make-marker) end))
6661 (cons beg end)))))
6662 (overlays-in (point-min) (point-max))))))))
6664 (defun org-set-outline-overlay-data (data)
6665 "Create visibility overlays for all positions in DATA.
6666 DATA should have been made by `org-outline-overlay-data'."
6667 (let (o)
6668 (save-excursion
6669 (save-restriction
6670 (widen)
6671 (show-all)
6672 (mapc (lambda (c)
6673 (outline-flag-region (car c) (cdr c) t))
6674 data)))))
6676 ;;; Folding of blocks
6678 (defvar org-hide-block-overlays nil
6679 "Overlays hiding blocks.")
6680 (make-variable-buffer-local 'org-hide-block-overlays)
6682 (defun org-block-map (function &optional start end)
6683 "Call FUNCTION at the head of all source blocks in the current buffer.
6684 Optional arguments START and END can be used to limit the range."
6685 (let ((start (or start (point-min)))
6686 (end (or end (point-max))))
6687 (save-excursion
6688 (goto-char start)
6689 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6690 (save-excursion
6691 (save-match-data
6692 (goto-char (match-beginning 0))
6693 (funcall function)))))))
6695 (defun org-hide-block-toggle-all ()
6696 "Toggle the visibility of all blocks in the current buffer."
6697 (org-block-map #'org-hide-block-toggle))
6699 (defun org-hide-block-all ()
6700 "Fold all blocks in the current buffer."
6701 (interactive)
6702 (org-show-block-all)
6703 (org-block-map #'org-hide-block-toggle-maybe))
6705 (defun org-show-block-all ()
6706 "Unfold all blocks in the current buffer."
6707 (interactive)
6708 (mapc 'delete-overlay org-hide-block-overlays)
6709 (setq org-hide-block-overlays nil))
6711 (defun org-hide-block-toggle-maybe ()
6712 "Toggle visibility of block at point."
6713 (interactive)
6714 (let ((case-fold-search t))
6715 (if (save-excursion
6716 (beginning-of-line 1)
6717 (looking-at org-block-regexp))
6718 (progn (org-hide-block-toggle)
6719 t) ;; to signal that we took action
6720 nil))) ;; to signal that we did not
6722 (defun org-hide-block-toggle (&optional force)
6723 "Toggle the visibility of the current block."
6724 (interactive)
6725 (save-excursion
6726 (beginning-of-line)
6727 (if (re-search-forward org-block-regexp nil t)
6728 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6729 (end (match-end 0)) ;; end of entire body
6731 (if (memq t (mapcar (lambda (overlay)
6732 (eq (overlay-get overlay 'invisible)
6733 'org-hide-block))
6734 (overlays-at start)))
6735 (if (or (not force) (eq force 'off))
6736 (mapc (lambda (ov)
6737 (when (member ov org-hide-block-overlays)
6738 (setq org-hide-block-overlays
6739 (delq ov org-hide-block-overlays)))
6740 (when (eq (overlay-get ov 'invisible)
6741 'org-hide-block)
6742 (delete-overlay ov)))
6743 (overlays-at start)))
6744 (setq ov (make-overlay start end))
6745 (overlay-put ov 'invisible 'org-hide-block)
6746 ;; make the block accessible to isearch
6747 (overlay-put
6748 ov 'isearch-open-invisible
6749 (lambda (ov)
6750 (when (member ov org-hide-block-overlays)
6751 (setq org-hide-block-overlays
6752 (delq ov org-hide-block-overlays)))
6753 (when (eq (overlay-get ov 'invisible)
6754 'org-hide-block)
6755 (delete-overlay ov))))
6756 (push ov org-hide-block-overlays)))
6757 (error "Not looking at a source block"))))
6759 ;; org-tab-after-check-for-cycling-hook
6760 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6761 ;; Remove overlays when changing major mode
6762 (add-hook 'org-mode-hook
6763 (lambda () (org-add-hook 'change-major-mode-hook
6764 'org-show-block-all 'append 'local)))
6766 ;;; Org-goto
6768 (defvar org-goto-window-configuration nil)
6769 (defvar org-goto-marker nil)
6770 (defvar org-goto-map)
6771 (defun org-goto-map ()
6772 "Set the keymap `org-goto'."
6773 (setq org-goto-map
6774 (let ((map (make-sparse-keymap)))
6775 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6776 mouse-drag-region universal-argument org-occur))
6777 cmd)
6778 (while (setq cmd (pop cmds))
6779 (substitute-key-definition cmd cmd map global-map)))
6780 (suppress-keymap map)
6781 (org-defkey map "\C-m" 'org-goto-ret)
6782 (org-defkey map [(return)] 'org-goto-ret)
6783 (org-defkey map [(left)] 'org-goto-left)
6784 (org-defkey map [(right)] 'org-goto-right)
6785 (org-defkey map [(control ?g)] 'org-goto-quit)
6786 (org-defkey map "\C-i" 'org-cycle)
6787 (org-defkey map [(tab)] 'org-cycle)
6788 (org-defkey map [(down)] 'outline-next-visible-heading)
6789 (org-defkey map [(up)] 'outline-previous-visible-heading)
6790 (if org-goto-auto-isearch
6791 (if (fboundp 'define-key-after)
6792 (define-key-after map [t] 'org-goto-local-auto-isearch)
6793 nil)
6794 (org-defkey map "q" 'org-goto-quit)
6795 (org-defkey map "n" 'outline-next-visible-heading)
6796 (org-defkey map "p" 'outline-previous-visible-heading)
6797 (org-defkey map "f" 'outline-forward-same-level)
6798 (org-defkey map "b" 'outline-backward-same-level)
6799 (org-defkey map "u" 'outline-up-heading))
6800 (org-defkey map "/" 'org-occur)
6801 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6802 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6803 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6804 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6805 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6806 map)))
6808 (defconst org-goto-help
6809 "Browse buffer copy, to find location or copy text.%s
6810 RET=jump to location C-g=quit and return to previous location
6811 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6813 (defvar org-goto-start-pos) ; dynamically scoped parameter
6815 ;; FIXME: Docstring does not mention both interfaces
6816 (defun org-goto (&optional alternative-interface)
6817 "Look up a different location in the current file, keeping current visibility.
6819 When you want look-up or go to a different location in a
6820 document, the fastest way is often to fold the entire buffer and
6821 then dive into the tree. This method has the disadvantage, that
6822 the previous location will be folded, which may not be what you
6823 want.
6825 This command works around this by showing a copy of the current
6826 buffer in an indirect buffer, in overview mode. You can dive
6827 into the tree in that copy, use org-occur and incremental search
6828 to find a location. When pressing RET or `Q', the command
6829 returns to the original buffer in which the visibility is still
6830 unchanged. After RET it will also jump to the location selected
6831 in the indirect buffer and expose the headline hierarchy above.
6833 With a prefix argument, use the alternative interface: e.g. if
6834 `org-goto-interface' is 'outline use 'outline-path-completion."
6835 (interactive "P")
6836 (org-goto-map)
6837 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6838 (org-refile-use-outline-path t)
6839 (org-refile-target-verify-function nil)
6840 (interface
6841 (if (not alternative-interface)
6842 org-goto-interface
6843 (if (eq org-goto-interface 'outline)
6844 'outline-path-completion
6845 'outline)))
6846 (org-goto-start-pos (point))
6847 (selected-point
6848 (if (eq interface 'outline)
6849 (car (org-get-location (current-buffer) org-goto-help))
6850 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6851 (org-refile-check-position pa)
6852 (nth 3 pa)))))
6853 (if selected-point
6854 (progn
6855 (org-mark-ring-push org-goto-start-pos)
6856 (goto-char selected-point)
6857 (if (or (outline-invisible-p) (org-invisible-p2))
6858 (org-show-context 'org-goto)))
6859 (message "Quit"))))
6861 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6862 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6863 (defvar org-goto-local-auto-isearch-map) ; defined below
6865 (defun org-get-location (buf help)
6866 "Let the user select a location in the Org-mode buffer BUF.
6867 This function uses a recursive edit. It returns the selected position
6868 or nil."
6869 (org-no-popups
6870 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6871 (isearch-hide-immediately nil)
6872 (isearch-search-fun-function
6873 (lambda () 'org-goto-local-search-headings))
6874 (org-goto-selected-point org-goto-exit-command))
6875 (save-excursion
6876 (save-window-excursion
6877 (delete-other-windows)
6878 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6879 (org-pop-to-buffer-same-window
6880 (condition-case nil
6881 (make-indirect-buffer (current-buffer) "*org-goto*")
6882 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6883 (with-output-to-temp-buffer "*Org Help*"
6884 (princ (format help (if org-goto-auto-isearch
6885 " Just type for auto-isearch."
6886 " n/p/f/b/u to navigate, q to quit."))))
6887 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
6888 (setq buffer-read-only nil)
6889 (let ((org-startup-truncated t)
6890 (org-startup-folded nil)
6891 (org-startup-align-all-tables nil))
6892 (org-mode)
6893 (org-overview))
6894 (setq buffer-read-only t)
6895 (if (and (boundp 'org-goto-start-pos)
6896 (integer-or-marker-p org-goto-start-pos))
6897 (let ((org-show-hierarchy-above t)
6898 (org-show-siblings t)
6899 (org-show-following-heading t))
6900 (goto-char org-goto-start-pos)
6901 (and (outline-invisible-p) (org-show-context)))
6902 (goto-char (point-min)))
6903 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6904 (message "Select location and press RET")
6905 (use-local-map org-goto-map)
6906 (recursive-edit)))
6907 (kill-buffer "*org-goto*")
6908 (cons org-goto-selected-point org-goto-exit-command))))
6910 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6911 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6912 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6913 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6915 (defun org-goto-local-search-headings (string bound noerror)
6916 "Search and make sure that any matches are in headlines."
6917 (catch 'return
6918 (while (if isearch-forward
6919 (search-forward string bound noerror)
6920 (search-backward string bound noerror))
6921 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6922 (and (member :headline context)
6923 (not (member :tags context))))
6924 (throw 'return (point))))))
6926 (defun org-goto-local-auto-isearch ()
6927 "Start isearch."
6928 (interactive)
6929 (goto-char (point-min))
6930 (let ((keys (this-command-keys)))
6931 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6932 (isearch-mode t)
6933 (isearch-process-search-char (string-to-char keys)))))
6935 (defun org-goto-ret (&optional arg)
6936 "Finish `org-goto' by going to the new location."
6937 (interactive "P")
6938 (setq org-goto-selected-point (point)
6939 org-goto-exit-command 'return)
6940 (throw 'exit nil))
6942 (defun org-goto-left ()
6943 "Finish `org-goto' by going to the new location."
6944 (interactive)
6945 (if (org-at-heading-p)
6946 (progn
6947 (beginning-of-line 1)
6948 (setq org-goto-selected-point (point)
6949 org-goto-exit-command 'left)
6950 (throw 'exit nil))
6951 (error "Not on a heading")))
6953 (defun org-goto-right ()
6954 "Finish `org-goto' by going to the new location."
6955 (interactive)
6956 (if (org-at-heading-p)
6957 (progn
6958 (setq org-goto-selected-point (point)
6959 org-goto-exit-command 'right)
6960 (throw 'exit nil))
6961 (error "Not on a heading")))
6963 (defun org-goto-quit ()
6964 "Finish `org-goto' without cursor motion."
6965 (interactive)
6966 (setq org-goto-selected-point nil)
6967 (setq org-goto-exit-command 'quit)
6968 (throw 'exit nil))
6970 ;;; Indirect buffer display of subtrees
6972 (defvar org-indirect-dedicated-frame nil
6973 "This is the frame being used for indirect tree display.")
6974 (defvar org-last-indirect-buffer nil)
6976 (defun org-tree-to-indirect-buffer (&optional arg)
6977 "Create indirect buffer and narrow it to current subtree.
6978 With a numerical prefix ARG, go up to this level and then take that tree.
6979 If ARG is negative, go up that many levels.
6981 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6982 indirect buffer previously made with this command, to avoid proliferation of
6983 indirect buffers. However, when you call the command with a \
6984 \\[universal-argument] prefix, or
6985 when `org-indirect-buffer-display' is `new-frame', the last buffer
6986 is kept so that you can work with several indirect buffers at the same time.
6987 If `org-indirect-buffer-display' is `dedicated-frame', the \
6988 \\[universal-argument] prefix also
6989 requests that a new frame be made for the new buffer, so that the dedicated
6990 frame is not changed."
6991 (interactive "P")
6992 (let ((cbuf (current-buffer))
6993 (cwin (selected-window))
6994 (pos (point))
6995 beg end level heading ibuf)
6996 (save-excursion
6997 (org-back-to-heading t)
6998 (when (numberp arg)
6999 (setq level (org-outline-level))
7000 (if (< arg 0) (setq arg (+ level arg)))
7001 (while (> (setq level (org-outline-level)) arg)
7002 (org-up-heading-safe)))
7003 (setq beg (point)
7004 heading (org-get-heading))
7005 (org-end-of-subtree t t)
7006 (if (org-at-heading-p) (backward-char 1))
7007 (setq end (point)))
7008 (if (and (buffer-live-p org-last-indirect-buffer)
7009 (not (eq org-indirect-buffer-display 'new-frame))
7010 (not arg))
7011 (kill-buffer org-last-indirect-buffer))
7012 (setq ibuf (org-get-indirect-buffer cbuf)
7013 org-last-indirect-buffer ibuf)
7014 (cond
7015 ((or (eq org-indirect-buffer-display 'new-frame)
7016 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7017 (select-frame (make-frame))
7018 (delete-other-windows)
7019 (org-pop-to-buffer-same-window ibuf)
7020 (org-set-frame-title heading))
7021 ((eq org-indirect-buffer-display 'dedicated-frame)
7022 (raise-frame
7023 (select-frame (or (and org-indirect-dedicated-frame
7024 (frame-live-p org-indirect-dedicated-frame)
7025 org-indirect-dedicated-frame)
7026 (setq org-indirect-dedicated-frame (make-frame)))))
7027 (delete-other-windows)
7028 (org-pop-to-buffer-same-window ibuf)
7029 (org-set-frame-title (concat "Indirect: " heading)))
7030 ((eq org-indirect-buffer-display 'current-window)
7031 (org-pop-to-buffer-same-window ibuf))
7032 ((eq org-indirect-buffer-display 'other-window)
7033 (pop-to-buffer ibuf))
7034 (t (error "Invalid value")))
7035 (if (featurep 'xemacs)
7036 (save-excursion (org-mode) (turn-on-font-lock)))
7037 (narrow-to-region beg end)
7038 (show-all)
7039 (goto-char pos)
7040 (run-hook-with-args 'org-cycle-hook 'all)
7041 (and (window-live-p cwin) (select-window cwin))))
7043 (defun org-get-indirect-buffer (&optional buffer)
7044 (setq buffer (or buffer (current-buffer)))
7045 (let ((n 1) (base (buffer-name buffer)) bname)
7046 (while (buffer-live-p
7047 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7048 (setq n (1+ n)))
7049 (condition-case nil
7050 (make-indirect-buffer buffer bname 'clone)
7051 (error (make-indirect-buffer buffer bname)))))
7053 (defun org-set-frame-title (title)
7054 "Set the title of the current frame to the string TITLE."
7055 ;; FIXME: how to name a single frame in XEmacs???
7056 (unless (featurep 'xemacs)
7057 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7059 ;;;; Structure editing
7061 ;;; Inserting headlines
7063 (defun org-previous-line-empty-p ()
7064 (save-excursion
7065 (and (not (bobp))
7066 (or (beginning-of-line 0) t)
7067 (save-match-data
7068 (looking-at "[ \t]*$")))))
7070 (defun org-insert-heading (&optional force-heading invisible-ok)
7071 "Insert a new heading or item with same depth at point.
7072 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7073 If point is at the beginning of a headline, insert a sibling before the
7074 current headline. If point is not at the beginning, split the line,
7075 create the new headline with the text in the current line after point
7076 \(but see also the variable `org-M-RET-may-split-line').
7078 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7079 This is important for non-interactive uses of the command."
7080 (interactive "P")
7081 (if (or (= (buffer-size) 0)
7082 (and (not (save-excursion
7083 (and (ignore-errors (org-back-to-heading invisible-ok))
7084 (org-at-heading-p))))
7085 (or force-heading (not (org-in-item-p)))))
7086 (progn
7087 (insert "\n* ")
7088 (run-hooks 'org-insert-heading-hook))
7089 (when (or force-heading (not (org-insert-item)))
7090 (let* ((empty-line-p nil)
7091 (level nil)
7092 (on-heading (org-at-heading-p))
7093 (head (save-excursion
7094 (condition-case nil
7095 (progn
7096 (org-back-to-heading invisible-ok)
7097 (when (and (not on-heading)
7098 (featurep 'org-inlinetask)
7099 (integerp org-inlinetask-min-level)
7100 (>= (length (match-string 0))
7101 org-inlinetask-min-level))
7102 ;; Find a heading level before the inline task
7103 (while (and (setq level (org-up-heading-safe))
7104 (>= level org-inlinetask-min-level)))
7105 (if (org-at-heading-p)
7106 (org-back-to-heading invisible-ok)
7107 (error "This should not happen")))
7108 (setq empty-line-p (org-previous-line-empty-p))
7109 (match-string 0))
7110 (error "*"))))
7111 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7112 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7113 pos hide-previous previous-pos)
7114 (cond
7115 ((and (org-at-heading-p) (bolp)
7116 (or (bobp)
7117 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7118 ;; insert before the current line
7119 (open-line (if blank 2 1)))
7120 ((and (bolp)
7121 (not org-insert-heading-respect-content)
7122 (or (bobp)
7123 (save-excursion
7124 (backward-char 1) (not (outline-invisible-p)))))
7125 ;; insert right here
7126 nil)
7128 ;; somewhere in the line
7129 (save-excursion
7130 (setq previous-pos (point-at-bol))
7131 (end-of-line)
7132 (setq hide-previous (outline-invisible-p)))
7133 (and org-insert-heading-respect-content (org-show-subtree))
7134 (let ((split
7135 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7136 (save-excursion
7137 (let ((p (point)))
7138 (goto-char (point-at-bol))
7139 (and (looking-at org-complex-heading-regexp)
7140 (match-beginning 4)
7141 (> p (match-beginning 4)))))))
7142 tags pos)
7143 (cond
7144 (org-insert-heading-respect-content
7145 (org-end-of-subtree nil t)
7146 (when (featurep 'org-inlinetask)
7147 (while (and (not (eobp))
7148 (looking-at "\\(\\*+\\)[ \t]+")
7149 (>= (length (match-string 1))
7150 org-inlinetask-min-level))
7151 (org-end-of-subtree nil t)))
7152 (or (bolp) (newline))
7153 (or (org-previous-line-empty-p)
7154 (and blank (newline)))
7155 (open-line 1))
7156 ((org-at-heading-p)
7157 (when hide-previous
7158 (show-children)
7159 (org-show-entry))
7160 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7161 (setq tags (and (match-end 2) (match-string 2)))
7162 (and (match-end 1)
7163 (delete-region (match-beginning 1) (match-end 1)))
7164 (setq pos (point-at-bol))
7165 (or split (end-of-line 1))
7166 (delete-horizontal-space)
7167 (if (string-match "\\`\\*+\\'"
7168 (buffer-substring (point-at-bol) (point)))
7169 (insert " "))
7170 (newline (if blank 2 1))
7171 (when tags
7172 (save-excursion
7173 (goto-char pos)
7174 (end-of-line 1)
7175 (insert " " tags)
7176 (org-set-tags nil 'align))))
7178 (or split (end-of-line 1))
7179 (newline (if blank 2 1)))))))
7180 (insert head) (just-one-space)
7181 (setq pos (point))
7182 (end-of-line 1)
7183 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7184 (when (and org-insert-heading-respect-content hide-previous)
7185 (save-excursion
7186 (goto-char previous-pos)
7187 (hide-subtree)))
7188 (run-hooks 'org-insert-heading-hook)))))
7190 (defun org-get-heading (&optional no-tags no-todo)
7191 "Return the heading of the current entry, without the stars.
7192 When NO-TAGS is non-nil, don't include tags.
7193 When NO-TODO is non-nil, don't include TODO keywords."
7194 (save-excursion
7195 (org-back-to-heading t)
7196 (cond
7197 ((and no-tags no-todo)
7198 (looking-at org-complex-heading-regexp)
7199 (match-string 4))
7200 (no-tags
7201 (looking-at (concat org-outline-regexp
7202 "\\(.*?\\)"
7203 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7204 (match-string 1))
7205 (no-todo
7206 (looking-at org-todo-line-regexp)
7207 (match-string 3))
7208 (t (looking-at org-heading-regexp)
7209 (match-string 2)))))
7211 (defun org-heading-components ()
7212 "Return the components of the current heading.
7213 This is a list with the following elements:
7214 - the level as an integer
7215 - the reduced level, different if `org-odd-levels-only' is set.
7216 - the TODO keyword, or nil
7217 - the priority character, like ?A, or nil if no priority is given
7218 - the headline text itself, or the tags string if no headline text
7219 - the tags string, or nil."
7220 (save-excursion
7221 (org-back-to-heading t)
7222 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7223 (list (length (match-string 1))
7224 (org-reduced-level (length (match-string 1)))
7225 (org-match-string-no-properties 2)
7226 (and (match-end 3) (aref (match-string 3) 2))
7227 (org-match-string-no-properties 4)
7228 (org-match-string-no-properties 5)))))
7230 (defun org-get-entry ()
7231 "Get the entry text, after heading, entire subtree."
7232 (save-excursion
7233 (org-back-to-heading t)
7234 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7236 (defun org-insert-heading-after-current ()
7237 "Insert a new heading with same level as current, after current subtree."
7238 (interactive)
7239 (org-back-to-heading)
7240 (org-insert-heading)
7241 (org-move-subtree-down)
7242 (end-of-line 1))
7244 (defun org-insert-heading-respect-content (invisible-ok)
7245 "Insert heading with `org-insert-heading-respect-content' set to t."
7246 (interactive "P")
7247 (let ((org-insert-heading-respect-content t))
7248 (org-insert-heading t invisible-ok)))
7250 (defun org-insert-todo-heading-respect-content (&optional force-state)
7251 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7252 (interactive "P")
7253 (let ((org-insert-heading-respect-content t))
7254 (org-insert-todo-heading force-state t)))
7256 (defun org-insert-todo-heading (arg &optional force-heading)
7257 "Insert a new heading with the same level and TODO state as current heading.
7258 If the heading has no TODO state, or if the state is DONE, use the first
7259 state (TODO by default). Also with prefix arg, force first state."
7260 (interactive "P")
7261 (when (or force-heading (not (org-insert-item 'checkbox)))
7262 (org-insert-heading force-heading)
7263 (save-excursion
7264 (org-back-to-heading)
7265 (outline-previous-heading)
7266 (looking-at org-todo-line-regexp))
7267 (let*
7268 ((new-mark-x
7269 (if (or arg
7270 (not (match-beginning 2))
7271 (member (match-string 2) org-done-keywords))
7272 (car org-todo-keywords-1)
7273 (match-string 2)))
7274 (new-mark
7276 (run-hook-with-args-until-success
7277 'org-todo-get-default-hook new-mark-x nil)
7278 new-mark-x)))
7279 (beginning-of-line 1)
7280 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7281 (if org-treat-insert-todo-heading-as-state-change
7282 (org-todo new-mark)
7283 (insert new-mark " "))))
7284 (when org-provide-todo-statistics
7285 (org-update-parent-todo-statistics))))
7287 (defun org-insert-subheading (arg)
7288 "Insert a new subheading and demote it.
7289 Works for outline headings and for plain lists alike."
7290 (interactive "P")
7291 (org-insert-heading arg)
7292 (cond
7293 ((org-at-heading-p) (org-do-demote))
7294 ((org-at-item-p) (org-indent-item))))
7296 (defun org-insert-todo-subheading (arg)
7297 "Insert a new subheading with TODO keyword or checkbox and demote it.
7298 Works for outline headings and for plain lists alike."
7299 (interactive "P")
7300 (org-insert-todo-heading arg)
7301 (cond
7302 ((org-at-heading-p) (org-do-demote))
7303 ((org-at-item-p) (org-indent-item))))
7305 ;;; Promotion and Demotion
7307 (defvar org-after-demote-entry-hook nil
7308 "Hook run after an entry has been demoted.
7309 The cursor will be at the beginning of the entry.
7310 When a subtree is being demoted, the hook will be called for each node.")
7312 (defvar org-after-promote-entry-hook nil
7313 "Hook run after an entry has been promoted.
7314 The cursor will be at the beginning of the entry.
7315 When a subtree is being promoted, the hook will be called for each node.")
7317 (defun org-promote-subtree ()
7318 "Promote the entire subtree.
7319 See also `org-promote'."
7320 (interactive)
7321 (save-excursion
7322 (org-with-limited-levels (org-map-tree 'org-promote)))
7323 (org-fix-position-after-promote))
7325 (defun org-demote-subtree ()
7326 "Demote the entire subtree. See `org-demote'.
7327 See also `org-promote'."
7328 (interactive)
7329 (save-excursion
7330 (org-with-limited-levels (org-map-tree 'org-demote)))
7331 (org-fix-position-after-promote))
7334 (defun org-do-promote ()
7335 "Promote the current heading higher up the tree.
7336 If the region is active in `transient-mark-mode', promote all headings
7337 in the region."
7338 (interactive)
7339 (save-excursion
7340 (if (org-region-active-p)
7341 (org-map-region 'org-promote (region-beginning) (region-end))
7342 (org-promote)))
7343 (org-fix-position-after-promote))
7345 (defun org-do-demote ()
7346 "Demote the current heading lower down the tree.
7347 If the region is active in `transient-mark-mode', demote all headings
7348 in the region."
7349 (interactive)
7350 (save-excursion
7351 (if (org-region-active-p)
7352 (org-map-region 'org-demote (region-beginning) (region-end))
7353 (org-demote)))
7354 (org-fix-position-after-promote))
7356 (defun org-fix-position-after-promote ()
7357 "Make sure that after pro/demotion cursor position is right."
7358 (let ((pos (point)))
7359 (when (save-excursion
7360 (beginning-of-line 1)
7361 (looking-at org-todo-line-regexp)
7362 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7363 (cond ((eobp) (insert " "))
7364 ((eolp) (insert " "))
7365 ((equal (char-after) ?\ ) (forward-char 1))))))
7367 (defun org-current-level ()
7368 "Return the level of the current entry, or nil if before the first headline.
7369 The level is the number of stars at the beginning of the headline."
7370 (save-excursion
7371 (org-with-limited-levels
7372 (if (ignore-errors (org-back-to-heading t))
7373 (funcall outline-level)))))
7375 (defun org-get-previous-line-level ()
7376 "Return the outline depth of the last headline before the current line.
7377 Returns 0 for the first headline in the buffer, and nil if before the
7378 first headline."
7379 (let ((current-level (org-current-level))
7380 (prev-level (when (> (line-number-at-pos) 1)
7381 (save-excursion
7382 (beginning-of-line 0)
7383 (org-current-level)))))
7384 (cond ((null current-level) nil) ; Before first headline
7385 ((null prev-level) 0) ; At first headline
7386 (prev-level))))
7388 (defun org-reduced-level (l)
7389 "Compute the effective level of a heading.
7390 This takes into account the setting of `org-odd-levels-only'."
7391 (cond
7392 ((zerop l) 0)
7393 (org-odd-levels-only (1+ (floor (/ l 2))))
7394 (t l)))
7396 (defun org-level-increment ()
7397 "Return the number of stars that will be added or removed at a
7398 time to headlines when structure editing, based on the value of
7399 `org-odd-levels-only'."
7400 (if org-odd-levels-only 2 1))
7402 (defun org-get-valid-level (level &optional change)
7403 "Rectify a level change under the influence of `org-odd-levels-only'
7404 LEVEL is a current level, CHANGE is by how much the level should be
7405 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7406 even level numbers will become the next higher odd number."
7407 (if org-odd-levels-only
7408 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7409 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7410 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7411 (max 1 (+ level (or change 0)))))
7413 (if (boundp 'define-obsolete-function-alias)
7414 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7415 (define-obsolete-function-alias 'org-get-legal-level
7416 'org-get-valid-level)
7417 (define-obsolete-function-alias 'org-get-legal-level
7418 'org-get-valid-level "23.1")))
7420 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7421 ;; ̀org-with-limited-levels'
7422 (defun org-promote ()
7423 "Promote the current heading higher up the tree.
7424 If the region is active in `transient-mark-mode', promote all headings
7425 in the region."
7426 (org-back-to-heading t)
7427 (let* ((level (save-match-data (funcall outline-level)))
7428 (after-change-functions (remove 'flyspell-after-change-function
7429 after-change-functions))
7430 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7431 (diff (abs (- level (length up-head) -1))))
7432 (cond ((and (= level 1) org-called-with-limited-levels
7433 org-allow-promoting-top-level-subtree)
7434 (replace-match "# " nil t))
7435 ((= level 1)
7436 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7437 (t (replace-match up-head nil t)))
7438 ;; Fixup tag positioning
7439 (unless (= level 1)
7440 (and org-auto-align-tags (org-set-tags nil t))
7441 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7442 (run-hooks 'org-after-promote-entry-hook)))
7444 (defun org-demote ()
7445 "Demote the current heading lower down the tree.
7446 If the region is active in `transient-mark-mode', demote all headings
7447 in the region."
7448 (org-back-to-heading t)
7449 (let* ((level (save-match-data (funcall outline-level)))
7450 (after-change-functions (remove 'flyspell-after-change-function
7451 after-change-functions))
7452 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7453 (diff (abs (- level (length down-head) -1))))
7454 (replace-match down-head nil t)
7455 ;; Fixup tag positioning
7456 (and org-auto-align-tags (org-set-tags nil t))
7457 (if org-adapt-indentation (org-fixup-indentation diff))
7458 (run-hooks 'org-after-demote-entry-hook)))
7460 (defun org-cycle-level ()
7461 "Cycle the level of an empty headline through possible states.
7462 This goes first to child, then to parent, level, then up the hierarchy.
7463 After top level, it switches back to sibling level."
7464 (interactive)
7465 (let ((org-adapt-indentation nil))
7466 (when (org-point-at-end-of-empty-headline)
7467 (setq this-command 'org-cycle-level) ; Only needed for caching
7468 (let ((cur-level (org-current-level))
7469 (prev-level (org-get-previous-line-level)))
7470 (cond
7471 ;; If first headline in file, promote to top-level.
7472 ((= prev-level 0)
7473 (loop repeat (/ (- cur-level 1) (org-level-increment))
7474 do (org-do-promote)))
7475 ;; If same level as prev, demote one.
7476 ((= prev-level cur-level)
7477 (org-do-demote))
7478 ;; If parent is top-level, promote to top level if not already.
7479 ((= prev-level 1)
7480 (loop repeat (/ (- cur-level 1) (org-level-increment))
7481 do (org-do-promote)))
7482 ;; If top-level, return to prev-level.
7483 ((= cur-level 1)
7484 (loop repeat (/ (- prev-level 1) (org-level-increment))
7485 do (org-do-demote)))
7486 ;; If less than prev-level, promote one.
7487 ((< cur-level prev-level)
7488 (org-do-promote))
7489 ;; If deeper than prev-level, promote until higher than
7490 ;; prev-level.
7491 ((> cur-level prev-level)
7492 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7493 do (org-do-promote))))
7494 t))))
7496 (defun org-map-tree (fun)
7497 "Call FUN for every heading underneath the current one."
7498 (org-back-to-heading)
7499 (let ((level (funcall outline-level)))
7500 (save-excursion
7501 (funcall fun)
7502 (while (and (progn
7503 (outline-next-heading)
7504 (> (funcall outline-level) level))
7505 (not (eobp)))
7506 (funcall fun)))))
7508 (defun org-map-region (fun beg end)
7509 "Call FUN for every heading between BEG and END."
7510 (let ((org-ignore-region t))
7511 (save-excursion
7512 (setq end (copy-marker end))
7513 (goto-char beg)
7514 (if (and (re-search-forward org-outline-regexp-bol nil t)
7515 (< (point) end))
7516 (funcall fun))
7517 (while (and (progn
7518 (outline-next-heading)
7519 (< (point) end))
7520 (not (eobp)))
7521 (funcall fun)))))
7523 (defvar org-property-end-re) ; silence byte-compiler
7524 (defun org-fixup-indentation (diff)
7525 "Change the indentation in the current entry by DIFF.
7526 However, if any line in the current entry has no indentation, or if it
7527 would end up with no indentation after the change, nothing at all is done."
7528 (save-excursion
7529 (let ((end (save-excursion (outline-next-heading)
7530 (point-marker)))
7531 (prohibit (if (> diff 0)
7532 "^\\S-"
7533 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7534 col)
7535 (unless (save-excursion (end-of-line 1)
7536 (re-search-forward prohibit end t))
7537 (while (and (< (point) end)
7538 (re-search-forward "^[ \t]+" end t))
7539 (goto-char (match-end 0))
7540 (setq col (current-column))
7541 (if (< diff 0) (replace-match ""))
7542 (org-indent-to-column (+ diff col))))
7543 (move-marker end nil))))
7545 (defun org-convert-to-odd-levels ()
7546 "Convert an org-mode file with all levels allowed to one with odd levels.
7547 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7548 level 5 etc."
7549 (interactive)
7550 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7551 (let ((outline-level 'org-outline-level)
7552 (org-odd-levels-only nil) n)
7553 (save-excursion
7554 (goto-char (point-min))
7555 (while (re-search-forward "^\\*\\*+ " nil t)
7556 (setq n (- (length (match-string 0)) 2))
7557 (while (>= (setq n (1- n)) 0)
7558 (org-demote))
7559 (end-of-line 1))))))
7561 (defun org-convert-to-oddeven-levels ()
7562 "Convert an org-mode file with only odd levels to one with odd/even levels.
7563 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7564 file contains a section with an even level, conversion would
7565 destroy the structure of the file. An error is signaled in this
7566 case."
7567 (interactive)
7568 (goto-char (point-min))
7569 ;; First check if there are no even levels
7570 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7571 (org-show-context t)
7572 (error "Not all levels are odd in this file. Conversion not possible"))
7573 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7574 (let ((outline-regexp org-outline-regexp)
7575 (outline-level 'org-outline-level)
7576 (org-odd-levels-only nil) n)
7577 (save-excursion
7578 (goto-char (point-min))
7579 (while (re-search-forward "^\\*\\*+ " nil t)
7580 (setq n (/ (1- (length (match-string 0))) 2))
7581 (while (>= (setq n (1- n)) 0)
7582 (org-promote))
7583 (end-of-line 1))))))
7585 (defun org-tr-level (n)
7586 "Make N odd if required."
7587 (if org-odd-levels-only (1+ (/ n 2)) n))
7589 ;;; Vertical tree motion, cutting and pasting of subtrees
7591 (defun org-move-subtree-up (&optional arg)
7592 "Move the current subtree up past ARG headlines of the same level."
7593 (interactive "p")
7594 (org-move-subtree-down (- (prefix-numeric-value arg))))
7596 (defun org-move-subtree-down (&optional arg)
7597 "Move the current subtree down past ARG headlines of the same level."
7598 (interactive "p")
7599 (setq arg (prefix-numeric-value arg))
7600 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7601 'org-get-last-sibling))
7602 (ins-point (make-marker))
7603 (cnt (abs arg))
7604 (col (current-column))
7605 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7606 ;; Select the tree
7607 (org-back-to-heading)
7608 (setq beg0 (point))
7609 (save-excursion
7610 (setq ne-beg (org-back-over-empty-lines))
7611 (setq beg (point)))
7612 (save-match-data
7613 (save-excursion (outline-end-of-heading)
7614 (setq folded (outline-invisible-p)))
7615 (outline-end-of-subtree))
7616 (outline-next-heading)
7617 (setq ne-end (org-back-over-empty-lines))
7618 (setq end (point))
7619 (goto-char beg0)
7620 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7621 ;; include less whitespace
7622 (save-excursion
7623 (goto-char beg)
7624 (forward-line (- ne-beg ne-end))
7625 (setq beg (point))))
7626 ;; Find insertion point, with error handling
7627 (while (> cnt 0)
7628 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7629 (progn (goto-char beg0)
7630 (error "Cannot move past superior level or buffer limit")))
7631 (setq cnt (1- cnt)))
7632 (if (> arg 0)
7633 ;; Moving forward - still need to move over subtree
7634 (progn (org-end-of-subtree t t)
7635 (save-excursion
7636 (org-back-over-empty-lines)
7637 (or (bolp) (newline)))))
7638 (setq ne-ins (org-back-over-empty-lines))
7639 (move-marker ins-point (point))
7640 (setq txt (buffer-substring beg end))
7641 (org-save-markers-in-region beg end)
7642 (delete-region beg end)
7643 (org-remove-empty-overlays-at beg)
7644 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7645 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7646 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7647 (let ((bbb (point)))
7648 (insert-before-markers txt)
7649 (org-reinstall-markers-in-region bbb)
7650 (move-marker ins-point bbb))
7651 (or (bolp) (insert "\n"))
7652 (setq ins-end (point))
7653 (goto-char ins-point)
7654 (org-skip-whitespace)
7655 (when (and (< arg 0)
7656 (org-first-sibling-p)
7657 (> ne-ins ne-beg))
7658 ;; Move whitespace back to beginning
7659 (save-excursion
7660 (goto-char ins-end)
7661 (let ((kill-whole-line t))
7662 (kill-line (- ne-ins ne-beg)) (point)))
7663 (insert (make-string (- ne-ins ne-beg) ?\n)))
7664 (move-marker ins-point nil)
7665 (if folded
7666 (hide-subtree)
7667 (org-show-entry)
7668 (show-children)
7669 (org-cycle-hide-drawers 'children))
7670 (org-clean-visibility-after-subtree-move)
7671 ;; move back to the initial column we were at
7672 (move-to-column col)))
7674 (defvar org-subtree-clip ""
7675 "Clipboard for cut and paste of subtrees.
7676 This is actually only a copy of the kill, because we use the normal kill
7677 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7679 (defvar org-subtree-clip-folded nil
7680 "Was the last copied subtree folded?
7681 This is used to fold the tree back after pasting.")
7683 (defun org-cut-subtree (&optional n)
7684 "Cut the current subtree into the clipboard.
7685 With prefix arg N, cut this many sequential subtrees.
7686 This is a short-hand for marking the subtree and then cutting it."
7687 (interactive "p")
7688 (org-copy-subtree n 'cut))
7690 (defun org-copy-subtree (&optional n cut force-store-markers)
7691 "Cut the current subtree into the clipboard.
7692 With prefix arg N, cut this many sequential subtrees.
7693 This is a short-hand for marking the subtree and then copying it.
7694 If CUT is non-nil, actually cut the subtree.
7695 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7696 of some markers in the region, even if CUT is non-nil. This is
7697 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7698 (interactive "p")
7699 (let (beg end folded (beg0 (point)))
7700 (if (org-called-interactively-p 'any)
7701 (org-back-to-heading nil) ; take what looks like a subtree
7702 (org-back-to-heading t)) ; take what is really there
7703 (setq beg (point))
7704 (skip-chars-forward " \t\r\n")
7705 (save-match-data
7706 (save-excursion (outline-end-of-heading)
7707 (setq folded (outline-invisible-p)))
7708 (condition-case nil
7709 (org-forward-heading-same-level (1- n) t)
7710 (error nil))
7711 (org-end-of-subtree t t))
7712 (setq end (point))
7713 (goto-char beg0)
7714 (when (> end beg)
7715 (setq org-subtree-clip-folded folded)
7716 (when (or cut force-store-markers)
7717 (org-save-markers-in-region beg end))
7718 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7719 (setq org-subtree-clip (current-kill 0))
7720 (message "%s: Subtree(s) with %d characters"
7721 (if cut "Cut" "Copied")
7722 (length org-subtree-clip)))))
7724 (defun org-paste-subtree (&optional level tree for-yank)
7725 "Paste the clipboard as a subtree, with modification of headline level.
7726 The entire subtree is promoted or demoted in order to match a new headline
7727 level.
7729 If the cursor is at the beginning of a headline, the same level as
7730 that headline is used to paste the tree
7732 If not, the new level is derived from the *visible* headings
7733 before and after the insertion point, and taken to be the inferior headline
7734 level of the two. So if the previous visible heading is level 3 and the
7735 next is level 4 (or vice versa), level 4 will be used for insertion.
7736 This makes sure that the subtree remains an independent subtree and does
7737 not swallow low level entries.
7739 You can also force a different level, either by using a numeric prefix
7740 argument, or by inserting the heading marker by hand. For example, if the
7741 cursor is after \"*****\", then the tree will be shifted to level 5.
7743 If optional TREE is given, use this text instead of the kill ring.
7745 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7746 move back over whitespace before inserting, and move point to the end of
7747 the inserted text when done."
7748 (interactive "P")
7749 (setq tree (or tree (and kill-ring (current-kill 0))))
7750 (unless (org-kill-is-subtree-p tree)
7751 (error "%s"
7752 (substitute-command-keys
7753 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7754 (org-with-limited-levels
7755 (let* ((visp (not (outline-invisible-p)))
7756 (txt tree)
7757 (^re_ "\\(\\*+\\)[ \t]*")
7758 (old-level (if (string-match org-outline-regexp-bol txt)
7759 (- (match-end 0) (match-beginning 0) 1)
7760 -1))
7761 (force-level (cond (level (prefix-numeric-value level))
7762 ((and (looking-at "[ \t]*$")
7763 (string-match
7764 "^\\*+$" (buffer-substring
7765 (point-at-bol) (point))))
7766 (- (match-end 1) (match-beginning 1)))
7767 ((and (bolp)
7768 (looking-at org-outline-regexp))
7769 (- (match-end 0) (point) 1))))
7770 (previous-level (save-excursion
7771 (condition-case nil
7772 (progn
7773 (outline-previous-visible-heading 1)
7774 (if (looking-at ^re_)
7775 (- (match-end 0) (match-beginning 0) 1)
7777 (error 1))))
7778 (next-level (save-excursion
7779 (condition-case nil
7780 (progn
7781 (or (looking-at org-outline-regexp)
7782 (outline-next-visible-heading 1))
7783 (if (looking-at ^re_)
7784 (- (match-end 0) (match-beginning 0) 1)
7786 (error 1))))
7787 (new-level (or force-level (max previous-level next-level)))
7788 (shift (if (or (= old-level -1)
7789 (= new-level -1)
7790 (= old-level new-level))
7792 (- new-level old-level)))
7793 (delta (if (> shift 0) -1 1))
7794 (func (if (> shift 0) 'org-demote 'org-promote))
7795 (org-odd-levels-only nil)
7796 beg end newend)
7797 ;; Remove the forced level indicator
7798 (if force-level
7799 (delete-region (point-at-bol) (point)))
7800 ;; Paste
7801 (beginning-of-line (if (bolp) 1 2))
7802 (setq beg (point))
7803 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7804 (insert-before-markers txt)
7805 (unless (string-match "\n\\'" txt) (insert "\n"))
7806 (setq newend (point))
7807 (org-reinstall-markers-in-region beg)
7808 (setq end (point))
7809 (goto-char beg)
7810 (skip-chars-forward " \t\n\r")
7811 (setq beg (point))
7812 (if (and (outline-invisible-p) visp)
7813 (save-excursion (outline-show-heading)))
7814 ;; Shift if necessary
7815 (unless (= shift 0)
7816 (save-restriction
7817 (narrow-to-region beg end)
7818 (while (not (= shift 0))
7819 (org-map-region func (point-min) (point-max))
7820 (setq shift (+ delta shift)))
7821 (goto-char (point-min))
7822 (setq newend (point-max))))
7823 (when (or (org-called-interactively-p 'interactive) for-yank)
7824 (message "Clipboard pasted as level %d subtree" new-level))
7825 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7826 kill-ring
7827 (eq org-subtree-clip (current-kill 0))
7828 org-subtree-clip-folded)
7829 ;; The tree was folded before it was killed/copied
7830 (hide-subtree))
7831 (and for-yank (goto-char newend)))))
7833 (defun org-kill-is-subtree-p (&optional txt)
7834 "Check if the current kill is an outline subtree, or a set of trees.
7835 Returns nil if kill does not start with a headline, or if the first
7836 headline level is not the largest headline level in the tree.
7837 So this will actually accept several entries of equal levels as well,
7838 which is OK for `org-paste-subtree'.
7839 If optional TXT is given, check this string instead of the current kill."
7840 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7841 (re (org-get-limited-outline-regexp))
7842 (^re (concat "^" re))
7843 (start-level (and kill
7844 (string-match
7845 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7846 kill)
7847 (- (match-end 2) (match-beginning 2) 1)))
7848 (start (1+ (or (match-beginning 2) -1))))
7849 (if (not start-level)
7850 (progn
7851 nil) ;; does not even start with a heading
7852 (catch 'exit
7853 (while (setq start (string-match ^re kill (1+ start)))
7854 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7855 (throw 'exit nil)))
7856 t))))
7858 (defvar org-markers-to-move nil
7859 "Markers that should be moved with a cut-and-paste operation.
7860 Those markers are stored together with their positions relative to
7861 the start of the region.")
7863 (defun org-save-markers-in-region (beg end)
7864 "Check markers in region.
7865 If these markers are between BEG and END, record their position relative
7866 to BEG, so that after moving the block of text, we can put the markers back
7867 into place.
7868 This function gets called just before an entry or tree gets cut from the
7869 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7870 called immediately, to move the markers with the entries."
7871 (setq org-markers-to-move nil)
7872 (when (featurep 'org-clock)
7873 (org-clock-save-markers-for-cut-and-paste beg end))
7874 (when (featurep 'org-agenda)
7875 (org-agenda-save-markers-for-cut-and-paste beg end)))
7877 (defun org-check-and-save-marker (marker beg end)
7878 "Check if MARKER is between BEG and END.
7879 If yes, remember the marker and the distance to BEG."
7880 (when (and (marker-buffer marker)
7881 (equal (marker-buffer marker) (current-buffer)))
7882 (if (and (>= marker beg) (< marker end))
7883 (push (cons marker (- marker beg)) org-markers-to-move))))
7885 (defun org-reinstall-markers-in-region (beg)
7886 "Move all remembered markers to their position relative to BEG."
7887 (mapc (lambda (x)
7888 (move-marker (car x) (+ beg (cdr x))))
7889 org-markers-to-move)
7890 (setq org-markers-to-move nil))
7892 (defun org-narrow-to-subtree ()
7893 "Narrow buffer to the current subtree."
7894 (interactive)
7895 (save-excursion
7896 (save-match-data
7897 (org-with-limited-levels
7898 (narrow-to-region
7899 (progn (org-back-to-heading t) (point))
7900 (progn (org-end-of-subtree t t)
7901 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7902 (point)))))))
7904 (defun org-narrow-to-block ()
7905 "Narrow buffer to the current block."
7906 (interactive)
7907 (let* ((case-fold-search t)
7908 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7909 "^[ \t]*#\\+end_.*")))
7910 (if blockp
7911 (narrow-to-region (car blockp) (cdr blockp))
7912 (error "Not in a block"))))
7914 (eval-when-compile
7915 (defvar org-property-drawer-re))
7917 (defvar org-property-start-re) ;; defined below
7918 (defun org-clone-subtree-with-time-shift (n &optional shift)
7919 "Clone the task (subtree) at point N times.
7920 The clones will be inserted as siblings.
7922 In interactive use, the user will be prompted for the number of
7923 clones to be produced, and for a time SHIFT, which may be a
7924 repeater as used in time stamps, for example `+3d'.
7926 When a valid repeater is given and the entry contains any time
7927 stamps, the clones will become a sequence in time, with time
7928 stamps in the subtree shifted for each clone produced. If SHIFT
7929 is nil or the empty string, time stamps will be left alone. The
7930 ID property of the original subtree is removed.
7932 If the original subtree did contain time stamps with a repeater,
7933 the following will happen:
7934 - the repeater will be removed in each clone
7935 - an additional clone will be produced, with the current, unshifted
7936 date(s) in the entry.
7937 - the original entry will be placed *after* all the clones, with
7938 repeater intact.
7939 - the start days in the repeater in the original entry will be shifted
7940 to past the last clone.
7941 In this way you can spell out a number of instances of a repeating task,
7942 and still retain the repeater to cover future instances of the task."
7943 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7944 (let (beg end template task idprop
7945 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7946 (drawer-re org-drawer-regexp))
7947 (if (not (and (integerp n) (> n 0)))
7948 (error "Invalid number of replications %s" n))
7949 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7950 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7951 shift)))
7952 (error "Invalid shift specification %s" shift))
7953 (when doshift
7954 (setq shift-n (string-to-number (match-string 1 shift))
7955 shift-what (cdr (assoc (match-string 2 shift)
7956 '(("d" . day) ("w" . week)
7957 ("m" . month) ("y" . year))))))
7958 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7959 (setq nmin 1 nmax n)
7960 (org-back-to-heading t)
7961 (setq beg (point))
7962 (setq idprop (org-entry-get nil "ID"))
7963 (org-end-of-subtree t t)
7964 (or (bolp) (insert "\n"))
7965 (setq end (point))
7966 (setq template (buffer-substring beg end))
7967 (when (and doshift
7968 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7969 (delete-region beg end)
7970 (setq end beg)
7971 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7972 (goto-char end)
7973 (loop for n from nmin to nmax do
7974 ;; prepare clone
7975 (with-temp-buffer
7976 (insert template)
7977 (org-mode)
7978 (goto-char (point-min))
7979 (org-show-subtree)
7980 (and idprop (if org-clone-delete-id
7981 (org-entry-delete nil "ID")
7982 (org-id-get-create t)))
7983 (unless (= n 0)
7984 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7985 (kill-whole-line))
7986 (goto-char (point-min))
7987 (while (re-search-forward drawer-re nil t)
7988 (mapc (lambda (d)
7989 (org-remove-empty-drawer-at d (point))) org-drawers)))
7990 (goto-char (point-min))
7991 (when doshift
7992 (while (re-search-forward org-ts-regexp-both nil t)
7993 (org-timestamp-change (* n shift-n) shift-what))
7994 (unless (= n n-no-remove)
7995 (goto-char (point-min))
7996 (while (re-search-forward org-ts-regexp nil t)
7997 (save-excursion
7998 (goto-char (match-beginning 0))
7999 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8000 (delete-region (match-beginning 1) (match-end 1)))))))
8001 (setq task (buffer-string)))
8002 (insert task))
8003 (goto-char beg)))
8005 ;;; Outline Sorting
8007 (defun org-sort (with-case)
8008 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8009 Optional argument WITH-CASE means sort case-sensitively."
8010 (interactive "P")
8011 (cond
8012 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8013 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8015 (org-call-with-arg 'org-sort-entries with-case))))
8017 (defun org-sort-remove-invisible (s)
8018 (remove-text-properties 0 (length s) org-rm-props s)
8019 (while (string-match org-bracket-link-regexp s)
8020 (setq s (replace-match (if (match-end 2)
8021 (match-string 3 s)
8022 (match-string 1 s)) t t s)))
8025 (defvar org-priority-regexp) ; defined later in the file
8027 (defvar org-after-sorting-entries-or-items-hook nil
8028 "Hook that is run after a bunch of entries or items have been sorted.
8029 When children are sorted, the cursor is in the parent line when this
8030 hook gets called. When a region or a plain list is sorted, the cursor
8031 will be in the first entry of the sorted region/list.")
8033 (defun org-sort-entries
8034 (&optional with-case sorting-type getkey-func compare-func property)
8035 "Sort entries on a certain level of an outline tree.
8036 If there is an active region, the entries in the region are sorted.
8037 Else, if the cursor is before the first entry, sort the top-level items.
8038 Else, the children of the entry at point are sorted.
8040 Sorting can be alphabetically, numerically, by date/time as given by
8041 a time stamp, by a property or by priority.
8043 The command prompts for the sorting type unless it has been given to the
8044 function through the SORTING-TYPE argument, which needs to be a character,
8045 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8046 precise meaning of each character:
8048 n Numerically, by converting the beginning of the entry/item to a number.
8049 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8050 o By order of TODO keywords.
8051 t By date/time, either the first active time stamp in the entry, or, if
8052 none exist, by the first inactive one.
8053 s By the scheduled date/time.
8054 d By deadline date/time.
8055 c By creation time, which is assumed to be the first inactive time stamp
8056 at the beginning of a line.
8057 p By priority according to the cookie.
8058 r By the value of a property.
8060 Capital letters will reverse the sort order.
8062 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8063 called with point at the beginning of the record. It must return either
8064 a string or a number that should serve as the sorting key for that record.
8066 Comparing entries ignores case by default. However, with an optional argument
8067 WITH-CASE, the sorting considers case as well."
8068 (interactive "P")
8069 (let ((case-func (if with-case 'identity 'downcase))
8070 (cmstr
8071 ;; The clock marker is lost when using `sort-subr', let's
8072 ;; store the clocking string.
8073 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8074 (save-excursion
8075 (goto-char org-clock-marker)
8076 (looking-back "^.*") (match-string-no-properties 0))))
8077 start beg end stars re re2
8078 txt what tmp)
8079 ;; Find beginning and end of region to sort
8080 (cond
8081 ((org-region-active-p)
8082 ;; we will sort the region
8083 (setq end (region-end)
8084 what "region")
8085 (goto-char (region-beginning))
8086 (if (not (org-at-heading-p)) (outline-next-heading))
8087 (setq start (point)))
8088 ((or (org-at-heading-p)
8089 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8090 ;; we will sort the children of the current headline
8091 (org-back-to-heading)
8092 (setq start (point)
8093 end (progn (org-end-of-subtree t t)
8094 (or (bolp) (insert "\n"))
8095 (org-back-over-empty-lines)
8096 (point))
8097 what "children")
8098 (goto-char start)
8099 (show-subtree)
8100 (outline-next-heading))
8102 ;; we will sort the top-level entries in this file
8103 (goto-char (point-min))
8104 (or (org-at-heading-p) (outline-next-heading))
8105 (setq start (point))
8106 (goto-char (point-max))
8107 (beginning-of-line 1)
8108 (when (looking-at ".*?\\S-")
8109 ;; File ends in a non-white line
8110 (end-of-line 1)
8111 (insert "\n"))
8112 (setq end (point-max))
8113 (setq what "top-level")
8114 (goto-char start)
8115 (show-all)))
8117 (setq beg (point))
8118 (if (>= beg end) (error "Nothing to sort"))
8120 (looking-at "\\(\\*+\\)")
8121 (setq stars (match-string 1)
8122 re (concat "^" (regexp-quote stars) " +")
8123 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8124 txt (buffer-substring beg end))
8125 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8126 (if (and (not (equal stars "*")) (string-match re2 txt))
8127 (error "Region to sort contains a level above the first entry"))
8129 (unless sorting-type
8130 (message
8131 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8132 [t]ime [s]cheduled [d]eadline [c]reated
8133 A/N/P/R/O/F/T/S/D/C means reversed:"
8134 what)
8135 (setq sorting-type (read-char-exclusive))
8137 (and (= (downcase sorting-type) ?f)
8138 (setq getkey-func
8139 (org-icompleting-read "Sort using function: "
8140 obarray 'fboundp t nil nil))
8141 (setq getkey-func (intern getkey-func)))
8143 (and (= (downcase sorting-type) ?r)
8144 (setq property
8145 (org-icompleting-read "Property: "
8146 (mapcar 'list (org-buffer-property-keys t))
8147 nil t))))
8149 (message "Sorting entries...")
8151 (save-restriction
8152 (narrow-to-region start end)
8153 (let ((dcst (downcase sorting-type))
8154 (case-fold-search nil)
8155 (now (current-time)))
8156 (sort-subr
8157 (/= dcst sorting-type)
8158 ;; This function moves to the beginning character of the "record" to
8159 ;; be sorted.
8160 (lambda nil
8161 (if (re-search-forward re nil t)
8162 (goto-char (match-beginning 0))
8163 (goto-char (point-max))))
8164 ;; This function moves to the last character of the "record" being
8165 ;; sorted.
8166 (lambda nil
8167 (save-match-data
8168 (condition-case nil
8169 (outline-forward-same-level 1)
8170 (error
8171 (goto-char (point-max))))))
8172 ;; This function returns the value that gets sorted against.
8173 (lambda nil
8174 (cond
8175 ((= dcst ?n)
8176 (if (looking-at org-complex-heading-regexp)
8177 (string-to-number (match-string 4))
8178 nil))
8179 ((= dcst ?a)
8180 (if (looking-at org-complex-heading-regexp)
8181 (funcall case-func (match-string 4))
8182 nil))
8183 ((= dcst ?t)
8184 (let ((end (save-excursion (outline-next-heading) (point))))
8185 (if (or (re-search-forward org-ts-regexp end t)
8186 (re-search-forward org-ts-regexp-both end t))
8187 (org-time-string-to-seconds (match-string 0))
8188 (org-float-time now))))
8189 ((= dcst ?c)
8190 (let ((end (save-excursion (outline-next-heading) (point))))
8191 (if (re-search-forward
8192 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8193 end t)
8194 (org-time-string-to-seconds (match-string 0))
8195 (org-float-time now))))
8196 ((= dcst ?s)
8197 (let ((end (save-excursion (outline-next-heading) (point))))
8198 (if (re-search-forward org-scheduled-time-regexp end t)
8199 (org-time-string-to-seconds (match-string 1))
8200 (org-float-time now))))
8201 ((= dcst ?d)
8202 (let ((end (save-excursion (outline-next-heading) (point))))
8203 (if (re-search-forward org-deadline-time-regexp end t)
8204 (org-time-string-to-seconds (match-string 1))
8205 (org-float-time now))))
8206 ((= dcst ?p)
8207 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8208 (string-to-char (match-string 2))
8209 org-default-priority))
8210 ((= dcst ?r)
8211 (or (org-entry-get nil property) ""))
8212 ((= dcst ?o)
8213 (if (looking-at org-complex-heading-regexp)
8214 (- 9999 (length (member (match-string 2)
8215 org-todo-keywords-1)))))
8216 ((= dcst ?f)
8217 (if getkey-func
8218 (progn
8219 (setq tmp (funcall getkey-func))
8220 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8221 tmp)
8222 (error "Invalid key function `%s'" getkey-func)))
8223 (t (error "Invalid sorting type `%c'" sorting-type))))
8225 (cond
8226 ((= dcst ?a) 'string<)
8227 ((= dcst ?f) compare-func)
8228 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8229 (run-hooks 'org-after-sorting-entries-or-items-hook)
8230 ;; Reset the clock marker if needed
8231 (when cmstr
8232 (save-excursion
8233 (goto-char start)
8234 (search-forward cmstr nil t)
8235 (move-marker org-clock-marker (point))))
8236 (message "Sorting entries...done")))
8238 (defun org-do-sort (table what &optional with-case sorting-type)
8239 "Sort TABLE of WHAT according to SORTING-TYPE.
8240 The user will be prompted for the SORTING-TYPE if the call to this
8241 function does not specify it. WHAT is only for the prompt, to indicate
8242 what is being sorted. The sorting key will be extracted from
8243 the car of the elements of the table.
8244 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8245 (unless sorting-type
8246 (message
8247 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8248 what)
8249 (setq sorting-type (read-char-exclusive)))
8250 (let ((dcst (downcase sorting-type))
8251 extractfun comparefun)
8252 ;; Define the appropriate functions
8253 (cond
8254 ((= dcst ?n)
8255 (setq extractfun 'string-to-number
8256 comparefun (if (= dcst sorting-type) '< '>)))
8257 ((= dcst ?a)
8258 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8259 (lambda(x) (downcase (org-sort-remove-invisible x))))
8260 comparefun (if (= dcst sorting-type)
8261 'string<
8262 (lambda (a b) (and (not (string< a b))
8263 (not (string= a b)))))))
8264 ((= dcst ?t)
8265 (setq extractfun
8266 (lambda (x)
8267 (if (or (string-match org-ts-regexp x)
8268 (string-match org-ts-regexp-both x))
8269 (org-float-time
8270 (org-time-string-to-time (match-string 0 x)))
8272 comparefun (if (= dcst sorting-type) '< '>)))
8273 (t (error "Invalid sorting type `%c'" sorting-type)))
8275 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8276 table)
8277 (lambda (a b) (funcall comparefun (car a) (car b))))))
8280 ;;; The orgstruct minor mode
8282 ;; Define a minor mode which can be used in other modes in order to
8283 ;; integrate the org-mode structure editing commands.
8285 ;; This is really a hack, because the org-mode structure commands use
8286 ;; keys which normally belong to the major mode. Here is how it
8287 ;; works: The minor mode defines all the keys necessary to operate the
8288 ;; structure commands, but wraps the commands into a function which
8289 ;; tests if the cursor is currently at a headline or a plain list
8290 ;; item. If that is the case, the structure command is used,
8291 ;; temporarily setting many Org-mode variables like regular
8292 ;; expressions for filling etc. However, when any of those keys is
8293 ;; used at a different location, function uses `key-binding' to look
8294 ;; up if the key has an associated command in another currently active
8295 ;; keymap (minor modes, major mode, global), and executes that
8296 ;; command. There might be problems if any of the keys is otherwise
8297 ;; used as a prefix key.
8299 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8300 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8301 ;; addresses this by checking explicitly for both bindings.
8303 (defvar orgstruct-mode-map (make-sparse-keymap)
8304 "Keymap for the minor `orgstruct-mode'.")
8306 (defvar org-local-vars nil
8307 "List of local variables, for use by `orgstruct-mode'.")
8309 ;;;###autoload
8310 (define-minor-mode orgstruct-mode
8311 "Toggle the minor mode `orgstruct-mode'.
8312 This mode is for using Org-mode structure commands in other
8313 modes. The following keys behave as if Org-mode were active, if
8314 the cursor is on a headline, or on a plain list item (both as
8315 defined by Org-mode).
8317 M-up Move entry/item up
8318 M-down Move entry/item down
8319 M-left Promote
8320 M-right Demote
8321 M-S-up Move entry/item up
8322 M-S-down Move entry/item down
8323 M-S-left Promote subtree
8324 M-S-right Demote subtree
8325 M-q Fill paragraph and items like in Org-mode
8326 C-c ^ Sort entries
8327 C-c - Cycle list bullet
8328 TAB Cycle item visibility
8329 M-RET Insert new heading/item
8330 S-M-RET Insert new TODO heading / Checkbox item
8331 C-c C-c Set tags / toggle checkbox"
8332 nil " OrgStruct" nil
8333 (org-load-modules-maybe)
8334 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8336 ;;;###autoload
8337 (defun turn-on-orgstruct ()
8338 "Unconditionally turn on `orgstruct-mode'."
8339 (orgstruct-mode 1))
8341 (defvar org-fb-vars nil)
8342 (make-variable-buffer-local 'org-fb-vars)
8343 (defun orgstruct++-mode (&optional arg)
8344 "Toggle `orgstruct-mode', the enhanced version of it.
8345 In addition to setting orgstruct-mode, this also exports all
8346 indentation and autofilling variables from org-mode into the
8347 buffer. It will also recognize item context in multiline items."
8348 (interactive "P")
8349 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8350 (if (< arg 1)
8351 (progn (orgstruct-mode -1)
8352 (mapc (lambda(v)
8353 (org-set-local (car v)
8354 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8355 org-fb-vars))
8356 (orgstruct-mode 1)
8357 (setq org-fb-vars nil)
8358 (let (var val)
8359 (mapc
8360 (lambda (x)
8361 (when (string-match
8362 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8363 (symbol-name (car x)))
8364 (setq var (car x) val (nth 1 x))
8365 (push (list var `(quote ,(eval var))) org-fb-vars)
8366 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8367 org-local-vars)
8368 (org-set-local 'orgstruct-is-++ t))))
8370 (defvar orgstruct-is-++ nil
8371 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8372 (make-variable-buffer-local 'orgstruct-is-++)
8374 ;;;###autoload
8375 (defun turn-on-orgstruct++ ()
8376 "Unconditionally turn on `orgstruct++-mode'."
8377 (orgstruct++-mode 1))
8379 (defun orgstruct-error ()
8380 "Error when there is no default binding for a structure key."
8381 (interactive)
8382 (error "This key has no function outside structure elements"))
8384 (defun orgstruct-setup ()
8385 "Setup orgstruct keymaps."
8386 (let ((nfunc 0)
8387 (bindings
8388 (list
8389 '([(meta up)] org-metaup)
8390 '([(meta down)] org-metadown)
8391 '([(meta left)] org-metaleft)
8392 '([(meta right)] org-metaright)
8393 '([(meta shift up)] org-shiftmetaup)
8394 '([(meta shift down)] org-shiftmetadown)
8395 '([(meta shift left)] org-shiftmetaleft)
8396 '([(meta shift right)] org-shiftmetaright)
8397 '([?\e (up)] org-metaup)
8398 '([?\e (down)] org-metadown)
8399 '([?\e (left)] org-metaleft)
8400 '([?\e (right)] org-metaright)
8401 '([?\e (shift up)] org-shiftmetaup)
8402 '([?\e (shift down)] org-shiftmetadown)
8403 '([?\e (shift left)] org-shiftmetaleft)
8404 '([?\e (shift right)] org-shiftmetaright)
8405 '([(shift up)] org-shiftup)
8406 '([(shift down)] org-shiftdown)
8407 '([(shift left)] org-shiftleft)
8408 '([(shift right)] org-shiftright)
8409 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8410 '("\M-q" fill-paragraph)
8411 '("\C-c^" org-sort)
8412 '("\C-c-" org-cycle-list-bullet)))
8413 elt key fun cmd)
8414 (while (setq elt (pop bindings))
8415 (setq nfunc (1+ nfunc))
8416 (setq key (org-key (car elt))
8417 fun (nth 1 elt)
8418 cmd (orgstruct-make-binding fun nfunc key))
8419 (org-defkey orgstruct-mode-map key cmd))
8421 ;; Prevent an error for users who forgot to make autoloads
8422 (require 'org-element)
8424 ;; Special treatment needed for TAB and RET
8425 (org-defkey orgstruct-mode-map [(tab)]
8426 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8427 (org-defkey orgstruct-mode-map "\C-i"
8428 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8430 (org-defkey orgstruct-mode-map "\M-\C-m"
8431 (orgstruct-make-binding 'org-insert-heading 105
8432 "\M-\C-m" [(meta return)]))
8433 (org-defkey orgstruct-mode-map [(meta return)]
8434 (orgstruct-make-binding 'org-insert-heading 106
8435 [(meta return)] "\M-\C-m"))
8437 (org-defkey orgstruct-mode-map [(shift meta return)]
8438 (orgstruct-make-binding 'org-insert-todo-heading 107
8439 [(meta return)] "\M-\C-m"))
8441 (org-defkey orgstruct-mode-map "\e\C-m"
8442 (orgstruct-make-binding 'org-insert-heading 108
8443 "\e\C-m" [?\e (return)]))
8444 (org-defkey orgstruct-mode-map [?\e (return)]
8445 (orgstruct-make-binding 'org-insert-heading 109
8446 [?\e (return)] "\e\C-m"))
8447 (org-defkey orgstruct-mode-map [?\e (shift return)]
8448 (orgstruct-make-binding 'org-insert-todo-heading 110
8449 [?\e (return)] "\e\C-m"))
8451 (unless org-local-vars
8452 (setq org-local-vars (org-get-local-variables)))
8456 (defun orgstruct-make-binding (fun n &rest keys)
8457 "Create a function for binding in the structure minor mode.
8458 FUN is the command to call inside a table. N is used to create a unique
8459 command name. KEYS are keys that should be checked in for a command
8460 to execute outside of tables."
8461 (eval
8462 (list 'defun
8463 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8464 '(arg)
8465 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8466 "Outside of structure, run the binding of `"
8467 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8468 "'.")
8469 '(interactive "p")
8470 (list 'if
8471 `(org-context-p 'headline 'item
8472 (and orgstruct-is-++
8473 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8474 'item-body))
8475 (list 'org-run-like-in-org-mode (list 'quote fun))
8476 (list 'let '(orgstruct-mode)
8477 (list 'call-interactively
8478 (append '(or)
8479 (mapcar (lambda (k)
8480 (list 'key-binding k))
8481 keys)
8482 '('orgstruct-error))))))))
8484 (defun org-contextualize-keys (alist contexts)
8485 "Return valid elements in ALIST depending on CONTEXTS.
8487 `org-agenda-custom-commands' or `org-capture-templates' are the
8488 values used for ALIST, and `org-agenda-custom-commands-contexts'
8489 or `org-capture-templates-contexts' are the associated contexts
8490 definitions."
8491 (let ((contexts
8492 ;; normalize contexts
8493 (mapcar
8494 (lambda(c) (cond ((listp (cadr c))
8495 (list (car c) (car c) (cadr c)))
8496 ((string= "" (cadr c))
8497 (list (car c) (car c) (caddr c)))
8498 (t c))) contexts))
8499 (a alist) c r s)
8500 ;; loop over all commands or templates
8501 (while (setq c (pop a))
8502 (let (vrules repl)
8503 (cond
8504 ((not (assoc (car c) contexts))
8505 (push c r))
8506 ((and (assoc (car c) contexts)
8507 (setq vrules (org-contextualize-validate-key
8508 (car c) contexts)))
8509 (mapc (lambda (vr)
8510 (when (not (equal (car vr) (cadr vr)))
8511 (setq repl vr))) vrules)
8512 (if (not repl) (push c r)
8513 (push (cadr repl) s)
8514 (push
8515 (cons (car c)
8516 (cdr (or (assoc (cadr repl) alist)
8517 (error "Undefined key `%s' as contextual replacement for `%s'"
8518 (cadr repl) (car c)))))
8519 r))))))
8520 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8521 (delq
8523 (delete-dups
8524 (mapcar (lambda (x)
8525 (let ((tpl (car x)))
8526 (when (not (delq
8528 (mapcar (lambda(y)
8529 (equal y tpl)) s))) x)))
8530 (reverse r))))))
8532 (defun org-contextualize-validate-key (key contexts)
8533 "Check CONTEXTS for agenda or capture KEY."
8534 (let (r rr res)
8535 (while (setq r (pop contexts))
8536 (mapc
8537 (lambda (rr)
8538 (when
8539 (and (equal key (car r))
8540 (if (functionp rr) (funcall rr)
8541 (or (and (eq (car rr) 'in-file)
8542 (buffer-file-name)
8543 (string-match (cdr rr) (buffer-file-name)))
8544 (and (eq (car rr) 'in-mode)
8545 (string-match (cdr rr) (symbol-name major-mode)))
8546 (when (and (eq (car rr) 'not-in-file)
8547 (buffer-file-name))
8548 (not (string-match (cdr rr) (buffer-file-name))))
8549 (when (eq (car rr) 'not-in-mode)
8550 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8551 (push r res)))
8552 (car (last r))))
8553 (delete-dups (delq nil res))))
8555 (defun org-context-p (&rest contexts)
8556 "Check if local context is any of CONTEXTS.
8557 Possible values in the list of contexts are `table', `headline', and `item'."
8558 (let ((pos (point)))
8559 (goto-char (point-at-bol))
8560 (prog1 (or (and (memq 'table contexts)
8561 (looking-at "[ \t]*|"))
8562 (and (memq 'headline contexts)
8563 (looking-at org-outline-regexp))
8564 (and (memq 'item contexts)
8565 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8566 (and (memq 'item-body contexts)
8567 (org-in-item-p)))
8568 (goto-char pos))))
8570 (defun org-get-local-variables ()
8571 "Return a list of all local variables in an Org mode buffer."
8572 (let (varlist)
8573 (with-current-buffer (get-buffer-create "*Org tmp*")
8574 (erase-buffer)
8575 (org-mode)
8576 (setq varlist (buffer-local-variables)))
8577 (kill-buffer "*Org tmp*")
8578 (delq nil
8579 (mapcar
8580 (lambda (x)
8581 (setq x
8582 (if (symbolp x)
8583 (list x)
8584 (list (car x) (list 'quote (cdr x)))))
8585 (if (string-match
8586 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8587 (symbol-name (car x)))
8588 x nil))
8589 varlist))))
8591 (defun org-clone-local-variables (from-buffer &optional regexp)
8592 "Clone local variables from FROM-BUFFER.
8593 Optional argument REGEXP selects variables to clone."
8594 (mapc
8595 (lambda (pair)
8596 (and (symbolp (car pair))
8597 (or (null regexp)
8598 (string-match regexp (symbol-name (car pair))))
8599 (set (make-local-variable (car pair))
8600 (cdr pair))))
8601 (buffer-local-variables from-buffer)))
8603 ;;;###autoload
8604 (defun org-run-like-in-org-mode (cmd)
8605 "Run a command, pretending that the current buffer is in Org-mode.
8606 This will temporarily bind local variables that are typically bound in
8607 Org-mode to the values they have in Org-mode, and then interactively
8608 call CMD."
8609 (org-load-modules-maybe)
8610 (unless org-local-vars
8611 (setq org-local-vars (org-get-local-variables)))
8612 (eval (list 'let org-local-vars
8613 (list 'call-interactively (list 'quote cmd)))))
8615 ;;;; Archiving
8617 (defun org-get-category (&optional pos force-refresh)
8618 "Get the category applying to position POS."
8619 (save-match-data
8620 (if force-refresh (org-refresh-category-properties))
8621 (let ((pos (or pos (point))))
8622 (or (get-text-property pos 'org-category)
8623 (progn (org-refresh-category-properties)
8624 (get-text-property pos 'org-category))))))
8626 (defun org-refresh-category-properties ()
8627 "Refresh category text properties in the buffer."
8628 (let ((case-fold-search t)
8629 (inhibit-read-only t)
8630 (def-cat (cond
8631 ((null org-category)
8632 (if buffer-file-name
8633 (file-name-sans-extension
8634 (file-name-nondirectory buffer-file-name))
8635 "???"))
8636 ((symbolp org-category) (symbol-name org-category))
8637 (t org-category)))
8638 beg end cat pos optionp)
8639 (org-unmodified
8640 (save-excursion
8641 (save-restriction
8642 (widen)
8643 (goto-char (point-min))
8644 (put-text-property (point) (point-max) 'org-category def-cat)
8645 (while (re-search-forward
8646 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8647 (setq pos (match-end 0)
8648 optionp (equal (char-after (match-beginning 0)) ?#)
8649 cat (org-trim (match-string 2)))
8650 (if optionp
8651 (setq beg (point-at-bol) end (point-max))
8652 (org-back-to-heading t)
8653 (setq beg (point) end (org-end-of-subtree t t)))
8654 (put-text-property beg end 'org-category cat)
8655 (put-text-property beg end 'org-category-position beg)
8656 (goto-char pos)))))))
8658 (defun org-refresh-properties (dprop tprop)
8659 "Refresh buffer text properties.
8660 DPROP is the drawer property and TPROP is the corresponding text
8661 property to set."
8662 (let ((case-fold-search t)
8663 (inhibit-read-only t) p)
8664 (org-unmodified
8665 (save-excursion
8666 (save-restriction
8667 (widen)
8668 (goto-char (point-min))
8669 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8670 (setq p (org-match-string-no-properties 1))
8671 (save-excursion
8672 (org-back-to-heading t)
8673 (put-text-property
8674 (point-at-bol) (point-at-eol) tprop p))))))))
8677 ;;;; Link Stuff
8679 ;;; Link abbreviations
8681 (defun org-link-expand-abbrev (link)
8682 "Apply replacements as defined in `org-link-abbrev-alist'."
8683 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8684 (let* ((key (match-string 1 link))
8685 (as (or (assoc key org-link-abbrev-alist-local)
8686 (assoc key org-link-abbrev-alist)))
8687 (tag (and (match-end 2) (match-string 3 link)))
8688 rpl)
8689 (if (not as)
8690 link
8691 (setq rpl (cdr as))
8692 (cond
8693 ((symbolp rpl) (funcall rpl tag))
8694 ((string-match "%(\\([^)]+\\))" rpl)
8695 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8696 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8697 ((string-match "%h" rpl)
8698 (replace-match (url-hexify-string (or tag "")) t t rpl))
8699 (t (concat rpl tag)))))
8700 link))
8702 ;;; Storing and inserting links
8704 (defvar org-insert-link-history nil
8705 "Minibuffer history for links inserted with `org-insert-link'.")
8707 (defvar org-stored-links nil
8708 "Contains the links stored with `org-store-link'.")
8710 (defvar org-store-link-plist nil
8711 "Plist with info about the most recently link created with `org-store-link'.")
8713 (defvar org-link-protocols nil
8714 "Link protocols added to Org-mode using `org-add-link-type'.")
8716 (defvar org-store-link-functions nil
8717 "List of functions that are called to create and store a link.
8718 Each function will be called in turn until one returns a non-nil
8719 value. Each function should check if it is responsible for creating
8720 this link (for example by looking at the major mode).
8721 If not, it must exit and return nil.
8722 If yes, it should return a non-nil value after a calling
8723 `org-store-link-props' with a list of properties and values.
8724 Special properties are:
8726 :type The link prefix, like \"http\". This must be given.
8727 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8728 This is obligatory as well.
8729 :description Optional default description for the second pair
8730 of brackets in an Org-mode link. The user can still change
8731 this when inserting this link into an Org-mode buffer.
8733 In addition to these, any additional properties can be specified
8734 and then used in capture templates.")
8736 (defun org-add-link-type (type &optional follow export)
8737 "Add TYPE to the list of `org-link-types'.
8738 Re-compute all regular expressions depending on `org-link-types'
8740 FOLLOW and EXPORT are two functions.
8742 FOLLOW should take the link path as the single argument and do whatever
8743 is necessary to follow the link, for example find a file or display
8744 a mail message.
8746 EXPORT should format the link path for export to one of the export formats.
8747 It should be a function accepting three arguments:
8749 path the path of the link, the text after the prefix (like \"http:\")
8750 desc the description of the link, if any, or a description added by
8751 org-export-normalize-links if there is none
8752 format the export format, a symbol like `html' or `latex' or `ascii'..
8754 The function may use the FORMAT information to return different values
8755 depending on the format. The return value will be put literally into
8756 the exported file. If the return value is nil, this means Org should
8757 do what it normally does with links which do not have EXPORT defined.
8759 Org-mode has a built-in default for exporting links. If you are happy with
8760 this default, there is no need to define an export function for the link
8761 type. For a simple example of an export function, see `org-bbdb.el'."
8762 (add-to-list 'org-link-types type t)
8763 (org-make-link-regexps)
8764 (if (assoc type org-link-protocols)
8765 (setcdr (assoc type org-link-protocols) (list follow export))
8766 (push (list type follow export) org-link-protocols)))
8768 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8769 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8771 ;;;###autoload
8772 (defun org-store-link (arg)
8773 "\\<org-mode-map>Store an org-link to the current location.
8774 This link is added to `org-stored-links' and can later be inserted
8775 into an org-buffer with \\[org-insert-link].
8777 For some link types, a prefix arg is interpreted:
8778 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8779 For file links, arg negates `org-context-in-file-links'."
8780 (interactive "P")
8781 (org-load-modules-maybe)
8782 (setq org-store-link-plist nil) ; reset
8783 (org-with-limited-levels
8784 (let (link cpltxt desc description search txt custom-id agenda-link)
8785 (cond
8787 ((run-hook-with-args-until-success 'org-store-link-functions)
8788 (setq link (plist-get org-store-link-plist :link)
8789 desc (or (plist-get org-store-link-plist :description) link)))
8791 ((org-src-edit-buffer-p)
8792 (let (label gc)
8793 (while (or (not label)
8794 (save-excursion
8795 (save-restriction
8796 (widen)
8797 (goto-char (point-min))
8798 (re-search-forward
8799 (regexp-quote (format org-coderef-label-format label))
8800 nil t))))
8801 (when label (message "Label exists already") (sit-for 2))
8802 (setq label (read-string "Code line label: " label)))
8803 (end-of-line 1)
8804 (setq link (format org-coderef-label-format label))
8805 (setq gc (- 79 (length link)))
8806 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8807 (insert link)
8808 (setq link (concat "(" label ")") desc nil)))
8810 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8811 ;; We are in the agenda, link to referenced location
8812 (let ((m (or (get-text-property (point) 'org-hd-marker)
8813 (get-text-property (point) 'org-marker))))
8814 (when m
8815 (org-with-point-at m
8816 (setq agenda-link
8817 (if (org-called-interactively-p 'any)
8818 (call-interactively 'org-store-link)
8819 (org-store-link nil)))))))
8821 ((eq major-mode 'calendar-mode)
8822 (let ((cd (calendar-cursor-to-date)))
8823 (setq link
8824 (format-time-string
8825 (car org-time-stamp-formats)
8826 (apply 'encode-time
8827 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8828 nil nil nil))))
8829 (org-store-link-props :type "calendar" :date cd)))
8831 ((eq major-mode 'help-mode)
8832 (setq link (concat "help:" (save-excursion
8833 (goto-char (point-min))
8834 (looking-at "^[^ ]+")
8835 (match-string 0))))
8836 (org-store-link-props :type "help"))
8838 ((eq major-mode 'w3-mode)
8839 (setq cpltxt (if (and (buffer-name)
8840 (not (string-match "Untitled" (buffer-name))))
8841 (buffer-name)
8842 (url-view-url t))
8843 link (url-view-url t))
8844 (org-store-link-props :type "w3" :url (url-view-url t)))
8846 ((eq major-mode 'w3m-mode)
8847 (setq cpltxt (or w3m-current-title w3m-current-url)
8848 link w3m-current-url)
8849 (org-store-link-props :type "w3m" :url (url-view-url t)))
8851 ((setq search (run-hook-with-args-until-success
8852 'org-create-file-search-functions))
8853 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8854 "::" search))
8855 (setq cpltxt (or description link)))
8857 ((eq major-mode 'image-mode)
8858 (setq cpltxt (concat "file:"
8859 (abbreviate-file-name buffer-file-name))
8860 link cpltxt)
8861 (org-store-link-props :type "image" :file buffer-file-name))
8863 ((eq major-mode 'dired-mode)
8864 ;; link to the file in the current line
8865 (let ((file (dired-get-filename nil t)))
8866 (setq file (if file
8867 (abbreviate-file-name
8868 (expand-file-name (dired-get-filename nil t)))
8869 ;; otherwise, no file so use current directory.
8870 default-directory))
8871 (setq cpltxt (concat "file:" file)
8872 link cpltxt)))
8874 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8875 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8876 (cond
8877 ((org-in-regexp "<<\\(.*?\\)>>")
8878 (setq cpltxt
8879 (concat "file:"
8880 (abbreviate-file-name
8881 (buffer-file-name (buffer-base-buffer)))
8882 "::" (match-string 1))
8883 link cpltxt))
8884 ((and (featurep 'org-id)
8885 (or (eq org-id-link-to-org-use-id t)
8886 (and (org-called-interactively-p 'any)
8887 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
8888 (and (eq org-id-link-to-org-use-id
8889 'create-if-interactive-and-no-custom-id)
8890 (not custom-id))))
8891 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
8892 ;; We can make a link using the ID.
8893 (setq link (condition-case nil
8894 (prog1 (org-id-store-link)
8895 (setq desc (plist-get org-store-link-plist :description)))
8896 (error
8897 ;; probably before first headline, link to file only
8898 (concat "file:"
8899 (abbreviate-file-name
8900 (buffer-file-name (buffer-base-buffer))))))))
8902 ;; Just link to current headline
8903 (setq cpltxt (concat "file:"
8904 (abbreviate-file-name
8905 (buffer-file-name (buffer-base-buffer)))))
8906 ;; Add a context search string
8907 (when (org-xor org-context-in-file-links arg)
8908 (setq txt (cond
8909 ((org-at-heading-p) nil)
8910 ((org-region-active-p)
8911 (buffer-substring (region-beginning) (region-end)))))
8912 (when (or (null txt) (string-match "\\S-" txt))
8913 (setq cpltxt
8914 (concat cpltxt "::"
8915 (condition-case nil
8916 (org-make-org-heading-search-string txt)
8917 (error "")))
8918 desc (or (nth 4 (ignore-errors
8919 (org-heading-components))) "NONE"))))
8920 (if (string-match "::\\'" cpltxt)
8921 (setq cpltxt (substring cpltxt 0 -2)))
8922 (setq link cpltxt))))
8924 ((buffer-file-name (buffer-base-buffer))
8925 ;; Just link to this file here.
8926 (setq cpltxt (concat "file:"
8927 (abbreviate-file-name
8928 (buffer-file-name (buffer-base-buffer)))))
8929 ;; Add a context string
8930 (when (org-xor org-context-in-file-links arg)
8931 (setq txt (if (org-region-active-p)
8932 (buffer-substring (region-beginning) (region-end))
8933 (buffer-substring (point-at-bol) (point-at-eol))))
8934 ;; Only use search option if there is some text.
8935 (when (string-match "\\S-" txt)
8936 (setq cpltxt
8937 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8938 desc "NONE")))
8939 (setq link cpltxt))
8941 ((org-called-interactively-p 'interactive)
8942 (error "Cannot link to a buffer which is not visiting a file"))
8944 (t (setq link nil)))
8946 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8947 (setq link (or link cpltxt)
8948 desc (or desc cpltxt))
8949 (if (equal desc "NONE") (setq desc nil))
8951 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8952 (progn
8953 (setq org-stored-links
8954 (cons (list link desc) org-stored-links))
8955 (message "Stored: %s" (or desc link))
8956 (when custom-id
8957 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8958 "::#" custom-id))
8959 (setq org-stored-links
8960 (cons (list link desc) org-stored-links))))
8961 (or agenda-link (and link (org-make-link-string link desc)))))))
8963 (defun org-store-link-props (&rest plist)
8964 "Store link properties, extract names and addresses."
8965 (let (x adr)
8966 (when (setq x (plist-get plist :from))
8967 (setq adr (mail-extract-address-components x))
8968 (setq plist (plist-put plist :fromname (car adr)))
8969 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8970 (when (setq x (plist-get plist :to))
8971 (setq adr (mail-extract-address-components x))
8972 (setq plist (plist-put plist :toname (car adr)))
8973 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8974 (let ((from (plist-get plist :from))
8975 (to (plist-get plist :to)))
8976 (when (and from to org-from-is-user-regexp)
8977 (setq plist
8978 (plist-put plist :fromto
8979 (if (string-match org-from-is-user-regexp from)
8980 (concat "to %t")
8981 (concat "from %f"))))))
8982 (setq org-store-link-plist plist))
8984 (defun org-add-link-props (&rest plist)
8985 "Add these properties to the link property list."
8986 (let (key value)
8987 (while plist
8988 (setq key (pop plist) value (pop plist))
8989 (setq org-store-link-plist
8990 (plist-put org-store-link-plist key value)))))
8992 (defun org-email-link-description (&optional fmt)
8993 "Return the description part of an email link.
8994 This takes information from `org-store-link-plist' and formats it
8995 according to FMT (default from `org-email-link-description-format')."
8996 (setq fmt (or fmt org-email-link-description-format))
8997 (let* ((p org-store-link-plist)
8998 (to (plist-get p :toaddress))
8999 (from (plist-get p :fromaddress))
9000 (table
9001 (list
9002 (cons "%c" (plist-get p :fromto))
9003 (cons "%F" (plist-get p :from))
9004 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9005 (cons "%T" (plist-get p :to))
9006 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9007 (cons "%s" (plist-get p :subject))
9008 (cons "%d" (plist-get p :date))
9009 (cons "%m" (plist-get p :message-id)))))
9010 (when (string-match "%c" fmt)
9011 ;; Check if the user wrote this message
9012 (if (and org-from-is-user-regexp from to
9013 (save-match-data (string-match org-from-is-user-regexp from)))
9014 (setq fmt (replace-match "to %t" t t fmt))
9015 (setq fmt (replace-match "from %f" t t fmt))))
9016 (org-replace-escapes fmt table)))
9018 (defun org-make-org-heading-search-string (&optional string heading)
9019 "Make search string for STRING or current headline."
9020 (interactive)
9021 (let ((s (or string (org-get-heading)))
9022 (lines org-context-in-file-links))
9023 (unless (and string (not heading))
9024 ;; We are using a headline, clean up garbage in there.
9025 (if (string-match org-todo-regexp s)
9026 (setq s (replace-match "" t t s)))
9027 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9028 (setq s (replace-match "" t t s)))
9029 (setq s (org-trim s))
9030 (if (string-match (concat "^\\(" org-quote-string "\\|"
9031 org-comment-string "\\)") s)
9032 (setq s (replace-match "" t t s)))
9033 (while (string-match org-ts-regexp s)
9034 (setq s (replace-match "" t t s))))
9035 (or string (setq s (concat "*" s))) ; Add * for headlines
9036 (when (and string (integerp lines) (> lines 0))
9037 (let ((slines (org-split-string s "\n")))
9038 (when (< lines (length slines))
9039 (setq s (mapconcat
9040 'identity
9041 (reverse (nthcdr (- (length slines) lines)
9042 (reverse slines))) "\n")))))
9043 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9045 (defun org-make-link-string (link &optional description)
9046 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9047 (unless (string-match "\\S-" link)
9048 (error "Empty link"))
9049 (when (and description
9050 (stringp description)
9051 (not (string-match "\\S-" description)))
9052 (setq description nil))
9053 (when (stringp description)
9054 ;; Remove brackets from the description, they are fatal.
9055 (while (string-match "\\[" description)
9056 (setq description (replace-match "{" t t description)))
9057 (while (string-match "\\]" description)
9058 (setq description (replace-match "}" t t description))))
9059 (when (equal link description)
9060 ;; No description needed, it is identical
9061 (setq description nil))
9062 (when (and (not description)
9063 (not (string-match (org-image-file-name-regexp) link))
9064 (not (equal link (org-link-escape link))))
9065 (setq description (org-extract-attributes link)))
9066 (setq link
9067 (cond ((string-match (org-image-file-name-regexp) link) link)
9068 ((string-match org-link-types-re link)
9069 (concat (match-string 1 link)
9070 (org-link-escape (substring link (match-end 1)))))
9071 (t (org-link-escape link))))
9072 (concat "[[" link "]"
9073 (if description (concat "[" description "]") "")
9074 "]"))
9076 (defconst org-link-escape-chars
9077 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9078 "List of characters that should be escaped in link.
9079 This is the list that is used for internal purposes.")
9081 (defconst org-link-escape-chars-browser
9082 '(?\ )
9083 "List of escapes for characters that are problematic in links.
9084 This is the list that is used before handing over to the browser.")
9086 (defun org-link-escape (text &optional table merge)
9087 "Return percent escaped representation of TEXT.
9088 TEXT is a string with the text to escape.
9089 Optional argument TABLE is a list with characters that should be
9090 escaped. When nil, `org-link-escape-chars' is used.
9091 If optional argument MERGE is set, merge TABLE into
9092 `org-link-escape-chars'."
9093 (cond
9094 ((and table merge)
9095 (mapc (lambda (defchr)
9096 (unless (member defchr table)
9097 (setq table (cons defchr table)))) org-link-escape-chars))
9098 ((null table)
9099 (setq table org-link-escape-chars)))
9100 (mapconcat
9101 (lambda (char)
9102 (if (or (member char table)
9103 (and (or (< char 32) (= char 37) (> char 126))
9104 org-url-hexify-p))
9105 (mapconcat (lambda (sequence-element)
9106 (format "%%%.2X" sequence-element))
9107 (or (encode-coding-char char 'utf-8)
9108 (error "Unable to percent escape character: %s"
9109 (char-to-string char))) "")
9110 (char-to-string char))) text ""))
9112 (defun org-link-unescape (str)
9113 "Unhex hexified Unicode strings as returned from the JavaScript function
9114 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9115 (unless (and (null str) (string= "" str))
9116 (let ((pos 0) (case-fold-search t) unhexed)
9117 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9118 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9119 (setq str (replace-match unhexed t t str))
9120 (setq pos (+ pos (length unhexed))))))
9121 str)
9123 (defun org-link-unescape-compound (hex)
9124 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9125 Note: this function also decodes single byte encodings like
9126 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9127 (save-match-data
9128 (let* ((bytes (cdr (split-string hex "%")))
9129 (ret "")
9130 (eat 0)
9131 (sum 0))
9132 (while bytes
9133 (let* ((val (string-to-number (pop bytes) 16))
9134 (shift-xor
9135 (if (= 0 eat)
9136 (cond
9137 ((>= val 252) (cons 6 252))
9138 ((>= val 248) (cons 5 248))
9139 ((>= val 240) (cons 4 240))
9140 ((>= val 224) (cons 3 224))
9141 ((>= val 192) (cons 2 192))
9142 (t (cons 0 0)))
9143 (cons 6 128))))
9144 (if (>= val 192) (setq eat (car shift-xor)))
9145 (setq val (logxor val (cdr shift-xor)))
9146 (setq sum (+ (lsh sum (car shift-xor)) val))
9147 (if (> eat 0) (setq eat (- eat 1)))
9148 (cond
9149 ((= 0 eat) ;multi byte
9150 (setq ret (concat ret (org-char-to-string sum)))
9151 (setq sum 0))
9152 ((not bytes) ; single byte(s)
9153 (setq ret (org-link-unescape-single-byte-sequence hex))))
9154 )) ;; end (while bytes
9155 ret )))
9157 (defun org-link-unescape-single-byte-sequence (hex)
9158 "Unhexify hex-encoded single byte character sequences."
9159 (mapconcat (lambda (byte)
9160 (char-to-string (string-to-number byte 16)))
9161 (cdr (split-string hex "%")) ""))
9163 (defun org-xor (a b)
9164 "Exclusive or."
9165 (if a (not b) b))
9167 (defun org-fixup-message-id-for-http (s)
9168 "Replace special characters in a message id, so it can be used in an http query."
9169 (when (string-match "%" s)
9170 (setq s (mapconcat (lambda (c)
9171 (if (eq c ?%)
9172 "%25"
9173 (char-to-string c)))
9174 s "")))
9175 (while (string-match "<" s)
9176 (setq s (replace-match "%3C" t t s)))
9177 (while (string-match ">" s)
9178 (setq s (replace-match "%3E" t t s)))
9179 (while (string-match "@" s)
9180 (setq s (replace-match "%40" t t s)))
9183 (defun org-link-prettify (link)
9184 "Return a human-readable representation of LINK.
9185 The car of LINK must be a raw link the cdr of LINK must be either
9186 a link description or nil."
9187 (let ((desc (or (cadr link) "<no description>")))
9188 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9189 "<" (car link) ">")))
9191 ;;;###autoload
9192 (defun org-insert-link-global ()
9193 "Insert a link like Org-mode does.
9194 This command can be called in any mode to insert a link in Org-mode syntax."
9195 (interactive)
9196 (org-load-modules-maybe)
9197 (org-run-like-in-org-mode 'org-insert-link))
9199 (defun org-insert-all-links (&optional keep)
9200 "Insert all links in `org-stored-links'."
9201 (interactive "P")
9202 (let ((links (copy-sequence org-stored-links)) l)
9203 (while (setq l (if keep (pop links) (pop org-stored-links)))
9204 (insert "- ")
9205 (org-insert-link nil (car l) (cadr l))
9206 (insert "\n"))))
9208 (defun org-link-fontify-links-to-this-file ()
9209 "Fontify links to the current file in `org-stored-links'."
9210 (let ((f (buffer-file-name)) a b)
9211 (setq a (mapcar (lambda(l)
9212 (let ((ll (car l)))
9213 (when (and (string-match "^file:\\(.+\\)::" ll)
9214 (equal f (expand-file-name (match-string 1 ll))))
9215 ll)))
9216 org-stored-links))
9217 (when (featurep 'org-id)
9218 (setq b (mapcar (lambda(l)
9219 (let ((ll (car l)))
9220 (when (and (string-match "^id:\\(.+\\)$" ll)
9221 (equal f (expand-file-name
9222 (or (org-id-find-id-file
9223 (match-string 1 ll)) ""))))
9224 ll)))
9225 org-stored-links)))
9226 (mapcar (lambda(l)
9227 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9228 (delq nil (append a b)))))
9230 (defvar org-link-links-in-this-file nil)
9231 (defun org-insert-link (&optional complete-file link-location default-description)
9232 "Insert a link. At the prompt, enter the link.
9234 Completion can be used to insert any of the link protocol prefixes like
9235 http or ftp in use.
9237 The history can be used to select a link previously stored with
9238 `org-store-link'. When the empty string is entered (i.e. if you just
9239 press RET at the prompt), the link defaults to the most recently
9240 stored link. As SPC triggers completion in the minibuffer, you need to
9241 use M-SPC or C-q SPC to force the insertion of a space character.
9243 You will also be prompted for a description, and if one is given, it will
9244 be displayed in the buffer instead of the link.
9246 If there is already a link at point, this command will allow you to edit link
9247 and description parts.
9249 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9250 be selected using completion. The path to the file will be relative to the
9251 current directory if the file is in the current directory or a subdirectory.
9252 Otherwise, the link will be the absolute path as completed in the minibuffer
9253 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9254 option `org-link-file-path-type'.
9256 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9257 the current directory or below.
9259 With three \\[universal-argument] prefixes, negate the meaning of
9260 `org-keep-stored-link-after-insertion'.
9262 If `org-make-link-description-function' is non-nil, this function will be
9263 called with the link target, and the result will be the default
9264 link description.
9266 If the LINK-LOCATION parameter is non-nil, this value will be
9267 used as the link location instead of reading one interactively.
9269 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9270 be used as the default description."
9271 (interactive "P")
9272 (let* ((wcf (current-window-configuration))
9273 (region (if (org-region-active-p)
9274 (buffer-substring (region-beginning) (region-end))))
9275 (remove (and region (list (region-beginning) (region-end))))
9276 (desc region)
9277 tmphist ; byte-compile incorrectly complains about this
9278 (link link-location)
9279 (abbrevs org-link-abbrev-alist-local)
9280 entry file all-prefixes auto-desc)
9281 (cond
9282 (link-location) ; specified by arg, just use it.
9283 ((org-in-regexp org-bracket-link-regexp 1)
9284 ;; We do have a link at point, and we are going to edit it.
9285 (setq remove (list (match-beginning 0) (match-end 0)))
9286 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9287 (setq link (read-string "Link: "
9288 (org-link-unescape
9289 (org-match-string-no-properties 1)))))
9290 ((or (org-in-regexp org-angle-link-re)
9291 (org-in-regexp org-plain-link-re))
9292 ;; Convert to bracket link
9293 (setq remove (list (match-beginning 0) (match-end 0))
9294 link (read-string "Link: "
9295 (org-remove-angle-brackets (match-string 0)))))
9296 ((member complete-file '((4) (16)))
9297 ;; Completing read for file names.
9298 (setq link (org-file-complete-link complete-file)))
9300 ;; Read link, with completion for stored links.
9301 (org-link-fontify-links-to-this-file)
9302 (org-switch-to-buffer-other-window "*Org Links*")
9303 (with-current-buffer "*Org Links*"
9304 (erase-buffer)
9305 (insert "Insert a link.
9306 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9307 (when org-stored-links
9308 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9309 (insert (mapconcat 'org-link-prettify
9310 (reverse org-stored-links) "\n")))
9311 (goto-char (point-min)))
9312 (let ((cw (selected-window)))
9313 (select-window (get-buffer-window "*Org Links*" 'visible))
9314 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9315 (unless (pos-visible-in-window-p (point-max))
9316 (org-fit-window-to-buffer))
9317 (and (window-live-p cw) (select-window cw)))
9318 ;; Fake a link history, containing the stored links.
9319 (setq tmphist (append (mapcar 'car org-stored-links)
9320 org-insert-link-history))
9321 (setq all-prefixes (append (mapcar 'car abbrevs)
9322 (mapcar 'car org-link-abbrev-alist)
9323 org-link-types))
9324 (unwind-protect
9325 (progn
9326 (setq link
9327 (let ((org-completion-use-ido nil)
9328 (org-completion-use-iswitchb nil))
9329 (org-completing-read
9330 "Link: "
9331 (append
9332 (mapcar (lambda (x) (list (concat x ":")))
9333 all-prefixes)
9334 (mapcar 'car org-stored-links)
9335 (mapcar 'cadr org-stored-links))
9336 nil nil nil
9337 'tmphist
9338 (caar org-stored-links))))
9339 (if (not (string-match "\\S-" link))
9340 (error "No link selected"))
9341 (mapc (lambda(l)
9342 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9343 org-stored-links)
9344 (if (or (member link all-prefixes)
9345 (and (equal ":" (substring link -1))
9346 (member (substring link 0 -1) all-prefixes)
9347 (setq link (substring link 0 -1))))
9348 (setq link (org-link-try-special-completion link))))
9349 (set-window-configuration wcf)
9350 (kill-buffer "*Org Links*"))
9351 (setq entry (assoc link org-stored-links))
9352 (or entry (push link org-insert-link-history))
9353 (setq desc (or desc (nth 1 entry)))))
9355 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9356 (not org-keep-stored-link-after-insertion))
9357 (setq org-stored-links (delq (assoc link org-stored-links)
9358 org-stored-links)))
9360 (if (string-match org-plain-link-re link)
9361 ;; URL-like link, normalize the use of angular brackets.
9362 (setq link (org-remove-angle-brackets link)))
9364 ;; Check if we are linking to the current file with a search
9365 ;; option If yes, simplify the link by using only the search
9366 ;; option.
9367 (when (and buffer-file-name
9368 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9369 (let* ((path (match-string 1 link))
9370 (case-fold-search nil)
9371 (search (match-string 2 link)))
9372 (save-match-data
9373 (if (equal (file-truename buffer-file-name) (file-truename path))
9374 ;; We are linking to this same file, with a search option
9375 (setq link search)))))
9377 ;; Check if we can/should use a relative path. If yes, simplify the link
9378 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9379 (let* ((type (match-string 1 link))
9380 (path (match-string 2 link))
9381 (origpath path)
9382 (case-fold-search nil))
9383 (cond
9384 ((or (eq org-link-file-path-type 'absolute)
9385 (equal complete-file '(16)))
9386 (setq path (abbreviate-file-name (expand-file-name path))))
9387 ((eq org-link-file-path-type 'noabbrev)
9388 (setq path (expand-file-name path)))
9389 ((eq org-link-file-path-type 'relative)
9390 (setq path (file-relative-name path)))
9392 (save-match-data
9393 (if (string-match (concat "^" (regexp-quote
9394 (expand-file-name
9395 (file-name-as-directory
9396 default-directory))))
9397 (expand-file-name path))
9398 ;; We are linking a file with relative path name.
9399 (setq path (substring (expand-file-name path)
9400 (match-end 0)))
9401 (setq path (abbreviate-file-name (expand-file-name path)))))))
9402 (setq link (concat type path))
9403 (if (equal desc origpath)
9404 (setq desc path))))
9406 (if org-make-link-description-function
9407 (setq desc
9408 (or (condition-case nil
9409 (funcall org-make-link-description-function link desc)
9410 (error (progn (message "Can't get link description from `%s'"
9411 (symbol-name org-make-link-description-function))
9412 (sit-for 2) nil)))
9413 (read-string "Description: " default-description)))
9414 (if default-description (setq desc default-description)
9415 (setq desc (or (and auto-desc desc)
9416 (read-string "Description: " desc)))))
9418 (unless (string-match "\\S-" desc) (setq desc nil))
9419 (if remove (apply 'delete-region remove))
9420 (insert (org-make-link-string link desc))))
9422 (defun org-link-try-special-completion (type)
9423 "If there is completion support for link type TYPE, offer it."
9424 (let ((fun (intern (concat "org-" type "-complete-link"))))
9425 (if (functionp fun)
9426 (funcall fun)
9427 (read-string "Link (no completion support): " (concat type ":")))))
9429 (defun org-file-complete-link (&optional arg)
9430 "Create a file link using completion."
9431 (let (file link)
9432 (setq file (read-file-name "File: "))
9433 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9434 (pwd1 (file-name-as-directory (abbreviate-file-name
9435 (expand-file-name ".")))))
9436 (cond
9437 ((equal arg '(16))
9438 (setq link (concat
9439 "file:"
9440 (abbreviate-file-name (expand-file-name file)))))
9441 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9442 (setq link (concat "file:" (match-string 1 file))))
9443 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9444 (expand-file-name file))
9445 (setq link (concat
9446 "file:" (match-string 1 (expand-file-name file)))))
9447 (t (setq link (concat "file:" file)))))
9448 link))
9450 (defun org-completing-read (&rest args)
9451 "Completing-read with SPACE being a normal character."
9452 (let ((enable-recursive-minibuffers t)
9453 (minibuffer-local-completion-map
9454 (copy-keymap minibuffer-local-completion-map)))
9455 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9456 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9457 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9458 (apply 'org-icompleting-read args)))
9460 (defun org-completing-read-no-i (&rest args)
9461 (let (org-completion-use-ido org-completion-use-iswitchb)
9462 (apply 'org-completing-read args)))
9464 (defun org-iswitchb-completing-read (prompt choices &rest args)
9465 "Use iswitch as a completing-read replacement to choose from choices.
9466 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9467 from."
9468 (let* ((iswitchb-use-virtual-buffers nil)
9469 (iswitchb-make-buflist-hook
9470 (lambda ()
9471 (setq iswitchb-temp-buflist choices))))
9472 (iswitchb-read-buffer prompt)))
9474 (defun org-icompleting-read (&rest args)
9475 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9476 (org-without-partial-completion
9477 (if (and org-completion-use-ido
9478 (fboundp 'ido-completing-read)
9479 (boundp 'ido-mode) ido-mode
9480 (listp (second args)))
9481 (let ((ido-enter-matching-directory nil))
9482 (apply 'ido-completing-read (concat (car args))
9483 (if (consp (car (nth 1 args)))
9484 (mapcar 'car (nth 1 args))
9485 (nth 1 args))
9486 (cddr args)))
9487 (if (and org-completion-use-iswitchb
9488 (boundp 'iswitchb-mode) iswitchb-mode
9489 (listp (second args)))
9490 (apply 'org-iswitchb-completing-read (concat (car args))
9491 (if (consp (car (nth 1 args)))
9492 (mapcar 'car (nth 1 args))
9493 (nth 1 args))
9494 (cddr args))
9495 (apply 'completing-read args)))))
9497 (defun org-extract-attributes (s)
9498 "Extract the attributes cookie from a string and set as text property."
9499 (let (a attr (start 0) key value)
9500 (save-match-data
9501 (when (string-match "{{\\([^}]+\\)}}$" s)
9502 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9503 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9504 (setq key (match-string 1 a) value (match-string 2 a)
9505 start (match-end 0)
9506 attr (plist-put attr (intern key) value))))
9507 (org-add-props s nil 'org-attr attr))
9510 (defun org-extract-attributes-from-string (tag)
9511 (let (key value attr)
9512 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9513 (setq key (match-string 1 tag) value (match-string 2 tag)
9514 tag (replace-match "" t t tag)
9515 attr (plist-put attr (intern key) value)))
9516 (cons tag attr)))
9518 (defun org-attributes-to-string (plist)
9519 "Format a property list into an HTML attribute list."
9520 (let ((s "") key value)
9521 (while plist
9522 (setq key (pop plist) value (pop plist))
9523 (and value
9524 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9527 ;;; Opening/following a link
9529 (defvar org-link-search-failed nil)
9531 (defvar org-open-link-functions nil
9532 "Hook for functions finding a plain text link.
9533 These functions must take a single argument, the link content.
9534 They will be called for links that look like [[link text][description]]
9535 when LINK TEXT does not have a protocol like \"http:\" and does not look
9536 like a filename (e.g. \"./blue.png\").
9538 These functions will be called *before* Org attempts to resolve the
9539 link by doing text searches in the current buffer - so if you want a
9540 link \"[[target]]\" to still find \"<<target>>\", your function should
9541 handle this as a special case.
9543 When the function does handle the link, it must return a non-nil value.
9544 If it decides that it is not responsible for this link, it must return
9545 nil to indicate that that Org-mode can continue with other options
9546 like exact and fuzzy text search.")
9548 (defun org-next-link ()
9549 "Move forward to the next link.
9550 If the link is in hidden text, expose it."
9551 (interactive)
9552 (when (and org-link-search-failed (eq this-command last-command))
9553 (goto-char (point-min))
9554 (message "Link search wrapped back to beginning of buffer"))
9555 (setq org-link-search-failed nil)
9556 (let* ((pos (point))
9557 (ct (org-context))
9558 (a (assoc :link ct)))
9559 (if a (goto-char (nth 2 a)))
9560 (if (re-search-forward org-any-link-re nil t)
9561 (progn
9562 (goto-char (match-beginning 0))
9563 (if (outline-invisible-p) (org-show-context)))
9564 (goto-char pos)
9565 (setq org-link-search-failed t)
9566 (error "No further link found"))))
9568 (defun org-previous-link ()
9569 "Move backward to the previous link.
9570 If the link is in hidden text, expose it."
9571 (interactive)
9572 (when (and org-link-search-failed (eq this-command last-command))
9573 (goto-char (point-max))
9574 (message "Link search wrapped back to end of buffer"))
9575 (setq org-link-search-failed nil)
9576 (let* ((pos (point))
9577 (ct (org-context))
9578 (a (assoc :link ct)))
9579 (if a (goto-char (nth 1 a)))
9580 (if (re-search-backward org-any-link-re nil t)
9581 (progn
9582 (goto-char (match-beginning 0))
9583 (if (outline-invisible-p) (org-show-context)))
9584 (goto-char pos)
9585 (setq org-link-search-failed t)
9586 (error "No further link found"))))
9588 (defun org-translate-link (s)
9589 "Translate a link string if a translation function has been defined."
9590 (if (and org-link-translation-function
9591 (fboundp org-link-translation-function)
9592 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9593 (progn
9594 (setq s (funcall org-link-translation-function
9595 (match-string 1 s) (match-string 2 s)))
9596 (concat (car s) ":" (cdr s)))
9599 (defun org-translate-link-from-planner (type path)
9600 "Translate a link from Emacs Planner syntax so that Org can follow it.
9601 This is still an experimental function, your mileage may vary."
9602 (cond
9603 ((member type '("http" "https" "news" "ftp"))
9604 ;; standard Internet links are the same.
9605 nil)
9606 ((and (equal type "irc") (string-match "^//" path))
9607 ;; Planner has two / at the beginning of an irc link, we have 1.
9608 ;; We should have zero, actually....
9609 (setq path (substring path 1)))
9610 ((and (equal type "lisp") (string-match "^/" path))
9611 ;; Planner has a slash, we do not.
9612 (setq type "elisp" path (substring path 1)))
9613 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9614 ;; A typical message link. Planner has the id after the final slash,
9615 ;; we separate it with a hash mark
9616 (setq path (concat (match-string 1 path) "#"
9617 (org-remove-angle-brackets (match-string 2 path)))))
9619 (cons type path))
9621 (defun org-find-file-at-mouse (ev)
9622 "Open file link or URL at mouse."
9623 (interactive "e")
9624 (mouse-set-point ev)
9625 (org-open-at-point 'in-emacs))
9627 (defun org-open-at-mouse (ev)
9628 "Open file link or URL at mouse.
9629 See the docstring of `org-open-file' for details."
9630 (interactive "e")
9631 (mouse-set-point ev)
9632 (if (eq major-mode 'org-agenda-mode)
9633 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9634 (org-open-at-point))
9636 (defvar org-window-config-before-follow-link nil
9637 "The window configuration before following a link.
9638 This is saved in case the need arises to restore it.")
9640 (defvar org-open-link-marker (make-marker)
9641 "Marker pointing to the location where `org-open-at-point; was called.")
9643 ;;;###autoload
9644 (defun org-open-at-point-global ()
9645 "Follow a link like Org-mode does.
9646 This command can be called in any mode to follow a link that has
9647 Org-mode syntax."
9648 (interactive)
9649 (org-run-like-in-org-mode 'org-open-at-point))
9651 ;;;###autoload
9652 (defun org-open-link-from-string (s &optional arg reference-buffer)
9653 "Open a link in the string S, as if it was in Org-mode."
9654 (interactive "sLink: \nP")
9655 (let ((reference-buffer (or reference-buffer (current-buffer))))
9656 (with-temp-buffer
9657 (let ((org-inhibit-startup (not reference-buffer)))
9658 (org-mode)
9659 (insert s)
9660 (goto-char (point-min))
9661 (when reference-buffer
9662 (setq org-link-abbrev-alist-local
9663 (with-current-buffer reference-buffer
9664 org-link-abbrev-alist-local)))
9665 (org-open-at-point arg reference-buffer)))))
9667 (defvar org-open-at-point-functions nil
9668 "Hook that is run when following a link at point.
9670 Functions in this hook must return t if they identify and follow
9671 a link at point. If they don't find anything interesting at point,
9672 they must return nil.")
9674 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9675 (defun org-open-at-point (&optional arg reference-buffer)
9676 "Open link at or after point.
9677 If there is no link at point, this function will search forward up to
9678 the end of the current line.
9679 Normally, files will be opened by an appropriate application. If the
9680 optional prefix argument ARG is non-nil, Emacs will visit the file.
9681 With a double prefix argument, try to open outside of Emacs, in the
9682 application the system uses for this file type."
9683 (interactive "P")
9684 ;; if in a code block, then open the block's results
9685 (unless (call-interactively #'org-babel-open-src-block-result)
9686 (org-load-modules-maybe)
9687 (move-marker org-open-link-marker (point))
9688 (setq org-window-config-before-follow-link (current-window-configuration))
9689 (org-remove-occur-highlights nil nil t)
9690 (cond
9691 ((and (org-at-heading-p)
9692 (not (org-at-timestamp-p t))
9693 (not (org-in-regexp
9694 (concat org-plain-link-re "\\|"
9695 org-bracket-link-regexp "\\|"
9696 org-angle-link-re "\\|"
9697 "[ \t]:[^ \t\n]+:[ \t]*$")))
9698 (not (get-text-property (point) 'org-linked-text)))
9699 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9700 (lk0 (car lkall))
9701 (lk (if (stringp lk0) (list lk0) lk0))
9702 (lkend (cdr lkall)))
9703 (mapcar (lambda(l)
9704 (search-forward l nil lkend)
9705 (goto-char (match-beginning 0))
9706 (org-open-at-point))
9707 lk))
9708 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9709 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9710 ((and (org-at-timestamp-p t)
9711 (not (org-in-regexp org-bracket-link-regexp)))
9712 (org-follow-timestamp-link))
9713 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9714 (not (org-in-regexp org-any-link-re)))
9715 (org-footnote-action))
9717 (let (type path link line search (pos (point)))
9718 (catch 'match
9719 (save-excursion
9720 (skip-chars-forward "^]\n\r")
9721 (when (org-in-regexp org-bracket-link-regexp 1)
9722 (setq link (org-extract-attributes
9723 (org-link-unescape (org-match-string-no-properties 1))))
9724 (while (string-match " *\n *" link)
9725 (setq link (replace-match " " t t link)))
9726 (setq link (org-link-expand-abbrev link))
9727 (cond
9728 ((or (file-name-absolute-p link)
9729 (string-match "^\\.\\.?/" link))
9730 (setq type "file" path link))
9731 ((string-match org-link-re-with-space3 link)
9732 (setq type (match-string 1 link) path (match-string 2 link)))
9733 ((string-match "^help:+\\(.+\\)" link)
9734 (setq type "help" path (match-string 1 link)))
9735 (t (setq type "thisfile" path link)))
9736 (throw 'match t)))
9738 (when (get-text-property (point) 'org-linked-text)
9739 (setq type "thisfile"
9740 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9741 (1+ (point)) (point))
9742 path (buffer-substring
9743 (or (previous-single-property-change pos 'org-linked-text)
9744 (point-min))
9745 (or (next-single-property-change pos 'org-linked-text)
9746 (point-max))))
9747 (throw 'match t))
9749 (save-excursion
9750 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9751 (when (or (org-in-regexp org-angle-link-re)
9752 (and plinkpos (goto-char (car plinkpos))
9753 (save-match-data (not (looking-back "\\[\\[")))))
9754 (setq type (match-string 1)
9755 path (org-link-unescape (match-string 2)))
9756 (throw 'match t))))
9757 (save-excursion
9758 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9759 (setq type "tags"
9760 path (match-string 1))
9761 (while (string-match ":" path)
9762 (setq path (replace-match "+" t t path)))
9763 (throw 'match t)))
9764 (when (org-in-regexp "<\\([^><\n]+\\)>")
9765 (setq type "tree-match"
9766 path (match-string 1))
9767 (throw 'match t)))
9768 (unless path
9769 (user-error "No link found"))
9771 ;; switch back to reference buffer
9772 ;; needed when if called in a temporary buffer through
9773 ;; org-open-link-from-string
9774 (with-current-buffer (or reference-buffer (current-buffer))
9776 ;; Remove any trailing spaces in path
9777 (if (string-match " +\\'" path)
9778 (setq path (replace-match "" t t path)))
9779 (if (and org-link-translation-function
9780 (fboundp org-link-translation-function))
9781 ;; Check if we need to translate the link
9782 (let ((tmp (funcall org-link-translation-function type path)))
9783 (setq type (car tmp) path (cdr tmp))))
9785 (cond
9787 ((assoc type org-link-protocols)
9788 (funcall (nth 1 (assoc type org-link-protocols)) path))
9790 ((equal type "help")
9791 (let ((f-or-v (intern path)))
9792 (cond ((fboundp f-or-v)
9793 (describe-function f-or-v))
9794 ((boundp f-or-v)
9795 (describe-variable f-or-v))
9796 (t (error "Not a known function or variable")))))
9798 ((equal type "mailto")
9799 (let ((cmd (car org-link-mailto-program))
9800 (args (cdr org-link-mailto-program)) args1
9801 (address path) (subject "") a)
9802 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9803 (setq address (match-string 1 path)
9804 subject (org-link-escape (match-string 2 path))))
9805 (while args
9806 (cond
9807 ((not (stringp (car args))) (push (pop args) args1))
9808 (t (setq a (pop args))
9809 (if (string-match "%a" a)
9810 (setq a (replace-match address t t a)))
9811 (if (string-match "%s" a)
9812 (setq a (replace-match subject t t a)))
9813 (push a args1))))
9814 (apply cmd (nreverse args1))))
9816 ((member type '("http" "https" "ftp" "news"))
9817 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9818 (org-link-escape
9819 path org-link-escape-chars-browser)
9820 path))))
9822 ((string= type "doi")
9823 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9824 (org-link-escape
9825 path org-link-escape-chars-browser)
9826 path))))
9828 ((member type '("message"))
9829 (browse-url (concat type ":" path)))
9831 ((string= type "tags")
9832 (org-tags-view arg path))
9834 ((string= type "tree-match")
9835 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9837 ((string= type "file")
9838 (if (string-match "::\\([0-9]+\\)\\'" path)
9839 (setq line (string-to-number (match-string 1 path))
9840 path (substring path 0 (match-beginning 0)))
9841 (if (string-match "::\\(.+\\)\\'" path)
9842 (setq search (match-string 1 path)
9843 path (substring path 0 (match-beginning 0)))))
9844 (if (string-match "[*?{]" (file-name-nondirectory path))
9845 (dired path)
9846 (org-open-file path arg line search)))
9848 ((string= type "shell")
9849 (let ((buf (generate-new-buffer "*Org Shell Output"))
9850 (cmd path))
9851 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9852 (string-match org-confirm-shell-link-not-regexp cmd))
9853 (not org-confirm-shell-link-function)
9854 (funcall org-confirm-shell-link-function
9855 (format "Execute \"%s\" in shell? "
9856 (org-add-props cmd nil
9857 'face 'org-warning))))
9858 (progn
9859 (message "Executing %s" cmd)
9860 (shell-command cmd buf)
9861 (if (featurep 'midnight)
9862 (setq clean-buffer-list-kill-buffer-names
9863 (cons buf clean-buffer-list-kill-buffer-names))))
9864 (error "Abort"))))
9866 ((string= type "elisp")
9867 (let ((cmd path))
9868 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9869 (string-match org-confirm-elisp-link-not-regexp cmd))
9870 (not org-confirm-elisp-link-function)
9871 (funcall org-confirm-elisp-link-function
9872 (format "Execute \"%s\" as elisp? "
9873 (org-add-props cmd nil
9874 'face 'org-warning))))
9875 (message "%s => %s" cmd
9876 (if (equal (string-to-char cmd) ?\()
9877 (eval (read cmd))
9878 (call-interactively (read cmd))))
9879 (error "Abort"))))
9881 ((and (string= type "thisfile")
9882 (run-hook-with-args-until-success
9883 'org-open-link-functions path)))
9885 ((string= type "thisfile")
9886 (if arg
9887 (switch-to-buffer-other-window
9888 (org-get-buffer-for-internal-link (current-buffer)))
9889 (org-mark-ring-push))
9890 (let ((cmd `(org-link-search
9891 ,path
9892 ,(cond ((equal arg '(4)) ''occur)
9893 ((equal arg '(16)) ''org-occur))
9894 ,pos)))
9895 (condition-case nil (let ((org-link-search-inhibit-query t))
9896 (eval cmd))
9897 (error (progn (widen) (eval cmd))))))
9899 (t (browse-url-at-point)))))))
9900 (move-marker org-open-link-marker nil)
9901 (run-hook-with-args 'org-follow-link-hook)))
9903 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9904 "Offer links in the current entry and return the selected link.
9905 If there is only one link, return it.
9906 If NTH is an integer, return the NTH link found.
9907 If ZERO is a string, check also this string for a link, and if
9908 there is one, return it."
9909 (with-current-buffer buffer
9910 (save-excursion
9911 (save-restriction
9912 (widen)
9913 (goto-char marker)
9914 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9915 "\\(" org-angle-link-re "\\)\\|"
9916 "\\(" org-plain-link-re "\\)"))
9917 (cnt ?0)
9918 (in-emacs (if (integerp nth) nil nth))
9919 have-zero end links link c)
9920 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9921 (push (match-string 0 zero) links)
9922 (setq cnt (1- cnt) have-zero t))
9923 (save-excursion
9924 (org-back-to-heading t)
9925 (setq end (save-excursion (outline-next-heading) (point)))
9926 (while (re-search-forward re end t)
9927 (push (match-string 0) links))
9928 (setq links (org-uniquify (reverse links))))
9929 (cond
9930 ((null links)
9931 (message "No links"))
9932 ((equal (length links) 1)
9933 (setq link (car links)))
9934 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9935 (setq link (nth (if have-zero nth (1- nth)) links)))
9936 (t ; we have to select a link
9937 (save-excursion
9938 (save-window-excursion
9939 (delete-other-windows)
9940 (with-output-to-temp-buffer "*Select Link*"
9941 (mapc (lambda (l)
9942 (if (not (string-match org-bracket-link-regexp l))
9943 (princ (format "[%c] %s\n" (incf cnt)
9944 (org-remove-angle-brackets l)))
9945 (if (match-end 3)
9946 (princ (format "[%c] %s (%s)\n" (incf cnt)
9947 (match-string 3 l) (match-string 1 l)))
9948 (princ (format "[%c] %s\n" (incf cnt)
9949 (match-string 1 l))))))
9950 links))
9951 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9952 (message "Select link to open, RET to open all:")
9953 (setq c (read-char-exclusive))
9954 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9955 (when (equal c ?q) (error "Abort"))
9956 (if (equal c ?\C-m)
9957 (setq link links)
9958 (setq nth (- c ?0))
9959 (if have-zero (setq nth (1+ nth)))
9960 (unless (and (integerp nth) (>= (length links) nth))
9961 (error "Invalid link selection"))
9962 (setq link (nth (1- nth) links)))))
9963 (cons link end))))))
9965 ;; Add special file links that specify the way of opening
9967 (org-add-link-type "file+sys" 'org-open-file-with-system)
9968 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9969 (defun org-open-file-with-system (path)
9970 "Open file at PATH using the system way of opening it."
9971 (org-open-file path 'system))
9972 (defun org-open-file-with-emacs (path)
9973 "Open file at PATH in Emacs."
9974 (org-open-file path 'emacs))
9975 (defun org-remove-file-link-modifiers ()
9976 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9977 (goto-char (point-min))
9978 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9979 (org-if-unprotected
9980 (replace-match "file:" t t))))
9981 (eval-after-load "org-exp"
9982 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9983 'org-remove-file-link-modifiers))
9985 ;;; File search
9987 (defvar org-create-file-search-functions nil
9988 "List of functions to construct the right search string for a file link.
9989 These functions are called in turn with point at the location to
9990 which the link should point.
9992 A function in the hook should first test if it would like to
9993 handle this file type, for example by checking the `major-mode'
9994 or the file extension. If it decides not to handle this file, it
9995 should just return nil to give other functions a chance. If it
9996 does handle the file, it must return the search string to be used
9997 when following the link. The search string will be part of the
9998 file link, given after a double colon, and `org-open-at-point'
9999 will automatically search for it. If special measures must be
10000 taken to make the search successful, another function should be
10001 added to the companion hook `org-execute-file-search-functions',
10002 which see.
10004 A function in this hook may also use `setq' to set the variable
10005 `description' to provide a suggestion for the descriptive text to
10006 be used for this link when it gets inserted into an Org-mode
10007 buffer with \\[org-insert-link].")
10009 (defvar org-execute-file-search-functions nil
10010 "List of functions to execute a file search triggered by a link.
10012 Functions added to this hook must accept a single argument, the
10013 search string that was part of the file link, the part after the
10014 double colon. The function must first check if it would like to
10015 handle this search, for example by checking the `major-mode' or
10016 the file extension. If it decides not to handle this search, it
10017 should just return nil to give other functions a chance. If it
10018 does handle the search, it must return a non-nil value to keep
10019 other functions from trying.
10021 Each function can access the current prefix argument through the
10022 variable `current-prefix-argument'. Note that a single prefix is
10023 used to force opening a link in Emacs, so it may be good to only
10024 use a numeric or double prefix to guide the search function.
10026 In case this is needed, a function in this hook can also restore
10027 the window configuration before `org-open-at-point' was called using:
10029 (set-window-configuration org-window-config-before-follow-link)")
10031 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10032 (defun org-link-search (s &optional type avoid-pos stealth)
10033 "Search for a link search option.
10034 If S is surrounded by forward slashes, it is interpreted as a
10035 regular expression. In org-mode files, this will create an `org-occur'
10036 sparse tree. In ordinary files, `occur' will be used to list matches.
10037 If the current buffer is in `dired-mode', grep will be used to search
10038 in all files. If AVOID-POS is given, ignore matches near that position.
10040 When optional argument STEALTH is non-nil, do not modify
10041 visibility around point, thus ignoring
10042 `org-show-hierarchy-above', `org-show-following-heading' and
10043 `org-show-siblings' variables."
10044 (let ((case-fold-search t)
10045 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10046 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10047 (append '(("") (" ") ("\t") ("\n"))
10048 org-emphasis-alist)
10049 "\\|") "\\)"))
10050 (pos (point))
10051 (pre nil) (post nil)
10052 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10053 (cond
10054 ;; First check if there are any special search functions
10055 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10056 ;; Now try the builtin stuff
10057 ((and (equal (string-to-char s0) ?#)
10058 (> (length s0) 1)
10059 (save-excursion
10060 (goto-char (point-min))
10061 (and
10062 (re-search-forward
10063 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10064 (setq type 'dedicated
10065 pos (match-beginning 0))))
10066 ;; There is an exact target for this
10067 (goto-char pos)
10068 (org-back-to-heading t)))
10069 ((save-excursion
10070 (goto-char (point-min))
10071 (and
10072 (re-search-forward
10073 (concat "<<" (regexp-quote s0) ">>") nil t)
10074 (setq type 'dedicated
10075 pos (match-beginning 0))))
10076 ;; There is an exact target for this
10077 (goto-char pos))
10078 ((save-excursion
10079 (goto-char (point-min))
10080 (and
10081 (re-search-forward
10082 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10083 (setq type 'dedicated pos (match-beginning 0))))
10084 ;; Found an invisible target.
10085 (goto-char pos))
10086 ((save-excursion
10087 (goto-char (point-min))
10088 (and
10089 (re-search-forward
10090 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10091 (setq type 'dedicated pos (match-beginning 0))))
10092 ;; Found an element with a matching #+name affiliated keyword.
10093 (goto-char pos))
10094 ((and (string-match "^(\\(.*\\))$" s0)
10095 (save-excursion
10096 (goto-char (point-min))
10097 (and
10098 (re-search-forward
10099 (concat "[^[]" (regexp-quote
10100 (format org-coderef-label-format
10101 (match-string 1 s0))))
10102 nil t)
10103 (setq type 'dedicated
10104 pos (1+ (match-beginning 0))))))
10105 ;; There is a coderef target for this
10106 (goto-char pos))
10107 ((string-match "^/\\(.*\\)/$" s)
10108 ;; A regular expression
10109 (cond
10110 ((derived-mode-p 'org-mode)
10111 (org-occur (match-string 1 s)))
10112 ;;((eq major-mode 'dired-mode)
10113 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10114 (t (org-do-occur (match-string 1 s)))))
10115 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10116 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10117 (goto-char (point-min))
10118 (cond
10119 ((let (case-fold-search)
10120 (re-search-forward (format org-complex-heading-regexp-format
10121 (regexp-quote s))
10122 nil t))
10123 ;; OK, found a match
10124 (setq type 'dedicated)
10125 (goto-char (match-beginning 0)))
10126 ((and (not org-link-search-inhibit-query)
10127 (eq org-link-search-must-match-exact-headline 'query-to-create)
10128 (y-or-n-p "No match - create this as a new heading? "))
10129 (goto-char (point-max))
10130 (or (bolp) (newline))
10131 (insert "* " s "\n")
10132 (beginning-of-line 0))
10134 (goto-char pos)
10135 (error "No match"))))
10137 ;; A normal search string
10138 (when (equal (string-to-char s) ?*)
10139 ;; Anchor on headlines, post may include tags.
10140 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10141 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10142 s (substring s 1)))
10143 (remove-text-properties
10144 0 (length s)
10145 '(face nil mouse-face nil keymap nil fontified nil) s)
10146 ;; Make a series of regular expressions to find a match
10147 (setq words (org-split-string s "[ \n\r\t]+")
10149 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10150 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10151 "\\)" markers)
10152 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10153 re2a (concat "[ \t\r\n]" re2a_)
10154 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10155 re4 (concat "[^a-zA-Z_]" re4_)
10157 re1 (concat pre re2 post)
10158 re3 (concat pre (if pre re4_ re4) post)
10159 re5 (concat pre ".*" re4)
10160 re2 (concat pre re2)
10161 re2a (concat pre (if pre re2a_ re2a))
10162 re4 (concat pre (if pre re4_ re4))
10163 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10164 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10165 re5 "\\)"
10167 (cond
10168 ((eq type 'org-occur) (org-occur reall))
10169 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10170 (t (goto-char (point-min))
10171 (setq type 'fuzzy)
10172 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10173 (org-search-not-self 1 re1 nil t)
10174 (org-search-not-self 1 re2 nil t)
10175 (org-search-not-self 1 re2a nil t)
10176 (org-search-not-self 1 re3 nil t)
10177 (org-search-not-self 1 re4 nil t)
10178 (org-search-not-self 1 re5 nil t)
10180 (goto-char (match-beginning 1))
10181 (goto-char pos)
10182 (error "No match"))))))
10183 (and (derived-mode-p 'org-mode)
10184 (not stealth)
10185 (org-show-context 'link-search))
10186 type))
10188 (defun org-search-not-self (group &rest args)
10189 "Execute `re-search-forward', but only accept matches that do not
10190 enclose the position of `org-open-link-marker'."
10191 (let ((m org-open-link-marker))
10192 (catch 'exit
10193 (while (apply 're-search-forward args)
10194 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10195 (goto-char (match-end group))
10196 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10197 (> (match-beginning 0) (marker-position m))
10198 (< (match-end 0) (marker-position m)))
10199 (save-match-data
10200 (or (not (org-in-regexp
10201 org-bracket-link-analytic-regexp 1))
10202 (not (match-end 4)) ; no description
10203 (and (<= (match-beginning 4) (point))
10204 (>= (match-end 4) (point))))))
10205 (throw 'exit (point))))))))
10207 (defun org-get-buffer-for-internal-link (buffer)
10208 "Return a buffer to be used for displaying the link target of internal links."
10209 (cond
10210 ((not org-display-internal-link-with-indirect-buffer)
10211 buffer)
10212 ((string-match "(Clone)$" (buffer-name buffer))
10213 (message "Buffer is already a clone, not making another one")
10214 ;; we also do not modify visibility in this case
10215 buffer)
10216 (t ; make a new indirect buffer for displaying the link
10217 (let* ((bn (buffer-name buffer))
10218 (ibn (concat bn "(Clone)"))
10219 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10220 (with-current-buffer ib (org-overview))
10221 ib))))
10223 (defun org-do-occur (regexp &optional cleanup)
10224 "Call the Emacs command `occur'.
10225 If CLEANUP is non-nil, remove the printout of the regular expression
10226 in the *Occur* buffer. This is useful if the regex is long and not useful
10227 to read."
10228 (occur regexp)
10229 (when cleanup
10230 (let ((cwin (selected-window)) win beg end)
10231 (when (setq win (get-buffer-window "*Occur*"))
10232 (select-window win))
10233 (goto-char (point-min))
10234 (when (re-search-forward "match[a-z]+" nil t)
10235 (setq beg (match-end 0))
10236 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10237 (setq end (1- (match-beginning 0)))))
10238 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10239 (goto-char (point-min))
10240 (select-window cwin))))
10242 ;;; The mark ring for links jumps
10244 (defvar org-mark-ring nil
10245 "Mark ring for positions before jumps in Org-mode.")
10246 (defvar org-mark-ring-last-goto nil
10247 "Last position in the mark ring used to go back.")
10248 ;; Fill and close the ring
10249 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10250 (loop for i from 1 to org-mark-ring-length do
10251 (push (make-marker) org-mark-ring))
10252 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10253 org-mark-ring)
10255 (defun org-mark-ring-push (&optional pos buffer)
10256 "Put the current position or POS into the mark ring and rotate it."
10257 (interactive)
10258 (setq pos (or pos (point)))
10259 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10260 (move-marker (car org-mark-ring)
10261 (or pos (point))
10262 (or buffer (current-buffer)))
10263 (message "%s"
10264 (substitute-command-keys
10265 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10267 (defun org-mark-ring-goto (&optional n)
10268 "Jump to the previous position in the mark ring.
10269 With prefix arg N, jump back that many stored positions. When
10270 called several times in succession, walk through the entire ring.
10271 Org-mode commands jumping to a different position in the current file,
10272 or to another Org-mode file, automatically push the old position
10273 onto the ring."
10274 (interactive "p")
10275 (let (p m)
10276 (if (eq last-command this-command)
10277 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10278 (setq p org-mark-ring))
10279 (setq org-mark-ring-last-goto p)
10280 (setq m (car p))
10281 (org-pop-to-buffer-same-window (marker-buffer m))
10282 (goto-char m)
10283 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10285 (defun org-remove-angle-brackets (s)
10286 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10287 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10289 (defun org-add-angle-brackets (s)
10290 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10291 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10293 (defun org-remove-double-quotes (s)
10294 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10295 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10298 ;;; Following specific links
10300 (defun org-follow-timestamp-link ()
10301 "Open an agenda view for the time-stamp date/range at point."
10302 (cond
10303 ((org-at-date-range-p t)
10304 (let ((org-agenda-start-on-weekday)
10305 (t1 (match-string 1))
10306 (t2 (match-string 2)) tt1 tt2)
10307 (setq tt1 (time-to-days (org-time-string-to-time t1))
10308 tt2 (time-to-days (org-time-string-to-time t2)))
10309 (let ((org-agenda-buffer-tmp-name
10310 (format "*Org Agenda(a:%s)"
10311 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10312 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10313 ((org-at-timestamp-p t)
10314 (let ((org-agenda-buffer-tmp-name
10315 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10316 (org-agenda-list nil (time-to-days (org-time-string-to-time
10317 (substring (match-string 1) 0 10)))
10318 1)))
10319 (t (error "This should not happen"))))
10322 ;;; Following file links
10323 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10324 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10325 (declare-function mailcap-mime-info
10326 "mailcap" (string &optional request no-decode))
10327 (defvar org-wait nil)
10328 (defun org-open-file (path &optional in-emacs line search)
10329 "Open the file at PATH.
10330 First, this expands any special file name abbreviations. Then the
10331 configuration variable `org-file-apps' is checked if it contains an
10332 entry for this file type, and if yes, the corresponding command is launched.
10334 If no application is found, Emacs simply visits the file.
10336 With optional prefix argument IN-EMACS, Emacs will visit the file.
10337 With a double \\[universal-argument] \\[universal-argument] \
10338 prefix arg, Org tries to avoid opening in Emacs
10339 and to use an external application to visit the file.
10341 Optional LINE specifies a line to go to, optional SEARCH a string
10342 to search for. If LINE or SEARCH is given, the file will be
10343 opened in Emacs, unless an entry from org-file-apps that makes
10344 use of groups in a regexp matches.
10346 If you want to change the way frames are used when following a
10347 link, please customize `org-link-frame-setup'.
10349 If the file does not exist, an error is thrown."
10350 (let* ((file (if (equal path "")
10351 buffer-file-name
10352 (substitute-in-file-name (expand-file-name path))))
10353 (file-apps (append org-file-apps (org-default-apps)))
10354 (apps (org-remove-if
10355 'org-file-apps-entry-match-against-dlink-p file-apps))
10356 (apps-dlink (org-remove-if-not
10357 'org-file-apps-entry-match-against-dlink-p file-apps))
10358 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10359 (dirp (if remp nil (file-directory-p file)))
10360 (file (if (and dirp org-open-directory-means-index-dot-org)
10361 (concat (file-name-as-directory file) "index.org")
10362 file))
10363 (a-m-a-p (assq 'auto-mode apps))
10364 (dfile (downcase file))
10365 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10366 (link (cond ((and (eq line nil)
10367 (eq search nil))
10368 file)
10369 (line
10370 (concat file "::" (number-to-string line)))
10371 (search
10372 (concat file "::" search))))
10373 (dlink (downcase link))
10374 (old-buffer (current-buffer))
10375 (old-pos (point))
10376 (old-mode major-mode)
10377 ext cmd link-match-data)
10378 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10379 (setq ext (match-string 1 dfile))
10380 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10381 (setq ext (match-string 1 dfile))))
10382 (cond
10383 ((member in-emacs '((16) system))
10384 (setq cmd (cdr (assoc 'system apps))))
10385 (in-emacs (setq cmd 'emacs))
10387 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10388 (and dirp (cdr (assoc 'directory apps)))
10389 ; first, try matching against apps-dlink
10390 ; if we get a match here, store the match data for later
10391 (let ((match (assoc-default dlink apps-dlink
10392 'string-match)))
10393 (if match
10394 (progn (setq link-match-data (match-data))
10395 match)
10396 (progn (setq in-emacs (or in-emacs line search))
10397 nil))) ; if we have no match in apps-dlink,
10398 ; always open the file in emacs if line or search
10399 ; is given (for backwards compatibility)
10400 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10401 'string-match)
10402 (cdr (assoc ext apps))
10403 (cdr (assoc t apps))))))
10404 (when (eq cmd 'system)
10405 (setq cmd (cdr (assoc 'system apps))))
10406 (when (eq cmd 'default)
10407 (setq cmd (cdr (assoc t apps))))
10408 (when (eq cmd 'mailcap)
10409 (require 'mailcap)
10410 (mailcap-parse-mailcaps)
10411 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10412 (command (mailcap-mime-info mime-type)))
10413 (if (stringp command)
10414 (setq cmd command)
10415 (setq cmd 'emacs))))
10416 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10417 (not (file-exists-p file))
10418 (not org-open-non-existing-files))
10419 (error "No such file: %s" file))
10420 (cond
10421 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10422 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10423 (while (string-match "['\"]%s['\"]" cmd)
10424 (setq cmd (replace-match "%s" t t cmd)))
10425 (while (string-match "%s" cmd)
10426 (setq cmd (replace-match
10427 (save-match-data
10428 (shell-quote-argument
10429 (convert-standard-filename file)))
10430 t t cmd)))
10432 ;; Replace "%1", "%2" etc. in command with group matches from regex
10433 (save-match-data
10434 (let ((match-index 1)
10435 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10436 (set-match-data link-match-data)
10437 (while (<= match-index number-of-groups)
10438 (let ((regex (concat "%" (number-to-string match-index)))
10439 (replace-with (match-string match-index dlink)))
10440 (while (string-match regex cmd)
10441 (setq cmd (replace-match replace-with t t cmd))))
10442 (setq match-index (+ match-index 1)))))
10444 (save-window-excursion
10445 (start-process-shell-command cmd nil cmd)
10446 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10448 ((or (stringp cmd)
10449 (eq cmd 'emacs))
10450 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10451 (widen)
10452 (if line (org-goto-line line)
10453 (if search (org-link-search search))))
10454 ((consp cmd)
10455 (let ((file (convert-standard-filename file)))
10456 (save-match-data
10457 (set-match-data link-match-data)
10458 (eval cmd))))
10459 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10460 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10461 (or (not (equal old-buffer (current-buffer)))
10462 (not (equal old-pos (point))))
10463 (org-mark-ring-push old-pos old-buffer))))
10465 (defun org-file-apps-entry-match-against-dlink-p (entry)
10466 "This function returns non-nil if `entry' uses a regular
10467 expression which should be matched against the whole link by
10468 org-open-file.
10470 It assumes that is the case when the entry uses a regular
10471 expression which has at least one grouping construct and the
10472 action is either a lisp form or a command string containing
10473 '%1', i.e. using at least one subexpression match as a
10474 parameter."
10475 (let ((selector (car entry))
10476 (action (cdr entry)))
10477 (if (stringp selector)
10478 (and (> (regexp-opt-depth selector) 0)
10479 (or (and (stringp action)
10480 (string-match "%[0-9]" action))
10481 (consp action)))
10482 nil)))
10484 (defun org-default-apps ()
10485 "Return the default applications for this operating system."
10486 (cond
10487 ((eq system-type 'darwin)
10488 org-file-apps-defaults-macosx)
10489 ((eq system-type 'windows-nt)
10490 org-file-apps-defaults-windowsnt)
10491 (t org-file-apps-defaults-gnu)))
10493 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10494 "Convert extensions to regular expressions in the cars of LIST.
10495 Also, weed out any non-string entries, because the return value is used
10496 only for regexp matching.
10497 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10498 point to the symbol `emacs', indicating that the file should
10499 be opened in Emacs."
10500 (append
10501 (delq nil
10502 (mapcar (lambda (x)
10503 (if (not (stringp (car x)))
10505 (if (string-match "\\W" (car x))
10507 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10508 list))
10509 (if add-auto-mode
10510 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10512 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10513 (defun org-file-remote-p (file)
10514 "Test whether FILE specifies a location on a remote system.
10515 Return non-nil if the location is indeed remote.
10517 For example, the filename \"/user@host:/foo\" specifies a location
10518 on the system \"/user@host:\"."
10519 (cond ((fboundp 'file-remote-p)
10520 (file-remote-p file))
10521 ((fboundp 'tramp-handle-file-remote-p)
10522 (tramp-handle-file-remote-p file))
10523 ((and (boundp 'ange-ftp-name-format)
10524 (string-match (car ange-ftp-name-format) file))
10525 t)))
10528 ;;;; Refiling
10530 (defun org-get-org-file ()
10531 "Read a filename, with default directory `org-directory'."
10532 (let ((default (or org-default-notes-file remember-data-file)))
10533 (read-file-name (format "File name [%s]: " default)
10534 (file-name-as-directory org-directory)
10535 default)))
10537 (defun org-notes-order-reversed-p ()
10538 "Check if the current file should receive notes in reversed order."
10539 (cond
10540 ((not org-reverse-note-order) nil)
10541 ((eq t org-reverse-note-order) t)
10542 ((not (listp org-reverse-note-order)) nil)
10543 (t (catch 'exit
10544 (let ((all org-reverse-note-order)
10545 entry)
10546 (while (setq entry (pop all))
10547 (if (string-match (car entry) buffer-file-name)
10548 (throw 'exit (cdr entry))))
10549 nil)))))
10551 (defvar org-refile-target-table nil
10552 "The list of refile targets, created by `org-refile'.")
10554 (defvar org-agenda-new-buffers nil
10555 "Buffers created to visit agenda files.")
10557 (defvar org-refile-cache nil
10558 "Cache for refile targets.")
10560 (defvar org-refile-markers nil
10561 "All the markers used for caching refile locations.")
10563 (defun org-refile-marker (pos)
10564 "Get a new refile marker, but only if caching is in use."
10565 (if (not org-refile-use-cache)
10567 (let ((m (make-marker)))
10568 (move-marker m pos)
10569 (push m org-refile-markers)
10570 m)))
10572 (defun org-refile-cache-clear ()
10573 "Clear the refile cache and disable all the markers."
10574 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10575 (setq org-refile-markers nil)
10576 (setq org-refile-cache nil)
10577 (message "Refile cache has been cleared"))
10579 (defun org-refile-cache-check-set (set)
10580 "Check if all the markers in the cache still have live buffers."
10581 (let (marker)
10582 (catch 'exit
10583 (while (and set (setq marker (nth 3 (pop set))))
10584 ;; if org-refile-use-outline-path is 'file, marker may be nil
10585 (when (and marker (null (marker-buffer marker)))
10586 (message "not found") (sit-for 3)
10587 (throw 'exit nil)))
10588 t)))
10590 (defun org-refile-cache-put (set &rest identifiers)
10591 "Push the refile targets SET into the cache, under IDENTIFIERS."
10592 (let* ((key (sha1 (prin1-to-string identifiers)))
10593 (entry (assoc key org-refile-cache)))
10594 (if entry
10595 (setcdr entry set)
10596 (push (cons key set) org-refile-cache))))
10598 (defun org-refile-cache-get (&rest identifiers)
10599 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10600 (cond
10601 ((not org-refile-cache) nil)
10602 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10604 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10605 org-refile-cache))))
10606 (and set (org-refile-cache-check-set set) set)))))
10608 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10609 "Produce a table with refile targets."
10610 (let ((case-fold-search nil)
10611 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10612 (entries (or org-refile-targets '((nil . (:level . 1)))))
10613 targets tgs txt re files f desc descre fast-path-p level pos0)
10614 (message "Getting targets...")
10615 (with-current-buffer (or default-buffer (current-buffer))
10616 (while (setq entry (pop entries))
10617 (setq files (car entry) desc (cdr entry))
10618 (setq fast-path-p nil)
10619 (cond
10620 ((null files) (setq files (list (current-buffer))))
10621 ((eq files 'org-agenda-files)
10622 (setq files (org-agenda-files 'unrestricted)))
10623 ((and (symbolp files) (fboundp files))
10624 (setq files (funcall files)))
10625 ((and (symbolp files) (boundp files))
10626 (setq files (symbol-value files))))
10627 (if (stringp files) (setq files (list files)))
10628 (cond
10629 ((eq (car desc) :tag)
10630 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10631 ((eq (car desc) :todo)
10632 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10633 ((eq (car desc) :regexp)
10634 (setq descre (cdr desc)))
10635 ((eq (car desc) :level)
10636 (setq descre (concat "^\\*\\{" (number-to-string
10637 (if org-odd-levels-only
10638 (1- (* 2 (cdr desc)))
10639 (cdr desc)))
10640 "\\}[ \t]")))
10641 ((eq (car desc) :maxlevel)
10642 (setq fast-path-p t)
10643 (setq descre (concat "^\\*\\{1," (number-to-string
10644 (if org-odd-levels-only
10645 (1- (* 2 (cdr desc)))
10646 (cdr desc)))
10647 "\\}[ \t]")))
10648 (t (error "Bad refiling target description %s" desc)))
10649 (while (setq f (pop files))
10650 (with-current-buffer
10651 (if (bufferp f) f (org-get-agenda-file-buffer f))
10653 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10654 (progn
10655 (if (bufferp f) (setq f (buffer-file-name
10656 (buffer-base-buffer f))))
10657 (setq f (and f (expand-file-name f)))
10658 (if (eq org-refile-use-outline-path 'file)
10659 (push (list (file-name-nondirectory f) f nil nil) tgs))
10660 (save-excursion
10661 (save-restriction
10662 (widen)
10663 (goto-char (point-min))
10664 (while (re-search-forward descre nil t)
10665 (goto-char (setq pos0 (point-at-bol)))
10666 (catch 'next
10667 (when org-refile-target-verify-function
10668 (save-match-data
10669 (or (funcall org-refile-target-verify-function)
10670 (throw 'next t))))
10671 (when (and (looking-at org-complex-heading-regexp)
10672 (not (member (match-string 4) excluded-entries))
10673 (match-string 4))
10674 (setq level (org-reduced-level
10675 (- (match-end 1) (match-beginning 1)))
10676 txt (org-link-display-format (match-string 4))
10677 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10678 re (format org-complex-heading-regexp-format
10679 (regexp-quote (match-string 4))))
10680 (when org-refile-use-outline-path
10681 (setq txt (mapconcat
10682 'org-protect-slash
10683 (append
10684 (if (eq org-refile-use-outline-path
10685 'file)
10686 (list (file-name-nondirectory
10687 (buffer-file-name
10688 (buffer-base-buffer))))
10689 (if (eq org-refile-use-outline-path
10690 'full-file-path)
10691 (list (buffer-file-name
10692 (buffer-base-buffer)))))
10693 (org-get-outline-path fast-path-p
10694 level txt)
10695 (list txt))
10696 "/")))
10697 (push (list txt f re (org-refile-marker (point)))
10698 tgs)))
10699 (when (= (point) pos0)
10700 ;; verification function has not moved point
10701 (goto-char (point-at-eol))))))))
10702 (when org-refile-use-cache
10703 (org-refile-cache-put tgs (buffer-file-name) descre))
10704 (setq targets (append tgs targets))
10705 ))))
10706 (message "Getting targets...done")
10707 (nreverse targets)))
10709 (defun org-protect-slash (s)
10710 (while (string-match "/" s)
10711 (setq s (replace-match "\\" t t s)))
10714 (defvar org-olpa (make-vector 20 nil))
10716 (defun org-get-outline-path (&optional fastp level heading)
10717 "Return the outline path to the current entry, as a list.
10719 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10720 routine which makes outline path derivations for an entire file,
10721 avoiding backtracing. Refile target collection makes use of that."
10722 (if fastp
10723 (progn
10724 (if (> level 19)
10725 (error "Outline path failure, more than 19 levels"))
10726 (loop for i from level upto 19 do
10727 (aset org-olpa i nil))
10728 (prog1
10729 (delq nil (append org-olpa nil))
10730 (aset org-olpa level heading)))
10731 (let (rtn case-fold-search)
10732 (save-excursion
10733 (save-restriction
10734 (widen)
10735 (while (org-up-heading-safe)
10736 (when (looking-at org-complex-heading-regexp)
10737 (push (org-match-string-no-properties 4) rtn)))
10738 rtn)))))
10740 (defun org-format-outline-path (path &optional width prefix)
10741 "Format the outline path PATH for display.
10742 Width is the maximum number of characters that is available.
10743 Prefix is a prefix to be included in the returned string,
10744 such as the file name."
10745 (setq width (or width 79))
10746 (if prefix (setq width (- width (length prefix))))
10747 (if (not path)
10748 (or prefix "")
10749 (let* ((nsteps (length path))
10750 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10751 (maxwidth (if (<= total-width width)
10752 10000 ;; everything fits
10753 ;; we need to shorten the level headings
10754 (/ (- width nsteps) nsteps)))
10755 (org-odd-levels-only nil)
10756 (n 0)
10757 (total (1+ (length prefix))))
10758 (setq maxwidth (max maxwidth 10))
10759 (concat prefix
10760 (mapconcat
10761 (lambda (h)
10762 (setq n (1+ n))
10763 (if (and (= n nsteps) (< maxwidth 10000))
10764 (setq maxwidth (- total-width total)))
10765 (if (< (length h) maxwidth)
10766 (progn (setq total (+ total (length h) 1)) h)
10767 (setq h (substring h 0 (- maxwidth 2))
10768 total (+ total maxwidth 1))
10769 (if (string-match "[ \t]+\\'" h)
10770 (setq h (substring h 0 (match-beginning 0))))
10771 (setq h (concat h "..")))
10772 (org-add-props h nil 'face
10773 (nth (% (1- n) org-n-level-faces)
10774 org-level-faces))
10776 path "/")))))
10778 (defun org-display-outline-path (&optional file current)
10779 "Display the current outline path in the echo area."
10780 (interactive "P")
10781 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10782 (case-fold-search nil)
10783 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10784 (if current (setq path (append path
10785 (save-excursion
10786 (org-back-to-heading t)
10787 (if (looking-at org-complex-heading-regexp)
10788 (list (match-string 4)))))))
10789 (message "%s"
10790 (org-format-outline-path
10791 path
10792 (1- (frame-width))
10793 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10795 (defvar org-refile-history nil
10796 "History for refiling operations.")
10798 (defvar org-after-refile-insert-hook nil
10799 "Hook run after `org-refile' has inserted its stuff at the new location.
10800 Note that this is still *before* the stuff will be removed from
10801 the *old* location.")
10803 (defvar org-capture-last-stored-marker)
10804 (defun org-refile (&optional goto default-buffer rfloc)
10805 "Move the entry or entries at point to another heading.
10806 The list of target headings is compiled using the information in
10807 `org-refile-targets', which see.
10809 At the target location, the entry is filed as a subitem of the target
10810 heading. Depending on `org-reverse-note-order', the new subitem will
10811 either be the first or the last subitem.
10813 If there is an active region, all entries in that region will be moved.
10814 However, the region must fulfill the requirement that the first heading
10815 is the first one sets the top-level of the moved text - at most siblings
10816 below it are allowed.
10818 With prefix arg GOTO, the command will only visit the target location
10819 and not actually move anything.
10821 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10822 go to the location where the last refiling operation has put the subtree.
10823 With a prefix argument of `2', refile to the running clock.
10825 RFLOC can be a refile location obtained in a different way.
10827 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10829 If you are using target caching (see `org-refile-use-cache'),
10830 you have to clear the target cache in order to find new targets.
10831 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10832 prefix argument (`C-u C-u C-u C-c C-w')."
10834 (interactive "P")
10835 (if (member goto '(0 (64)))
10836 (org-refile-cache-clear)
10837 (let* ((cbuf (current-buffer))
10838 (regionp (org-region-active-p))
10839 (region-start (and regionp (region-beginning)))
10840 (region-end (and regionp (region-end)))
10841 (region-length (and regionp (- region-end region-start)))
10842 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10843 pos it nbuf file re level reversed)
10844 (setq last-command nil)
10845 (when regionp
10846 (goto-char region-start)
10847 (or (bolp) (goto-char (point-at-bol)))
10848 (setq region-start (point))
10849 (unless (or (org-kill-is-subtree-p
10850 (buffer-substring region-start region-end))
10851 (prog1 org-refile-active-region-within-subtree
10852 (org-toggle-heading)))
10853 (error "The region is not a (sequence of) subtree(s)")))
10854 (if (equal goto '(16))
10855 (org-refile-goto-last-stored)
10856 (when (or
10857 (and (equal goto 2)
10858 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10859 (prog1
10860 (setq it (list (or org-clock-heading "running clock")
10861 (buffer-file-name
10862 (marker-buffer org-clock-hd-marker))
10864 (marker-position org-clock-hd-marker)))
10865 (setq goto nil)))
10866 (setq it (or rfloc
10867 (let (heading-text)
10868 (save-excursion
10869 (unless goto
10870 (org-back-to-heading t)
10871 (setq heading-text
10872 (nth 4 (org-heading-components))))
10873 (org-refile-get-location
10874 (cond (goto "Goto")
10875 (regionp "Refile region to")
10876 (t (concat "Refile subtree \""
10877 heading-text "\" to")))
10878 default-buffer
10879 (and (not (equal '(4) goto))
10880 org-refile-allow-creating-parent-nodes)
10881 goto))))))
10882 (setq file (nth 1 it)
10883 re (nth 2 it)
10884 pos (nth 3 it))
10885 (if (and (not goto)
10887 (equal (buffer-file-name) file)
10888 (if regionp
10889 (and (>= pos region-start)
10890 (<= pos region-end))
10891 (and (>= pos (point))
10892 (< pos (save-excursion
10893 (org-end-of-subtree t t))))))
10894 (error "Cannot refile to position inside the tree or region"))
10896 (setq nbuf (or (find-buffer-visiting file)
10897 (find-file-noselect file)))
10898 (if goto
10899 (progn
10900 (org-pop-to-buffer-same-window nbuf)
10901 (goto-char pos)
10902 (org-show-context 'org-goto))
10903 (if regionp
10904 (progn
10905 (org-kill-new (buffer-substring region-start region-end))
10906 (org-save-markers-in-region region-start region-end))
10907 (org-copy-subtree 1 nil t))
10908 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10909 (find-file-noselect file)))
10910 (setq reversed (org-notes-order-reversed-p))
10911 (save-excursion
10912 (save-restriction
10913 (widen)
10914 (if pos
10915 (progn
10916 (goto-char pos)
10917 (looking-at org-outline-regexp)
10918 (setq level (org-get-valid-level (funcall outline-level) 1))
10919 (goto-char
10920 (if reversed
10921 (or (outline-next-heading) (point-max))
10922 (or (save-excursion (org-get-next-sibling))
10923 (org-end-of-subtree t t)
10924 (point-max)))))
10925 (setq level 1)
10926 (if (not reversed)
10927 (goto-char (point-max))
10928 (goto-char (point-min))
10929 (or (outline-next-heading) (goto-char (point-max)))))
10930 (if (not (bolp)) (newline))
10931 (org-paste-subtree level)
10932 (when org-log-refile
10933 (org-add-log-setup 'refile nil nil 'findpos
10934 org-log-refile)
10935 (unless (eq org-log-refile 'note)
10936 (save-excursion (org-add-log-note))))
10937 (and org-auto-align-tags
10938 (let ((org-loop-over-headlines-in-active-region nil))
10939 (org-set-tags nil t)))
10940 (with-demoted-errors
10941 (bookmark-set "org-refile-last-stored"))
10942 ;; If we are refiling for capture, make sure that the
10943 ;; last-capture pointers point here
10944 (when (org-bound-and-true-p org-refile-for-capture)
10945 (with-demoted-errors
10946 (bookmark-set "org-capture-last-stored-marker"))
10947 (move-marker org-capture-last-stored-marker (point)))
10948 (if (fboundp 'deactivate-mark) (deactivate-mark))
10949 (run-hooks 'org-after-refile-insert-hook))))
10950 (if regionp
10951 (delete-region (point) (+ (point) region-length))
10952 (org-cut-subtree))
10953 (when (featurep 'org-inlinetask)
10954 (org-inlinetask-remove-END-maybe))
10955 (setq org-markers-to-move nil)
10956 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10958 (defun org-refile-goto-last-stored ()
10959 "Go to the location where the last refile was stored."
10960 (interactive)
10961 (bookmark-jump "org-refile-last-stored")
10962 (message "This is the location of the last refile"))
10964 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10965 no-exclude)
10966 "Prompt the user for a refile location, using PROMPT.
10967 PROMPT should not be suffixed with a colon and a space, because
10968 this function appends the default value from
10969 `org-refile-history' automatically, if that is not empty.
10970 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10971 this is used for the GOTO interface."
10972 (let ((org-refile-targets org-refile-targets)
10973 (org-refile-use-outline-path org-refile-use-outline-path)
10974 excluded-entries)
10975 (when (and (derived-mode-p 'org-mode)
10976 (not org-refile-use-cache)
10977 (not no-exclude))
10978 (org-map-tree
10979 (lambda()
10980 (setq excluded-entries
10981 (append excluded-entries (list (org-get-heading t t)))))))
10982 (setq org-refile-target-table
10983 (org-refile-get-targets default-buffer excluded-entries)))
10984 (unless org-refile-target-table
10985 (error "No refile targets"))
10986 (let* ((prompt (concat prompt
10987 (and (car org-refile-history)
10988 (concat " (default " (car org-refile-history) ")"))
10989 ": "))
10990 (cbuf (current-buffer))
10991 (partial-completion-mode nil)
10992 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10993 (cfunc (if (and org-refile-use-outline-path
10994 org-outline-path-complete-in-steps)
10995 'org-olpath-completing-read
10996 'org-icompleting-read))
10997 (extra (if org-refile-use-outline-path "/" ""))
10998 (filename (and cfn (expand-file-name cfn)))
10999 (tbl (mapcar
11000 (lambda (x)
11001 (if (and (not (member org-refile-use-outline-path
11002 '(file full-file-path)))
11003 (not (equal filename (nth 1 x))))
11004 (cons (concat (car x) extra " ("
11005 (file-name-nondirectory (nth 1 x)) ")")
11006 (cdr x))
11007 (cons (concat (car x) extra) (cdr x))))
11008 org-refile-target-table))
11009 (completion-ignore-case t)
11010 pa answ parent-target child parent old-hist)
11011 (setq old-hist org-refile-history)
11012 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11013 nil 'org-refile-history (car org-refile-history)))
11014 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11015 (org-refile-check-position pa)
11016 (if pa
11017 (progn
11018 (when (or (not org-refile-history)
11019 (not (eq old-hist org-refile-history))
11020 (not (equal (car pa) (car org-refile-history))))
11021 (setq org-refile-history
11022 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11023 org-refile-history
11024 (cdr org-refile-history))))
11025 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11026 (pop org-refile-history)))
11028 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11029 (progn
11030 (setq parent (match-string 1 answ)
11031 child (match-string 2 answ))
11032 (setq parent-target (or (assoc parent tbl)
11033 (assoc (concat parent "/") tbl)))
11034 (when (and parent-target
11035 (or (eq new-nodes t)
11036 (and (eq new-nodes 'confirm)
11037 (y-or-n-p (format "Create new node \"%s\"? "
11038 child)))))
11039 (org-refile-new-child parent-target child)))
11040 (error "Invalid target location")))))
11042 (declare-function org-string-nw-p "org-macs" (s))
11043 (defun org-refile-check-position (refile-pointer)
11044 "Check if the refile pointer matches the headline to which it points."
11045 (let* ((file (nth 1 refile-pointer))
11046 (re (nth 2 refile-pointer))
11047 (pos (nth 3 refile-pointer))
11048 buffer)
11049 (if (and (not (markerp pos)) (not file))
11050 (error "Please save the buffer to a file before refiling")
11051 (when (org-string-nw-p re)
11052 (setq buffer (if (markerp pos)
11053 (marker-buffer pos)
11054 (or (find-buffer-visiting file)
11055 (find-file-noselect file))))
11056 (with-current-buffer buffer
11057 (save-excursion
11058 (save-restriction
11059 (widen)
11060 (goto-char pos)
11061 (beginning-of-line 1)
11062 (unless (org-looking-at-p re)
11063 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11065 (defun org-refile-new-child (parent-target child)
11066 "Use refile target PARENT-TARGET to add new CHILD below it."
11067 (unless parent-target
11068 (error "Cannot find parent for new node"))
11069 (let ((file (nth 1 parent-target))
11070 (pos (nth 3 parent-target))
11071 level)
11072 (with-current-buffer (or (find-buffer-visiting file)
11073 (find-file-noselect file))
11074 (save-excursion
11075 (save-restriction
11076 (widen)
11077 (if pos
11078 (goto-char pos)
11079 (goto-char (point-max))
11080 (if (not (bolp)) (newline)))
11081 (when (looking-at org-outline-regexp)
11082 (setq level (funcall outline-level))
11083 (org-end-of-subtree t t))
11084 (org-back-over-empty-lines)
11085 (insert "\n" (make-string
11086 (if pos (org-get-valid-level level 1) 1) ?*)
11087 " " child "\n")
11088 (beginning-of-line 0)
11089 (list (concat (car parent-target) "/" child) file "" (point)))))))
11091 (defun org-olpath-completing-read (prompt collection &rest args)
11092 "Read an outline path like a file name."
11093 (let ((thetable collection)
11094 (org-completion-use-ido nil) ; does not work with ido.
11095 (org-completion-use-iswitchb nil)) ; or iswitchb
11096 (apply
11097 'org-icompleting-read prompt
11098 (lambda (string predicate &optional flag)
11099 (let (rtn r f (l (length string)))
11100 (cond
11101 ((eq flag nil)
11102 ;; try completion
11103 (try-completion string thetable))
11104 ((eq flag t)
11105 ;; all-completions
11106 (setq rtn (all-completions string thetable predicate))
11107 (mapcar
11108 (lambda (x)
11109 (setq r (substring x l))
11110 (if (string-match " ([^)]*)$" x)
11111 (setq f (match-string 0 x))
11112 (setq f ""))
11113 (if (string-match "/" r)
11114 (concat string (substring r 0 (match-end 0)) f)
11116 rtn))
11117 ((eq flag 'lambda)
11118 ;; exact match?
11119 (assoc string thetable)))))
11120 args)))
11122 ;;;; Dynamic blocks
11124 (defun org-find-dblock (name)
11125 "Find the first dynamic block with name NAME in the buffer.
11126 If not found, stay at current position and return nil."
11127 (let ((case-fold-search t) pos)
11128 (save-excursion
11129 (goto-char (point-min))
11130 (setq pos (and (re-search-forward
11131 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11132 (match-beginning 0))))
11133 (if pos (goto-char pos))
11134 pos))
11136 (defconst org-dblock-start-re
11137 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11138 "Matches the start line of a dynamic block, with parameters.")
11140 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11141 "Matches the end of a dynamic block.")
11143 (defun org-create-dblock (plist)
11144 "Create a dynamic block section, with parameters taken from PLIST.
11145 PLIST must contain a :name entry which is used as name of the block."
11146 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11147 (end-of-line 1)
11148 (newline))
11149 (let ((col (current-column))
11150 (name (plist-get plist :name)))
11151 (insert "#+BEGIN: " name)
11152 (while plist
11153 (if (eq (car plist) :name)
11154 (setq plist (cddr plist))
11155 (insert " " (prin1-to-string (pop plist)))))
11156 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11157 (beginning-of-line -2)))
11159 (defun org-prepare-dblock ()
11160 "Prepare dynamic block for refresh.
11161 This empties the block, puts the cursor at the insert position and returns
11162 the property list including an extra property :name with the block name."
11163 (unless (looking-at org-dblock-start-re)
11164 (error "Not at a dynamic block"))
11165 (let* ((begdel (1+ (match-end 0)))
11166 (name (org-no-properties (match-string 1)))
11167 (params (append (list :name name)
11168 (read (concat "(" (match-string 3) ")")))))
11169 (save-excursion
11170 (beginning-of-line 1)
11171 (skip-chars-forward " \t")
11172 (setq params (plist-put params :indentation-column (current-column))))
11173 (unless (re-search-forward org-dblock-end-re nil t)
11174 (error "Dynamic block not terminated"))
11175 (setq params
11176 (append params
11177 (list :content (buffer-substring
11178 begdel (match-beginning 0)))))
11179 (delete-region begdel (match-beginning 0))
11180 (goto-char begdel)
11181 (open-line 1)
11182 params))
11184 (defun org-map-dblocks (&optional command)
11185 "Apply COMMAND to all dynamic blocks in the current buffer.
11186 If COMMAND is not given, use `org-update-dblock'."
11187 (let ((cmd (or command 'org-update-dblock)))
11188 (save-excursion
11189 (goto-char (point-min))
11190 (while (re-search-forward org-dblock-start-re nil t)
11191 (goto-char (match-beginning 0))
11192 (save-excursion
11193 (condition-case nil
11194 (funcall cmd)
11195 (error (message "Error during update of dynamic block"))))
11196 (unless (re-search-forward org-dblock-end-re nil t)
11197 (error "Dynamic block not terminated"))))))
11199 (defun org-dblock-update (&optional arg)
11200 "User command for updating dynamic blocks.
11201 Update the dynamic block at point. With prefix ARG, update all dynamic
11202 blocks in the buffer."
11203 (interactive "P")
11204 (if arg
11205 (org-update-all-dblocks)
11206 (or (looking-at org-dblock-start-re)
11207 (org-beginning-of-dblock))
11208 (org-update-dblock)))
11210 (defun org-update-dblock ()
11211 "Update the dynamic block at point.
11212 This means to empty the block, parse for parameters and then call
11213 the correct writing function."
11214 (interactive)
11215 (save-window-excursion
11216 (let* ((pos (point))
11217 (line (org-current-line))
11218 (params (org-prepare-dblock))
11219 (name (plist-get params :name))
11220 (indent (plist-get params :indentation-column))
11221 (cmd (intern (concat "org-dblock-write:" name))))
11222 (message "Updating dynamic block `%s' at line %d..." name line)
11223 (funcall cmd params)
11224 (message "Updating dynamic block `%s' at line %d...done" name line)
11225 (goto-char pos)
11226 (when (and indent (> indent 0))
11227 (setq indent (make-string indent ?\ ))
11228 (save-excursion
11229 (org-beginning-of-dblock)
11230 (forward-line 1)
11231 (while (not (looking-at org-dblock-end-re))
11232 (insert indent)
11233 (beginning-of-line 2))
11234 (when (looking-at org-dblock-end-re)
11235 (and (looking-at "[ \t]+")
11236 (replace-match ""))
11237 (insert indent)))))))
11239 (defun org-beginning-of-dblock ()
11240 "Find the beginning of the dynamic block at point.
11241 Error if there is no such block at point."
11242 (let ((pos (point))
11243 beg)
11244 (end-of-line 1)
11245 (if (and (re-search-backward org-dblock-start-re nil t)
11246 (setq beg (match-beginning 0))
11247 (re-search-forward org-dblock-end-re nil t)
11248 (> (match-end 0) pos))
11249 (goto-char beg)
11250 (goto-char pos)
11251 (error "Not in a dynamic block"))))
11253 (defun org-update-all-dblocks ()
11254 "Update all dynamic blocks in the buffer.
11255 This function can be used in a hook."
11256 (interactive)
11257 (when (derived-mode-p 'org-mode)
11258 (org-map-dblocks 'org-update-dblock)))
11261 ;;;; Completion
11263 (defconst org-additional-option-like-keywords
11264 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11265 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11266 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11267 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11268 "BEGIN:" "END:"
11269 "ORGTBL" "TBLFM:" "TBLNAME:"
11270 "BEGIN_EXAMPLE" "END_EXAMPLE"
11271 "BEGIN_VERBATIM" "END_VERBATIM"
11272 "BEGIN_QUOTE" "END_QUOTE"
11273 "BEGIN_VERSE" "END_VERSE"
11274 "BEGIN_CENTER" "END_CENTER"
11275 "BEGIN_SRC" "END_SRC"
11276 "BEGIN_RESULT" "END_RESULT"
11277 "BEGIN_lstlisting" "END_lstlisting"
11278 "NAME:" "RESULTS:"
11279 "HEADER:" "HEADERS:"
11280 "COLUMNS:" "PROPERTY:"
11281 "CAPTION:" "LABEL:"
11282 "SETUPFILE:"
11283 "INCLUDE:" "INDEX:"
11284 "BIND:"
11285 "MACRO:"))
11287 (defconst org-options-keywords
11288 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11289 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11290 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11291 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11292 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11293 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11294 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11296 (defconst org-additional-option-like-keywords-for-flyspell
11297 (delete-dups
11298 (split-string
11299 (mapconcat (lambda(k)
11300 (replace-regexp-in-string
11301 "_\\|:" " "
11302 (concat k " " (downcase k) " " (upcase k))))
11303 (append org-options-keywords org-additional-option-like-keywords)
11304 " ")
11305 " +" t)))
11307 (defcustom org-structure-template-alist
11308 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11309 "<src lang=\"?\">\n\n</src>")
11310 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11311 "<example>\n?\n</example>")
11312 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11313 "<quote>\n?\n</quote>")
11314 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11315 "<verse>\n?\n</verse>")
11316 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11317 "<verbatim>\n?\n</verbatim>")
11318 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11319 "<center>\n?\n</center>")
11320 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11321 "<literal style=\"latex\">\n?\n</literal>")
11322 ("L" "#+LaTeX: "
11323 "<literal style=\"latex\">?</literal>")
11324 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11325 "<literal style=\"html\">\n?\n</literal>")
11326 ("H" "#+HTML: "
11327 "<literal style=\"html\">?</literal>")
11328 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11329 ("A" "#+ASCII: ")
11330 ("i" "#+INDEX: ?"
11331 "#+INDEX: ?")
11332 ("I" "#+INCLUDE: %file ?"
11333 "<include file=%file markup=\"?\">"))
11334 "Structure completion elements.
11335 This is a list of abbreviation keys and values. The value gets inserted
11336 if you type `<' followed by the key and then press the completion key,
11337 usually `M-TAB'. %file will be replaced by a file name after prompting
11338 for the file using completion. The cursor will be placed at the position
11339 of the `?` in the template.
11340 There are two templates for each key, the first uses the original Org syntax,
11341 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11342 the default when the /org-mtags.el/ module has been loaded. See also the
11343 variable `org-mtags-prefer-muse-templates'."
11344 :group 'org-completion
11345 :type '(repeat
11346 (string :tag "Key")
11347 (string :tag "Template")
11348 (string :tag "Muse Template")))
11350 (defun org-try-structure-completion ()
11351 "Try to complete a structure template before point.
11352 This looks for strings like \"<e\" on an otherwise empty line and
11353 expands them."
11354 (let ((l (buffer-substring (point-at-bol) (point)))
11356 (when (and (looking-at "[ \t]*$")
11357 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11358 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11359 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11360 (match-beginning 1)) a)
11361 t)))
11363 (defun org-complete-expand-structure-template (start cell)
11364 "Expand a structure template."
11365 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11366 (rpl (nth (if musep 2 1) cell))
11367 (ind ""))
11368 (delete-region start (point))
11369 (when (string-match "\\`#\\+" rpl)
11370 (cond
11371 ((bolp))
11372 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11373 (setq ind (buffer-substring (point-at-bol) (point))))
11374 (t (newline))))
11375 (setq start (point))
11376 (if (string-match "%file" rpl)
11377 (setq rpl (replace-match
11378 (concat
11379 "\""
11380 (save-match-data
11381 (abbreviate-file-name (read-file-name "Include file: ")))
11382 "\"")
11383 t t rpl)))
11384 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11385 (concat "\n" ind)))
11386 (insert rpl)
11387 (if (re-search-backward "\\?" start t) (delete-char 1))))
11389 ;;;; TODO, DEADLINE, Comments
11391 (defun org-toggle-comment ()
11392 "Change the COMMENT state of an entry."
11393 (interactive)
11394 (save-excursion
11395 (org-back-to-heading)
11396 (let (case-fold-search)
11397 (cond
11398 ((looking-at (format org-heading-keyword-regexp-format
11399 org-comment-string))
11400 (goto-char (match-end 1))
11401 (looking-at (concat " +" org-comment-string))
11402 (replace-match "" t t)
11403 (when (eolp) (insert " ")))
11404 ((looking-at org-outline-regexp)
11405 (goto-char (match-end 0))
11406 (insert org-comment-string " "))))))
11408 (defvar org-last-todo-state-is-todo nil
11409 "This is non-nil when the last TODO state change led to a TODO state.
11410 If the last change removed the TODO tag or switched to DONE, then
11411 this is nil.")
11413 (defvar org-setting-tags nil) ; dynamically skipped
11415 (defvar org-todo-setup-filter-hook nil
11416 "Hook for functions that pre-filter todo specs.
11417 Each function takes a todo spec and returns either nil or the spec
11418 transformed into canonical form." )
11420 (defvar org-todo-get-default-hook nil
11421 "Hook for functions that get a default item for todo.
11422 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11423 nil or a string to be used for the todo mark." )
11425 (defvar org-agenda-headline-snapshot-before-repeat)
11427 (defun org-current-effective-time ()
11428 "Return current time adjusted for `org-extend-today-until' variable."
11429 (let* ((ct (org-current-time))
11430 (dct (decode-time ct))
11431 (ct1
11432 (if (and org-use-effective-time
11433 (< (nth 2 dct) org-extend-today-until))
11434 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11435 ct)))
11436 ct1))
11438 (defun org-todo-yesterday (&optional arg)
11439 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11440 (interactive "P")
11441 (if (eq major-mode 'org-agenda-mode)
11442 (apply 'org-agenda-todo-yesterday arg)
11443 (let* ((hour (third (decode-time
11444 (org-current-time))))
11445 (org-extend-today-until (1+ hour)))
11446 (org-todo arg))))
11448 (defun org-todo (&optional arg)
11449 "Change the TODO state of an item.
11450 The state of an item is given by a keyword at the start of the heading,
11451 like
11452 *** TODO Write paper
11453 *** DONE Call mom
11455 The different keywords are specified in the variable `org-todo-keywords'.
11456 By default the available states are \"TODO\" and \"DONE\".
11457 So for this example: when the item starts with TODO, it is changed to DONE.
11458 When it starts with DONE, the DONE is removed. And when neither TODO nor
11459 DONE are present, add TODO at the beginning of the heading.
11461 With \\[universal-argument] prefix arg, use completion to determine the new \
11462 state.
11463 With numeric prefix arg, switch to that state.
11464 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11465 keywords (nextset).
11466 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11467 With a numeric prefix arg of 0, inhibit note taking for the change.
11469 For calling through lisp, arg is also interpreted in the following way:
11470 'none -> empty state
11471 \"\"(empty string) -> switch to empty state
11472 'done -> switch to DONE
11473 'nextset -> switch to the next set of keywords
11474 'previousset -> switch to the previous set of keywords
11475 \"WAITING\" -> switch to the specified keyword, but only if it
11476 really is a member of `org-todo-keywords'."
11477 (interactive "P")
11478 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11479 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11480 'region-start-level 'region))
11481 org-loop-over-headlines-in-active-region)
11482 (org-map-entries
11483 `(org-todo ,arg)
11484 org-loop-over-headlines-in-active-region
11485 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11486 (if (equal arg '(16)) (setq arg 'nextset))
11487 (let ((org-blocker-hook org-blocker-hook)
11488 commentp
11489 case-fold-search)
11490 (when (equal arg '(64))
11491 (setq arg nil org-blocker-hook nil))
11492 (when (and org-blocker-hook
11493 (or org-inhibit-blocking
11494 (org-entry-get nil "NOBLOCKING")))
11495 (setq org-blocker-hook nil))
11496 (save-excursion
11497 (catch 'exit
11498 (org-back-to-heading t)
11499 (when (looking-at (concat "^\\*+ " org-comment-string))
11500 (org-toggle-comment)
11501 (setq commentp t))
11502 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11503 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11504 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11505 (let* ((match-data (match-data))
11506 (startpos (point-at-bol))
11507 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11508 (org-log-done org-log-done)
11509 (org-log-repeat org-log-repeat)
11510 (org-todo-log-states org-todo-log-states)
11511 (org-inhibit-logging
11512 (if (equal arg 0)
11513 (progn (setq arg nil) 'note) org-inhibit-logging))
11514 (this (match-string 1))
11515 (hl-pos (match-beginning 0))
11516 (head (org-get-todo-sequence-head this))
11517 (ass (assoc head org-todo-kwd-alist))
11518 (interpret (nth 1 ass))
11519 (done-word (nth 3 ass))
11520 (final-done-word (nth 4 ass))
11521 (org-last-state (or this ""))
11522 (completion-ignore-case t)
11523 (member (member this org-todo-keywords-1))
11524 (tail (cdr member))
11525 (org-state (cond
11526 ((and org-todo-key-trigger
11527 (or (and (equal arg '(4))
11528 (eq org-use-fast-todo-selection 'prefix))
11529 (and (not arg) org-use-fast-todo-selection
11530 (not (eq org-use-fast-todo-selection
11531 'prefix)))))
11532 ;; Use fast selection
11533 (org-fast-todo-selection))
11534 ((and (equal arg '(4))
11535 (or (not org-use-fast-todo-selection)
11536 (not org-todo-key-trigger)))
11537 ;; Read a state with completion
11538 (org-icompleting-read
11539 "State: " (mapcar (lambda(x) (list x))
11540 org-todo-keywords-1)
11541 nil t))
11542 ((eq arg 'right)
11543 (if this
11544 (if tail (car tail) nil)
11545 (car org-todo-keywords-1)))
11546 ((eq arg 'left)
11547 (if (equal member org-todo-keywords-1)
11549 (if this
11550 (nth (- (length org-todo-keywords-1)
11551 (length tail) 2)
11552 org-todo-keywords-1)
11553 (org-last org-todo-keywords-1))))
11554 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11555 (setq arg nil))) ; hack to fall back to cycling
11556 (arg
11557 ;; user or caller requests a specific state
11558 (cond
11559 ((equal arg "") nil)
11560 ((eq arg 'none) nil)
11561 ((eq arg 'done) (or done-word (car org-done-keywords)))
11562 ((eq arg 'nextset)
11563 (or (car (cdr (member head org-todo-heads)))
11564 (car org-todo-heads)))
11565 ((eq arg 'previousset)
11566 (let ((org-todo-heads (reverse org-todo-heads)))
11567 (or (car (cdr (member head org-todo-heads)))
11568 (car org-todo-heads))))
11569 ((car (member arg org-todo-keywords-1)))
11570 ((stringp arg)
11571 (error "State `%s' not valid in this file" arg))
11572 ((nth (1- (prefix-numeric-value arg))
11573 org-todo-keywords-1))))
11574 ((null member) (or head (car org-todo-keywords-1)))
11575 ((equal this final-done-word) nil) ;; -> make empty
11576 ((null tail) nil) ;; -> first entry
11577 ((memq interpret '(type priority))
11578 (if (eq this-command last-command)
11579 (car tail)
11580 (if (> (length tail) 0)
11581 (or done-word (car org-done-keywords))
11582 nil)))
11584 (car tail))))
11585 (org-state (or
11586 (run-hook-with-args-until-success
11587 'org-todo-get-default-hook org-state org-last-state)
11588 org-state))
11589 (next (if org-state (concat " " org-state " ") " "))
11590 (change-plist (list :type 'todo-state-change :from this :to org-state
11591 :position startpos))
11592 dolog now-done-p)
11593 (when org-blocker-hook
11594 (setq org-last-todo-state-is-todo
11595 (not (member this org-done-keywords)))
11596 (unless (save-excursion
11597 (save-match-data
11598 (org-with-wide-buffer
11599 (run-hook-with-args-until-failure
11600 'org-blocker-hook change-plist))))
11601 (if (org-called-interactively-p 'interactive)
11602 (error "TODO state change from %s to %s blocked" this org-state)
11603 ;; fail silently
11604 (message "TODO state change from %s to %s blocked" this org-state)
11605 (throw 'exit nil))))
11606 (store-match-data match-data)
11607 (replace-match next t t)
11608 (unless (pos-visible-in-window-p hl-pos)
11609 (message "TODO state changed to %s" (org-trim next)))
11610 (unless head
11611 (setq head (org-get-todo-sequence-head org-state)
11612 ass (assoc head org-todo-kwd-alist)
11613 interpret (nth 1 ass)
11614 done-word (nth 3 ass)
11615 final-done-word (nth 4 ass)))
11616 (when (memq arg '(nextset previousset))
11617 (message "Keyword-Set %d/%d: %s"
11618 (- (length org-todo-sets) -1
11619 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11620 (length org-todo-sets)
11621 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11622 (setq org-last-todo-state-is-todo
11623 (not (member org-state org-done-keywords)))
11624 (setq now-done-p (and (member org-state org-done-keywords)
11625 (not (member this org-done-keywords))))
11626 (and logging (org-local-logging logging))
11627 (when (and (or org-todo-log-states org-log-done)
11628 (not (eq org-inhibit-logging t))
11629 (not (memq arg '(nextset previousset))))
11630 ;; we need to look at recording a time and note
11631 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11632 (nth 2 (assoc this org-todo-log-states))))
11633 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11634 (setq dolog 'time))
11635 (when (and org-state
11636 (member org-state org-not-done-keywords)
11637 (not (member this org-not-done-keywords)))
11638 ;; This is now a todo state and was not one before
11639 ;; If there was a CLOSED time stamp, get rid of it.
11640 (org-add-planning-info nil nil 'closed))
11641 (when (and now-done-p org-log-done)
11642 ;; It is now done, and it was not done before
11643 (org-add-planning-info 'closed (org-current-effective-time))
11644 (if (and (not dolog) (eq 'note org-log-done))
11645 (org-add-log-setup 'done org-state this 'findpos 'note)))
11646 (when (and org-state dolog)
11647 ;; This is a non-nil state, and we need to log it
11648 (org-add-log-setup 'state org-state this 'findpos dolog)))
11649 ;; Fixup tag positioning
11650 (org-todo-trigger-tag-changes org-state)
11651 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11652 (when org-provide-todo-statistics
11653 (org-update-parent-todo-statistics))
11654 (run-hooks 'org-after-todo-state-change-hook)
11655 (if (and arg (not (member org-state org-done-keywords)))
11656 (setq head (org-get-todo-sequence-head org-state)))
11657 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11658 ;; Do we need to trigger a repeat?
11659 (when now-done-p
11660 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11661 ;; This is for the agenda, take a snapshot of the headline.
11662 (save-match-data
11663 (setq org-agenda-headline-snapshot-before-repeat
11664 (org-get-heading))))
11665 (org-auto-repeat-maybe org-state))
11666 ;; Fixup cursor location if close to the keyword
11667 (if (and (outline-on-heading-p)
11668 (not (bolp))
11669 (save-excursion (beginning-of-line 1)
11670 (looking-at org-todo-line-regexp))
11671 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11672 (progn
11673 (goto-char (or (match-end 2) (match-end 1)))
11674 (and (looking-at " ") (just-one-space))))
11675 (when org-trigger-hook
11676 (save-excursion
11677 (run-hook-with-args 'org-trigger-hook change-plist)))
11678 (when commentp (org-toggle-comment))))))))
11680 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11681 "Block turning an entry into a TODO, using the hierarchy.
11682 This checks whether the current task should be blocked from state
11683 changes. Such blocking occurs when:
11685 1. The task has children which are not all in a completed state.
11687 2. A task has a parent with the property :ORDERED:, and there
11688 are siblings prior to the current task with incomplete
11689 status.
11691 3. The parent of the task is blocked because it has siblings that should
11692 be done first, or is child of a block grandparent TODO entry."
11694 (if (not org-enforce-todo-dependencies)
11695 t ; if locally turned off don't block
11696 (catch 'dont-block
11697 ;; If this is not a todo state change, or if this entry is already DONE,
11698 ;; do not block
11699 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11700 (member (plist-get change-plist :from)
11701 (cons 'done org-done-keywords))
11702 (member (plist-get change-plist :to)
11703 (cons 'todo org-not-done-keywords))
11704 (not (plist-get change-plist :to)))
11705 (throw 'dont-block t))
11706 ;; If this task has children, and any are undone, it's blocked
11707 (save-excursion
11708 (org-back-to-heading t)
11709 (let ((this-level (funcall outline-level)))
11710 (outline-next-heading)
11711 (let ((child-level (funcall outline-level)))
11712 (while (and (not (eobp))
11713 (> child-level this-level))
11714 ;; this todo has children, check whether they are all
11715 ;; completed
11716 (if (and (not (org-entry-is-done-p))
11717 (org-entry-is-todo-p))
11718 (throw 'dont-block nil))
11719 (outline-next-heading)
11720 (setq child-level (funcall outline-level))))))
11721 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11722 ;; any previous siblings are undone, it's blocked
11723 (save-excursion
11724 (org-back-to-heading t)
11725 (let* ((pos (point))
11726 (parent-pos (and (org-up-heading-safe) (point))))
11727 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11728 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11729 (forward-line 1)
11730 (re-search-forward org-not-done-heading-regexp pos t))
11731 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11732 ;; Search further up the hierarchy, to see if an ancestor is blocked
11733 (while t
11734 (goto-char parent-pos)
11735 (if (not (looking-at org-not-done-heading-regexp))
11736 (throw 'dont-block t)) ; do not block, parent is not a TODO
11737 (setq pos (point))
11738 (setq parent-pos (and (org-up-heading-safe) (point)))
11739 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11740 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11741 (forward-line 1)
11742 (re-search-forward org-not-done-heading-regexp pos t))
11743 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11745 (defcustom org-track-ordered-property-with-tag nil
11746 "Should the ORDERED property also be shown as a tag?
11747 The ORDERED property decides if an entry should require subtasks to be
11748 completed in sequence. Since a property is not very visible, setting
11749 this option means that toggling the ORDERED property with the command
11750 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11751 not relevant for the behavior, but it makes things more visible.
11753 Note that toggling the tag with tags commands will not change the property
11754 and therefore not influence behavior!
11756 This can be t, meaning the tag ORDERED should be used, It can also be a
11757 string to select a different tag for this task."
11758 :group 'org-todo
11759 :type '(choice
11760 (const :tag "No tracking" nil)
11761 (const :tag "Track with ORDERED tag" t)
11762 (string :tag "Use other tag")))
11764 (defun org-toggle-ordered-property ()
11765 "Toggle the ORDERED property of the current entry.
11766 For better visibility, you can track the value of this property with a tag.
11767 See variable `org-track-ordered-property-with-tag'."
11768 (interactive)
11769 (let* ((t1 org-track-ordered-property-with-tag)
11770 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11771 (save-excursion
11772 (org-back-to-heading)
11773 (if (org-entry-get nil "ORDERED")
11774 (progn
11775 (org-delete-property "ORDERED")
11776 (and tag (org-toggle-tag tag 'off))
11777 (message "Subtasks can be completed in arbitrary order"))
11778 (org-entry-put nil "ORDERED" "t")
11779 (and tag (org-toggle-tag tag 'on))
11780 (message "Subtasks must be completed in sequence")))))
11782 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11783 (defun org-block-todo-from-checkboxes (change-plist)
11784 "Block turning an entry into a TODO, using checkboxes.
11785 This checks whether the current task should be blocked from state
11786 changes because there are unchecked boxes in this entry."
11787 (if (not org-enforce-todo-checkbox-dependencies)
11788 t ; if locally turned off don't block
11789 (catch 'dont-block
11790 ;; If this is not a todo state change, or if this entry is already DONE,
11791 ;; do not block
11792 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11793 (member (plist-get change-plist :from)
11794 (cons 'done org-done-keywords))
11795 (member (plist-get change-plist :to)
11796 (cons 'todo org-not-done-keywords))
11797 (not (plist-get change-plist :to)))
11798 (throw 'dont-block t))
11799 ;; If this task has checkboxes that are not checked, it's blocked
11800 (save-excursion
11801 (org-back-to-heading t)
11802 (let ((beg (point)) end)
11803 (outline-next-heading)
11804 (setq end (point))
11805 (goto-char beg)
11806 (if (org-list-search-forward
11807 (concat (org-item-beginning-re)
11808 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11809 "\\[[- ]\\]")
11810 end t)
11811 (progn
11812 (if (boundp 'org-blocked-by-checkboxes)
11813 (setq org-blocked-by-checkboxes t))
11814 (throw 'dont-block nil)))))
11815 t))) ; do not block
11817 (defun org-entry-blocked-p ()
11818 "Is the current entry blocked?"
11819 (org-with-buffer-modified-unmodified
11820 (if (org-entry-get nil "NOBLOCKING")
11821 nil ;; Never block this entry
11822 (not
11823 (run-hook-with-args-until-failure
11824 'org-blocker-hook
11825 (list :type 'todo-state-change
11826 :position (point)
11827 :from 'todo
11828 :to 'done))))))
11830 (defun org-update-statistics-cookies (all)
11831 "Update the statistics cookie, either from TODO or from checkboxes.
11832 This should be called with the cursor in a line with a statistics cookie."
11833 (interactive "P")
11834 (if all
11835 (progn
11836 (org-update-checkbox-count 'all)
11837 (org-map-entries 'org-update-parent-todo-statistics))
11838 (if (not (org-at-heading-p))
11839 (org-update-checkbox-count)
11840 (let ((pos (point-marker))
11841 end l1 l2)
11842 (ignore-errors (org-back-to-heading t))
11843 (if (not (org-at-heading-p))
11844 (org-update-checkbox-count)
11845 (setq l1 (org-outline-level))
11846 (setq end (save-excursion
11847 (outline-next-heading)
11848 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11849 (point)))
11850 (if (and (save-excursion
11851 (re-search-forward
11852 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11853 (not (save-excursion (re-search-forward
11854 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11855 (org-update-checkbox-count)
11856 (if (and l2 (> l2 l1))
11857 (progn
11858 (goto-char end)
11859 (org-update-parent-todo-statistics))
11860 (goto-char pos)
11861 (beginning-of-line 1)
11862 (while (re-search-forward
11863 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11864 (point-at-eol) t)
11865 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11866 (goto-char pos)
11867 (move-marker pos nil)))))
11869 (defvar org-entry-property-inherited-from) ;; defined below
11870 (defun org-update-parent-todo-statistics ()
11871 "Update any statistics cookie in the parent of the current headline.
11872 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11873 the entire subtree and this will travel up the hierarchy and update
11874 statistics everywhere."
11875 (let* ((prop (save-excursion (org-up-heading-safe)
11876 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11877 (recursive (or (not org-hierarchical-todo-statistics)
11878 (and prop (string-match "\\<recursive\\>" prop))))
11879 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11881 (first t)
11882 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11883 level ltoggle l1 new ndel
11884 (cnt-all 0) (cnt-done 0) is-percent kwd
11885 checkbox-beg ov ovs ove cookie-present)
11886 (catch 'exit
11887 (save-excursion
11888 (beginning-of-line 1)
11889 (setq ltoggle (funcall outline-level))
11890 ;; Three situations are to consider:
11892 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11893 ;; to the top-level ancestor on the headline;
11895 ;; 2. If parent has "recursive" property, repeat up to the
11896 ;; headline setting that property, taking inheritance into
11897 ;; account;
11899 ;; 3. Else, move up to direct parent and proceed only once.
11900 (while (and (setq level (org-up-heading-safe))
11901 (or recursive first)
11902 (>= (point) lim))
11903 (setq first nil cookie-present nil)
11904 (unless (and level
11905 (not (string-match
11906 "\\<checkbox\\>"
11907 (downcase (or (org-entry-get nil "COOKIE_DATA")
11908 "")))))
11909 (throw 'exit nil))
11910 (while (re-search-forward box-re (point-at-eol) t)
11911 (setq cnt-all 0 cnt-done 0 cookie-present t)
11912 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11913 (save-match-data
11914 (unless (outline-next-heading) (throw 'exit nil))
11915 (while (and (looking-at org-complex-heading-regexp)
11916 (> (setq l1 (length (match-string 1))) level))
11917 (setq kwd (and (or recursive (= l1 ltoggle))
11918 (match-string 2)))
11919 (if (or (eq org-provide-todo-statistics 'all-headlines)
11920 (and (listp org-provide-todo-statistics)
11921 (or (member kwd org-provide-todo-statistics)
11922 (member kwd org-done-keywords))))
11923 (setq cnt-all (1+ cnt-all))
11924 (if (eq org-provide-todo-statistics t)
11925 (and kwd (setq cnt-all (1+ cnt-all)))))
11926 (and (member kwd org-done-keywords)
11927 (setq cnt-done (1+ cnt-done)))
11928 (outline-next-heading)))
11929 (setq new
11930 (if is-percent
11931 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11932 (format "[%d/%d]" cnt-done cnt-all))
11933 ndel (- (match-end 0) checkbox-beg))
11934 ;; handle overlays when updating cookie from column view
11935 (when (setq ov (car (overlays-at checkbox-beg)))
11936 (setq ovs (overlay-start ov) ove (overlay-end ov))
11937 (delete-overlay ov))
11938 (goto-char checkbox-beg)
11939 (insert new)
11940 (delete-region (point) (+ (point) ndel))
11941 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11942 (when ov (move-overlay ov ovs ove)))
11943 (when cookie-present
11944 (run-hook-with-args 'org-after-todo-statistics-hook
11945 cnt-done (- cnt-all cnt-done))))))
11946 (run-hooks 'org-todo-statistics-hook)))
11948 (defvar org-after-todo-statistics-hook nil
11949 "Hook that is called after a TODO statistics cookie has been updated.
11950 Each function is called with two arguments: the number of not-done entries
11951 and the number of done entries.
11953 For example, the following function, when added to this hook, will switch
11954 an entry to DONE when all children are done, and back to TODO when new
11955 entries are set to a TODO status. Note that this hook is only called
11956 when there is a statistics cookie in the headline!
11958 (defun org-summary-todo (n-done n-not-done)
11959 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11960 (let (org-log-done org-log-states) ; turn off logging
11961 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11964 (defvar org-todo-statistics-hook nil
11965 "Hook that is run whenever Org thinks TODO statistics should be updated.
11966 This hook runs even if there is no statistics cookie present, in which case
11967 `org-after-todo-statistics-hook' would not run.")
11969 (defun org-todo-trigger-tag-changes (state)
11970 "Apply the changes defined in `org-todo-state-tags-triggers'."
11971 (let ((l org-todo-state-tags-triggers)
11972 changes)
11973 (when (or (not state) (equal state ""))
11974 (setq changes (append changes (cdr (assoc "" l)))))
11975 (when (and (stringp state) (> (length state) 0))
11976 (setq changes (append changes (cdr (assoc state l)))))
11977 (when (member state org-not-done-keywords)
11978 (setq changes (append changes (cdr (assoc 'todo l)))))
11979 (when (member state org-done-keywords)
11980 (setq changes (append changes (cdr (assoc 'done l)))))
11981 (dolist (c changes)
11982 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11984 (defun org-local-logging (value)
11985 "Get logging settings from a property VALUE."
11986 (let* (words w a)
11987 ;; directly set the variables, they are already local.
11988 (setq org-log-done nil
11989 org-log-repeat nil
11990 org-todo-log-states nil)
11991 (setq words (org-split-string value))
11992 (while (setq w (pop words))
11993 (cond
11994 ((setq a (assoc w org-startup-options))
11995 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11996 (set (nth 1 a) (nth 2 a))))
11997 ((setq a (org-extract-log-state-settings w))
11998 (and (member (car a) org-todo-keywords-1)
11999 (push a org-todo-log-states)))))))
12001 (defun org-get-todo-sequence-head (kwd)
12002 "Return the head of the TODO sequence to which KWD belongs.
12003 If KWD is not set, check if there is a text property remembering the
12004 right sequence."
12005 (let (p)
12006 (cond
12007 ((not kwd)
12008 (or (get-text-property (point-at-bol) 'org-todo-head)
12009 (progn
12010 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12011 nil (point-at-eol)))
12012 (get-text-property p 'org-todo-head))))
12013 ((not (member kwd org-todo-keywords-1))
12014 (car org-todo-keywords-1))
12015 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12017 (defun org-fast-todo-selection ()
12018 "Fast TODO keyword selection with single keys.
12019 Returns the new TODO keyword, or nil if no state change should occur."
12020 (let* ((fulltable org-todo-key-alist)
12021 (done-keywords org-done-keywords) ;; needed for the faces.
12022 (maxlen (apply 'max (mapcar
12023 (lambda (x)
12024 (if (stringp (car x)) (string-width (car x)) 0))
12025 fulltable)))
12026 (expert nil)
12027 (fwidth (+ maxlen 3 1 3))
12028 (ncol (/ (- (window-width) 4) fwidth))
12029 tg cnt e c tbl
12030 groups ingroup)
12031 (save-excursion
12032 (save-window-excursion
12033 (if expert
12034 (set-buffer (get-buffer-create " *Org todo*"))
12035 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12036 (erase-buffer)
12037 (org-set-local 'org-done-keywords done-keywords)
12038 (setq tbl fulltable cnt 0)
12039 (while (setq e (pop tbl))
12040 (cond
12041 ((equal e '(:startgroup))
12042 (push '() groups) (setq ingroup t)
12043 (when (not (= cnt 0))
12044 (setq cnt 0)
12045 (insert "\n"))
12046 (insert "{ "))
12047 ((equal e '(:endgroup))
12048 (setq ingroup nil cnt 0)
12049 (insert "}\n"))
12050 ((equal e '(:newline))
12051 (when (not (= cnt 0))
12052 (setq cnt 0)
12053 (insert "\n")
12054 (setq e (car tbl))
12055 (while (equal (car tbl) '(:newline))
12056 (insert "\n")
12057 (setq tbl (cdr tbl)))))
12059 (setq tg (car e) c (cdr e))
12060 (if ingroup (push tg (car groups)))
12061 (setq tg (org-add-props tg nil 'face
12062 (org-get-todo-face tg)))
12063 (if (and (= cnt 0) (not ingroup)) (insert " "))
12064 (insert "[" c "] " tg (make-string
12065 (- fwidth 4 (length tg)) ?\ ))
12066 (when (= (setq cnt (1+ cnt)) ncol)
12067 (insert "\n")
12068 (if ingroup (insert " "))
12069 (setq cnt 0)))))
12070 (insert "\n")
12071 (goto-char (point-min))
12072 (if (not expert) (org-fit-window-to-buffer))
12073 (message "[a-z..]:Set [SPC]:clear")
12074 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12075 (cond
12076 ((or (= c ?\C-g)
12077 (and (= c ?q) (not (rassoc c fulltable))))
12078 (setq quit-flag t))
12079 ((= c ?\ ) nil)
12080 ((setq e (rassoc c fulltable) tg (car e))
12082 (t (setq quit-flag t)))))))
12084 (defun org-entry-is-todo-p ()
12085 (member (org-get-todo-state) org-not-done-keywords))
12087 (defun org-entry-is-done-p ()
12088 (member (org-get-todo-state) org-done-keywords))
12090 (defun org-get-todo-state ()
12091 (save-excursion
12092 (org-back-to-heading t)
12093 (and (looking-at org-todo-line-regexp)
12094 (match-end 2)
12095 (match-string 2))))
12097 (defun org-at-date-range-p (&optional inactive-ok)
12098 "Is the cursor inside a date range?"
12099 (interactive)
12100 (save-excursion
12101 (catch 'exit
12102 (let ((pos (point)))
12103 (skip-chars-backward "^[<\r\n")
12104 (skip-chars-backward "<[")
12105 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12106 (>= (match-end 0) pos)
12107 (throw 'exit t))
12108 (skip-chars-backward "^<[\r\n")
12109 (skip-chars-backward "<[")
12110 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12111 (>= (match-end 0) pos)
12112 (throw 'exit t)))
12113 nil)))
12115 (defun org-get-repeat (&optional tagline)
12116 "Check if there is a deadline/schedule with repeater in this entry."
12117 (save-match-data
12118 (save-excursion
12119 (org-back-to-heading t)
12120 (and (re-search-forward (if tagline
12121 (concat tagline "\\s-*" org-repeat-re)
12122 org-repeat-re)
12123 (org-entry-end-position) t)
12124 (match-string-no-properties 1)))))
12126 (defvar org-last-changed-timestamp)
12127 (defvar org-last-inserted-timestamp)
12128 (defvar org-log-post-message)
12129 (defvar org-log-note-purpose)
12130 (defvar org-log-note-how)
12131 (defvar org-log-note-extra)
12132 (defun org-auto-repeat-maybe (done-word)
12133 "Check if the current headline contains a repeated deadline/schedule.
12134 If yes, set TODO state back to what it was and change the base date
12135 of repeating deadline/scheduled time stamps to new date.
12136 This function is run automatically after each state change to a DONE state."
12137 ;; last-state is dynamically scoped into this function
12138 (let* ((repeat (org-get-repeat))
12139 (aa (assoc org-last-state org-todo-kwd-alist))
12140 (interpret (nth 1 aa))
12141 (head (nth 2 aa))
12142 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12143 (msg "Entry repeats: ")
12144 (org-log-done nil)
12145 (org-todo-log-states nil)
12146 re type n what ts time to-state)
12147 (when repeat
12148 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12149 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12150 org-todo-repeat-to-state))
12151 (unless (and to-state (member to-state org-todo-keywords-1))
12152 (setq to-state (if (eq interpret 'type) org-last-state head)))
12153 (org-todo to-state)
12154 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12155 (org-entry-put nil "LAST_REPEAT" (format-time-string
12156 (org-time-stamp-format t t))))
12157 (when org-log-repeat
12158 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12159 (memq 'org-add-log-note post-command-hook))
12160 ;; OK, we are already setup for some record
12161 (if (eq org-log-repeat 'note)
12162 ;; make sure we take a note, not only a time stamp
12163 (setq org-log-note-how 'note))
12164 ;; Set up for taking a record
12165 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12166 org-last-state
12167 'findpos org-log-repeat)))
12168 (org-back-to-heading t)
12169 (org-add-planning-info nil nil 'closed)
12170 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12171 org-deadline-time-regexp "\\)\\|\\("
12172 org-ts-regexp "\\)"))
12173 (while (re-search-forward
12174 re (save-excursion (outline-next-heading) (point)) t)
12175 (setq type (if (match-end 1) org-scheduled-string
12176 (if (match-end 3) org-deadline-string "Plain:"))
12177 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12178 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12179 (setq n (string-to-number (match-string 2 ts))
12180 what (match-string 3 ts))
12181 (if (equal what "w") (setq n (* n 7) what "d"))
12182 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12183 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12184 ;; Preparation, see if we need to modify the start date for the change
12185 (when (match-end 1)
12186 (setq time (save-match-data (org-time-string-to-time ts)))
12187 (cond
12188 ((equal (match-string 1 ts) ".")
12189 ;; Shift starting date to today
12190 (org-timestamp-change
12191 (- (org-today) (time-to-days time))
12192 'day))
12193 ((equal (match-string 1 ts) "+")
12194 (let ((nshiftmax 10) (nshift 0))
12195 (while (or (= nshift 0)
12196 (<= (time-to-days time)
12197 (time-to-days (current-time))))
12198 (when (= (incf nshift) nshiftmax)
12199 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12200 (error "Abort")))
12201 (org-timestamp-change n (cdr (assoc what whata)))
12202 (org-at-timestamp-p t)
12203 (setq ts (match-string 1))
12204 (setq time (save-match-data (org-time-string-to-time ts)))))
12205 (org-timestamp-change (- n) (cdr (assoc what whata)))
12206 ;; rematch, so that we have everything in place for the real shift
12207 (org-at-timestamp-p t)
12208 (setq ts (match-string 1))
12209 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12210 (org-timestamp-change n (cdr (assoc what whata)))
12211 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12212 (setq org-log-post-message msg)
12213 (message "%s" msg))))
12215 (defun org-show-todo-tree (arg)
12216 "Make a compact tree which shows all headlines marked with TODO.
12217 The tree will show the lines where the regexp matches, and all higher
12218 headlines above the match.
12219 With a \\[universal-argument] prefix, prompt for a regexp to match.
12220 With a numeric prefix N, construct a sparse tree for the Nth element
12221 of `org-todo-keywords-1'."
12222 (interactive "P")
12223 (let ((case-fold-search nil)
12224 (kwd-re
12225 (cond ((null arg) org-not-done-regexp)
12226 ((equal arg '(4))
12227 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12228 (mapcar 'list org-todo-keywords-1))))
12229 (concat "\\("
12230 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12231 "\\)\\>")))
12232 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12233 (regexp-quote (nth (1- (prefix-numeric-value arg))
12234 org-todo-keywords-1)))
12235 (t (error "Invalid prefix argument: %s" arg)))))
12236 (message "%d TODO entries found"
12237 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12239 (defun org-deadline (&optional remove time)
12240 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12241 With argument REMOVE, remove any deadline from the item.
12242 With argument TIME, set the deadline at the corresponding date. TIME
12243 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12244 (interactive "P")
12245 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12246 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12247 'region-start-level 'region))
12248 org-loop-over-headlines-in-active-region)
12249 (org-map-entries
12250 `(org-deadline ',remove ,time)
12251 org-loop-over-headlines-in-active-region
12252 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12253 (let* ((old-date (org-entry-get nil "DEADLINE"))
12254 (repeater (and old-date
12255 (string-match
12256 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12257 old-date)
12258 (match-string 1 old-date))))
12259 (if remove
12260 (progn
12261 (when (and old-date org-log-redeadline)
12262 (org-add-log-setup 'deldeadline nil old-date 'findpos
12263 org-log-redeadline))
12264 (org-remove-timestamp-with-keyword org-deadline-string)
12265 (message "Item no longer has a deadline."))
12266 (org-add-planning-info 'deadline time 'closed)
12267 (when (and old-date org-log-redeadline
12268 (not (equal old-date
12269 (substring org-last-inserted-timestamp 1 -1))))
12270 (org-add-log-setup 'redeadline nil old-date 'findpos
12271 org-log-redeadline))
12272 (when repeater
12273 (save-excursion
12274 (org-back-to-heading t)
12275 (when (re-search-forward (concat org-deadline-string " "
12276 org-last-inserted-timestamp)
12277 (save-excursion
12278 (outline-next-heading) (point)) t)
12279 (goto-char (1- (match-end 0)))
12280 (insert " " repeater)
12281 (setq org-last-inserted-timestamp
12282 (concat (substring org-last-inserted-timestamp 0 -1)
12283 " " repeater
12284 (substring org-last-inserted-timestamp -1))))))
12285 (message "Deadline on %s" org-last-inserted-timestamp)))))
12287 (defun org-schedule (&optional remove time)
12288 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12289 With argument REMOVE, remove any scheduling date from the item.
12290 With argument TIME, scheduled at the corresponding date. TIME can
12291 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12292 (interactive "P")
12293 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12294 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12295 'region-start-level 'region))
12296 org-loop-over-headlines-in-active-region)
12297 (org-map-entries
12298 `(org-schedule ',remove ,time)
12299 org-loop-over-headlines-in-active-region
12300 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12301 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12302 (repeater (and old-date
12303 (string-match
12304 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12305 old-date)
12306 (match-string 1 old-date))))
12307 (if remove
12308 (progn
12309 (when (and old-date org-log-reschedule)
12310 (org-add-log-setup 'delschedule nil old-date 'findpos
12311 org-log-reschedule))
12312 (org-remove-timestamp-with-keyword org-scheduled-string)
12313 (message "Item is no longer scheduled."))
12314 (org-add-planning-info 'scheduled time 'closed)
12315 (when (and old-date org-log-reschedule
12316 (not (equal old-date
12317 (substring org-last-inserted-timestamp 1 -1))))
12318 (org-add-log-setup 'reschedule nil old-date 'findpos
12319 org-log-reschedule))
12320 (when repeater
12321 (save-excursion
12322 (org-back-to-heading t)
12323 (when (re-search-forward (concat org-scheduled-string " "
12324 org-last-inserted-timestamp)
12325 (save-excursion
12326 (outline-next-heading) (point)) t)
12327 (goto-char (1- (match-end 0)))
12328 (insert " " repeater)
12329 (setq org-last-inserted-timestamp
12330 (concat (substring org-last-inserted-timestamp 0 -1)
12331 " " repeater
12332 (substring org-last-inserted-timestamp -1))))))
12333 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12335 (defun org-get-scheduled-time (pom &optional inherit)
12336 "Get the scheduled time as a time tuple, of a format suitable
12337 for calling org-schedule with, or if there is no scheduling,
12338 returns nil."
12339 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12340 (when time
12341 (apply 'encode-time (org-parse-time-string time)))))
12343 (defun org-get-deadline-time (pom &optional inherit)
12344 "Get the deadline as a time tuple, of a format suitable for
12345 calling org-deadline with, or if there is no scheduling, returns
12346 nil."
12347 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12348 (when time
12349 (apply 'encode-time (org-parse-time-string time)))))
12351 (defun org-remove-timestamp-with-keyword (keyword)
12352 "Remove all time stamps with KEYWORD in the current entry."
12353 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12354 beg)
12355 (save-excursion
12356 (org-back-to-heading t)
12357 (setq beg (point))
12358 (outline-next-heading)
12359 (while (re-search-backward re beg t)
12360 (replace-match "")
12361 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12362 (equal (char-before) ?\ ))
12363 (backward-delete-char 1)
12364 (if (string-match "^[ \t]*$" (buffer-substring
12365 (point-at-bol) (point-at-eol)))
12366 (delete-region (point-at-bol)
12367 (min (point-max) (1+ (point-at-eol))))))))))
12369 (defun org-add-planning-info (what &optional time &rest remove)
12370 "Insert new timestamp with keyword in the line directly after the headline.
12371 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12372 If non is given, the user is prompted for a date.
12373 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12374 be removed."
12375 (interactive)
12376 (let (org-time-was-given org-end-time-was-given ts
12377 end default-time default-input)
12379 (catch 'exit
12380 (when (and (memq what '(scheduled deadline))
12381 (or (not time)
12382 (and (stringp time)
12383 (string-match "^[-+]+[0-9]" time))))
12384 ;; Try to get a default date/time from existing timestamp
12385 (save-excursion
12386 (org-back-to-heading t)
12387 (setq end (save-excursion (outline-next-heading) (point)))
12388 (when (re-search-forward (if (eq what 'scheduled)
12389 org-scheduled-time-regexp
12390 org-deadline-time-regexp)
12391 end t)
12392 (setq ts (match-string 1)
12393 default-time
12394 (apply 'encode-time (org-parse-time-string ts))
12395 default-input (and ts (org-get-compact-tod ts))))))
12396 (when what
12397 (setq time
12398 (if (stringp time)
12399 ;; This is a string (relative or absolute), set proper date
12400 (apply 'encode-time
12401 (org-read-date-analyze
12402 time default-time (decode-time default-time)))
12403 ;; If necessary, get the time from the user
12404 (or time (org-read-date nil 'to-time nil nil
12405 default-time default-input)))))
12407 (when (and org-insert-labeled-timestamps-at-point
12408 (member what '(scheduled deadline)))
12409 (insert
12410 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12411 (org-insert-time-stamp time org-time-was-given
12412 nil nil nil (list org-end-time-was-given))
12413 (setq what nil))
12414 (save-excursion
12415 (save-restriction
12416 (let (col list elt ts buffer-invisibility-spec)
12417 (org-back-to-heading t)
12418 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12419 (goto-char (match-end 1))
12420 (setq col (current-column))
12421 (goto-char (match-end 0))
12422 (if (eobp) (insert "\n") (forward-char 1))
12423 (when (and (not what)
12424 (not (looking-at
12425 (concat "[ \t]*"
12426 org-keyword-time-not-clock-regexp))))
12427 ;; Nothing to add, nothing to remove...... :-)
12428 (throw 'exit nil))
12429 (if (and (not (looking-at org-outline-regexp))
12430 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12431 "[^\r\n]*"))
12432 (not (equal (match-string 1) org-clock-string)))
12433 (narrow-to-region (match-beginning 0) (match-end 0))
12434 (insert-before-markers "\n")
12435 (backward-char 1)
12436 (narrow-to-region (point) (point))
12437 (and org-adapt-indentation (org-indent-to-column col)))
12438 ;; Check if we have to remove something.
12439 (setq list (cons what remove))
12440 (while list
12441 (setq elt (pop list))
12442 (when (or (and (eq elt 'scheduled)
12443 (re-search-forward org-scheduled-time-regexp nil t))
12444 (and (eq elt 'deadline)
12445 (re-search-forward org-deadline-time-regexp nil t))
12446 (and (eq elt 'closed)
12447 (re-search-forward org-closed-time-regexp nil t)))
12448 (replace-match "")
12449 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12450 (and (looking-at "[ \t]+") (replace-match ""))
12451 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12452 (when what
12453 (insert
12454 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12455 (cond ((eq what 'scheduled) org-scheduled-string)
12456 ((eq what 'deadline) org-deadline-string)
12457 ((eq what 'closed) org-closed-string))
12458 " ")
12459 (setq ts (org-insert-time-stamp
12460 time
12461 (or org-time-was-given
12462 (and (eq what 'closed) org-log-done-with-time))
12463 (eq what 'closed)
12464 nil nil (list org-end-time-was-given)))
12465 (insert
12466 (if (not (or (bolp) (eq (char-before) ?\ )
12467 (memq (char-after) '(32 10))
12468 (eobp))) " " ""))
12469 (end-of-line 1))
12470 (goto-char (point-min))
12471 (widen)
12472 (if (and (looking-at "[ \t]*\n")
12473 (equal (char-before) ?\n))
12474 (delete-region (1- (point)) (point-at-eol)))
12475 ts))))))
12477 (defvar org-log-note-marker (make-marker))
12478 (defvar org-log-note-purpose nil)
12479 (defvar org-log-note-state nil)
12480 (defvar org-log-note-previous-state nil)
12481 (defvar org-log-note-how nil)
12482 (defvar org-log-note-extra nil)
12483 (defvar org-log-note-window-configuration nil)
12484 (defvar org-log-note-return-to (make-marker))
12485 (defvar org-log-note-effective-time nil
12486 "Remembered current time so that dynamically scoped
12487 `org-extend-today-until' affects tha timestamps in state change
12488 log")
12490 (defvar org-log-post-message nil
12491 "Message to be displayed after a log note has been stored.
12492 The auto-repeater uses this.")
12494 (defun org-add-note ()
12495 "Add a note to the current entry.
12496 This is done in the same way as adding a state change note."
12497 (interactive)
12498 (org-add-log-setup 'note nil nil 'findpos nil))
12500 (defvar org-property-end-re)
12501 (defun org-add-log-setup (&optional purpose state prev-state
12502 findpos how extra)
12503 "Set up the post command hook to take a note.
12504 If this is about to TODO state change, the new state is expected in STATE.
12505 When FINDPOS is non-nil, find the correct position for the note in
12506 the current entry. If not, assume that it can be inserted at point.
12507 HOW is an indicator what kind of note should be created.
12508 EXTRA is additional text that will be inserted into the notes buffer."
12509 (let* ((org-log-into-drawer (org-log-into-drawer))
12510 (drawer (cond ((stringp org-log-into-drawer)
12511 org-log-into-drawer)
12512 (org-log-into-drawer "LOGBOOK"))))
12513 (save-restriction
12514 (save-excursion
12515 (when findpos
12516 (org-back-to-heading t)
12517 (narrow-to-region (point) (save-excursion
12518 (outline-next-heading) (point)))
12519 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12520 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12521 "[^\r\n]*\\)?"))
12522 (goto-char (match-end 0))
12523 (cond
12524 (drawer
12525 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12526 nil t)
12527 (progn
12528 (goto-char (match-end 0))
12529 (or org-log-states-order-reversed
12530 (and (re-search-forward org-property-end-re nil t)
12531 (goto-char (1- (match-beginning 0))))))
12532 (insert "\n:" drawer ":\n:END:")
12533 (beginning-of-line 0)
12534 (org-indent-line)
12535 (beginning-of-line 2)
12536 (org-indent-line)
12537 (end-of-line 0)))
12538 ((and org-log-state-notes-insert-after-drawers
12539 (save-excursion
12540 (forward-line) (looking-at org-drawer-regexp)))
12541 (forward-line)
12542 (while (looking-at org-drawer-regexp)
12543 (goto-char (match-end 0))
12544 (re-search-forward org-property-end-re (point-max) t)
12545 (forward-line))
12546 (forward-line -1)))
12547 (unless org-log-states-order-reversed
12548 (and (= (char-after) ?\n) (forward-char 1))
12549 (org-skip-over-state-notes)
12550 (skip-chars-backward " \t\n\r")))
12551 (move-marker org-log-note-marker (point))
12552 (setq org-log-note-purpose purpose
12553 org-log-note-state state
12554 org-log-note-previous-state prev-state
12555 org-log-note-how how
12556 org-log-note-extra extra
12557 org-log-note-effective-time (org-current-effective-time))
12558 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12560 (defun org-skip-over-state-notes ()
12561 "Skip past the list of State notes in an entry."
12562 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12563 (when (ignore-errors (goto-char (org-in-item-p)))
12564 (let* ((struct (org-list-struct))
12565 (prevs (org-list-prevs-alist struct)))
12566 (while (looking-at "[ \t]*- State")
12567 (goto-char (or (org-list-get-next-item (point) struct prevs)
12568 (org-list-get-item-end (point) struct)))))))
12570 (defun org-add-log-note (&optional purpose)
12571 "Pop up a window for taking a note, and add this note later at point."
12572 (remove-hook 'post-command-hook 'org-add-log-note)
12573 (setq org-log-note-window-configuration (current-window-configuration))
12574 (delete-other-windows)
12575 (move-marker org-log-note-return-to (point))
12576 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12577 (goto-char org-log-note-marker)
12578 (org-switch-to-buffer-other-window "*Org Note*")
12579 (erase-buffer)
12580 (if (memq org-log-note-how '(time state))
12581 (let (current-prefix-arg) (org-store-log-note))
12582 (let ((org-inhibit-startup t)) (org-mode))
12583 (insert (format "# Insert note for %s.
12584 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12585 (cond
12586 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12587 ((eq org-log-note-purpose 'done) "closed todo item")
12588 ((eq org-log-note-purpose 'state)
12589 (format "state change from \"%s\" to \"%s\""
12590 (or org-log-note-previous-state "")
12591 (or org-log-note-state "")))
12592 ((eq org-log-note-purpose 'reschedule)
12593 "rescheduling")
12594 ((eq org-log-note-purpose 'delschedule)
12595 "no longer scheduled")
12596 ((eq org-log-note-purpose 'redeadline)
12597 "changing deadline")
12598 ((eq org-log-note-purpose 'deldeadline)
12599 "removing deadline")
12600 ((eq org-log-note-purpose 'refile)
12601 "refiling")
12602 ((eq org-log-note-purpose 'note)
12603 "this entry")
12604 (t (error "This should not happen")))))
12605 (if org-log-note-extra (insert org-log-note-extra))
12606 (org-set-local 'org-finish-function 'org-store-log-note)
12607 (run-hooks 'org-log-buffer-setup-hook)))
12609 (defvar org-note-abort nil) ; dynamically scoped
12610 (defun org-store-log-note ()
12611 "Finish taking a log note, and insert it to where it belongs."
12612 (let ((txt (buffer-string))
12613 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12614 lines ind bul)
12615 (kill-buffer (current-buffer))
12616 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12617 (setq txt (replace-match "" t t txt)))
12618 (if (string-match "\\s-+\\'" txt)
12619 (setq txt (replace-match "" t t txt)))
12620 (setq lines (org-split-string txt "\n"))
12621 (when (and note (string-match "\\S-" note))
12622 (setq note
12623 (org-replace-escapes
12624 note
12625 (list (cons "%u" (user-login-name))
12626 (cons "%U" user-full-name)
12627 (cons "%t" (format-time-string
12628 (org-time-stamp-format 'long 'inactive)
12629 org-log-note-effective-time))
12630 (cons "%T" (format-time-string
12631 (org-time-stamp-format 'long nil)
12632 org-log-note-effective-time))
12633 (cons "%d" (format-time-string
12634 (org-time-stamp-format nil 'inactive)
12635 org-log-note-effective-time))
12636 (cons "%D" (format-time-string
12637 (org-time-stamp-format nil nil)
12638 org-log-note-effective-time))
12639 (cons "%s" (if org-log-note-state
12640 (concat "\"" org-log-note-state "\"")
12641 ""))
12642 (cons "%S" (if org-log-note-previous-state
12643 (concat "\"" org-log-note-previous-state "\"")
12644 "\"\"")))))
12645 (if lines (setq note (concat note " \\\\")))
12646 (push note lines))
12647 (when (or current-prefix-arg org-note-abort)
12648 (when org-log-into-drawer
12649 (org-remove-empty-drawer-at
12650 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12651 org-log-note-marker))
12652 (setq lines nil))
12653 (when lines
12654 (with-current-buffer (marker-buffer org-log-note-marker)
12655 (save-excursion
12656 (goto-char org-log-note-marker)
12657 (move-marker org-log-note-marker nil)
12658 (end-of-line 1)
12659 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12660 (setq ind (save-excursion
12661 (if (ignore-errors (goto-char (org-in-item-p)))
12662 (let ((struct (org-list-struct)))
12663 (org-list-get-ind
12664 (org-list-get-top-point struct) struct))
12665 (skip-chars-backward " \r\t\n")
12666 (cond
12667 ((and (org-at-heading-p)
12668 org-adapt-indentation)
12669 (1+ (org-current-level)))
12670 ((org-at-heading-p) 0)
12671 (t (org-get-indentation))))))
12672 (setq bul (org-list-bullet-string "-"))
12673 (org-indent-line-to ind)
12674 (insert bul (pop lines))
12675 (let ((ind-body (+ (length bul) ind)))
12676 (while lines
12677 (insert "\n")
12678 (org-indent-line-to ind-body)
12679 (insert (pop lines))))
12680 (message "Note stored")
12681 (org-back-to-heading t)
12682 (org-cycle-hide-drawers 'children)))))
12683 (set-window-configuration org-log-note-window-configuration)
12684 (with-current-buffer (marker-buffer org-log-note-return-to)
12685 (goto-char org-log-note-return-to))
12686 (move-marker org-log-note-return-to nil)
12687 (and org-log-post-message (message "%s" org-log-post-message)))
12689 (defun org-remove-empty-drawer-at (drawer pos)
12690 "Remove an empty drawer DRAWER at position POS.
12691 POS may also be a marker."
12692 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12693 (save-excursion
12694 (save-restriction
12695 (widen)
12696 (goto-char pos)
12697 (if (org-in-regexp
12698 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12699 (replace-match ""))))))
12701 (defvar org-ts-type nil)
12702 (defun org-sparse-tree (&optional arg type)
12703 "Create a sparse tree, prompt for the details.
12704 This command can create sparse trees. You first need to select the type
12705 of match used to create the tree:
12707 t Show all TODO entries.
12708 T Show entries with a specific TODO keyword.
12709 m Show entries selected by a tags/property match.
12710 p Enter a property name and its value (both with completion on existing
12711 names/values) and show entries with that property.
12712 r Show entries matching a regular expression (`/' can be used as well).
12713 b Show deadlines and scheduled items before a date.
12714 a Show deadlines and scheduled items after a date.
12715 d Show deadlines due within `org-deadline-warning-days'.
12716 D Show deadlines and scheduled items between a date range."
12717 (interactive "P")
12718 (let (ans kwd value ts-type)
12719 (setq type (or type org-sparse-tree-default-date-type))
12720 (setq org-ts-type type)
12721 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12722 (cond ((eq type 'all) "all timestamps")
12723 ((eq type 'scheduled) "only scheduled")
12724 ((eq type 'deadline) "only deadline")
12725 ((eq type 'active) "only active timestamps")
12726 ((eq type 'inactive) "only inactive timestamps")
12727 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12728 (t "scheduled/deadline")))
12729 (setq ans (read-char-exclusive))
12730 (cond
12731 ((equal ans ?c)
12732 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12733 ((equal ans ?d)
12734 (call-interactively 'org-check-deadlines))
12735 ((equal ans ?b)
12736 (call-interactively 'org-check-before-date))
12737 ((equal ans ?a)
12738 (call-interactively 'org-check-after-date))
12739 ((equal ans ?D)
12740 (call-interactively 'org-check-dates-range))
12741 ((equal ans ?t)
12742 (call-interactively 'org-show-todo-tree))
12743 ((equal ans ?T)
12744 (org-show-todo-tree '(4)))
12745 ((member ans '(?T ?m))
12746 (call-interactively 'org-match-sparse-tree))
12747 ((member ans '(?p ?P))
12748 (setq kwd (org-icompleting-read "Property: "
12749 (mapcar 'list (org-buffer-property-keys))))
12750 (setq value (org-icompleting-read "Value: "
12751 (mapcar 'list (org-property-values kwd))))
12752 (unless (string-match "\\`{.*}\\'" value)
12753 (setq value (concat "\"" value "\"")))
12754 (org-match-sparse-tree arg (concat kwd "=" value)))
12755 ((member ans '(?r ?R ?/))
12756 (call-interactively 'org-occur))
12757 (t (error "No such sparse tree command \"%c\"" ans)))))
12759 (defvar org-occur-highlights nil
12760 "List of overlays used for occur matches.")
12761 (make-variable-buffer-local 'org-occur-highlights)
12762 (defvar org-occur-parameters nil
12763 "Parameters of the active org-occur calls.
12764 This is a list, each call to org-occur pushes as cons cell,
12765 containing the regular expression and the callback, onto the list.
12766 The list can contain several entries if `org-occur' has been called
12767 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12768 will only contain one set of parameters. When the highlights are
12769 removed (for example with `C-c C-c', or with the next edit (depending
12770 on `org-remove-highlights-with-change'), this variable is emptied
12771 as well.")
12772 (make-variable-buffer-local 'org-occur-parameters)
12774 (defun org-occur (regexp &optional keep-previous callback)
12775 "Make a compact tree which shows all matches of REGEXP.
12776 The tree will show the lines where the regexp matches, and all higher
12777 headlines above the match. It will also show the heading after the match,
12778 to make sure editing the matching entry is easy.
12779 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12780 call to `org-occur' will be kept, to allow stacking of calls to this
12781 command.
12782 If CALLBACK is non-nil, it is a function which is called to confirm
12783 that the match should indeed be shown."
12784 (interactive "sRegexp: \nP")
12785 (when (equal regexp "")
12786 (error "Regexp cannot be empty"))
12787 (unless keep-previous
12788 (org-remove-occur-highlights nil nil t))
12789 (push (cons regexp callback) org-occur-parameters)
12790 (let ((cnt 0))
12791 (save-excursion
12792 (goto-char (point-min))
12793 (if (or (not keep-previous) ; do not want to keep
12794 (not org-occur-highlights)) ; no previous matches
12795 ;; hide everything
12796 (org-overview))
12797 (while (re-search-forward regexp nil t)
12798 (when (or (not callback)
12799 (save-match-data (funcall callback)))
12800 (setq cnt (1+ cnt))
12801 (when org-highlight-sparse-tree-matches
12802 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12803 (org-show-context 'occur-tree))))
12804 (when org-remove-highlights-with-change
12805 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12806 nil 'local))
12807 (unless org-sparse-tree-open-archived-trees
12808 (org-hide-archived-subtrees (point-min) (point-max)))
12809 (run-hooks 'org-occur-hook)
12810 (if (org-called-interactively-p 'interactive)
12811 (message "%d match(es) for regexp %s" cnt regexp))
12812 cnt))
12814 (defun org-occur-next-match (&optional n reset)
12815 "Function for `next-error-function' to find sparse tree matches.
12816 N is the number of matches to move, when negative move backwards.
12817 RESET is entirely ignored - this function always goes back to the
12818 starting point when no match is found."
12819 (let* ((limit (if (< n 0) (point-min) (point-max)))
12820 (search-func (if (< n 0)
12821 'previous-single-char-property-change
12822 'next-single-char-property-change))
12823 (n (abs n))
12824 (pos (point))
12826 (catch 'exit
12827 (while (setq p1 (funcall search-func (point) 'org-type))
12828 (when (equal p1 limit)
12829 (goto-char pos)
12830 (error "No more matches"))
12831 (when (equal (get-char-property p1 'org-type) 'org-occur)
12832 (setq n (1- n))
12833 (when (= n 0)
12834 (goto-char p1)
12835 (throw 'exit (point))))
12836 (goto-char p1))
12837 (goto-char p1)
12838 (error "No more matches"))))
12840 (defun org-show-context (&optional key)
12841 "Make sure point and context are visible.
12842 How much context is shown depends upon the variables
12843 `org-show-hierarchy-above', `org-show-following-heading',
12844 `org-show-entry-below' and `org-show-siblings'."
12845 (let ((heading-p (org-at-heading-p t))
12846 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12847 (following-p (org-get-alist-option org-show-following-heading key))
12848 (entry-p (org-get-alist-option org-show-entry-below key))
12849 (siblings-p (org-get-alist-option org-show-siblings key)))
12850 ;; Show heading or entry text
12851 (if (and heading-p (not entry-p))
12852 (org-flag-heading nil) ; only show the heading
12853 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12854 (org-show-hidden-entry))) ; show entire entry
12855 (when following-p
12856 ;; Show next sibling, or heading below text
12857 (save-excursion
12858 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12859 (org-flag-heading nil))))
12860 (when siblings-p (org-show-siblings))
12861 (when hierarchy-p
12862 ;; show all higher headings, possibly with siblings
12863 (save-excursion
12864 (while (and (condition-case nil
12865 (progn (org-up-heading-all 1) t)
12866 (error nil))
12867 (not (bobp)))
12868 (org-flag-heading nil)
12869 (when siblings-p (org-show-siblings)))))
12870 (org-fix-ellipsis-at-bol)))
12872 (defvar org-reveal-start-hook nil
12873 "Hook run before revealing a location.")
12875 (defun org-reveal (&optional siblings)
12876 "Show current entry, hierarchy above it, and the following headline.
12877 This can be used to show a consistent set of context around locations
12878 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12879 not t for the search context.
12881 With optional argument SIBLINGS, on each level of the hierarchy all
12882 siblings are shown. This repairs the tree structure to what it would
12883 look like when opened with hierarchical calls to `org-cycle'.
12884 With double optional argument \\[universal-argument] \\[universal-argument], \
12885 go to the parent and show the
12886 entire tree."
12887 (interactive "P")
12888 (run-hooks 'org-reveal-start-hook)
12889 (let ((org-show-hierarchy-above t)
12890 (org-show-following-heading t)
12891 (org-show-siblings (if siblings t org-show-siblings)))
12892 (org-show-context nil))
12893 (when (equal siblings '(16))
12894 (save-excursion
12895 (when (org-up-heading-safe)
12896 (org-show-subtree)
12897 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12899 (defun org-highlight-new-match (beg end)
12900 "Highlight from BEG to END and mark the highlight is an occur headline."
12901 (let ((ov (make-overlay beg end)))
12902 (overlay-put ov 'face 'secondary-selection)
12903 (overlay-put ov 'org-type 'org-occur)
12904 (push ov org-occur-highlights)))
12906 (defun org-remove-occur-highlights (&optional beg end noremove)
12907 "Remove the occur highlights from the buffer.
12908 BEG and END are ignored. If NOREMOVE is nil, remove this function
12909 from the `before-change-functions' in the current buffer."
12910 (interactive)
12911 (unless org-inhibit-highlight-removal
12912 (mapc 'delete-overlay org-occur-highlights)
12913 (setq org-occur-highlights nil)
12914 (setq org-occur-parameters nil)
12915 (unless noremove
12916 (remove-hook 'before-change-functions
12917 'org-remove-occur-highlights 'local))))
12919 ;;;; Priorities
12921 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12922 "Regular expression matching the priority indicator.")
12924 (defvar org-remove-priority-next-time nil)
12926 (defun org-priority-up ()
12927 "Increase the priority of the current item."
12928 (interactive)
12929 (org-priority 'up))
12931 (defun org-priority-down ()
12932 "Decrease the priority of the current item."
12933 (interactive)
12934 (org-priority 'down))
12936 (defun org-priority (&optional action show)
12937 "Change the priority of an item.
12938 ACTION can be `set', `up', `down', or a character."
12939 (interactive "P")
12940 (if (equal action '(4))
12941 (org-show-priority)
12942 (unless org-enable-priority-commands
12943 (error "Priority commands are disabled"))
12944 (setq action (or action 'set))
12945 (let (current new news have remove)
12946 (save-excursion
12947 (org-back-to-heading t)
12948 (if (looking-at org-priority-regexp)
12949 (setq current (string-to-char (match-string 2))
12950 have t))
12951 (cond
12952 ((eq action 'remove)
12953 (setq remove t new ?\ ))
12954 ((or (eq action 'set)
12955 (if (featurep 'xemacs) (characterp action) (integerp action)))
12956 (if (not (eq action 'set))
12957 (setq new action)
12958 (message "Priority %c-%c, SPC to remove: "
12959 org-highest-priority org-lowest-priority)
12960 (save-match-data
12961 (setq new (read-char-exclusive))))
12962 (if (and (= (upcase org-highest-priority) org-highest-priority)
12963 (= (upcase org-lowest-priority) org-lowest-priority))
12964 (setq new (upcase new)))
12965 (cond ((equal new ?\ ) (setq remove t))
12966 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12967 (error "Priority must be between `%c' and `%c'"
12968 org-highest-priority org-lowest-priority))))
12969 ((eq action 'up)
12970 (setq new (if have
12971 (1- current) ; normal cycling
12972 ;; last priority was empty
12973 (if (eq last-command this-command)
12974 org-lowest-priority ; wrap around empty to lowest
12975 ;; default
12976 (if org-priority-start-cycle-with-default
12977 org-default-priority
12978 (1- org-default-priority))))))
12979 ((eq action 'down)
12980 (setq new (if have
12981 (1+ current) ; normal cycling
12982 ;; last priority was empty
12983 (if (eq last-command this-command)
12984 org-highest-priority ; wrap around empty to highest
12985 ;; default
12986 (if org-priority-start-cycle-with-default
12987 org-default-priority
12988 (1+ org-default-priority))))))
12989 (t (error "Invalid action")))
12990 (if (or (< (upcase new) org-highest-priority)
12991 (> (upcase new) org-lowest-priority))
12992 (if (and (memq action '(up down))
12993 (not have) (not (eq last-command this-command)))
12994 ;; `new' is from default priority
12995 (error
12996 "The default can not be set, see `org-default-priority' why")
12997 ;; normal cycling: `new' is beyond highest/lowest priority
12998 ;; and is wrapped around to the empty priority
12999 (setq remove t)))
13000 (setq news (format "%c" new))
13001 (if have
13002 (if remove
13003 (replace-match "" t t nil 1)
13004 (replace-match news t t nil 2))
13005 (if remove
13006 (error "No priority cookie found in line")
13007 (let ((case-fold-search nil))
13008 (looking-at org-todo-line-regexp))
13009 (if (match-end 2)
13010 (progn
13011 (goto-char (match-end 2))
13012 (insert " [#" news "]"))
13013 (goto-char (match-beginning 3))
13014 (insert "[#" news "] "))))
13015 (org-preserve-lc (org-set-tags nil 'align)))
13016 (if remove
13017 (message "Priority removed")
13018 (message "Priority of current item set to %s" news)))))
13020 (defun org-show-priority ()
13021 "Show the priority of the current item.
13022 This priority is composed of the main priority given with the [#A] cookies,
13023 and by additional input from the age of a schedules or deadline entry."
13024 (interactive)
13025 (let ((pri (if (eq major-mode 'org-agenda-mode)
13026 (org-get-at-bol 'priority)
13027 (save-excursion
13028 (save-match-data
13029 (beginning-of-line)
13030 (and (looking-at org-heading-regexp)
13031 (org-get-priority (match-string 0))))))))
13032 (message "Priority is %d" (if pri pri -1000))))
13034 (defun org-get-priority (s)
13035 "Find priority cookie and return priority."
13036 (save-match-data
13037 (if (functionp org-get-priority-function)
13038 (funcall org-get-priority-function)
13039 (if (not (string-match org-priority-regexp s))
13040 (* 1000 (- org-lowest-priority org-default-priority))
13041 (* 1000 (- org-lowest-priority
13042 (string-to-char (match-string 2 s))))))))
13044 ;;;; Tags
13046 (defvar org-agenda-archives-mode)
13047 (defvar org-map-continue-from nil
13048 "Position from where mapping should continue.
13049 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13051 (defvar org-scanner-tags nil
13052 "The current tag list while the tags scanner is running.")
13053 (defvar org-trust-scanner-tags nil
13054 "Should `org-get-tags-at' use the tags for the scanner.
13055 This is for internal dynamical scoping only.
13056 When this is non-nil, the function `org-get-tags-at' will return the value
13057 of `org-scanner-tags' instead of building the list by itself. This
13058 can lead to large speed-ups when the tags scanner is used in a file with
13059 many entries, and when the list of tags is retrieved, for example to
13060 obtain a list of properties. Building the tags list for each entry in such
13061 a file becomes an N^2 operation - but with this variable set, it scales
13062 as N.")
13064 (defun org-scan-tags (action matcher todo-only &optional start-level)
13065 "Scan headline tags with inheritance and produce output ACTION.
13067 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13068 or `agenda' to produce an entry list for an agenda view. It can also be
13069 a Lisp form or a function that should be called at each matched headline, in
13070 this case the return value is a list of all return values from these calls.
13072 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13073 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13074 only lines with a not-done TODO keyword are included in the output.
13075 This should be the same variable that was scoped into
13076 and set by `org-make-tags-matcher' when it constructed MATCHER.
13078 START-LEVEL can be a string with asterisks, reducing the scope to
13079 headlines matching this string."
13080 (require 'org-agenda)
13081 (let* ((re (concat "^"
13082 (if start-level
13083 ;; Get the correct level to match
13084 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13085 org-outline-regexp)
13086 " *\\(\\<\\("
13087 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13088 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13089 (props (list 'face 'default
13090 'done-face 'org-agenda-done
13091 'undone-face 'default
13092 'mouse-face 'highlight
13093 'org-not-done-regexp org-not-done-regexp
13094 'org-todo-regexp org-todo-regexp
13095 'org-complex-heading-regexp org-complex-heading-regexp
13096 'help-echo
13097 (format "mouse-2 or RET jump to org file %s"
13098 (abbreviate-file-name
13099 (or (buffer-file-name (buffer-base-buffer))
13100 (buffer-name (buffer-base-buffer)))))))
13101 (case-fold-search nil)
13102 (org-map-continue-from nil)
13103 lspos tags tags-list
13104 (tags-alist (list (cons 0 org-file-tags)))
13105 (llast 0) rtn rtn1 level category i txt
13106 todo marker entry priority)
13107 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13108 (setq action (list 'lambda nil action)))
13109 (save-excursion
13110 (goto-char (point-min))
13111 (when (eq action 'sparse-tree)
13112 (org-overview)
13113 (org-remove-occur-highlights))
13114 (while (re-search-forward re nil t)
13115 (setq org-map-continue-from nil)
13116 (catch :skip
13117 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13118 tags (if (match-end 4) (org-match-string-no-properties 4)))
13119 (goto-char (setq lspos (match-beginning 0)))
13120 (setq level (org-reduced-level (funcall outline-level))
13121 category (org-get-category))
13122 (setq i llast llast level)
13123 ;; remove tag lists from same and sublevels
13124 (while (>= i level)
13125 (when (setq entry (assoc i tags-alist))
13126 (setq tags-alist (delete entry tags-alist)))
13127 (setq i (1- i)))
13128 ;; add the next tags
13129 (when tags
13130 (setq tags (org-split-string tags ":")
13131 tags-alist
13132 (cons (cons level tags) tags-alist)))
13133 ;; compile tags for current headline
13134 (setq tags-list
13135 (if org-use-tag-inheritance
13136 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13137 tags)
13138 org-scanner-tags tags-list)
13139 (when org-use-tag-inheritance
13140 (setcdr (car tags-alist)
13141 (mapcar (lambda (x)
13142 (setq x (copy-sequence x))
13143 (org-add-prop-inherited x))
13144 (cdar tags-alist))))
13145 (when (and tags org-use-tag-inheritance
13146 (or (not (eq t org-use-tag-inheritance))
13147 org-tags-exclude-from-inheritance))
13148 ;; selective inheritance, remove uninherited ones
13149 (setcdr (car tags-alist)
13150 (org-remove-uninherited-tags (cdar tags-alist))))
13151 (when (and
13153 ;; eval matcher only when the todo condition is OK
13154 (and (or (not todo-only) (member todo org-not-done-keywords))
13155 (let ((case-fold-search t) (org-trust-scanner-tags t))
13156 (eval matcher)))
13158 ;; Call the skipper, but return t if it does not skip,
13159 ;; so that the `and' form continues evaluating
13160 (progn
13161 (unless (eq action 'sparse-tree) (org-agenda-skip))
13164 ;; Check if timestamps are deselecting this entry
13165 (or (not todo-only)
13166 (and (member todo org-not-done-keywords)
13167 (or (not org-agenda-tags-todo-honor-ignore-options)
13168 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13170 ;; select this headline
13171 (cond
13172 ((eq action 'sparse-tree)
13173 (and org-highlight-sparse-tree-matches
13174 (org-get-heading) (match-end 0)
13175 (org-highlight-new-match
13176 (match-beginning 1) (match-end 1)))
13177 (org-show-context 'tags-tree))
13178 ((eq action 'agenda)
13179 (setq txt (org-agenda-format-item
13181 (concat
13182 (if (eq org-tags-match-list-sublevels 'indented)
13183 (make-string (1- level) ?.) "")
13184 (org-get-heading))
13185 category
13186 tags-list)
13187 priority (org-get-priority txt))
13188 (goto-char lspos)
13189 (setq marker (org-agenda-new-marker))
13190 (org-add-props txt props
13191 'org-marker marker 'org-hd-marker marker 'org-category category
13192 'todo-state todo
13193 'priority priority 'type "tagsmatch")
13194 (push txt rtn))
13195 ((functionp action)
13196 (setq org-map-continue-from nil)
13197 (save-excursion
13198 (setq rtn1 (funcall action))
13199 (push rtn1 rtn)))
13200 (t (error "Invalid action")))
13202 ;; if we are to skip sublevels, jump to end of subtree
13203 (unless org-tags-match-list-sublevels
13204 (org-end-of-subtree t)
13205 (backward-char 1))))
13206 ;; Get the correct position from where to continue
13207 (if org-map-continue-from
13208 (goto-char org-map-continue-from)
13209 (and (= (point) lspos) (end-of-line 1)))))
13210 (when (and (eq action 'sparse-tree)
13211 (not org-sparse-tree-open-archived-trees))
13212 (org-hide-archived-subtrees (point-min) (point-max)))
13213 (nreverse rtn)))
13215 (defun org-remove-uninherited-tags (tags)
13216 "Remove all tags that are not inherited from the list TAGS."
13217 (cond
13218 ((eq org-use-tag-inheritance t)
13219 (if org-tags-exclude-from-inheritance
13220 (org-delete-all org-tags-exclude-from-inheritance tags)
13221 tags))
13222 ((not org-use-tag-inheritance) nil)
13223 ((stringp org-use-tag-inheritance)
13224 (delq nil (mapcar
13225 (lambda (x)
13226 (if (and (string-match org-use-tag-inheritance x)
13227 (not (member x org-tags-exclude-from-inheritance)))
13228 x nil))
13229 tags)))
13230 ((listp org-use-tag-inheritance)
13231 (delq nil (mapcar
13232 (lambda (x)
13233 (if (member x org-use-tag-inheritance) x nil))
13234 tags)))))
13236 (defun org-match-sparse-tree (&optional todo-only match)
13237 "Create a sparse tree according to tags string MATCH.
13238 MATCH can contain positive and negative selection of tags, like
13239 \"+WORK+URGENT-WITHBOSS\".
13240 If optional argument TODO-ONLY is non-nil, only select lines that are
13241 also TODO lines."
13242 (interactive "P")
13243 (org-agenda-prepare-buffers (list (current-buffer)))
13244 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13246 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13248 (defvar org-cached-props nil)
13249 (defun org-cached-entry-get (pom property)
13250 (if (or (eq t org-use-property-inheritance)
13251 (and (stringp org-use-property-inheritance)
13252 (string-match org-use-property-inheritance property))
13253 (and (listp org-use-property-inheritance)
13254 (member property org-use-property-inheritance)))
13255 ;; Caching is not possible, check it directly
13256 (org-entry-get pom property 'inherit)
13257 ;; Get all properties, so that we can do complicated checks easily
13258 (cdr (assoc property (or org-cached-props
13259 (setq org-cached-props
13260 (org-entry-properties pom)))))))
13262 (defun org-global-tags-completion-table (&optional files)
13263 "Return the list of all tags in all agenda buffer/files.
13264 Optional FILES argument is a list of files which can be used
13265 instead of the agenda files."
13266 (save-excursion
13267 (org-uniquify
13268 (delq nil
13269 (apply 'append
13270 (mapcar
13271 (lambda (file)
13272 (set-buffer (find-file-noselect file))
13273 (append (org-get-buffer-tags)
13274 (mapcar (lambda (x) (if (stringp (car-safe x))
13275 (list (car-safe x)) nil))
13276 org-tag-alist)))
13277 (if (and files (car files))
13278 files
13279 (org-agenda-files))))))))
13281 (defun org-make-tags-matcher (match)
13282 "Create the TAGS/TODO matcher form for the selection string MATCH.
13284 The variable `todo-only' is scoped dynamically into this function.
13285 It will be set to t if the matcher restricts matching to TODO entries,
13286 otherwise will not be touched.
13288 Returns a cons of the selection string MATCH and the constructed
13289 lisp form implementing the matcher. The matcher is to be evaluated
13290 at an Org entry, with point on the headline, and returns t if the
13291 entry matches the selection string MATCH. The returned lisp form
13292 references two variables with information about the entry, which
13293 must be bound around the form's evaluation: todo, the TODO keyword
13294 at the entry (or nil of none); and tags-list, the list of all tags
13295 at the entry including inherited ones. Additionally, the category
13296 of the entry (if any) must be specified as the text property
13297 'org-category on the headline.
13299 See also `org-scan-tags'.
13301 (declare (special todo-only))
13302 (unless (boundp 'todo-only)
13303 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13304 (unless match
13305 ;; Get a new match request, with completion
13306 (let ((org-last-tags-completion-table
13307 (org-global-tags-completion-table)))
13308 (setq match (org-completing-read-no-i
13309 "Match: " 'org-tags-completion-function nil nil nil
13310 'org-tags-history))))
13312 ;; Parse the string and create a lisp form
13313 (let ((match0 match)
13314 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13315 minus tag mm
13316 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13317 orterms term orlist re-p str-p level-p level-op time-p
13318 prop-p pn pv po gv rest)
13319 (if (string-match "/+" match)
13320 ;; match contains also a todo-matching request
13321 (progn
13322 (setq tagsmatch (substring match 0 (match-beginning 0))
13323 todomatch (substring match (match-end 0)))
13324 (if (string-match "^!" todomatch)
13325 (setq todo-only t todomatch (substring todomatch 1)))
13326 (if (string-match "^\\s-*$" todomatch)
13327 (setq todomatch nil)))
13328 ;; only matching tags
13329 (setq tagsmatch match todomatch nil))
13331 ;; Make the tags matcher
13332 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13333 (setq tagsmatcher t)
13334 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13335 (while (setq term (pop orterms))
13336 (while (and (equal (substring term -1) "\\") orterms)
13337 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13338 (while (string-match re term)
13339 (setq rest (substring term (match-end 0))
13340 minus (and (match-end 1)
13341 (equal (match-string 1 term) "-"))
13342 tag (save-match-data (replace-regexp-in-string
13343 "\\\\-" "-"
13344 (match-string 2 term)))
13345 re-p (equal (string-to-char tag) ?{)
13346 level-p (match-end 4)
13347 prop-p (match-end 5)
13348 mm (cond
13349 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13350 (level-p
13351 (setq level-op (org-op-to-function (match-string 3 term)))
13352 `(,level-op level ,(string-to-number
13353 (match-string 4 term))))
13354 (prop-p
13355 (setq pn (match-string 5 term)
13356 po (match-string 6 term)
13357 pv (match-string 7 term)
13358 re-p (equal (string-to-char pv) ?{)
13359 str-p (equal (string-to-char pv) ?\")
13360 time-p (save-match-data
13361 (string-match "^\"[[<].*[]>]\"$" pv))
13362 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13363 (if time-p (setq pv (org-matcher-time pv)))
13364 (setq po (org-op-to-function po (if time-p 'time str-p)))
13365 (cond
13366 ((equal pn "CATEGORY")
13367 (setq gv '(get-text-property (point) 'org-category)))
13368 ((equal pn "TODO")
13369 (setq gv 'todo))
13371 (setq gv `(org-cached-entry-get nil ,pn))))
13372 (if re-p
13373 (if (eq po 'org<>)
13374 `(not (string-match ,pv (or ,gv "")))
13375 `(string-match ,pv (or ,gv "")))
13376 (if str-p
13377 `(,po (or ,gv "") ,pv)
13378 `(,po (string-to-number (or ,gv ""))
13379 ,(string-to-number pv) ))))
13380 (t `(member ,tag tags-list)))
13381 mm (if minus (list 'not mm) mm)
13382 term rest)
13383 (push mm tagsmatcher))
13384 (push (if (> (length tagsmatcher) 1)
13385 (cons 'and tagsmatcher)
13386 (car tagsmatcher))
13387 orlist)
13388 (setq tagsmatcher nil))
13389 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13390 (setq tagsmatcher
13391 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13392 ;; Make the todo matcher
13393 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13394 (setq todomatcher t)
13395 (setq orterms (org-split-string todomatch "|") orlist nil)
13396 (while (setq term (pop orterms))
13397 (while (string-match re term)
13398 (setq minus (and (match-end 1)
13399 (equal (match-string 1 term) "-"))
13400 kwd (match-string 2 term)
13401 re-p (equal (string-to-char kwd) ?{)
13402 term (substring term (match-end 0))
13403 mm (if re-p
13404 `(string-match ,(substring kwd 1 -1) todo)
13405 (list 'equal 'todo kwd))
13406 mm (if minus (list 'not mm) mm))
13407 (push mm todomatcher))
13408 (push (if (> (length todomatcher) 1)
13409 (cons 'and todomatcher)
13410 (car todomatcher))
13411 orlist)
13412 (setq todomatcher nil))
13413 (setq todomatcher (if (> (length orlist) 1)
13414 (cons 'or orlist) (car orlist))))
13416 ;; Return the string and lisp forms of the matcher
13417 (setq matcher (if todomatcher
13418 (list 'and tagsmatcher todomatcher)
13419 tagsmatcher))
13420 (when todo-only
13421 (setq matcher (list 'and '(member todo org-not-done-keywords)
13422 matcher)))
13423 (cons match0 matcher)))
13425 (defun org-op-to-function (op &optional stringp)
13426 "Turn an operator into the appropriate function."
13427 (setq op
13428 (cond
13429 ((equal op "<" ) '(< string< org-time<))
13430 ((equal op ">" ) '(> org-string> org-time>))
13431 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13432 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13433 ((member op '("=" "==")) '(= string= org-time=))
13434 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13435 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13437 (defun org<> (a b) (not (= a b)))
13438 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13439 (defun org-string>= (a b) (not (string< a b)))
13440 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13441 (defun org-string<> (a b) (not (string= a b)))
13442 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13443 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13444 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13445 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13446 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13447 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13448 (defun org-2ft (s)
13449 "Convert S to a floating point time.
13450 If S is already a number, just return it. If it is a string, parse
13451 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13452 (cond
13453 ((numberp s) s)
13454 ((stringp s)
13455 (condition-case nil
13456 (float-time (apply 'encode-time (org-parse-time-string s)))
13457 (error 0.)))
13458 (t 0.)))
13460 (defun org-time-today ()
13461 "Time in seconds today at 0:00.
13462 Returns the float number of seconds since the beginning of the
13463 epoch to the beginning of today (00:00)."
13464 (float-time (apply 'encode-time
13465 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13467 (defun org-matcher-time (s)
13468 "Interpret a time comparison value."
13469 (save-match-data
13470 (cond
13471 ((string= s "<now>") (float-time))
13472 ((string= s "<today>") (org-time-today))
13473 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13474 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13475 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13476 (+ (org-time-today)
13477 (* (string-to-number (match-string 1 s))
13478 (cdr (assoc (match-string 2 s)
13479 '(("d" . 86400.0) ("w" . 604800.0)
13480 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13481 (t (org-2ft s)))))
13483 (defun org-match-any-p (re list)
13484 "Does re match any element of list?"
13485 (setq list (mapcar (lambda (x) (string-match re x)) list))
13486 (delq nil list))
13488 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13489 (defvar org-tags-overlay (make-overlay 1 1))
13490 (org-detach-overlay org-tags-overlay)
13492 (defun org-get-local-tags-at (&optional pos)
13493 "Get a list of tags defined in the current headline."
13494 (org-get-tags-at pos 'local))
13496 (defun org-get-local-tags ()
13497 "Get a list of tags defined in the current headline."
13498 (org-get-tags-at nil 'local))
13500 (defun org-get-tags-at (&optional pos local)
13501 "Get a list of all headline tags applicable at POS.
13502 POS defaults to point. If tags are inherited, the list contains
13503 the targets in the same sequence as the headlines appear, i.e.
13504 the tags of the current headline come last.
13505 When LOCAL is non-nil, only return tags from the current headline,
13506 ignore inherited ones."
13507 (interactive)
13508 (if (and org-trust-scanner-tags
13509 (or (not pos) (equal pos (point)))
13510 (not local))
13511 org-scanner-tags
13512 (let (tags ltags lastpos parent)
13513 (save-excursion
13514 (save-restriction
13515 (widen)
13516 (goto-char (or pos (point)))
13517 (save-match-data
13518 (catch 'done
13519 (condition-case nil
13520 (progn
13521 (org-back-to-heading t)
13522 (while (not (equal lastpos (point)))
13523 (setq lastpos (point))
13524 (when (looking-at
13525 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13526 (setq ltags (org-split-string
13527 (org-match-string-no-properties 1) ":"))
13528 (when parent
13529 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13530 (setq tags (append
13531 (if parent
13532 (org-remove-uninherited-tags ltags)
13533 ltags)
13534 tags)))
13535 (or org-use-tag-inheritance (throw 'done t))
13536 (if local (throw 'done t))
13537 (or (org-up-heading-safe) (error nil))
13538 (setq parent t)))
13539 (error nil)))))
13540 (if local
13541 tags
13542 (reverse (delete-dups
13543 (reverse (append
13544 (org-remove-uninherited-tags
13545 org-file-tags) tags)))))))))
13547 (defun org-add-prop-inherited (s)
13548 (add-text-properties 0 (length s) '(inherited t) s)
13551 (defun org-toggle-tag (tag &optional onoff)
13552 "Toggle the tag TAG for the current line.
13553 If ONOFF is `on' or `off', don't toggle but set to this state."
13554 (let (res current)
13555 (save-excursion
13556 (org-back-to-heading t)
13557 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13558 (point-at-eol) t)
13559 (progn
13560 (setq current (match-string 1))
13561 (replace-match ""))
13562 (setq current ""))
13563 (setq current (nreverse (org-split-string current ":")))
13564 (cond
13565 ((eq onoff 'on)
13566 (setq res t)
13567 (or (member tag current) (push tag current)))
13568 ((eq onoff 'off)
13569 (or (not (member tag current)) (setq current (delete tag current))))
13570 (t (if (member tag current)
13571 (setq current (delete tag current))
13572 (setq res t)
13573 (push tag current))))
13574 (end-of-line 1)
13575 (if current
13576 (progn
13577 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13578 (org-set-tags nil t))
13579 (delete-horizontal-space))
13580 (run-hooks 'org-after-tags-change-hook))
13581 res))
13583 (defun org-align-tags-here (to-col)
13584 ;; Assumes that this is a headline
13585 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13586 (beginning-of-line 1)
13587 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13588 (< pos (match-beginning 2)))
13589 (progn
13590 (setq tags-l (- (match-end 2) (match-beginning 2)))
13591 (goto-char (match-beginning 1))
13592 (insert " ")
13593 (delete-region (point) (1+ (match-beginning 2)))
13594 (setq ncol (max (current-column)
13595 (1+ col)
13596 (if (> to-col 0)
13597 to-col
13598 (- (abs to-col) tags-l))))
13599 (setq p (point))
13600 (insert (make-string (- ncol (current-column)) ?\ ))
13601 (setq ncol (current-column))
13602 (when indent-tabs-mode (tabify p (point-at-eol)))
13603 (org-move-to-column (min ncol col) t))
13604 (goto-char pos))))
13606 (defun org-set-tags-command (&optional arg just-align)
13607 "Call the set-tags command for the current entry."
13608 (interactive "P")
13609 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13610 (org-set-tags arg just-align)
13611 (save-excursion
13612 (unless (and (org-region-active-p)
13613 org-loop-over-headlines-in-active-region)
13614 (org-back-to-heading t))
13615 (org-set-tags arg just-align))))
13617 (defun org-set-tags-to (data)
13618 "Set the tags of the current entry to DATA, replacing the current tags.
13619 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13620 If DATA is nil or the empty string, any tags will be removed."
13621 (interactive "sTags: ")
13622 (setq data
13623 (cond
13624 ((eq data nil) "")
13625 ((equal data "") "")
13626 ((stringp data)
13627 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13628 ":"))
13629 ((listp data)
13630 (concat ":" (mapconcat 'identity data ":") ":"))))
13631 (when data
13632 (save-excursion
13633 (org-back-to-heading t)
13634 (when (looking-at org-complex-heading-regexp)
13635 (if (match-end 5)
13636 (progn
13637 (goto-char (match-beginning 5))
13638 (insert data)
13639 (delete-region (point) (point-at-eol))
13640 (org-set-tags nil 'align))
13641 (goto-char (point-at-eol))
13642 (insert " " data)
13643 (org-set-tags nil 'align)))
13644 (beginning-of-line 1)
13645 (if (looking-at ".*?\\([ \t]+\\)$")
13646 (delete-region (match-beginning 1) (match-end 1))))))
13648 (defun org-align-all-tags ()
13649 "Align the tags i all headings."
13650 (interactive)
13651 (save-excursion
13652 (or (ignore-errors (org-back-to-heading t))
13653 (outline-next-heading))
13654 (if (org-at-heading-p)
13655 (org-set-tags t)
13656 (message "No headings"))))
13658 (defvar org-indent-indentation-per-level)
13659 (defun org-set-tags (&optional arg just-align)
13660 "Set the tags for the current headline.
13661 With prefix ARG, realign all tags in headings in the current buffer."
13662 (interactive "P")
13663 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13664 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13665 'region-start-level 'region))
13666 org-loop-over-headlines-in-active-region)
13667 (org-map-entries
13668 ;; We don't use ARG and JUST-ALIGN here these args are not
13669 ;; useful when looping over headlines
13670 `(org-set-tags)
13671 org-loop-over-headlines-in-active-region
13672 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13673 (let* ((re org-outline-regexp-bol)
13674 (current (unless arg (org-get-tags-string)))
13675 (col (current-column))
13676 (org-setting-tags t)
13677 table current-tags inherited-tags ; computed below when needed
13678 tags p0 c0 c1 rpl di tc level)
13679 (if arg
13680 (save-excursion
13681 (goto-char (point-min))
13682 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13683 (while (re-search-forward re nil t)
13684 (org-set-tags nil t)
13685 (end-of-line 1)))
13686 (message "All tags realigned to column %d" org-tags-column))
13687 (if just-align
13688 (setq tags current)
13689 ;; Get a new set of tags from the user
13690 (save-excursion
13691 (setq table (append org-tag-persistent-alist
13692 (or org-tag-alist (org-get-buffer-tags))
13693 (and
13694 org-complete-tags-always-offer-all-agenda-tags
13695 (org-global-tags-completion-table
13696 (org-agenda-files))))
13697 org-last-tags-completion-table table
13698 current-tags (org-split-string current ":")
13699 inherited-tags (nreverse
13700 (nthcdr (length current-tags)
13701 (nreverse (org-get-tags-at))))
13702 tags
13703 (if (or (eq t org-use-fast-tag-selection)
13704 (and org-use-fast-tag-selection
13705 (delq nil (mapcar 'cdr table))))
13706 (org-fast-tag-selection
13707 current-tags inherited-tags table
13708 (if org-fast-tag-selection-include-todo
13709 org-todo-key-alist))
13710 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13711 (org-trim
13712 (org-icompleting-read "Tags: "
13713 'org-tags-completion-function
13714 nil nil current 'org-tags-history))))))
13715 (while (string-match "[-+&]+" tags)
13716 ;; No boolean logic, just a list
13717 (setq tags (replace-match ":" t t tags))))
13719 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13721 (if org-tags-sort-function
13722 (setq tags (mapconcat 'identity
13723 (sort (org-split-string
13724 tags (org-re "[^[:alnum:]_@#%]+"))
13725 org-tags-sort-function) ":")))
13727 (if (string-match "\\`[\t ]*\\'" tags)
13728 (setq tags "")
13729 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13730 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13732 ;; Insert new tags at the correct column
13733 (beginning-of-line 1)
13734 (setq level (or (and (looking-at org-outline-regexp)
13735 (- (match-end 0) (point) 1))
13737 (cond
13738 ((and (equal current "") (equal tags "")))
13739 ((re-search-forward
13740 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13741 (point-at-eol) t)
13742 (if (equal tags "")
13743 (setq rpl "")
13744 (goto-char (match-beginning 0))
13745 (setq c0 (current-column)
13746 ;; compute offset for the case of org-indent-mode active
13747 di (if org-indent-mode
13748 (* (1- org-indent-indentation-per-level) (1- level))
13750 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13751 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13752 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13753 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13754 (replace-match rpl t t)
13755 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13756 tags)
13757 (t (error "Tags alignment failed")))
13758 (org-move-to-column col)
13759 (unless just-align
13760 (run-hooks 'org-after-tags-change-hook))))))
13762 (defun org-change-tag-in-region (beg end tag off)
13763 "Add or remove TAG for each entry in the region.
13764 This works in the agenda, and also in an org-mode buffer."
13765 (interactive
13766 (list (region-beginning) (region-end)
13767 (let ((org-last-tags-completion-table
13768 (if (derived-mode-p 'org-mode)
13769 (org-get-buffer-tags)
13770 (org-global-tags-completion-table))))
13771 (org-icompleting-read
13772 "Tag: " 'org-tags-completion-function nil nil nil
13773 'org-tags-history))
13774 (progn
13775 (message "[s]et or [r]emove? ")
13776 (equal (read-char-exclusive) ?r))))
13777 (if (fboundp 'deactivate-mark) (deactivate-mark))
13778 (let ((agendap (equal major-mode 'org-agenda-mode))
13779 l1 l2 m buf pos newhead (cnt 0))
13780 (goto-char end)
13781 (setq l2 (1- (org-current-line)))
13782 (goto-char beg)
13783 (setq l1 (org-current-line))
13784 (loop for l from l1 to l2 do
13785 (org-goto-line l)
13786 (setq m (get-text-property (point) 'org-hd-marker))
13787 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13788 (and agendap m))
13789 (setq buf (if agendap (marker-buffer m) (current-buffer))
13790 pos (if agendap m (point)))
13791 (with-current-buffer buf
13792 (save-excursion
13793 (save-restriction
13794 (goto-char pos)
13795 (setq cnt (1+ cnt))
13796 (org-toggle-tag tag (if off 'off 'on))
13797 (setq newhead (org-get-heading)))))
13798 (and agendap (org-agenda-change-all-lines newhead m))))
13799 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13801 (defun org-tags-completion-function (string predicate &optional flag)
13802 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13803 (confirm (lambda (x) (stringp (car x)))))
13804 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13805 (setq s1 (match-string 1 string)
13806 s2 (match-string 2 string))
13807 (setq s1 "" s2 string))
13808 (cond
13809 ((eq flag nil)
13810 ;; try completion
13811 (setq rtn (try-completion s2 ctable confirm))
13812 (if (stringp rtn)
13813 (setq rtn
13814 (concat s1 s2 (substring rtn (length s2))
13815 (if (and org-add-colon-after-tag-completion
13816 (assoc rtn ctable))
13817 ":" ""))))
13818 rtn)
13819 ((eq flag t)
13820 ;; all-completions
13821 (all-completions s2 ctable confirm)
13823 ((eq flag 'lambda)
13824 ;; exact match?
13825 (assoc s2 ctable)))
13828 (defun org-fast-tag-insert (kwd tags face &optional end)
13829 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13830 (insert (format "%-12s" (concat kwd ":"))
13831 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13832 (or end "")))
13834 (defun org-fast-tag-show-exit (flag)
13835 (save-excursion
13836 (org-goto-line 3)
13837 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13838 (replace-match ""))
13839 (when flag
13840 (end-of-line 1)
13841 (org-move-to-column (- (window-width) 19) t)
13842 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13844 (defun org-set-current-tags-overlay (current prefix)
13845 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13846 (if (featurep 'xemacs)
13847 (org-overlay-display org-tags-overlay (concat prefix s)
13848 'secondary-selection)
13849 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13850 (org-overlay-display org-tags-overlay (concat prefix s)))))
13852 (defvar org-last-tag-selection-key nil)
13853 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13854 "Fast tag selection with single keys.
13855 CURRENT is the current list of tags in the headline, INHERITED is the
13856 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13857 possibly with grouping information. TODO-TABLE is a similar table with
13858 TODO keywords, should these have keys assigned to them.
13859 If the keys are nil, a-z are automatically assigned.
13860 Returns the new tags string, or nil to not change the current settings."
13861 (let* ((fulltable (append table todo-table))
13862 (maxlen (apply 'max (mapcar
13863 (lambda (x)
13864 (if (stringp (car x)) (string-width (car x)) 0))
13865 fulltable)))
13866 (buf (current-buffer))
13867 (expert (eq org-fast-tag-selection-single-key 'expert))
13868 (buffer-tags nil)
13869 (fwidth (+ maxlen 3 1 3))
13870 (ncol (/ (- (window-width) 4) fwidth))
13871 (i-face 'org-done)
13872 (c-face 'org-todo)
13873 tg cnt e c char c1 c2 ntable tbl rtn
13874 ov-start ov-end ov-prefix
13875 (exit-after-next org-fast-tag-selection-single-key)
13876 (done-keywords org-done-keywords)
13877 groups ingroup)
13878 (save-excursion
13879 (beginning-of-line 1)
13880 (if (looking-at
13881 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13882 (setq ov-start (match-beginning 1)
13883 ov-end (match-end 1)
13884 ov-prefix "")
13885 (setq ov-start (1- (point-at-eol))
13886 ov-end (1+ ov-start))
13887 (skip-chars-forward "^\n\r")
13888 (setq ov-prefix
13889 (concat
13890 (buffer-substring (1- (point)) (point))
13891 (if (> (current-column) org-tags-column)
13893 (make-string (- org-tags-column (current-column)) ?\ ))))))
13894 (move-overlay org-tags-overlay ov-start ov-end)
13895 (save-window-excursion
13896 (if expert
13897 (set-buffer (get-buffer-create " *Org tags*"))
13898 (delete-other-windows)
13899 (split-window-vertically)
13900 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13901 (erase-buffer)
13902 (org-set-local 'org-done-keywords done-keywords)
13903 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13904 (org-fast-tag-insert "Current" current c-face "\n\n")
13905 (org-fast-tag-show-exit exit-after-next)
13906 (org-set-current-tags-overlay current ov-prefix)
13907 (setq tbl fulltable char ?a cnt 0)
13908 (while (setq e (pop tbl))
13909 (cond
13910 ((equal (car e) :startgroup)
13911 (push '() groups) (setq ingroup t)
13912 (when (not (= cnt 0))
13913 (setq cnt 0)
13914 (insert "\n"))
13915 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13916 ((equal (car e) :endgroup)
13917 (setq ingroup nil cnt 0)
13918 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13919 ((equal e '(:newline))
13920 (when (not (= cnt 0))
13921 (setq cnt 0)
13922 (insert "\n")
13923 (setq e (car tbl))
13924 (while (equal (car tbl) '(:newline))
13925 (insert "\n")
13926 (setq tbl (cdr tbl)))))
13928 (setq tg (copy-sequence (car e)) c2 nil)
13929 (if (cdr e)
13930 (setq c (cdr e))
13931 ;; automatically assign a character.
13932 (setq c1 (string-to-char
13933 (downcase (substring
13934 tg (if (= (string-to-char tg) ?@) 1 0)))))
13935 (if (or (rassoc c1 ntable) (rassoc c1 table))
13936 (while (or (rassoc char ntable) (rassoc char table))
13937 (setq char (1+ char)))
13938 (setq c2 c1))
13939 (setq c (or c2 char)))
13940 (if ingroup (push tg (car groups)))
13941 (setq tg (org-add-props tg nil 'face
13942 (cond
13943 ((not (assoc tg table))
13944 (org-get-todo-face tg))
13945 ((member tg current) c-face)
13946 ((member tg inherited) i-face))))
13947 (if (and (= cnt 0) (not ingroup)) (insert " "))
13948 (insert "[" c "] " tg (make-string
13949 (- fwidth 4 (length tg)) ?\ ))
13950 (push (cons tg c) ntable)
13951 (when (= (setq cnt (1+ cnt)) ncol)
13952 (insert "\n")
13953 (if ingroup (insert " "))
13954 (setq cnt 0)))))
13955 (setq ntable (nreverse ntable))
13956 (insert "\n")
13957 (goto-char (point-min))
13958 (if (not expert) (org-fit-window-to-buffer))
13959 (setq rtn
13960 (catch 'exit
13961 (while t
13962 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13963 (if (not groups) "no " "")
13964 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13965 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13966 (setq org-last-tag-selection-key c)
13967 (cond
13968 ((= c ?\r) (throw 'exit t))
13969 ((= c ?!)
13970 (setq groups (not groups))
13971 (goto-char (point-min))
13972 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13973 ((= c ?\C-c)
13974 (if (not expert)
13975 (org-fast-tag-show-exit
13976 (setq exit-after-next (not exit-after-next)))
13977 (setq expert nil)
13978 (delete-other-windows)
13979 (set-window-buffer (split-window-vertically) " *Org tags*")
13980 (org-switch-to-buffer-other-window " *Org tags*")
13981 (org-fit-window-to-buffer)))
13982 ((or (= c ?\C-g)
13983 (and (= c ?q) (not (rassoc c ntable))))
13984 (org-detach-overlay org-tags-overlay)
13985 (setq quit-flag t))
13986 ((= c ?\ )
13987 (setq current nil)
13988 (if exit-after-next (setq exit-after-next 'now)))
13989 ((= c ?\t)
13990 (condition-case nil
13991 (setq tg (org-icompleting-read
13992 "Tag: "
13993 (or buffer-tags
13994 (with-current-buffer buf
13995 (org-get-buffer-tags)))))
13996 (quit (setq tg "")))
13997 (when (string-match "\\S-" tg)
13998 (add-to-list 'buffer-tags (list tg))
13999 (if (member tg current)
14000 (setq current (delete tg current))
14001 (push tg current)))
14002 (if exit-after-next (setq exit-after-next 'now)))
14003 ((setq e (rassoc c todo-table) tg (car e))
14004 (with-current-buffer buf
14005 (save-excursion (org-todo tg)))
14006 (if exit-after-next (setq exit-after-next 'now)))
14007 ((setq e (rassoc c ntable) tg (car e))
14008 (if (member tg current)
14009 (setq current (delete tg current))
14010 (loop for g in groups do
14011 (if (member tg g)
14012 (mapc (lambda (x)
14013 (setq current (delete x current)))
14014 g)))
14015 (push tg current))
14016 (if exit-after-next (setq exit-after-next 'now))))
14018 ;; Create a sorted list
14019 (setq current
14020 (sort current
14021 (lambda (a b)
14022 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14023 (if (eq exit-after-next 'now) (throw 'exit t))
14024 (goto-char (point-min))
14025 (beginning-of-line 2)
14026 (delete-region (point) (point-at-eol))
14027 (org-fast-tag-insert "Current" current c-face)
14028 (org-set-current-tags-overlay current ov-prefix)
14029 (while (re-search-forward
14030 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14031 (setq tg (match-string 1))
14032 (add-text-properties
14033 (match-beginning 1) (match-end 1)
14034 (list 'face
14035 (cond
14036 ((member tg current) c-face)
14037 ((member tg inherited) i-face)
14038 (t (get-text-property (match-beginning 1) 'face))))))
14039 (goto-char (point-min)))))
14040 (org-detach-overlay org-tags-overlay)
14041 (if rtn
14042 (mapconcat 'identity current ":")
14043 nil))))
14045 (defun org-get-tags-string ()
14046 "Get the TAGS string in the current headline."
14047 (unless (org-at-heading-p t)
14048 (error "Not on a heading"))
14049 (save-excursion
14050 (beginning-of-line 1)
14051 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14052 (org-match-string-no-properties 1)
14053 "")))
14055 (defun org-get-tags ()
14056 "Get the list of tags specified in the current headline."
14057 (org-split-string (org-get-tags-string) ":"))
14059 (defun org-get-buffer-tags ()
14060 "Get a table of all tags used in the buffer, for completion."
14061 (let (tags)
14062 (save-excursion
14063 (goto-char (point-min))
14064 (while (re-search-forward
14065 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14066 (when (equal (char-after (point-at-bol 0)) ?*)
14067 (mapc (lambda (x) (add-to-list 'tags x))
14068 (org-split-string (org-match-string-no-properties 1) ":")))))
14069 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14070 (mapcar 'list tags)))
14072 ;;;; The mapping API
14074 (defun org-map-entries (func &optional match scope &rest skip)
14075 "Call FUNC at each headline selected by MATCH in SCOPE.
14077 FUNC is a function or a lisp form. The function will be called without
14078 arguments, with the cursor positioned at the beginning of the headline.
14079 The return values of all calls to the function will be collected and
14080 returned as a list.
14082 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14083 does not need to preserve point. After evaluation, the cursor will be
14084 moved to the end of the line (presumably of the headline of the
14085 processed entry) and search continues from there. Under some
14086 circumstances, this may not produce the wanted results. For example,
14087 if you have removed (e.g. archived) the current (sub)tree it could
14088 mean that the next entry will be skipped entirely. In such cases, you
14089 can specify the position from where search should continue by making
14090 FUNC set the variable `org-map-continue-from' to the desired buffer
14091 position.
14093 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14094 Only headlines that are matched by this query will be considered during
14095 the iteration. When MATCH is nil or t, all headlines will be
14096 visited by the iteration.
14098 SCOPE determines the scope of this command. It can be any of:
14100 nil The current buffer, respecting the restriction if any
14101 tree The subtree started with the entry at point
14102 region The entries within the active region, if any
14103 region-start-level
14104 The entries within the active region, but only those at
14105 the same level than the first one.
14106 file The current buffer, without restriction
14107 file-with-archives
14108 The current buffer, and any archives associated with it
14109 agenda All agenda files
14110 agenda-with-archives
14111 All agenda files with any archive files associated with them
14112 \(file1 file2 ...)
14113 If this is a list, all files in the list will be scanned
14115 The remaining args are treated as settings for the skipping facilities of
14116 the scanner. The following items can be given here:
14118 archive skip trees with the archive tag
14119 comment skip trees with the COMMENT keyword
14120 function or Emacs Lisp form:
14121 will be used as value for `org-agenda-skip-function', so
14122 whenever the function returns a position, FUNC will not be
14123 called for that entry and search will continue from the
14124 position returned
14126 If your function needs to retrieve the tags including inherited tags
14127 at the *current* entry, you can use the value of the variable
14128 `org-scanner-tags' which will be much faster than getting the value
14129 with `org-get-tags-at'. If your function gets properties with
14130 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14131 to t around the call to `org-entry-properties' to get the same speedup.
14132 Note that if your function moves around to retrieve tags and properties at
14133 a *different* entry, you cannot use these techniques."
14134 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14135 (not (org-region-active-p)))
14136 (let* ((org-agenda-archives-mode nil) ; just to make sure
14137 (org-agenda-skip-archived-trees (memq 'archive skip))
14138 (org-agenda-skip-comment-trees (memq 'comment skip))
14139 (org-agenda-skip-function
14140 (car (org-delete-all '(comment archive) skip)))
14141 (org-tags-match-list-sublevels t)
14142 (start-level (eq scope 'region-start-level))
14143 matcher file res
14144 org-todo-keywords-for-agenda
14145 org-done-keywords-for-agenda
14146 org-todo-keyword-alist-for-agenda
14147 org-drawers-for-agenda
14148 org-tag-alist-for-agenda
14149 todo-only)
14151 (cond
14152 ((eq match t) (setq matcher t))
14153 ((eq match nil) (setq matcher t))
14154 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14156 (save-excursion
14157 (save-restriction
14158 (cond ((eq scope 'tree)
14159 (org-back-to-heading t)
14160 (org-narrow-to-subtree)
14161 (setq scope nil))
14162 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14163 (org-region-active-p))
14164 ;; If needed, set start-level to a string like "2"
14165 (when start-level
14166 (save-excursion
14167 (goto-char (region-beginning))
14168 (unless (org-at-heading-p) (outline-next-heading))
14169 (setq start-level (org-current-level))))
14170 (narrow-to-region (region-beginning)
14171 (save-excursion
14172 (goto-char (region-end))
14173 (unless (and (bolp) (org-at-heading-p))
14174 (outline-next-heading))
14175 (point)))
14176 (setq scope nil)))
14178 (if (not scope)
14179 (progn
14180 (org-agenda-prepare-buffers
14181 (list (buffer-file-name (current-buffer))))
14182 (setq res (org-scan-tags func matcher todo-only start-level)))
14183 ;; Get the right scope
14184 (cond
14185 ((and scope (listp scope) (symbolp (car scope)))
14186 (setq scope (eval scope)))
14187 ((eq scope 'agenda)
14188 (setq scope (org-agenda-files t)))
14189 ((eq scope 'agenda-with-archives)
14190 (setq scope (org-agenda-files t))
14191 (setq scope (org-add-archive-files scope)))
14192 ((eq scope 'file)
14193 (setq scope (list (buffer-file-name))))
14194 ((eq scope 'file-with-archives)
14195 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14196 (org-agenda-prepare-buffers scope)
14197 (while (setq file (pop scope))
14198 (with-current-buffer (org-find-base-buffer-visiting file)
14199 (save-excursion
14200 (save-restriction
14201 (widen)
14202 (goto-char (point-min))
14203 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14204 res)))
14206 ;;;; Properties
14208 ;;; Setting and retrieving properties
14210 (defconst org-special-properties
14211 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14212 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14213 "The special properties valid in Org-mode.
14215 These are properties that are not defined in the property drawer,
14216 but in some other way.")
14218 (defconst org-default-properties
14219 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14220 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14221 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14222 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14223 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14224 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14225 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14226 "Some properties that are used by Org-mode for various purposes.
14227 Being in this list makes sure that they are offered for completion.")
14229 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14230 "Regular expression matching the first line of a property drawer.")
14232 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14233 "Regular expression matching the last line of a property drawer.")
14235 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14236 "Regular expression matching the first line of a property drawer.")
14238 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14239 "Regular expression matching the first line of a property drawer.")
14241 (defconst org-property-drawer-re
14242 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14243 org-property-end-re "\\)\n?")
14244 "Matches an entire property drawer.")
14246 (defconst org-clock-drawer-re
14247 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14248 org-property-end-re "\\)\n?")
14249 "Matches an entire clock drawer.")
14251 (defsubst org-re-property (property)
14252 "Return a regexp matching a PROPERTY line.
14253 Match group 1 will be set to the value."
14254 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14256 (defsubst org-re-property-keyword (property)
14257 "Return a regexp matching a PROPERTY line, possibly with no
14258 value for the property."
14259 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14261 (defun org-property-action ()
14262 "Do an action on properties."
14263 (interactive)
14264 (let (c)
14265 (org-at-property-p)
14266 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14267 (setq c (read-char-exclusive))
14268 (cond
14269 ((equal c ?s)
14270 (call-interactively 'org-set-property))
14271 ((equal c ?d)
14272 (call-interactively 'org-delete-property))
14273 ((equal c ?D)
14274 (call-interactively 'org-delete-property-globally))
14275 ((equal c ?c)
14276 (call-interactively 'org-compute-property-at-point))
14277 (t (error "No such property action %c" c)))))
14279 (defun org-inc-effort ()
14280 "Increment the value of the effort property in the current entry."
14281 (interactive)
14282 (org-set-effort nil t))
14284 (defun org-set-effort (&optional value increment)
14285 "Set the effort property of the current entry.
14286 With numerical prefix arg, use the nth allowed value, 0 stands for the
14287 10th allowed value.
14289 When INCREMENT is non-nil, set the property to the next allowed value."
14290 (interactive "P")
14291 (if (equal value 0) (setq value 10))
14292 (let* ((completion-ignore-case t)
14293 (prop org-effort-property)
14294 (cur (org-entry-get nil prop))
14295 (allowed (org-property-get-allowed-values nil prop 'table))
14296 (existing (mapcar 'list (org-property-values prop)))
14298 (val (cond
14299 ((stringp value) value)
14300 ((and allowed (integerp value))
14301 (or (car (nth (1- value) allowed))
14302 (car (org-last allowed))))
14303 ((and allowed increment)
14304 (or (caadr (member (list cur) allowed))
14305 (error "Allowed effort values are not set")))
14306 (allowed
14307 (message "Select 1-9,0, [RET%s]: %s"
14308 (if cur (concat "=" cur) "")
14309 (mapconcat 'car allowed " "))
14310 (setq rpl (read-char-exclusive))
14311 (if (equal rpl ?\r)
14313 (setq rpl (- rpl ?0))
14314 (if (equal rpl 0) (setq rpl 10))
14315 (if (and (> rpl 0) (<= rpl (length allowed)))
14316 (car (nth (1- rpl) allowed))
14317 (org-completing-read "Effort: " allowed nil))))
14319 (let (org-completion-use-ido org-completion-use-iswitchb)
14320 (org-completing-read
14321 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14322 (concat "[" cur "]") "")
14323 ": ")
14324 existing nil nil "" nil cur))))))
14325 (unless (equal (org-entry-get nil prop) val)
14326 (org-entry-put nil prop val))
14327 (save-excursion
14328 (org-back-to-heading t)
14329 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14330 (message "%s is now %s" prop val)))
14332 (defun org-at-property-p ()
14333 "Is cursor inside a property drawer?"
14334 (save-excursion
14335 (beginning-of-line 1)
14336 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14337 (save-match-data ;; Used by calling procedures
14338 (let ((p (point))
14339 (range (unless (org-before-first-heading-p)
14340 (org-get-property-block))))
14341 (and range (<= (car range) p) (< p (cdr range))))))))
14343 (defun org-get-property-block (&optional beg end force)
14344 "Return the (beg . end) range of the body of the property drawer.
14345 BEG and END are the beginning and end of the current subtree, or of
14346 the part before the first headline. If they are not given, they will
14347 be found. If the drawer does not exist and FORCE is non-nil, create
14348 the drawer."
14349 (catch 'exit
14350 (save-excursion
14351 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14352 (progn (org-back-to-heading t) (point))))
14353 (end (or end (and (not (outline-next-heading)) (point-max))
14354 (point))))
14355 (goto-char beg)
14356 (if (re-search-forward org-property-start-re end t)
14357 (setq beg (1+ (match-end 0)))
14358 (if force
14359 (save-excursion
14360 (org-insert-property-drawer)
14361 (setq end (progn (outline-next-heading) (point))))
14362 (throw 'exit nil))
14363 (goto-char beg)
14364 (if (re-search-forward org-property-start-re end t)
14365 (setq beg (1+ (match-end 0)))))
14366 (if (re-search-forward org-property-end-re end t)
14367 (setq end (match-beginning 0))
14368 (or force (throw 'exit nil))
14369 (goto-char beg)
14370 (setq end beg)
14371 (org-indent-line)
14372 (insert ":END:\n"))
14373 (cons beg end)))))
14375 (defun org-entry-properties (&optional pom which specific)
14376 "Get all properties of the entry at point-or-marker POM.
14377 This includes the TODO keyword, the tags, time strings for deadline,
14378 scheduled, and clocking, and any additional properties defined in the
14379 entry. The return value is an alist, keys may occur multiple times
14380 if the property key was used several times.
14381 POM may also be nil, in which case the current entry is used.
14382 If WHICH is nil or `all', get all properties. If WHICH is
14383 `special' or `standard', only get that subclass. If WHICH
14384 is a string only get exactly this property. SPECIFIC can be a string, the
14385 specific property we are interested in. Specifying it can speed
14386 things up because then unnecessary parsing is avoided."
14387 (setq which (or which 'all))
14388 (org-with-point-at pom
14389 (let ((clockstr (substring org-clock-string 0 -1))
14390 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14391 (case-fold-search nil)
14392 beg end range props sum-props key key1 value string clocksum clocksumt)
14393 (save-excursion
14394 (when (condition-case nil
14395 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14396 (error nil))
14397 (setq beg (point))
14398 (setq sum-props (get-text-property (point) 'org-summaries))
14399 (setq clocksum (get-text-property (point) :org-clock-minutes)
14400 clocksumt (get-text-property (point) :org-clock-minutes-today))
14401 (outline-next-heading)
14402 (setq end (point))
14403 (when (memq which '(all special))
14404 ;; Get the special properties, like TODO and tags
14405 (goto-char beg)
14406 (when (and (or (not specific) (string= specific "TODO"))
14407 (looking-at org-todo-line-regexp) (match-end 2))
14408 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14409 (when (and (or (not specific) (string= specific "PRIORITY"))
14410 (looking-at org-priority-regexp))
14411 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14412 (when (or (not specific) (string= specific "FILE"))
14413 (push (cons "FILE" buffer-file-name) props))
14414 (when (and (or (not specific) (string= specific "TAGS"))
14415 (setq value (org-get-tags-string))
14416 (string-match "\\S-" value))
14417 (push (cons "TAGS" value) props))
14418 (when (and (or (not specific) (string= specific "ALLTAGS"))
14419 (setq value (org-get-tags-at)))
14420 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14421 ":"))
14422 props))
14423 (when (or (not specific) (string= specific "BLOCKED"))
14424 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14425 (when (or (not specific)
14426 (member specific
14427 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14428 "TIMESTAMP" "TIMESTAMP_IA")))
14429 (catch 'match
14430 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14431 (setq key (if (match-end 1)
14432 (substring (org-match-string-no-properties 1)
14433 0 -1))
14434 string (if (equal key clockstr)
14435 (org-trim
14436 (buffer-substring-no-properties
14437 (match-beginning 3) (goto-char
14438 (point-at-eol))))
14439 (substring (org-match-string-no-properties 3)
14440 1 -1)))
14441 ;; Get the correct property name from the key. This is
14442 ;; necessary if the user has configured time keywords.
14443 (setq key1 (concat key ":"))
14444 (cond
14445 ((not key)
14446 (setq key
14447 (if (= (char-after (match-beginning 3)) ?\[)
14448 "TIMESTAMP_IA" "TIMESTAMP")))
14449 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14450 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14451 ((equal key1 org-closed-string) (setq key "CLOSED"))
14452 ((equal key1 org-clock-string) (setq key "CLOCK")))
14453 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14454 (progn
14455 (push (cons key string) props)
14456 ;; no need to search further if match is found
14457 (throw 'match t))
14458 (when (or (equal key "CLOCK") (not (assoc key props)))
14459 (push (cons key string) props)))))))
14461 (when (memq which '(all standard))
14462 ;; Get the standard properties, like :PROP: ...
14463 (setq range (org-get-property-block beg end))
14464 (when range
14465 (goto-char (car range))
14466 (while (re-search-forward
14467 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14468 (cdr range) t)
14469 (setq key (org-match-string-no-properties 1)
14470 value (org-trim (or (org-match-string-no-properties 2) "")))
14471 (unless (member key excluded)
14472 (push (cons key (or value "")) props)))))
14473 (if clocksum
14474 (push (cons "CLOCKSUM"
14475 (org-columns-number-to-string (/ (float clocksum) 60.)
14476 'add_times))
14477 props))
14478 (if clocksumt
14479 (push (cons "CLOCKSUM_T"
14480 (org-columns-number-to-string (/ (float clocksumt) 60.)
14481 'add_times))
14482 props))
14483 (unless (assoc "CATEGORY" props)
14484 (push (cons "CATEGORY" (org-get-category)) props))
14485 (append sum-props (nreverse props)))))))
14487 (defun org-entry-get (pom property &optional inherit literal-nil)
14488 "Get value of PROPERTY for entry or content at point-or-marker POM.
14489 If INHERIT is non-nil and the entry does not have the property,
14490 then also check higher levels of the hierarchy.
14491 If INHERIT is the symbol `selective', use inheritance only if the setting
14492 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14493 If the property is present but empty, the return value is the empty string.
14494 If the property is not present at all, nil is returned.
14496 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14497 do not interpret it as the list atom nil. This is used for inheritance
14498 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14499 (org-with-point-at pom
14500 (if (and inherit (if (eq inherit 'selective)
14501 (org-property-inherit-p property)
14503 (org-entry-get-with-inheritance property literal-nil)
14504 (if (member property org-special-properties)
14505 ;; We need a special property. Use `org-entry-properties' to
14506 ;; retrieve it, but specify the wanted property
14507 (cdr (assoc property (org-entry-properties nil 'special property)))
14508 (let ((range (org-get-property-block)))
14509 (when (and range (not (eq (car range) (cdr range))))
14510 (let* ((props (list (or (assoc property org-file-properties)
14511 (assoc property org-global-properties)
14512 (assoc property org-global-properties-fixed))))
14513 (ap (lambda (key)
14514 (when (re-search-forward
14515 (org-re-property key) (cdr range) t)
14516 (setq props
14517 (org-update-property-plist
14519 (if (match-end 1)
14520 (org-match-string-no-properties 1) "")
14521 props)))))
14522 val)
14523 (goto-char (car range))
14524 (funcall ap property)
14525 (goto-char (car range))
14526 (while (funcall ap (concat property "+")))
14527 (setq val (cdr (assoc property props)))
14528 (when val (if literal-nil val (org-not-nil val))))))))))
14530 (defun org-property-or-variable-value (var &optional inherit)
14531 "Check if there is a property fixing the value of VAR.
14532 If yes, return this value. If not, return the current value of the variable."
14533 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14534 (if (and prop (stringp prop) (string-match "\\S-" prop))
14535 (read prop)
14536 (symbol-value var))))
14538 (defun org-entry-delete (pom property)
14539 "Delete the property PROPERTY from entry at point-or-marker POM."
14540 (org-with-point-at pom
14541 (if (member property org-special-properties)
14542 nil ; cannot delete these properties.
14543 (let ((range (org-get-property-block)))
14544 (if (and range
14545 (goto-char (car range))
14546 (re-search-forward
14547 (org-re-property property)
14548 (cdr range) t))
14549 (progn
14550 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14552 nil)))))
14554 ;; Multi-values properties are properties that contain multiple values
14555 ;; These values are assumed to be single words, separated by whitespace.
14556 (defun org-entry-add-to-multivalued-property (pom property value)
14557 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14558 (let* ((old (org-entry-get pom property))
14559 (values (and old (org-split-string old "[ \t]"))))
14560 (setq value (org-entry-protect-space value))
14561 (unless (member value values)
14562 (setq values (cons value values))
14563 (org-entry-put pom property
14564 (mapconcat 'identity values " ")))))
14566 (defun org-entry-remove-from-multivalued-property (pom property value)
14567 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14568 (let* ((old (org-entry-get pom property))
14569 (values (and old (org-split-string old "[ \t]"))))
14570 (setq value (org-entry-protect-space value))
14571 (when (member value values)
14572 (setq values (delete value values))
14573 (org-entry-put pom property
14574 (mapconcat 'identity values " ")))))
14576 (defun org-entry-member-in-multivalued-property (pom property value)
14577 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14578 (let* ((old (org-entry-get pom property))
14579 (values (and old (org-split-string old "[ \t]"))))
14580 (setq value (org-entry-protect-space value))
14581 (member value values)))
14583 (defun org-entry-get-multivalued-property (pom property)
14584 "Return a list of values in a multivalued property."
14585 (let* ((value (org-entry-get pom property))
14586 (values (and value (org-split-string value "[ \t]"))))
14587 (mapcar 'org-entry-restore-space values)))
14589 (defun org-entry-put-multivalued-property (pom property &rest values)
14590 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14591 VALUES should be a list of strings. Spaces will be protected."
14592 (org-entry-put pom property
14593 (mapconcat 'org-entry-protect-space values " "))
14594 (let* ((value (org-entry-get pom property))
14595 (values (and value (org-split-string value "[ \t]"))))
14596 (mapcar 'org-entry-restore-space values)))
14598 (defun org-entry-protect-space (s)
14599 "Protect spaces and newline in string S."
14600 (while (string-match " " s)
14601 (setq s (replace-match "%20" t t s)))
14602 (while (string-match "\n" s)
14603 (setq s (replace-match "%0A" t t s)))
14606 (defun org-entry-restore-space (s)
14607 "Restore spaces and newline in string S."
14608 (while (string-match "%20" s)
14609 (setq s (replace-match " " t t s)))
14610 (while (string-match "%0A" s)
14611 (setq s (replace-match "\n" t t s)))
14614 (defvar org-entry-property-inherited-from (make-marker)
14615 "Marker pointing to the entry from where a property was inherited.
14616 Each call to `org-entry-get-with-inheritance' will set this marker to the
14617 location of the entry where the inheritance search matched. If there was
14618 no match, the marker will point nowhere.
14619 Note that also `org-entry-get' calls this function, if the INHERIT flag
14620 is set.")
14622 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14623 "Get PROPERTY of entry or content at point, search higher levels if needed.
14624 The search will stop at the first ancestor which has the property defined.
14625 If the value found is \"nil\", return nil to show that the property
14626 should be considered as undefined (this is the meaning of nil here).
14627 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14628 (move-marker org-entry-property-inherited-from nil)
14629 (let (tmp)
14630 (save-excursion
14631 (save-restriction
14632 (widen)
14633 (catch 'ex
14634 (while t
14635 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14636 (or (ignore-errors (org-back-to-heading t))
14637 (goto-char (point-min)))
14638 (move-marker org-entry-property-inherited-from (point))
14639 (throw 'ex tmp))
14640 (or (ignore-errors (org-up-heading-safe))
14641 (throw 'ex nil))))))
14642 (setq tmp (or tmp
14643 (cdr (assoc property org-file-properties))
14644 (cdr (assoc property org-global-properties))
14645 (cdr (assoc property org-global-properties-fixed))))
14646 (if literal-nil tmp (org-not-nil tmp))))
14648 (defvar org-property-changed-functions nil
14649 "Hook called when the value of a property has changed.
14650 Each hook function should accept two arguments, the name of the property
14651 and the new value.")
14653 (defun org-entry-put (pom property value)
14654 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14655 (org-with-point-at pom
14656 (org-back-to-heading t)
14657 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14658 range)
14659 (cond
14660 ((equal property "TODO")
14661 (when (and (stringp value) (string-match "\\S-" value)
14662 (not (member value org-todo-keywords-1)))
14663 (error "\"%s\" is not a valid TODO state" value))
14664 (if (or (not value)
14665 (not (string-match "\\S-" value)))
14666 (setq value 'none))
14667 (org-todo value)
14668 (org-set-tags nil 'align))
14669 ((equal property "PRIORITY")
14670 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14671 (string-to-char value) ?\ ))
14672 (org-set-tags nil 'align))
14673 ((equal property "SCHEDULED")
14674 (if (re-search-forward org-scheduled-time-regexp end t)
14675 (cond
14676 ((eq value 'earlier) (org-timestamp-change -1 'day))
14677 ((eq value 'later) (org-timestamp-change 1 'day))
14678 (t (call-interactively 'org-schedule)))
14679 (call-interactively 'org-schedule)))
14680 ((equal property "DEADLINE")
14681 (if (re-search-forward org-deadline-time-regexp end t)
14682 (cond
14683 ((eq value 'earlier) (org-timestamp-change -1 'day))
14684 ((eq value 'later) (org-timestamp-change 1 'day))
14685 (t (call-interactively 'org-deadline)))
14686 (call-interactively 'org-deadline)))
14687 ((member property org-special-properties)
14688 (error "The %s property can not yet be set with `org-entry-put'"
14689 property))
14690 (t ; a non-special property
14691 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14692 (setq range (org-get-property-block beg end 'force))
14693 (goto-char (car range))
14694 (if (re-search-forward
14695 (org-re-property-keyword property) (cdr range) t)
14696 (progn
14697 (delete-region (match-beginning 0) (match-end 0))
14698 (goto-char (match-beginning 0)))
14699 (goto-char (cdr range))
14700 (insert "\n")
14701 (backward-char 1)
14702 (org-indent-line))
14703 (insert ":" property ":")
14704 (and value (insert " " value))
14705 (org-indent-line)))))
14706 (run-hook-with-args 'org-property-changed-functions property value)))
14708 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14709 "Get all property keys in the current buffer.
14710 With INCLUDE-SPECIALS, also list the special properties that reflect things
14711 like tags and TODO state.
14712 With INCLUDE-DEFAULTS, also include properties that has special meaning
14713 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14714 and others.
14715 With INCLUDE-COLUMNS, also include property names given in COLUMN
14716 formats in the current buffer."
14717 (let (rtn range cfmt s p)
14718 (save-excursion
14719 (save-restriction
14720 (widen)
14721 (goto-char (point-min))
14722 (while (re-search-forward org-property-start-re nil t)
14723 (setq range (org-get-property-block))
14724 (goto-char (car range))
14725 (while (re-search-forward
14726 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14727 (cdr range) t)
14728 (add-to-list 'rtn (org-match-string-no-properties 1)))
14729 (outline-next-heading))))
14731 (when include-specials
14732 (setq rtn (append org-special-properties rtn)))
14734 (when include-defaults
14735 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14736 (add-to-list 'rtn org-effort-property))
14738 (when include-columns
14739 (save-excursion
14740 (save-restriction
14741 (widen)
14742 (goto-char (point-min))
14743 (while (re-search-forward
14744 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14745 nil t)
14746 (setq cfmt (match-string 2) s 0)
14747 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14748 cfmt s)
14749 (setq s (match-end 0)
14750 p (match-string 1 cfmt))
14751 (unless (or (equal p "ITEM")
14752 (member p org-special-properties))
14753 (add-to-list 'rtn (match-string 1 cfmt))))))))
14755 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14757 (defun org-property-values (key)
14758 "Return a list of all values of property KEY in the current buffer."
14759 (save-excursion
14760 (save-restriction
14761 (widen)
14762 (goto-char (point-min))
14763 (let ((re (org-re-property key))
14764 values)
14765 (while (re-search-forward re nil t)
14766 (add-to-list 'values (org-trim (match-string 1))))
14767 (delete "" values)))))
14769 (defun org-insert-property-drawer ()
14770 "Insert a property drawer into the current entry."
14771 (org-back-to-heading t)
14772 (looking-at org-outline-regexp)
14773 (let ((indent (if org-adapt-indentation
14774 (- (match-end 0) (match-beginning 0))
14776 (beg (point))
14777 (re (concat "^[ \t]*" org-keyword-time-regexp))
14778 end hiddenp)
14779 (outline-next-heading)
14780 (setq end (point))
14781 (goto-char beg)
14782 (while (re-search-forward re end t))
14783 (setq hiddenp (outline-invisible-p))
14784 (end-of-line 1)
14785 (and (equal (char-after) ?\n) (forward-char 1))
14786 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14787 (if (member (match-string 1) '("CLOCK:" ":END:"))
14788 ;; just skip this line
14789 (beginning-of-line 2)
14790 ;; Drawer start, find the end
14791 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14792 (beginning-of-line 1)))
14793 (org-skip-over-state-notes)
14794 (skip-chars-backward " \t\n\r")
14795 (if (eq (char-before) ?*) (forward-char 1))
14796 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14797 (beginning-of-line 0)
14798 (org-indent-to-column indent)
14799 (beginning-of-line 2)
14800 (org-indent-to-column indent)
14801 (beginning-of-line 0)
14802 (if hiddenp
14803 (save-excursion
14804 (org-back-to-heading t)
14805 (hide-entry))
14806 (org-flag-drawer t))))
14808 (defun org-insert-drawer (&optional arg drawer)
14809 "Insert a drawer at point.
14811 Optional argument DRAWER, when non-nil, is a string representing
14812 drawer's name. Otherwise, the user is prompted for a name.
14814 If a region is active, insert the drawer around that region
14815 instead.
14817 Point is left between drawer's boundaries."
14818 (interactive "P")
14819 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14820 "LOGBOOK"))
14821 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14822 ;; internally by Org. They are meant to be inserted
14823 ;; automatically.
14824 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14825 ;; Remove system drawers from list. Note: For some reason,
14826 ;; `org-completing-read' ignores the predicate while
14827 ;; `completing-read' handles it fine.
14828 (drawer (if arg "PROPERTIES"
14829 (or drawer
14830 (completing-read
14831 "Drawer: " org-drawers
14832 (lambda (d) (not (member d system-drawers))))))))
14833 (cond
14834 ;; With C-u, fall back on `org-insert-property-drawer'
14835 (arg (org-insert-property-drawer))
14836 ;; With an active region, insert a drawer at point.
14837 ((not (org-region-active-p))
14838 (progn
14839 (unless (bolp) (insert "\n"))
14840 (insert (format ":%s:\n\n:END:\n" drawer))
14841 (forward-line -2)))
14842 ;; Otherwise, insert the drawer at point
14844 (let ((rbeg (region-beginning))
14845 (rend (copy-marker (region-end))))
14846 (unwind-protect
14847 (progn
14848 (goto-char rbeg)
14849 (beginning-of-line)
14850 (when (save-excursion
14851 (re-search-forward org-outline-regexp-bol rend t))
14852 (error "Drawers cannot contain headlines"))
14853 ;; Position point at the beginning of the first
14854 ;; non-blank line in region. Insert drawer's opening
14855 ;; there, then indent it.
14856 (org-skip-whitespace)
14857 (beginning-of-line)
14858 (insert ":" drawer ":\n")
14859 (forward-line -1)
14860 (indent-for-tab-command)
14861 ;; Move point to the beginning of the first blank line
14862 ;; after the last non-blank line in region. Insert
14863 ;; drawer's closing, then indent it.
14864 (goto-char rend)
14865 (skip-chars-backward " \r\t\n")
14866 (insert "\n:END:")
14867 (deactivate-mark t)
14868 (indent-for-tab-command)
14869 (unless (eolp) (insert "\n")))
14870 ;; Clear marker, whatever the outcome of insertion is.
14871 (set-marker rend nil)))))))
14873 (defvar org-property-set-functions-alist nil
14874 "Property set function alist.
14875 Each entry should have the following format:
14877 (PROPERTY . READ-FUNCTION)
14879 The read function will be called with the same argument as
14880 `org-completing-read'.")
14882 (defun org-set-property-function (property)
14883 "Get the function that should be used to set PROPERTY.
14884 This is computed according to `org-property-set-functions-alist'."
14885 (or (cdr (assoc property org-property-set-functions-alist))
14886 'org-completing-read))
14888 (defun org-read-property-value (property)
14889 "Read PROPERTY value from user."
14890 (let* ((completion-ignore-case t)
14891 (allowed (org-property-get-allowed-values nil property 'table))
14892 (cur (org-entry-get nil property))
14893 (prompt (concat property " value"
14894 (if (and cur (string-match "\\S-" cur))
14895 (concat " [" cur "]") "") ": "))
14896 (set-function (org-set-property-function property))
14897 (val (if allowed
14898 (funcall set-function prompt allowed nil
14899 (not (get-text-property 0 'org-unrestricted
14900 (caar allowed))))
14901 (let (org-completion-use-ido org-completion-use-iswitchb)
14902 (funcall set-function prompt
14903 (mapcar 'list (org-property-values property))
14904 nil nil "" nil cur)))))
14905 (if (equal val "")
14907 val)))
14909 (defvar org-last-set-property nil)
14910 (defun org-read-property-name ()
14911 "Read a property name."
14912 (let* ((completion-ignore-case t)
14913 (keys (org-buffer-property-keys nil t t))
14914 (default-prop (or (save-excursion
14915 (save-match-data
14916 (beginning-of-line)
14917 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14918 (null (string= (match-string 1) "END"))
14919 (match-string 1))))
14920 org-last-set-property))
14921 (property (org-icompleting-read
14922 (concat "Property"
14923 (if default-prop (concat " [" default-prop "]") "")
14924 ": ")
14925 (mapcar 'list keys)
14926 nil nil nil nil
14927 default-prop
14929 (if (member property keys)
14930 property
14931 (or (cdr (assoc (downcase property)
14932 (mapcar (lambda (x) (cons (downcase x) x))
14933 keys)))
14934 property))))
14936 (defun org-set-property (property value)
14937 "In the current entry, set PROPERTY to VALUE.
14938 When called interactively, this will prompt for a property name, offering
14939 completion on existing and default properties. And then it will prompt
14940 for a value, offering completion either on allowed values (via an inherited
14941 xxx_ALL property) or on existing values in other instances of this property
14942 in the current file."
14943 (interactive (list nil nil))
14944 (let* ((property (or property (org-read-property-name)))
14945 (value (or value (org-read-property-value property)))
14946 (fn (cdr (assoc property org-properties-postprocess-alist))))
14947 (setq org-last-set-property property)
14948 ;; Possibly postprocess the inserted value:
14949 (when fn (setq value (funcall fn value)))
14950 (unless (equal (org-entry-get nil property) value)
14951 (org-entry-put nil property value))))
14953 (defun org-delete-property (property)
14954 "In the current entry, delete PROPERTY."
14955 (interactive
14956 (let* ((completion-ignore-case t)
14957 (prop (org-icompleting-read "Property: "
14958 (org-entry-properties nil 'standard))))
14959 (list prop)))
14960 (message "Property %s %s" property
14961 (if (org-entry-delete nil property)
14962 "deleted"
14963 "was not present in the entry")))
14965 (defun org-delete-property-globally (property)
14966 "Remove PROPERTY globally, from all entries."
14967 (interactive
14968 (let* ((completion-ignore-case t)
14969 (prop (org-icompleting-read
14970 "Globally remove property: "
14971 (mapcar 'list (org-buffer-property-keys)))))
14972 (list prop)))
14973 (save-excursion
14974 (save-restriction
14975 (widen)
14976 (goto-char (point-min))
14977 (let ((cnt 0))
14978 (while (re-search-forward
14979 (org-re-property property)
14980 nil t)
14981 (setq cnt (1+ cnt))
14982 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14983 (message "Property \"%s\" removed from %d entries" property cnt)))))
14985 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14987 (defun org-compute-property-at-point ()
14988 "Compute the property at point.
14989 This looks for an enclosing column format, extracts the operator and
14990 then applies it to the property in the column format's scope."
14991 (interactive)
14992 (unless (org-at-property-p)
14993 (error "Not at a property"))
14994 (let ((prop (org-match-string-no-properties 2)))
14995 (org-columns-get-format-and-top-level)
14996 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14997 (error "No operator defined for property %s" prop))
14998 (org-columns-compute prop)))
15000 (defvar org-property-allowed-value-functions nil
15001 "Hook for functions supplying allowed values for a specific property.
15002 The functions must take a single argument, the name of the property, and
15003 return a flat list of allowed values. If \":ETC\" is one of
15004 the values, this means that these values are intended as defaults for
15005 completion, but that other values should be allowed too.
15006 The functions must return nil if they are not responsible for this
15007 property.")
15009 (defun org-property-get-allowed-values (pom property &optional table)
15010 "Get allowed values for the property PROPERTY.
15011 When TABLE is non-nil, return an alist that can directly be used for
15012 completion."
15013 (let (vals)
15014 (cond
15015 ((equal property "TODO")
15016 (setq vals (org-with-point-at pom
15017 (append org-todo-keywords-1 '("")))))
15018 ((equal property "PRIORITY")
15019 (let ((n org-lowest-priority))
15020 (while (>= n org-highest-priority)
15021 (push (char-to-string n) vals)
15022 (setq n (1- n)))))
15023 ((member property org-special-properties))
15024 ((setq vals (run-hook-with-args-until-success
15025 'org-property-allowed-value-functions property)))
15027 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15028 (when (and vals (string-match "\\S-" vals))
15029 (setq vals (car (read-from-string (concat "(" vals ")"))))
15030 (setq vals (mapcar (lambda (x)
15031 (cond ((stringp x) x)
15032 ((numberp x) (number-to-string x))
15033 ((symbolp x) (symbol-name x))
15034 (t "???")))
15035 vals)))))
15036 (when (member ":ETC" vals)
15037 (setq vals (remove ":ETC" vals))
15038 (org-add-props (car vals) '(org-unrestricted t)))
15039 (if table (mapcar 'list vals) vals)))
15041 (defun org-property-previous-allowed-value (&optional previous)
15042 "Switch to the next allowed value for this property."
15043 (interactive)
15044 (org-property-next-allowed-value t))
15046 (defun org-property-next-allowed-value (&optional previous)
15047 "Switch to the next allowed value for this property."
15048 (interactive)
15049 (unless (org-at-property-p)
15050 (error "Not at a property"))
15051 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15052 (key (match-string 2))
15053 (value (match-string 3))
15054 (allowed (or (org-property-get-allowed-values (point) key)
15055 (and (member value '("[ ]" "[-]" "[X]"))
15056 '("[ ]" "[X]"))))
15057 nval)
15058 (unless allowed
15059 (error "Allowed values for this property have not been defined"))
15060 (if previous (setq allowed (reverse allowed)))
15061 (if (member value allowed)
15062 (setq nval (car (cdr (member value allowed)))))
15063 (setq nval (or nval (car allowed)))
15064 (if (equal nval value)
15065 (error "Only one allowed value for this property"))
15066 (org-at-property-p)
15067 (replace-match (concat " :" key ": " nval) t t)
15068 (org-indent-line)
15069 (beginning-of-line 1)
15070 (skip-chars-forward " \t")
15071 (when (equal prop org-effort-property)
15072 (save-excursion
15073 (org-back-to-heading t)
15074 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15075 (run-hook-with-args 'org-property-changed-functions key nval)))
15077 (defun org-find-olp (path &optional this-buffer)
15078 "Return a marker pointing to the entry at outline path OLP.
15079 If anything goes wrong, throw an error.
15080 You can wrap this call to catch the error like this:
15082 (condition-case msg
15083 (org-mobile-locate-entry (match-string 4))
15084 (error (nth 1 msg)))
15086 The return value will then be either a string with the error message,
15087 or a marker if everything is OK.
15089 If THIS-BUFFER is set, the outline path does not contain a file,
15090 only headings."
15091 (let* ((file (if this-buffer buffer-file-name (pop path)))
15092 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15093 (level 1)
15094 (lmin 1)
15095 (lmax 1)
15096 limit re end found pos heading cnt flevel)
15097 (unless buffer (error "File not found :%s" file))
15098 (with-current-buffer buffer
15099 (save-excursion
15100 (save-restriction
15101 (widen)
15102 (setq limit (point-max))
15103 (goto-char (point-min))
15104 (while (setq heading (pop path))
15105 (setq re (format org-complex-heading-regexp-format
15106 (regexp-quote heading)))
15107 (setq cnt 0 pos (point))
15108 (while (re-search-forward re end t)
15109 (setq level (- (match-end 1) (match-beginning 1)))
15110 (if (and (>= level lmin) (<= level lmax))
15111 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15112 (when (= cnt 0) (error "Heading not found on level %d: %s"
15113 lmax heading))
15114 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15115 lmax heading))
15116 (goto-char found)
15117 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15118 (setq end (save-excursion (org-end-of-subtree t t))))
15119 (when (org-at-heading-p)
15120 (point-marker)))))))
15122 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15123 "Find node HEADING in BUFFER.
15124 Return a marker to the heading if it was found, or nil if not.
15125 If POS-ONLY is set, return just the position instead of a marker.
15127 The heading text must match exact, but it may have a TODO keyword,
15128 a priority cookie and tags in the standard locations."
15129 (with-current-buffer (or buffer (current-buffer))
15130 (save-excursion
15131 (save-restriction
15132 (widen)
15133 (goto-char (point-min))
15134 (let (case-fold-search)
15135 (if (re-search-forward
15136 (format org-complex-heading-regexp-format
15137 (regexp-quote heading)) nil t)
15138 (if pos-only
15139 (match-beginning 0)
15140 (move-marker (make-marker) (match-beginning 0)))))))))
15142 (defun org-find-exact-heading-in-directory (heading &optional dir)
15143 "Find Org node headline HEADING in all .org files in directory DIR.
15144 When the target headline is found, return a marker to this location."
15145 (let ((files (directory-files (or dir default-directory)
15146 nil "\\`[^.#].*\\.org\\'"))
15147 file visiting m buffer)
15148 (catch 'found
15149 (while (setq file (pop files))
15150 (message "trying %s" file)
15151 (setq visiting (org-find-base-buffer-visiting file))
15152 (setq buffer (or visiting (find-file-noselect file)))
15153 (setq m (org-find-exact-headline-in-buffer
15154 heading buffer))
15155 (when (and (not m) (not visiting)) (kill-buffer buffer))
15156 (and m (throw 'found m))))))
15158 (defun org-find-entry-with-id (ident)
15159 "Locate the entry that contains the ID property with exact value IDENT.
15160 IDENT can be a string, a symbol or a number, this function will search for
15161 the string representation of it.
15162 Return the position where this entry starts, or nil if there is no such entry."
15163 (interactive "sID: ")
15164 (let ((id (cond
15165 ((stringp ident) ident)
15166 ((symbol-name ident) (symbol-name ident))
15167 ((numberp ident) (number-to-string ident))
15168 (t (error "IDENT %s must be a string, symbol or number" ident))))
15169 (case-fold-search nil))
15170 (save-excursion
15171 (save-restriction
15172 (widen)
15173 (goto-char (point-min))
15174 (when (re-search-forward
15175 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15176 nil t)
15177 (org-back-to-heading t)
15178 (point))))))
15180 ;;;; Timestamps
15182 (defvar org-last-changed-timestamp nil)
15183 (defvar org-last-inserted-timestamp nil
15184 "The last time stamp inserted with `org-insert-time-stamp'.")
15185 (defvar org-time-was-given) ; dynamically scoped parameter
15186 (defvar org-end-time-was-given) ; dynamically scoped parameter
15187 (defvar org-ts-what) ; dynamically scoped parameter
15189 (defun org-time-stamp (arg &optional inactive)
15190 "Prompt for a date/time and insert a time stamp.
15191 If the user specifies a time like HH:MM or if this command is
15192 called with at least one prefix argument, the time stamp contains
15193 the date and the time. Otherwise, only the date is be included.
15195 All parts of a date not specified by the user is filled in from
15196 the current date/time. So if you just press return without
15197 typing anything, the time stamp will represent the current
15198 date/time.
15200 If there is already a timestamp at the cursor, it will be
15201 modified.
15203 With two universal prefix arguments, insert an active timestamp
15204 with the current time without prompting the user."
15205 (interactive "P")
15206 (let* ((ts nil)
15207 (default-time
15208 ;; Default time is either today, or, when entering a range,
15209 ;; the range start.
15210 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15211 (save-excursion
15212 (re-search-backward
15213 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15214 (- (point) 20) t)))
15215 (apply 'encode-time (org-parse-time-string (match-string 1)))
15216 (current-time)))
15217 (default-input (and ts (org-get-compact-tod ts)))
15218 (repeater (save-excursion
15219 (save-match-data
15220 (beginning-of-line)
15221 (when (re-search-forward
15222 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15223 (save-excursion (progn (end-of-line) (point))) t)
15224 (match-string 0)))))
15225 org-time-was-given org-end-time-was-given time)
15226 (cond
15227 ((and (org-at-timestamp-p t)
15228 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15229 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15230 (insert "--")
15231 (setq time (let ((this-command this-command))
15232 (org-read-date arg 'totime nil nil
15233 default-time default-input inactive)))
15234 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15235 ((org-at-timestamp-p t)
15236 (setq time (let ((this-command this-command))
15237 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15238 (when (org-at-timestamp-p t) ; just to get the match data
15239 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15240 (replace-match "")
15241 (setq org-last-changed-timestamp
15242 (org-insert-time-stamp
15243 time (or org-time-was-given arg)
15244 inactive nil nil (list org-end-time-was-given)))
15245 (when repeater (goto-char (1- (point))) (insert " " repeater)
15246 (setq org-last-changed-timestamp
15247 (concat (substring org-last-inserted-timestamp 0 -1)
15248 " " repeater ">"))))
15249 (message "Timestamp updated"))
15250 ((equal arg '(16))
15251 (org-insert-time-stamp (current-time) t))
15253 (setq time (let ((this-command this-command))
15254 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15255 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15256 nil nil (list org-end-time-was-given))))))
15258 ;; FIXME: can we use this for something else, like computing time differences?
15259 (defun org-get-compact-tod (s)
15260 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15261 (let* ((t1 (match-string 1 s))
15262 (h1 (string-to-number (match-string 2 s)))
15263 (m1 (string-to-number (match-string 3 s)))
15264 (t2 (and (match-end 4) (match-string 5 s)))
15265 (h2 (and t2 (string-to-number (match-string 6 s))))
15266 (m2 (and t2 (string-to-number (match-string 7 s))))
15267 dh dm)
15268 (if (not t2)
15270 (setq dh (- h2 h1) dm (- m2 m1))
15271 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15272 (concat t1 "+" (number-to-string dh)
15273 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15275 (defun org-time-stamp-inactive (&optional arg)
15276 "Insert an inactive time stamp.
15277 An inactive time stamp is enclosed in square brackets instead of angle
15278 brackets. It is inactive in the sense that it does not trigger agenda entries,
15279 does not link to the calendar and cannot be changed with the S-cursor keys.
15280 So these are more for recording a certain time/date."
15281 (interactive "P")
15282 (org-time-stamp arg 'inactive))
15284 (defvar org-date-ovl (make-overlay 1 1))
15285 (overlay-put org-date-ovl 'face 'org-date-selected)
15286 (org-detach-overlay org-date-ovl)
15288 (defvar org-ans1) ; dynamically scoped parameter
15289 (defvar org-ans2) ; dynamically scoped parameter
15291 (defvar org-plain-time-of-day-regexp) ; defined below
15293 (defvar org-overriding-default-time nil) ; dynamically scoped
15294 (defvar org-read-date-overlay nil)
15295 (defvar org-dcst nil) ; dynamically scoped
15296 (defvar org-read-date-history nil)
15297 (defvar org-read-date-final-answer nil)
15298 (defvar org-read-date-analyze-futurep nil)
15299 (defvar org-read-date-analyze-forced-year nil)
15300 (defvar org-read-date-inactive)
15302 (defun org-read-date (&optional org-with-time to-time from-string prompt
15303 default-time default-input inactive)
15304 "Read a date, possibly a time, and make things smooth for the user.
15305 The prompt will suggest to enter an ISO date, but you can also enter anything
15306 which will at least partially be understood by `parse-time-string'.
15307 Unrecognized parts of the date will default to the current day, month, year,
15308 hour and minute. If this command is called to replace a timestamp at point,
15309 or to enter the second timestamp of a range, the default time is taken
15310 from the existing stamp. Furthermore, the command prefers the future,
15311 so if you are giving a date where the year is not given, and the day-month
15312 combination is already past in the current year, it will assume you
15313 mean next year. For details, see the manual. A few examples:
15315 3-2-5 --> 2003-02-05
15316 feb 15 --> currentyear-02-15
15317 2/15 --> currentyear-02-15
15318 sep 12 9 --> 2009-09-12
15319 12:45 --> today 12:45
15320 22 sept 0:34 --> currentyear-09-22 0:34
15321 12 --> currentyear-currentmonth-12
15322 Fri --> nearest Friday (today or later)
15323 etc.
15325 Furthermore you can specify a relative date by giving, as the *first* thing
15326 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15327 change in days weeks, months, years.
15328 With a single plus or minus, the date is relative to today. With a double
15329 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15330 +4d --> four days from today
15331 +4 --> same as above
15332 +2w --> two weeks from today
15333 ++5 --> five days from default date
15335 The function understands only English month and weekday abbreviations.
15337 While prompting, a calendar is popped up - you can also select the
15338 date with the mouse (button 1). The calendar shows a period of three
15339 months. To scroll it to other months, use the keys `>' and `<'.
15340 If you don't like the calendar, turn it off with
15341 \(setq org-read-date-popup-calendar nil)
15343 With optional argument TO-TIME, the date will immediately be converted
15344 to an internal time.
15345 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15346 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15347 still enter a time, and this function will inform the calling routine
15348 about this change. The calling routine may then choose to change the
15349 format used to insert the time stamp into the buffer to include the time.
15350 With optional argument FROM-STRING, read from this string instead from
15351 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15352 the time/date that is used for everything that is not specified by the
15353 user."
15354 (require 'parse-time)
15355 (let* ((org-time-stamp-rounding-minutes
15356 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15357 (org-dcst org-display-custom-times)
15358 (ct (org-current-time))
15359 (org-def (or org-overriding-default-time default-time ct))
15360 (org-defdecode (decode-time org-def))
15361 (dummy (progn
15362 (when (< (nth 2 org-defdecode) org-extend-today-until)
15363 (setcar (nthcdr 2 org-defdecode) -1)
15364 (setcar (nthcdr 1 org-defdecode) 59)
15365 (setq org-def (apply 'encode-time org-defdecode)
15366 org-defdecode (decode-time org-def)))))
15367 (mouse-autoselect-window nil) ; Don't let the mouse jump
15368 (calendar-frame-setup nil)
15369 (calendar-setup nil)
15370 (calendar-move-hook nil)
15371 (calendar-view-diary-initially-flag nil)
15372 (calendar-view-holidays-initially-flag nil)
15373 (timestr (format-time-string
15374 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15375 (prompt (concat (if prompt (concat prompt " ") "")
15376 (format "Date+time [%s]: " timestr)))
15377 ans (org-ans0 "") org-ans1 org-ans2 final)
15379 (cond
15380 (from-string (setq ans from-string))
15381 (org-read-date-popup-calendar
15382 (save-excursion
15383 (save-window-excursion
15384 (calendar)
15385 (org-eval-in-calendar '(setq cursor-type nil) t)
15386 (unwind-protect
15387 (progn
15388 (calendar-forward-day (- (time-to-days org-def)
15389 (calendar-absolute-from-gregorian
15390 (calendar-current-date))))
15391 (org-eval-in-calendar nil t)
15392 (let* ((old-map (current-local-map))
15393 (map (copy-keymap calendar-mode-map))
15394 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15395 (org-defkey map (kbd "RET") 'org-calendar-select)
15396 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15397 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15398 (org-defkey minibuffer-local-map [(meta shift left)]
15399 (lambda () (interactive)
15400 (org-eval-in-calendar '(calendar-backward-month 1))))
15401 (org-defkey minibuffer-local-map [(meta shift right)]
15402 (lambda () (interactive)
15403 (org-eval-in-calendar '(calendar-forward-month 1))))
15404 (org-defkey minibuffer-local-map [(meta shift up)]
15405 (lambda () (interactive)
15406 (org-eval-in-calendar '(calendar-backward-year 1))))
15407 (org-defkey minibuffer-local-map [(meta shift down)]
15408 (lambda () (interactive)
15409 (org-eval-in-calendar '(calendar-forward-year 1))))
15410 (org-defkey minibuffer-local-map [?\e (shift left)]
15411 (lambda () (interactive)
15412 (org-eval-in-calendar '(calendar-backward-month 1))))
15413 (org-defkey minibuffer-local-map [?\e (shift right)]
15414 (lambda () (interactive)
15415 (org-eval-in-calendar '(calendar-forward-month 1))))
15416 (org-defkey minibuffer-local-map [?\e (shift up)]
15417 (lambda () (interactive)
15418 (org-eval-in-calendar '(calendar-backward-year 1))))
15419 (org-defkey minibuffer-local-map [?\e (shift down)]
15420 (lambda () (interactive)
15421 (org-eval-in-calendar '(calendar-forward-year 1))))
15422 (org-defkey minibuffer-local-map [(shift up)]
15423 (lambda () (interactive)
15424 (org-eval-in-calendar '(calendar-backward-week 1))))
15425 (org-defkey minibuffer-local-map [(shift down)]
15426 (lambda () (interactive)
15427 (org-eval-in-calendar '(calendar-forward-week 1))))
15428 (org-defkey minibuffer-local-map [(shift left)]
15429 (lambda () (interactive)
15430 (org-eval-in-calendar '(calendar-backward-day 1))))
15431 (org-defkey minibuffer-local-map [(shift right)]
15432 (lambda () (interactive)
15433 (org-eval-in-calendar '(calendar-forward-day 1))))
15434 (org-defkey minibuffer-local-map ">"
15435 (lambda () (interactive)
15436 (org-eval-in-calendar '(scroll-calendar-left 1))))
15437 (org-defkey minibuffer-local-map "<"
15438 (lambda () (interactive)
15439 (org-eval-in-calendar '(scroll-calendar-right 1))))
15440 (org-defkey minibuffer-local-map "\C-v"
15441 (lambda () (interactive)
15442 (org-eval-in-calendar
15443 '(calendar-scroll-left-three-months 1))))
15444 (org-defkey minibuffer-local-map "\M-v"
15445 (lambda () (interactive)
15446 (org-eval-in-calendar
15447 '(calendar-scroll-right-three-months 1))))
15448 (run-hooks 'org-read-date-minibuffer-setup-hook)
15449 (unwind-protect
15450 (progn
15451 (use-local-map map)
15452 (setq org-read-date-inactive inactive)
15453 (add-hook 'post-command-hook 'org-read-date-display)
15454 (setq org-ans0 (read-string prompt default-input
15455 'org-read-date-history nil))
15456 ;; org-ans0: from prompt
15457 ;; org-ans1: from mouse click
15458 ;; org-ans2: from calendar motion
15459 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15460 (remove-hook 'post-command-hook 'org-read-date-display)
15461 (use-local-map old-map)
15462 (when org-read-date-overlay
15463 (delete-overlay org-read-date-overlay)
15464 (setq org-read-date-overlay nil)))))
15465 (bury-buffer "*Calendar*")))))
15467 (t ; Naked prompt only
15468 (unwind-protect
15469 (setq ans (read-string prompt default-input
15470 'org-read-date-history timestr))
15471 (when org-read-date-overlay
15472 (delete-overlay org-read-date-overlay)
15473 (setq org-read-date-overlay nil)))))
15475 (setq final (org-read-date-analyze ans org-def org-defdecode))
15477 (when org-read-date-analyze-forced-year
15478 (message "Year was forced into %s"
15479 (if org-read-date-force-compatible-dates
15480 "compatible range (1970-2037)"
15481 "range representable on this machine"))
15482 (ding))
15484 ;; One round trip to get rid of 34th of August and stuff like that....
15485 (setq final (decode-time (apply 'encode-time final)))
15487 (setq org-read-date-final-answer ans)
15489 (if to-time
15490 (apply 'encode-time final)
15491 (if (and (boundp 'org-time-was-given) org-time-was-given)
15492 (format "%04d-%02d-%02d %02d:%02d"
15493 (nth 5 final) (nth 4 final) (nth 3 final)
15494 (nth 2 final) (nth 1 final))
15495 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15497 (defvar org-def)
15498 (defvar org-defdecode)
15499 (defvar org-with-time)
15500 (defun org-read-date-display ()
15501 "Display the current date prompt interpretation in the minibuffer."
15502 (when org-read-date-display-live
15503 (when org-read-date-overlay
15504 (delete-overlay org-read-date-overlay))
15505 (when (minibufferp (current-buffer))
15506 (save-excursion
15507 (end-of-line 1)
15508 (while (not (equal (buffer-substring
15509 (max (point-min) (- (point) 4)) (point))
15510 " "))
15511 (insert " ")))
15512 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15513 " " (or org-ans1 org-ans2)))
15514 (org-end-time-was-given nil)
15515 (f (org-read-date-analyze ans org-def org-defdecode))
15516 (fmts (if org-dcst
15517 org-time-stamp-custom-formats
15518 org-time-stamp-formats))
15519 (fmt (if (or org-with-time
15520 (and (boundp 'org-time-was-given) org-time-was-given))
15521 (cdr fmts)
15522 (car fmts)))
15523 (txt (format-time-string fmt (apply 'encode-time f)))
15524 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15525 (txt (concat "=> " txt)))
15526 (when (and org-end-time-was-given
15527 (string-match org-plain-time-of-day-regexp txt))
15528 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15529 org-end-time-was-given
15530 (substring txt (match-end 0)))))
15531 (when org-read-date-analyze-futurep
15532 (setq txt (concat txt " (=>F)")))
15533 (setq org-read-date-overlay
15534 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15535 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15537 (defun org-read-date-analyze (ans org-def org-defdecode)
15538 "Analyze the combined answer of the date prompt."
15539 ;; FIXME: cleanup and comment
15540 (let ((nowdecode (decode-time (current-time)))
15541 delta deltan deltaw deltadef year month day
15542 hour minute second wday pm h2 m2 tl wday1
15543 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15544 (setq org-read-date-analyze-futurep nil
15545 org-read-date-analyze-forced-year nil)
15546 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15547 (setq ans "+0"))
15549 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15550 (setq ans (replace-match "" t t ans)
15551 deltan (car delta)
15552 deltaw (nth 1 delta)
15553 deltadef (nth 2 delta)))
15555 ;; Check if there is an iso week date in there. If yes, store the
15556 ;; info and postpone interpreting it until the rest of the parsing
15557 ;; is done.
15558 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15559 (setq iso-year (if (match-end 1)
15560 (org-small-year-to-year
15561 (string-to-number (match-string 1 ans))))
15562 iso-weekday (if (match-end 3)
15563 (string-to-number (match-string 3 ans)))
15564 iso-week (string-to-number (match-string 2 ans)))
15565 (setq ans (replace-match "" t t ans)))
15567 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15568 (when (string-match
15569 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15570 (setq year (if (match-end 2)
15571 (string-to-number (match-string 2 ans))
15572 (progn (setq kill-year t)
15573 (string-to-number (format-time-string "%Y"))))
15574 month (string-to-number (match-string 3 ans))
15575 day (string-to-number (match-string 4 ans)))
15576 (if (< year 100) (setq year (+ 2000 year)))
15577 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15578 t nil ans)))
15580 ;; Help matching dotted european dates
15581 (when (string-match
15582 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15583 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15584 (setq kill-year t)
15585 (string-to-number (format-time-string "%Y")))
15586 day (string-to-number (match-string 1 ans))
15587 month (string-to-number (match-string 2 ans))
15588 ans (replace-match (format "%04d-%02d-%02d" year month day)
15589 t nil ans)))
15591 ;; Help matching american dates, like 5/30 or 5/30/7
15592 (when (string-match
15593 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15594 (setq year (if (match-end 4)
15595 (string-to-number (match-string 4 ans))
15596 (progn (setq kill-year t)
15597 (string-to-number (format-time-string "%Y"))))
15598 month (string-to-number (match-string 1 ans))
15599 day (string-to-number (match-string 2 ans)))
15600 (if (< year 100) (setq year (+ 2000 year)))
15601 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15602 t nil ans)))
15603 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15604 ;; If there is a time with am/pm, and *no* time without it, we convert
15605 ;; so that matching will be successful.
15606 (loop for i from 1 to 2 do ; twice, for end time as well
15607 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15608 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15609 (setq hour (string-to-number (match-string 1 ans))
15610 minute (if (match-end 3)
15611 (string-to-number (match-string 3 ans))
15613 pm (equal ?p
15614 (string-to-char (downcase (match-string 4 ans)))))
15615 (if (and (= hour 12) (not pm))
15616 (setq hour 0)
15617 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15618 (setq ans (replace-match (format "%02d:%02d" hour minute)
15619 t t ans))))
15621 ;; Check if a time range is given as a duration
15622 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15623 (setq hour (string-to-number (match-string 1 ans))
15624 h2 (+ hour (string-to-number (match-string 3 ans)))
15625 minute (string-to-number (match-string 2 ans))
15626 m2 (+ minute (if (match-end 5) (string-to-number
15627 (match-string 5 ans))0)))
15628 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15629 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15630 t t ans)))
15632 ;; Check if there is a time range
15633 (when (boundp 'org-end-time-was-given)
15634 (setq org-time-was-given nil)
15635 (when (and (string-match org-plain-time-of-day-regexp ans)
15636 (match-end 8))
15637 (setq org-end-time-was-given (match-string 8 ans))
15638 (setq ans (concat (substring ans 0 (match-beginning 7))
15639 (substring ans (match-end 7))))))
15641 (setq tl (parse-time-string ans)
15642 day (or (nth 3 tl) (nth 3 org-defdecode))
15643 month (or (nth 4 tl)
15644 (if (and org-read-date-prefer-future
15645 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15646 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15647 (nth 4 org-defdecode)))
15648 year (or (and (not kill-year) (nth 5 tl))
15649 (if (and org-read-date-prefer-future
15650 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15651 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15652 (nth 5 org-defdecode)))
15653 hour (or (nth 2 tl) (nth 2 org-defdecode))
15654 minute (or (nth 1 tl) (nth 1 org-defdecode))
15655 second (or (nth 0 tl) 0)
15656 wday (nth 6 tl))
15658 (when (and (eq org-read-date-prefer-future 'time)
15659 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15660 (equal day (nth 3 nowdecode))
15661 (equal month (nth 4 nowdecode))
15662 (equal year (nth 5 nowdecode))
15663 (nth 2 tl)
15664 (or (< (nth 2 tl) (nth 2 nowdecode))
15665 (and (= (nth 2 tl) (nth 2 nowdecode))
15666 (nth 1 tl)
15667 (< (nth 1 tl) (nth 1 nowdecode)))))
15668 (setq day (1+ day)
15669 futurep t))
15671 ;; Special date definitions below
15672 (cond
15673 (iso-week
15674 ;; There was an iso week
15675 (require 'cal-iso)
15676 (setq futurep nil)
15677 (setq year (or iso-year year)
15678 day (or iso-weekday wday 1)
15679 wday nil ; to make sure that the trigger below does not match
15680 iso-date (calendar-gregorian-from-absolute
15681 (calendar-absolute-from-iso
15682 (list iso-week day year))))
15683 ; FIXME: Should we also push ISO weeks into the future?
15684 ; (when (and org-read-date-prefer-future
15685 ; (not iso-year)
15686 ; (< (calendar-absolute-from-gregorian iso-date)
15687 ; (time-to-days (current-time))))
15688 ; (setq year (1+ year)
15689 ; iso-date (calendar-gregorian-from-absolute
15690 ; (calendar-absolute-from-iso
15691 ; (list iso-week day year)))))
15692 (setq month (car iso-date)
15693 year (nth 2 iso-date)
15694 day (nth 1 iso-date)))
15695 (deltan
15696 (setq futurep nil)
15697 (unless deltadef
15698 (let ((now (decode-time (current-time))))
15699 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15700 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15701 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15702 ((equal deltaw "m") (setq month (+ month deltan)))
15703 ((equal deltaw "y") (setq year (+ year deltan)))))
15704 ((and wday (not (nth 3 tl)))
15705 ;; Weekday was given, but no day, so pick that day in the week
15706 ;; on or after the derived date.
15707 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15708 (unless (equal wday wday1)
15709 (setq day (+ day (% (- wday wday1 -7) 7))))))
15710 (if (and (boundp 'org-time-was-given)
15711 (nth 2 tl))
15712 (setq org-time-was-given t))
15713 (if (< year 100) (setq year (+ 2000 year)))
15714 ;; Check of the date is representable
15715 (if org-read-date-force-compatible-dates
15716 (progn
15717 (if (< year 1970)
15718 (setq year 1970 org-read-date-analyze-forced-year t))
15719 (if (> year 2037)
15720 (setq year 2037 org-read-date-analyze-forced-year t)))
15721 (condition-case nil
15722 (ignore (encode-time second minute hour day month year))
15723 (error
15724 (setq year (nth 5 org-defdecode))
15725 (setq org-read-date-analyze-forced-year t))))
15726 (setq org-read-date-analyze-futurep futurep)
15727 (list second minute hour day month year)))
15729 (defvar parse-time-weekdays)
15730 (defun org-read-date-get-relative (s today default)
15731 "Check string S for special relative date string.
15732 TODAY and DEFAULT are internal times, for today and for a default.
15733 Return shift list (N what def-flag)
15734 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15735 N is the number of WHATs to shift.
15736 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15737 the DEFAULT date rather than TODAY."
15738 (require 'parse-time)
15739 (when (and
15740 (string-match
15741 (concat
15742 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15743 "\\([0-9]+\\)?"
15744 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15745 "\\([ \t]\\|$\\)") s)
15746 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15747 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15748 (string-to-char (substring (match-string 1 s) -1))
15749 ?+))
15750 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15751 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15752 (what (if (match-end 3) (match-string 3 s) "d"))
15753 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15754 (date (if rel default today))
15755 (wday (nth 6 (decode-time date)))
15756 delta)
15757 (if wday1
15758 (progn
15759 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15760 (if (= dir ?-) (setq delta (- delta 7)))
15761 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15762 (list delta "d" rel))
15763 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15765 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15766 "Turn a user-specified date into the internal representation.
15767 The internal representation needed by the calendar is (month day year).
15768 This is a wrapper to handle the brain-dead convention in calendar that
15769 user function argument order change dependent on argument order."
15770 (if (boundp 'calendar-date-style)
15771 (cond
15772 ((eq calendar-date-style 'american)
15773 (list arg1 arg2 arg3))
15774 ((eq calendar-date-style 'european)
15775 (list arg2 arg1 arg3))
15776 ((eq calendar-date-style 'iso)
15777 (list arg2 arg3 arg1)))
15778 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15779 (if (org-bound-and-true-p european-calendar-style)
15780 (list arg2 arg1 arg3)
15781 (list arg1 arg2 arg3)))))
15783 (defun org-eval-in-calendar (form &optional keepdate)
15784 "Eval FORM in the calendar window and return to current window.
15785 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15786 otherwise stick to the current value of `org-ans2'."
15787 (let ((sf (selected-frame))
15788 (sw (selected-window)))
15789 (select-window (get-buffer-window "*Calendar*" t))
15790 (eval form)
15791 (when (and (not keepdate) (calendar-cursor-to-date))
15792 (let* ((date (calendar-cursor-to-date))
15793 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15794 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15795 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15796 (select-window sw)
15797 (org-select-frame-set-input-focus sf)))
15799 (defun org-calendar-select ()
15800 "Return to `org-read-date' with the date currently selected.
15801 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15802 (interactive)
15803 (when (calendar-cursor-to-date)
15804 (let* ((date (calendar-cursor-to-date))
15805 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15806 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15807 (if (active-minibuffer-window) (exit-minibuffer))))
15809 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15810 "Insert a date stamp for the date given by the internal TIME.
15811 WITH-HM means use the stamp format that includes the time of the day.
15812 INACTIVE means use square brackets instead of angular ones, so that the
15813 stamp will not contribute to the agenda.
15814 PRE and POST are optional strings to be inserted before and after the
15815 stamp.
15816 The command returns the inserted time stamp."
15817 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15818 stamp)
15819 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15820 (insert-before-markers (or pre ""))
15821 (when (listp extra)
15822 (setq extra (car extra))
15823 (if (and (stringp extra)
15824 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15825 (setq extra (format "-%02d:%02d"
15826 (string-to-number (match-string 1 extra))
15827 (string-to-number (match-string 2 extra))))
15828 (setq extra nil)))
15829 (when extra
15830 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15831 (insert-before-markers (setq stamp (format-time-string fmt time)))
15832 (insert-before-markers (or post ""))
15833 (setq org-last-inserted-timestamp stamp)))
15835 (defun org-toggle-time-stamp-overlays ()
15836 "Toggle the use of custom time stamp formats."
15837 (interactive)
15838 (setq org-display-custom-times (not org-display-custom-times))
15839 (unless org-display-custom-times
15840 (let ((p (point-min)) (bmp (buffer-modified-p)))
15841 (while (setq p (next-single-property-change p 'display))
15842 (if (and (get-text-property p 'display)
15843 (eq (get-text-property p 'face) 'org-date))
15844 (remove-text-properties
15845 p (setq p (next-single-property-change p 'display))
15846 '(display t))))
15847 (set-buffer-modified-p bmp)))
15848 (if (featurep 'xemacs)
15849 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15850 (org-restart-font-lock)
15851 (setq org-table-may-need-update t)
15852 (if org-display-custom-times
15853 (message "Time stamps are overlaid with custom format")
15854 (message "Time stamp overlays removed")))
15856 (defun org-display-custom-time (beg end)
15857 "Overlay modified time stamp format over timestamp between BEG and END."
15858 (let* ((ts (buffer-substring beg end))
15859 t1 w1 with-hm tf time str w2 (off 0))
15860 (save-match-data
15861 (setq t1 (org-parse-time-string ts t))
15862 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15863 (setq off (- (match-end 0) (match-beginning 0)))))
15864 (setq end (- end off))
15865 (setq w1 (- end beg)
15866 with-hm (and (nth 1 t1) (nth 2 t1))
15867 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15868 time (org-fix-decoded-time t1)
15869 str (org-add-props
15870 (format-time-string
15871 (substring tf 1 -1) (apply 'encode-time time))
15872 nil 'mouse-face 'highlight)
15873 w2 (length str))
15874 (if (not (= w2 w1))
15875 (add-text-properties (1+ beg) (+ 2 beg)
15876 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15877 (if (featurep 'xemacs)
15878 (progn
15879 (put-text-property beg end 'invisible t)
15880 (put-text-property beg end 'end-glyph (make-glyph str)))
15881 (put-text-property beg end 'display str))))
15883 (defun org-translate-time (string)
15884 "Translate all timestamps in STRING to custom format.
15885 But do this only if the variable `org-display-custom-times' is set."
15886 (when org-display-custom-times
15887 (save-match-data
15888 (let* ((start 0)
15889 (re org-ts-regexp-both)
15890 t1 with-hm inactive tf time str beg end)
15891 (while (setq start (string-match re string start))
15892 (setq beg (match-beginning 0)
15893 end (match-end 0)
15894 t1 (save-match-data
15895 (org-parse-time-string (substring string beg end) t))
15896 with-hm (and (nth 1 t1) (nth 2 t1))
15897 inactive (equal (substring string beg (1+ beg)) "[")
15898 tf (funcall (if with-hm 'cdr 'car)
15899 org-time-stamp-custom-formats)
15900 time (org-fix-decoded-time t1)
15901 str (format-time-string
15902 (concat
15903 (if inactive "[" "<") (substring tf 1 -1)
15904 (if inactive "]" ">"))
15905 (apply 'encode-time time))
15906 string (replace-match str t t string)
15907 start (+ start (length str)))))))
15908 string)
15910 (defun org-fix-decoded-time (time)
15911 "Set 0 instead of nil for the first 6 elements of time.
15912 Don't touch the rest."
15913 (let ((n 0))
15914 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15916 (defun org-days-to-time (timestamp-string)
15917 "Difference between TIMESTAMP-STRING and now in days."
15918 (- (time-to-days (org-time-string-to-time timestamp-string))
15919 (time-to-days (current-time))))
15921 (defun org-deadline-close (timestamp-string &optional ndays)
15922 "Is the time in TIMESTAMP-STRING close to the current date?"
15923 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15924 (and (< (org-days-to-time timestamp-string) ndays)
15925 (not (org-entry-is-done-p))))
15927 (defun org-get-wdays (ts)
15928 "Get the deadline lead time appropriate for timestring TS."
15929 (cond
15930 ((<= org-deadline-warning-days 0)
15931 ;; 0 or negative, enforce this value no matter what
15932 (- org-deadline-warning-days))
15933 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15934 ;; lead time is specified.
15935 (floor (* (string-to-number (match-string 1 ts))
15936 (cdr (assoc (match-string 2 ts)
15937 '(("d" . 1) ("w" . 7)
15938 ("m" . 30.4) ("y" . 365.25)
15939 ("h" . 0.041667)))))))
15940 ;; go for the default.
15941 (t org-deadline-warning-days)))
15943 (defun org-calendar-select-mouse (ev)
15944 "Return to `org-read-date' with the date currently selected.
15945 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15946 (interactive "e")
15947 (mouse-set-point ev)
15948 (when (calendar-cursor-to-date)
15949 (let* ((date (calendar-cursor-to-date))
15950 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15951 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15952 (if (active-minibuffer-window) (exit-minibuffer))))
15954 (defun org-check-deadlines (ndays)
15955 "Check if there are any deadlines due or past due.
15956 A deadline is considered due if it happens within `org-deadline-warning-days'
15957 days from today's date. If the deadline appears in an entry marked DONE,
15958 it is not shown. The prefix arg NDAYS can be used to test that many
15959 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15960 (interactive "P")
15961 (let* ((org-warn-days
15962 (cond
15963 ((equal ndays '(4)) 100000)
15964 (ndays (prefix-numeric-value ndays))
15965 (t (abs org-deadline-warning-days))))
15966 (case-fold-search nil)
15967 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15968 (callback
15969 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15971 (message "%d deadlines past-due or due within %d days"
15972 (org-occur regexp nil callback)
15973 org-warn-days)))
15975 (defsubst org-re-timestamp (type)
15976 "Return a regexp for timestamp TYPE.
15977 Allowed values for TYPE are:
15979 all: all timestamps
15980 active: only active timestamps (<...>)
15981 inactive: only inactive timestamps ([...])
15982 scheduled: only scheduled timestamps
15983 deadline: only deadline timestamps
15985 When TYPE is nil, fall back on returning a regexp that matches
15986 both scheduled and deadline timestamps."
15987 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15988 ((eq type 'active) org-ts-regexp)
15989 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15990 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15991 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15992 ((eq type 'scheduled-or-deadline)
15993 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15995 (defun org-check-before-date (date)
15996 "Check if there are deadlines or scheduled entries before DATE."
15997 (interactive (list (org-read-date)))
15998 (let ((case-fold-search nil)
15999 (regexp (org-re-timestamp org-ts-type))
16000 (callback
16001 (lambda () (time-less-p
16002 (org-time-string-to-time (match-string 1))
16003 (org-time-string-to-time date)))))
16004 (message "%d entries before %s"
16005 (org-occur regexp nil callback) date)))
16007 (defun org-check-after-date (date)
16008 "Check if there are deadlines or scheduled entries after DATE."
16009 (interactive (list (org-read-date)))
16010 (let ((case-fold-search nil)
16011 (regexp (org-re-timestamp org-ts-type))
16012 (callback
16013 (lambda () (not
16014 (time-less-p
16015 (org-time-string-to-time (match-string 1))
16016 (org-time-string-to-time date))))))
16017 (message "%d entries after %s"
16018 (org-occur regexp nil callback) date)))
16020 (defun org-check-dates-range (start-date end-date)
16021 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16022 (interactive (list (org-read-date nil nil nil "Range starts")
16023 (org-read-date nil nil nil "Range end")))
16024 (let ((case-fold-search nil)
16025 (regexp (org-re-timestamp org-ts-type))
16026 (callback
16027 (lambda ()
16028 (let ((match (match-string 1)))
16029 (and
16030 (not (time-less-p
16031 (org-time-string-to-time match)
16032 (org-time-string-to-time start-date)))
16033 (time-less-p
16034 (org-time-string-to-time match)
16035 (org-time-string-to-time end-date)))))))
16036 (message "%d entries between %s and %s"
16037 (org-occur regexp nil callback) start-date end-date)))
16039 (defun org-evaluate-time-range (&optional to-buffer)
16040 "Evaluate a time range by computing the difference between start and end.
16041 Normally the result is just printed in the echo area, but with prefix arg
16042 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16043 If the time range is actually in a table, the result is inserted into the
16044 next column.
16045 For time difference computation, a year is assumed to be exactly 365
16046 days in order to avoid rounding problems."
16047 (interactive "P")
16049 (org-clock-update-time-maybe)
16050 (save-excursion
16051 (unless (org-at-date-range-p t)
16052 (goto-char (point-at-bol))
16053 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16054 (if (not (org-at-date-range-p t))
16055 (error "Not at a time-stamp range, and none found in current line")))
16056 (let* ((ts1 (match-string 1))
16057 (ts2 (match-string 2))
16058 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16059 (match-end (match-end 0))
16060 (time1 (org-time-string-to-time ts1))
16061 (time2 (org-time-string-to-time ts2))
16062 (t1 (org-float-time time1))
16063 (t2 (org-float-time time2))
16064 (diff (abs (- t2 t1)))
16065 (negative (< (- t2 t1) 0))
16066 ;; (ys (floor (* 365 24 60 60)))
16067 (ds (* 24 60 60))
16068 (hs (* 60 60))
16069 (fy "%dy %dd %02d:%02d")
16070 (fy1 "%dy %dd")
16071 (fd "%dd %02d:%02d")
16072 (fd1 "%dd")
16073 (fh "%02d:%02d")
16074 y d h m align)
16075 (if havetime
16076 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16078 d (floor (/ diff ds)) diff (mod diff ds)
16079 h (floor (/ diff hs)) diff (mod diff hs)
16080 m (floor (/ diff 60)))
16081 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16083 d (floor (+ (/ diff ds) 0.5))
16084 h 0 m 0))
16085 (if (not to-buffer)
16086 (message "%s" (org-make-tdiff-string y d h m))
16087 (if (org-at-table-p)
16088 (progn
16089 (goto-char match-end)
16090 (setq align t)
16091 (and (looking-at " *|") (goto-char (match-end 0))))
16092 (goto-char match-end))
16093 (if (looking-at
16094 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16095 (replace-match ""))
16096 (if negative (insert " -"))
16097 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16098 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16099 (insert " " (format fh h m))))
16100 (if align (org-table-align))
16101 (message "Time difference inserted")))))
16103 (defun org-make-tdiff-string (y d h m)
16104 (let ((fmt "")
16105 (l nil))
16106 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16107 l (push y l)))
16108 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16109 l (push d l)))
16110 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16111 l (push h l)))
16112 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16113 l (push m l)))
16114 (apply 'format fmt (nreverse l))))
16116 (defun org-time-string-to-time (s &optional buffer pos)
16117 "Convert a timestamp string into internal time."
16118 (condition-case errdata
16119 (apply 'encode-time (org-parse-time-string s))
16120 (error (error "Bad timestamp `%s'%s\nError was: %s"
16121 s (if (not (and buffer pos))
16123 (format " at %d in buffer `%s'" pos buffer))
16124 (cdr errdata)))))
16126 (defun org-time-string-to-seconds (s)
16127 "Convert a timestamp string to a number of seconds."
16128 (org-float-time (org-time-string-to-time s)))
16130 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16131 "Convert a time stamp to an absolute day number.
16132 If there is a specifier for a cyclic time stamp, get the closest date to
16133 DAYNR.
16134 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16135 The variable date is bound by the calendar when this is called."
16136 (cond
16137 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16138 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16139 daynr
16140 (+ daynr 1000)))
16141 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16142 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16143 (time-to-days (current-time))) (match-string 0 s)
16144 prefer show-all))
16145 (t (time-to-days
16146 (condition-case errdata
16147 (apply 'encode-time (org-parse-time-string s))
16148 (error (error "Bad timestamp `%s'%s\nError was: %s"
16149 s (if (not (and buffer pos))
16151 (format " at %d in buffer `%s'" pos buffer))
16152 (cdr errdata))))))))
16154 (defun org-days-to-iso-week (days)
16155 "Return the iso week number."
16156 (require 'cal-iso)
16157 (car (calendar-iso-from-absolute days)))
16159 (defun org-small-year-to-year (year)
16160 "Convert 2-digit years into 4-digit years.
16161 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16162 The year 2000 cannot be abbreviated. Any year larger than 99
16163 is returned unchanged."
16164 (if (< year 38)
16165 (setq year (+ 2000 year))
16166 (if (< year 100)
16167 (setq year (+ 1900 year))))
16168 year)
16170 (defun org-time-from-absolute (d)
16171 "Return the time corresponding to date D.
16172 D may be an absolute day number, or a calendar-type list (month day year)."
16173 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16174 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16176 (defun org-calendar-holiday ()
16177 "List of holidays, for Diary display in Org-mode."
16178 (require 'holidays)
16179 (let ((hl (funcall
16180 (if (fboundp 'calendar-check-holidays)
16181 'calendar-check-holidays 'check-calendar-holidays) date)))
16182 (if hl (mapconcat 'identity hl "; "))))
16184 (defun org-diary-sexp-entry (sexp entry date)
16185 "Process a SEXP diary ENTRY for DATE."
16186 (require 'diary-lib)
16187 (let ((result (if calendar-debug-sexp
16188 (let ((stack-trace-on-error t))
16189 (eval (car (read-from-string sexp))))
16190 (condition-case nil
16191 (eval (car (read-from-string sexp)))
16192 (error
16193 (beep)
16194 (message "Bad sexp at line %d in %s: %s"
16195 (org-current-line)
16196 (buffer-file-name) sexp)
16197 (sleep-for 2))))))
16198 (cond ((stringp result) (split-string result "; "))
16199 ((and (consp result)
16200 (not (consp (cdr result)))
16201 (stringp (cdr result))) (cdr result))
16202 ((and (consp result)
16203 (stringp (car result))) result)
16204 (result entry))))
16206 (defun org-diary-to-ical-string (frombuf)
16207 "Get iCalendar entries from diary entries in buffer FROMBUF.
16208 This uses the icalendar.el library."
16209 (let* ((tmpdir (if (featurep 'xemacs)
16210 (temp-directory)
16211 temporary-file-directory))
16212 (tmpfile (make-temp-name
16213 (expand-file-name "orgics" tmpdir)))
16214 buf rtn b e)
16215 (with-current-buffer frombuf
16216 (icalendar-export-region (point-min) (point-max) tmpfile)
16217 (setq buf (find-buffer-visiting tmpfile))
16218 (set-buffer buf)
16219 (goto-char (point-min))
16220 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16221 (setq b (match-beginning 0)))
16222 (goto-char (point-max))
16223 (if (re-search-backward "^END:VEVENT" nil t)
16224 (setq e (match-end 0)))
16225 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16226 (kill-buffer buf)
16227 (delete-file tmpfile)
16228 rtn))
16230 (defun org-closest-date (start current change prefer show-all)
16231 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16232 When PREFER is `past', return a date that is either CURRENT or past.
16233 When PREFER is `future', return a date that is either CURRENT or future.
16234 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16235 ;; Make the proper lists from the dates
16236 (catch 'exit
16237 (let ((a1 '(("h" . hour)
16238 ("d" . day)
16239 ("w" . week)
16240 ("m" . month)
16241 ("y" . year)))
16242 (shour (nth 2 (org-parse-time-string start)))
16243 dn dw sday cday n1 n2 n0
16244 d m y y1 y2 date1 date2 nmonths nm ny m2)
16246 (setq start (org-date-to-gregorian start)
16247 current (org-date-to-gregorian
16248 (if show-all
16249 current
16250 (time-to-days (current-time))))
16251 sday (calendar-absolute-from-gregorian start)
16252 cday (calendar-absolute-from-gregorian current))
16254 (if (<= cday sday) (throw 'exit sday))
16256 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16257 (setq dn (string-to-number (match-string 1 change))
16258 dw (cdr (assoc (match-string 2 change) a1)))
16259 (error "Invalid change specifier: %s" change))
16260 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16261 (cond
16262 ((eq dw 'hour)
16263 (let ((missing-hours
16264 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16265 dn)))
16266 (setq n1 (if (zerop missing-hours) cday
16267 (- cday (1+ (floor (/ missing-hours 24)))))
16268 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16269 ((eq dw 'day)
16270 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16271 n2 (+ n1 dn)))
16272 ((eq dw 'year)
16273 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16274 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16275 (setq date1 (list m d y1)
16276 n1 (calendar-absolute-from-gregorian date1)
16277 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16278 n2 (calendar-absolute-from-gregorian date2)))
16279 ((eq dw 'month)
16280 ;; approx number of month between the two dates
16281 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16282 ;; How often does dn fit in there?
16283 (setq d (nth 1 start) m (car start) y (nth 2 start)
16284 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16285 m (+ m nm)
16286 ny (floor (/ m 12))
16287 y (+ y ny)
16288 m (- m (* ny 12)))
16289 (while (> m 12) (setq m (- m 12) y (1+ y)))
16290 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16291 (setq m2 (+ m dn) y2 y)
16292 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16293 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16294 (while (<= n2 cday)
16295 (setq n1 n2 m m2 y y2)
16296 (setq m2 (+ m dn) y2 y)
16297 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16298 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16299 ;; Make sure n1 is the earlier date
16300 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16301 (if show-all
16302 (cond
16303 ((eq prefer 'past) (if (= cday n2) n2 n1))
16304 ((eq prefer 'future) (if (= cday n1) n1 n2))
16305 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16306 (cond
16307 ((eq prefer 'past) (if (= cday n2) n2 n1))
16308 ((eq prefer 'future) (if (= cday n1) n1 n2))
16309 (t (if (= cday n1) n1 n2)))))))
16311 (defun org-date-to-gregorian (date)
16312 "Turn any specification of DATE into a Gregorian date for the calendar."
16313 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16314 ((and (listp date) (= (length date) 3)) date)
16315 ((stringp date)
16316 (setq date (org-parse-time-string date))
16317 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16318 ((listp date)
16319 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16321 (defun org-parse-time-string (s &optional nodefault)
16322 "Parse the standard Org-mode time string.
16323 This should be a lot faster than the normal `parse-time-string'.
16324 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16325 hour and minute fields will be nil if not given."
16326 (if (string-match org-ts-regexp0 s)
16327 (list 0
16328 (if (or (match-beginning 8) (not nodefault))
16329 (string-to-number (or (match-string 8 s) "0")))
16330 (if (or (match-beginning 7) (not nodefault))
16331 (string-to-number (or (match-string 7 s) "0")))
16332 (string-to-number (match-string 4 s))
16333 (string-to-number (match-string 3 s))
16334 (string-to-number (match-string 2 s))
16335 nil nil nil)
16336 (error "Not a standard Org-mode time string: %s" s)))
16338 (defun org-timestamp-up (&optional arg)
16339 "Increase the date item at the cursor by one.
16340 If the cursor is on the year, change the year. If it is on the month,
16341 the day or the time, change that.
16342 With prefix ARG, change by that many units."
16343 (interactive "p")
16344 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16346 (defun org-timestamp-down (&optional arg)
16347 "Decrease the date item at the cursor by one.
16348 If the cursor is on the year, change the year. If it is on the month,
16349 the day or the time, change that.
16350 With prefix ARG, change by that many units."
16351 (interactive "p")
16352 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16354 (defun org-timestamp-up-day (&optional arg)
16355 "Increase the date in the time stamp by one day.
16356 With prefix ARG, change that many days."
16357 (interactive "p")
16358 (if (and (not (org-at-timestamp-p t))
16359 (org-at-heading-p))
16360 (org-todo 'up)
16361 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16363 (defun org-timestamp-down-day (&optional arg)
16364 "Decrease the date in the time stamp by one day.
16365 With prefix ARG, change that many days."
16366 (interactive "p")
16367 (if (and (not (org-at-timestamp-p t))
16368 (org-at-heading-p))
16369 (org-todo 'down)
16370 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16372 (defun org-at-timestamp-p (&optional inactive-ok)
16373 "Determine if the cursor is in or at a timestamp."
16374 (interactive)
16375 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16376 (pos (point))
16377 (ans (or (looking-at tsr)
16378 (save-excursion
16379 (skip-chars-backward "^[<\n\r\t")
16380 (if (> (point) (point-min)) (backward-char 1))
16381 (and (looking-at tsr)
16382 (> (- (match-end 0) pos) -1))))))
16383 (and ans
16384 (boundp 'org-ts-what)
16385 (setq org-ts-what
16386 (cond
16387 ((= pos (match-beginning 0)) 'bracket)
16388 ;; Point is considered to be "on the bracket" whether
16389 ;; it's really on it or right after it.
16390 ((= pos (1- (match-end 0))) 'bracket)
16391 ((= pos (match-end 0)) 'after)
16392 ((org-pos-in-match-range pos 2) 'year)
16393 ((org-pos-in-match-range pos 3) 'month)
16394 ((org-pos-in-match-range pos 7) 'hour)
16395 ((org-pos-in-match-range pos 8) 'minute)
16396 ((or (org-pos-in-match-range pos 4)
16397 (org-pos-in-match-range pos 5)) 'day)
16398 ((and (> pos (or (match-end 8) (match-end 5)))
16399 (< pos (match-end 0)))
16400 (- pos (or (match-end 8) (match-end 5))))
16401 (t 'day))))
16402 ans))
16404 (defun org-toggle-timestamp-type ()
16405 "Toggle the type (<active> or [inactive]) of a time stamp."
16406 (interactive)
16407 (when (org-at-timestamp-p t)
16408 (let ((beg (match-beginning 0)) (end (match-end 0))
16409 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16410 (save-excursion
16411 (goto-char beg)
16412 (while (re-search-forward "[][<>]" end t)
16413 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16414 t t)))
16415 (message "Timestamp is now %sactive"
16416 (if (equal (char-after beg) ?<) "" "in")))))
16418 (defun org-at-clock-log-p nil
16419 "Is the cursor on the clock log line?"
16420 (save-excursion
16421 (move-beginning-of-line 1)
16422 (looking-at "^[ \t]*CLOCK:")))
16424 (defvar org-clock-history) ; defined in org-clock.el
16425 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16426 (defun org-timestamp-change (n &optional what updown)
16427 "Change the date in the time stamp at point.
16428 The date will be changed by N times WHAT. WHAT can be `day', `month',
16429 `year', `minute', `second'. If WHAT is not given, the cursor position
16430 in the timestamp determines what will be changed."
16431 (let ((origin (point)) origin-cat
16432 with-hm inactive
16433 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16434 org-ts-what
16435 extra rem
16436 ts time time0 fixnext clrgx)
16437 (if (not (org-at-timestamp-p t))
16438 (error "Not at a timestamp"))
16439 (if (and (not what) (eq org-ts-what 'bracket))
16440 (org-toggle-timestamp-type)
16441 ;; Point isn't on brackets. Remember the part of the time-stamp
16442 ;; the point was in. Indeed, size of time-stamps may change,
16443 ;; but point must be kept in the same category nonetheless.
16444 (setq origin-cat org-ts-what)
16445 (if (and (not what) (not (eq org-ts-what 'day))
16446 org-display-custom-times
16447 (get-text-property (point) 'display)
16448 (not (get-text-property (1- (point)) 'display)))
16449 (setq org-ts-what 'day))
16450 (setq org-ts-what (or what org-ts-what)
16451 inactive (= (char-after (match-beginning 0)) ?\[)
16452 ts (match-string 0))
16453 (replace-match "")
16454 (if (string-match
16455 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16457 (setq extra (match-string 1 ts)))
16458 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16459 (setq with-hm t))
16460 (setq time0 (org-parse-time-string ts))
16461 (when (and updown
16462 (eq org-ts-what 'minute)
16463 (not current-prefix-arg))
16464 ;; This looks like s-up and s-down. Change by one rounding step.
16465 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16466 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16467 (setcar (cdr time0) (+ (nth 1 time0)
16468 (if (> n 0) (- rem) (- dm rem))))))
16469 (setq time
16470 (encode-time (or (car time0) 0)
16471 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16472 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16473 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16474 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16475 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16476 (nthcdr 6 time0)))
16477 (when (and (member org-ts-what '(hour minute))
16478 extra
16479 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16480 (setq extra (org-modify-ts-extra
16481 extra
16482 (if (eq org-ts-what 'hour) 2 5)
16483 n dm)))
16484 (when (integerp org-ts-what)
16485 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16486 (if (eq what 'calendar)
16487 (let ((cal-date (org-get-date-from-calendar)))
16488 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16489 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16490 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16491 (setcar time0 (or (car time0) 0))
16492 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16493 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16494 (setq time (apply 'encode-time time0))))
16495 ;; Insert the new time-stamp, and ensure point stays in the same
16496 ;; category as before (i.e. not after the last position in that
16497 ;; category).
16498 (let ((pos (point)))
16499 ;; Stay before inserted string. `save-excursion' is of no use.
16500 (setq org-last-changed-timestamp
16501 (org-insert-time-stamp time with-hm inactive nil nil extra))
16502 (goto-char pos))
16503 (save-match-data
16504 (looking-at org-ts-regexp3)
16505 (goto-char (cond
16506 ;; `day' category ends before `hour' if any, or at
16507 ;; the end of the day name.
16508 ((eq origin-cat 'day)
16509 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16510 ((eq origin-cat 'hour) (min (match-end 7) origin))
16511 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16512 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16513 ;; `year' and `month' have both fixed size: point
16514 ;; couldn't have moved into another part.
16515 (t origin))))
16516 ;; Update clock if on a CLOCK line.
16517 (org-clock-update-time-maybe)
16518 ;; Maybe adjust the closest clock in `org-clock-history'
16519 (when org-clock-adjust-closest
16520 (if (not (and (org-at-clock-log-p)
16521 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16522 org-clock-history))))))
16523 (message "No clock to adjust")
16524 (cond ((save-excursion ; fix previous clock?
16525 (re-search-backward org-ts-regexp0 nil t)
16526 (org-looking-back (concat org-clock-string " \\[")))
16527 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16528 ((save-excursion ; fix next clock?
16529 (re-search-backward org-ts-regexp0 nil t)
16530 (looking-at (concat org-ts-regexp0 "\\] =>")))
16531 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16532 (save-window-excursion
16533 ;; Find closest clock to point, adjust the previous/next one in history
16534 (let* ((p (save-excursion (org-back-to-heading t)))
16535 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16536 (clfixnth
16537 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16538 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16539 (if (not clfixpos)
16540 (message "No clock to adjust")
16541 (save-excursion
16542 (org-goto-marker-or-bmk clfixpos)
16543 (org-show-subtree)
16544 (when (re-search-forward clrgx nil t)
16545 (goto-char (match-beginning 1))
16546 (let (org-clock-adjust-closest)
16547 (org-timestamp-change n org-ts-what updown))
16548 (message "Clock adjusted in %s for heading: %s"
16549 (file-name-nondirectory (buffer-file-name))
16550 (org-get-heading t t)))))))))
16551 ;; Try to recenter the calendar window, if any.
16552 (if (and org-calendar-follow-timestamp-change
16553 (get-buffer-window "*Calendar*" t)
16554 (memq org-ts-what '(day month year)))
16555 (org-recenter-calendar (time-to-days time))))))
16557 (defun org-modify-ts-extra (s pos n dm)
16558 "Change the different parts of the lead-time and repeat fields in timestamp."
16559 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16560 ng h m new rem)
16561 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16562 (cond
16563 ((or (org-pos-in-match-range pos 2)
16564 (org-pos-in-match-range pos 3))
16565 (setq m (string-to-number (match-string 3 s))
16566 h (string-to-number (match-string 2 s)))
16567 (if (org-pos-in-match-range pos 2)
16568 (setq h (+ h n))
16569 (setq n (* dm (org-no-warnings (signum n))))
16570 (when (not (= 0 (setq rem (% m dm))))
16571 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16572 (setq m (+ m n)))
16573 (if (< m 0) (setq m (+ m 60) h (1- h)))
16574 (if (> m 59) (setq m (- m 60) h (1+ h)))
16575 (setq h (min 24 (max 0 h)))
16576 (setq ng 1 new (format "-%02d:%02d" h m)))
16577 ((org-pos-in-match-range pos 6)
16578 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16579 ((org-pos-in-match-range pos 5)
16580 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16582 ((org-pos-in-match-range pos 9)
16583 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16584 ((org-pos-in-match-range pos 8)
16585 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16587 (when ng
16588 (setq s (concat
16589 (substring s 0 (match-beginning ng))
16591 (substring s (match-end ng))))))
16594 (defun org-recenter-calendar (date)
16595 "If the calendar is visible, recenter it to DATE."
16596 (let ((cwin (get-buffer-window "*Calendar*" t)))
16597 (when cwin
16598 (let ((calendar-move-hook nil))
16599 (with-selected-window cwin
16600 (calendar-goto-date (if (listp date) date
16601 (calendar-gregorian-from-absolute date))))))))
16603 (defun org-goto-calendar (&optional arg)
16604 "Go to the Emacs calendar at the current date.
16605 If there is a time stamp in the current line, go to that date.
16606 A prefix ARG can be used to force the current date."
16607 (interactive "P")
16608 (let ((tsr org-ts-regexp) diff
16609 (calendar-move-hook nil)
16610 (calendar-view-holidays-initially-flag nil)
16611 (calendar-view-diary-initially-flag nil))
16612 (if (or (org-at-timestamp-p)
16613 (save-excursion
16614 (beginning-of-line 1)
16615 (looking-at (concat ".*" tsr))))
16616 (let ((d1 (time-to-days (current-time)))
16617 (d2 (time-to-days
16618 (org-time-string-to-time (match-string 1)))))
16619 (setq diff (- d2 d1))))
16620 (calendar)
16621 (calendar-goto-today)
16622 (if (and diff (not arg)) (calendar-forward-day diff))))
16624 (defun org-get-date-from-calendar ()
16625 "Return a list (month day year) of date at point in calendar."
16626 (with-current-buffer "*Calendar*"
16627 (save-match-data
16628 (calendar-cursor-to-date))))
16630 (defun org-date-from-calendar ()
16631 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16632 If there is already a time stamp at the cursor position, update it."
16633 (interactive)
16634 (if (org-at-timestamp-p t)
16635 (org-timestamp-change 0 'calendar)
16636 (let ((cal-date (org-get-date-from-calendar)))
16637 (org-insert-time-stamp
16638 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16640 (defun org-minutes-to-hh:mm-string (m)
16641 "Compute H:MM from a number of minutes."
16642 (let ((h (/ m 60)))
16643 (setq m (- m (* 60 h)))
16644 (format org-time-clocksum-format h m)))
16646 (defun org-hh:mm-string-to-minutes (s)
16647 "Convert a string H:MM to a number of minutes.
16648 If the string is just a number, interpret it as minutes.
16649 In fact, the first hh:mm or number in the string will be taken,
16650 there can be extra stuff in the string.
16651 If no number is found, the return value is 0."
16652 (cond
16653 ((integerp s) s)
16654 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16655 (+ (* (string-to-number (match-string 1 s)) 60)
16656 (string-to-number (match-string 2 s))))
16657 ((string-match "\\([0-9]+\\)" s)
16658 (string-to-number (match-string 1 s)))
16659 (t 0)))
16661 (defcustom org-effort-durations
16662 `(("h" . 60)
16663 ("d" . ,(* 60 8))
16664 ("w" . ,(* 60 8 5))
16665 ("m" . ,(* 60 8 5 4))
16666 ("y" . ,(* 60 8 5 40)))
16667 "Conversion factor to minutes for an effort modifier.
16669 Each entry has the form (MODIFIER . MINUTES).
16671 In an effort string, a number followed by MODIFIER is multiplied
16672 by the specified number of MINUTES to obtain an effort in
16673 minutes.
16675 For example, if the value of this variable is ((\"hours\" . 60)), then an
16676 effort string \"2hours\" is equivalent to 120 minutes."
16677 :group 'org-agenda
16678 :version "24.1"
16679 :type '(alist :key-type (string :tag "Modifier")
16680 :value-type (number :tag "Minutes")))
16682 (defcustom org-agenda-inhibit-startup t
16683 "Inhibit startup when preparing agenda buffers.
16684 When this variable is `t' (the default), the initialization of
16685 the Org agenda buffers is inhibited: e.g. the visibility state
16686 is not set, the tables are not re-aligned, etc."
16687 :type 'boolean
16688 :version "24.3"
16689 :group 'org-agenda)
16691 (defun org-duration-string-to-minutes (s &optional output-to-string)
16692 "Convert a duration string S to minutes.
16694 A bare number is interpreted as minutes, modifiers can be set by
16695 customizing `org-effort-durations' (which see).
16697 Entries containing a colon are interpreted as H:MM by
16698 `org-hh:mm-string-to-minutes'."
16699 (let ((result 0)
16700 (re (concat "\\([0-9.]+\\) *\\("
16701 (regexp-opt (mapcar 'car org-effort-durations))
16702 "\\)")))
16703 (while (string-match re s)
16704 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16705 (string-to-number (match-string 1 s))))
16706 (setq s (replace-match "" nil t s)))
16707 (setq result (floor result))
16708 (incf result (org-hh:mm-string-to-minutes s))
16709 (if output-to-string (number-to-string result) result)))
16711 ;;;; Files
16713 (defun org-save-all-org-buffers ()
16714 "Save all Org-mode buffers without user confirmation."
16715 (interactive)
16716 (message "Saving all Org-mode buffers...")
16717 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16718 (when (featurep 'org-id) (org-id-locations-save))
16719 (message "Saving all Org-mode buffers... done"))
16721 (defun org-revert-all-org-buffers ()
16722 "Revert all Org-mode buffers.
16723 Prompt for confirmation when there are unsaved changes.
16724 Be sure you know what you are doing before letting this function
16725 overwrite your changes.
16727 This function is useful in a setup where one tracks org files
16728 with a version control system, to revert on one machine after pulling
16729 changes from another. I believe the procedure must be like this:
16731 1. M-x org-save-all-org-buffers
16732 2. Pull changes from the other machine, resolve conflicts
16733 3. M-x org-revert-all-org-buffers"
16734 (interactive)
16735 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16736 (error "Abort"))
16737 (save-excursion
16738 (save-window-excursion
16739 (mapc
16740 (lambda (b)
16741 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16742 (with-current-buffer b buffer-file-name))
16743 (org-pop-to-buffer-same-window b)
16744 (revert-buffer t 'no-confirm)))
16745 (buffer-list))
16746 (when (and (featurep 'org-id) org-id-track-globally)
16747 (org-id-locations-load)))))
16749 ;;;; Agenda files
16751 ;;;###autoload
16752 (defun org-switchb (&optional arg)
16753 "Switch between Org buffers.
16754 With one prefix argument, restrict available buffers to files.
16755 With two prefix arguments, restrict available buffers to agenda files.
16757 Defaults to `iswitchb' for buffer name completion.
16758 Set `org-completion-use-ido' to make it use ido instead."
16759 (interactive "P")
16760 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16761 ((equal arg '(16)) (org-buffer-list 'agenda))
16762 (t (org-buffer-list))))
16763 (org-completion-use-iswitchb org-completion-use-iswitchb)
16764 (org-completion-use-ido org-completion-use-ido))
16765 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16766 (setq org-completion-use-iswitchb t))
16767 (org-pop-to-buffer-same-window
16768 (org-icompleting-read "Org buffer: "
16769 (mapcar 'list (mapcar 'buffer-name blist))
16770 nil t))))
16772 ;;; Define some older names previously used for this functionality
16773 ;;;###autoload
16774 (defalias 'org-ido-switchb 'org-switchb)
16775 ;;;###autoload
16776 (defalias 'org-iswitchb 'org-switchb)
16778 (defun org-buffer-list (&optional predicate exclude-tmp)
16779 "Return a list of Org buffers.
16780 PREDICATE can be `export', `files' or `agenda'.
16782 export restrict the list to Export buffers.
16783 files restrict the list to buffers visiting Org files.
16784 agenda restrict the list to buffers visiting agenda files.
16786 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16787 (let* ((bfn nil)
16788 (agenda-files (and (eq predicate 'agenda)
16789 (mapcar 'file-truename (org-agenda-files t))))
16790 (filter
16791 (cond
16792 ((eq predicate 'files)
16793 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16794 ((eq predicate 'export)
16795 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16796 ((eq predicate 'agenda)
16797 (lambda (b)
16798 (with-current-buffer b
16799 (and (derived-mode-p 'org-mode)
16800 (setq bfn (buffer-file-name b))
16801 (member (file-truename bfn) agenda-files)))))
16802 (t (lambda (b) (with-current-buffer b
16803 (or (derived-mode-p 'org-mode)
16804 (string-match "\*Org .*Export"
16805 (buffer-name b)))))))))
16806 (delq nil
16807 (mapcar
16808 (lambda(b)
16809 (if (and (funcall filter b)
16810 (or (not exclude-tmp)
16811 (not (string-match "tmp" (buffer-name b)))))
16813 nil))
16814 (buffer-list)))))
16816 (defun org-agenda-files (&optional unrestricted archives)
16817 "Get the list of agenda files.
16818 Optional UNRESTRICTED means return the full list even if a restriction
16819 is currently in place.
16820 When ARCHIVES is t, include all archive files that are really being
16821 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16822 `org-agenda-archives-mode' is t."
16823 (let ((files
16824 (cond
16825 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16826 ((stringp org-agenda-files) (org-read-agenda-file-list))
16827 ((listp org-agenda-files) org-agenda-files)
16828 (t (error "Invalid value of `org-agenda-files'")))))
16829 (setq files (apply 'append
16830 (mapcar (lambda (f)
16831 (if (file-directory-p f)
16832 (directory-files
16833 f t org-agenda-file-regexp)
16834 (list f)))
16835 files)))
16836 (when org-agenda-skip-unavailable-files
16837 (setq files (delq nil
16838 (mapcar (function
16839 (lambda (file)
16840 (and (file-readable-p file) file)))
16841 files))))
16842 (when (or (eq archives t)
16843 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16844 (setq files (org-add-archive-files files)))
16845 files))
16847 (defun org-agenda-file-p (&optional file)
16848 "Return non-nil, if FILE is an agenda file.
16849 If FILE is omitted, use the file associated with the current
16850 buffer."
16851 (member (or file (buffer-file-name))
16852 (org-agenda-files t)))
16854 (defun org-edit-agenda-file-list ()
16855 "Edit the list of agenda files.
16856 Depending on setup, this either uses customize to edit the variable
16857 `org-agenda-files', or it visits the file that is holding the list. In the
16858 latter case, the buffer is set up in a way that saving it automatically kills
16859 the buffer and restores the previous window configuration."
16860 (interactive)
16861 (if (stringp org-agenda-files)
16862 (let ((cw (current-window-configuration)))
16863 (find-file org-agenda-files)
16864 (org-set-local 'org-window-configuration cw)
16865 (org-add-hook 'after-save-hook
16866 (lambda ()
16867 (set-window-configuration
16868 (prog1 org-window-configuration
16869 (kill-buffer (current-buffer))))
16870 (org-install-agenda-files-menu)
16871 (message "New agenda file list installed"))
16872 nil 'local)
16873 (message "%s" (substitute-command-keys
16874 "Edit list and finish with \\[save-buffer]")))
16875 (customize-variable 'org-agenda-files)))
16877 (defun org-store-new-agenda-file-list (list)
16878 "Set new value for the agenda file list and save it correctly."
16879 (if (stringp org-agenda-files)
16880 (let ((fe (org-read-agenda-file-list t)) b u)
16881 (while (setq b (find-buffer-visiting org-agenda-files))
16882 (kill-buffer b))
16883 (with-temp-file org-agenda-files
16884 (insert
16885 (mapconcat
16886 (lambda (f) ;; Keep un-expanded entries.
16887 (if (setq u (assoc f fe))
16888 (cdr u)
16890 list "\n")
16891 "\n")))
16892 (let ((org-mode-hook nil) (org-inhibit-startup t)
16893 (org-insert-mode-line-in-empty-file nil))
16894 (setq org-agenda-files list)
16895 (customize-save-variable 'org-agenda-files org-agenda-files))))
16897 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16898 "Read the list of agenda files from a file.
16899 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16900 filenames, used by `org-store-new-agenda-file-list' to write back
16901 un-expanded file names."
16902 (when (file-directory-p org-agenda-files)
16903 (error "`org-agenda-files' cannot be a single directory"))
16904 (when (stringp org-agenda-files)
16905 (with-temp-buffer
16906 (insert-file-contents org-agenda-files)
16907 (mapcar
16908 (lambda (f)
16909 (let ((e (expand-file-name (substitute-in-file-name f)
16910 org-directory)))
16911 (if pair-with-expansion
16912 (cons e f)
16913 e)))
16914 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16916 ;;;###autoload
16917 (defun org-cycle-agenda-files ()
16918 "Cycle through the files in `org-agenda-files'.
16919 If the current buffer visits an agenda file, find the next one in the list.
16920 If the current buffer does not, find the first agenda file."
16921 (interactive)
16922 (let* ((fs (org-agenda-files t))
16923 (files (append fs (list (car fs))))
16924 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16925 file)
16926 (unless files (error "No agenda files"))
16927 (catch 'exit
16928 (while (setq file (pop files))
16929 (if (equal (file-truename file) tcf)
16930 (when (car files)
16931 (find-file (car files))
16932 (throw 'exit t))))
16933 (find-file (car fs)))
16934 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16936 (defun org-agenda-file-to-front (&optional to-end)
16937 "Move/add the current file to the top of the agenda file list.
16938 If the file is not present in the list, it is added to the front. If it is
16939 present, it is moved there. With optional argument TO-END, add/move to the
16940 end of the list."
16941 (interactive "P")
16942 (let ((org-agenda-skip-unavailable-files nil)
16943 (file-alist (mapcar (lambda (x)
16944 (cons (file-truename x) x))
16945 (org-agenda-files t)))
16946 (ctf (file-truename
16947 (or buffer-file-name
16948 (error "Please save the current buffer to a file"))))
16949 x had)
16950 (setq x (assoc ctf file-alist) had x)
16952 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16953 (if to-end
16954 (setq file-alist (append (delq x file-alist) (list x)))
16955 (setq file-alist (cons x (delq x file-alist))))
16956 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16957 (org-install-agenda-files-menu)
16958 (message "File %s to %s of agenda file list"
16959 (if had "moved" "added") (if to-end "end" "front"))))
16961 (defun org-remove-file (&optional file)
16962 "Remove current file from the list of files in variable `org-agenda-files'.
16963 These are the files which are being checked for agenda entries.
16964 Optional argument FILE means use this file instead of the current."
16965 (interactive)
16966 (let* ((org-agenda-skip-unavailable-files nil)
16967 (file (or file buffer-file-name
16968 (error "Current buffer does not visit a file")))
16969 (true-file (file-truename file))
16970 (afile (abbreviate-file-name file))
16971 (files (delq nil (mapcar
16972 (lambda (x)
16973 (if (equal true-file
16974 (file-truename x))
16975 nil x))
16976 (org-agenda-files t)))))
16977 (if (not (= (length files) (length (org-agenda-files t))))
16978 (progn
16979 (org-store-new-agenda-file-list files)
16980 (org-install-agenda-files-menu)
16981 (message "Removed file: %s" afile))
16982 (message "File was not in list: %s (not removed)" afile))))
16984 (defun org-file-menu-entry (file)
16985 (vector file (list 'find-file file) t))
16987 (defun org-check-agenda-file (file)
16988 "Make sure FILE exists. If not, ask user what to do."
16989 (when (not (file-exists-p file))
16990 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16991 (abbreviate-file-name file))
16992 (let ((r (downcase (read-char-exclusive))))
16993 (cond
16994 ((equal r ?r)
16995 (org-remove-file file)
16996 (throw 'nextfile t))
16997 (t (error "Abort"))))))
16999 (defun org-get-agenda-file-buffer (file)
17000 "Get a buffer visiting FILE. If the buffer needs to be created, add
17001 it to the list of buffers which might be released later."
17002 (let ((buf (org-find-base-buffer-visiting file)))
17003 (if buf
17004 buf ; just return it
17005 ;; Make a new buffer and remember it
17006 (setq buf (find-file-noselect file))
17007 (if buf (push buf org-agenda-new-buffers))
17008 buf)))
17010 (defun org-release-buffers (blist)
17011 "Release all buffers in list, asking the user for confirmation when needed.
17012 When a buffer is unmodified, it is just killed. When modified, it is saved
17013 \(if the user agrees) and then killed."
17014 (let (buf file)
17015 (while (setq buf (pop blist))
17016 (setq file (buffer-file-name buf))
17017 (when (and (buffer-modified-p buf)
17018 file
17019 (y-or-n-p (format "Save file %s? " file)))
17020 (with-current-buffer buf (save-buffer)))
17021 (kill-buffer buf))))
17023 (defun org-agenda-prepare-buffers (files)
17024 "Create buffers for all agenda files, protect archived trees and comments."
17025 (interactive)
17026 (let ((pa '(:org-archived t))
17027 (pc '(:org-comment t))
17028 (pall '(:org-archived t :org-comment t))
17029 (inhibit-read-only t)
17030 (org-inhibit-startup org-agenda-inhibit-startup)
17031 (rea (concat ":" org-archive-tag ":"))
17032 bmp file re)
17033 (save-excursion
17034 (save-restriction
17035 (while (setq file (pop files))
17036 (catch 'nextfile
17037 (if (bufferp file)
17038 (set-buffer file)
17039 (org-check-agenda-file file)
17040 (set-buffer (org-get-agenda-file-buffer file)))
17041 (widen)
17042 (setq bmp (buffer-modified-p))
17043 (org-refresh-category-properties)
17044 (org-refresh-properties org-effort-property 'org-effort)
17045 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17046 (setq org-todo-keywords-for-agenda
17047 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17048 (setq org-done-keywords-for-agenda
17049 (append org-done-keywords-for-agenda org-done-keywords))
17050 (setq org-todo-keyword-alist-for-agenda
17051 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17052 (setq org-drawers-for-agenda
17053 (append org-drawers-for-agenda org-drawers))
17054 (setq org-tag-alist-for-agenda
17055 (append org-tag-alist-for-agenda org-tag-alist))
17057 (save-excursion
17058 (remove-text-properties (point-min) (point-max) pall)
17059 (when org-agenda-skip-archived-trees
17060 (goto-char (point-min))
17061 (while (re-search-forward rea nil t)
17062 (if (org-at-heading-p t)
17063 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17064 (goto-char (point-min))
17065 (setq re (format org-heading-keyword-regexp-format
17066 org-comment-string))
17067 (while (re-search-forward re nil t)
17068 (add-text-properties
17069 (match-beginning 0) (org-end-of-subtree t) pc)))
17070 (set-buffer-modified-p bmp)))))
17071 (setq org-todo-keywords-for-agenda
17072 (org-uniquify org-todo-keywords-for-agenda))
17073 (setq org-todo-keyword-alist-for-agenda
17074 (org-uniquify org-todo-keyword-alist-for-agenda)
17075 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17077 ;;;; Embedded LaTeX
17079 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17080 "Keymap for the minor `org-cdlatex-mode'.")
17082 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17083 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17084 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17085 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17086 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17088 (defvar org-cdlatex-texmathp-advice-is-done nil
17089 "Flag remembering if we have applied the advice to texmathp already.")
17091 (define-minor-mode org-cdlatex-mode
17092 "Toggle the minor `org-cdlatex-mode'.
17093 This mode supports entering LaTeX environment and math in LaTeX fragments
17094 in Org-mode.
17095 \\{org-cdlatex-mode-map}"
17096 nil " OCDL" nil
17097 (when org-cdlatex-mode
17098 (require 'cdlatex)
17099 (run-hooks 'cdlatex-mode-hook)
17100 (cdlatex-compute-tables))
17101 (unless org-cdlatex-texmathp-advice-is-done
17102 (setq org-cdlatex-texmathp-advice-is-done t)
17103 (defadvice texmathp (around org-math-always-on activate)
17104 "Always return t in org-mode buffers.
17105 This is because we want to insert math symbols without dollars even outside
17106 the LaTeX math segments. If Orgmode thinks that point is actually inside
17107 an embedded LaTeX fragment, let texmathp do its job.
17108 \\[org-cdlatex-mode-map]"
17109 (interactive)
17110 (let (p)
17111 (cond
17112 ((not (derived-mode-p 'org-mode)) ad-do-it)
17113 ((eq this-command 'cdlatex-math-symbol)
17114 (setq ad-return-value t
17115 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17117 (let ((p (org-inside-LaTeX-fragment-p)))
17118 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17119 (setq ad-return-value t
17120 texmathp-why '("Org-mode embedded math" . 0))
17121 (if p ad-do-it)))))))))
17123 (defun turn-on-org-cdlatex ()
17124 "Unconditionally turn on `org-cdlatex-mode'."
17125 (org-cdlatex-mode 1))
17127 (defun org-inside-LaTeX-fragment-p ()
17128 "Test if point is inside a LaTeX fragment.
17129 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17130 sequence appearing also before point.
17131 Even though the matchers for math are configurable, this function assumes
17132 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17133 delimiters are skipped when they have been removed by customization.
17134 The return value is nil, or a cons cell with the delimiter and the
17135 position of this delimiter.
17137 This function does a reasonably good job, but can locally be fooled by
17138 for example currency specifications. For example it will assume being in
17139 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17140 fragments that are properly closed, but during editing, we have to live
17141 with the uncertainty caused by missing closing delimiters. This function
17142 looks only before point, not after."
17143 (catch 'exit
17144 (let ((pos (point))
17145 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17146 (lim (progn
17147 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17148 (point)))
17149 dd-on str (start 0) m re)
17150 (goto-char pos)
17151 (when dodollar
17152 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17153 re (nth 1 (assoc "$" org-latex-regexps)))
17154 (while (string-match re str start)
17155 (cond
17156 ((= (match-end 0) (length str))
17157 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17158 ((= (match-end 0) (- (length str) 5))
17159 (throw 'exit nil))
17160 (t (setq start (match-end 0))))))
17161 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17162 (goto-char pos)
17163 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17164 (and (match-beginning 2) (throw 'exit nil))
17165 ;; count $$
17166 (while (re-search-backward "\\$\\$" lim t)
17167 (setq dd-on (not dd-on)))
17168 (goto-char pos)
17169 (if dd-on (cons "$$" m))))))
17171 (defun org-inside-latex-macro-p ()
17172 "Is point inside a LaTeX macro or its arguments?"
17173 (save-match-data
17174 (org-in-regexp
17175 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17177 (defun org-try-cdlatex-tab ()
17178 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17179 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17180 - inside a LaTeX fragment, or
17181 - after the first word in a line, where an abbreviation expansion could
17182 insert a LaTeX environment."
17183 (when org-cdlatex-mode
17184 (cond
17185 ;; Before any word on the line: No expansion possible.
17186 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17187 ;; Just after first word on the line: Expand it. Make sure it
17188 ;; cannot happen on headlines, though.
17189 ((save-excursion
17190 (skip-chars-backward "a-zA-Z0-9*")
17191 (skip-chars-backward " \t")
17192 (and (bolp) (not (org-at-heading-p))))
17193 (cdlatex-tab) t)
17194 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17196 (defun org-cdlatex-underscore-caret (&optional arg)
17197 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17198 Revert to the normal definition outside of these fragments."
17199 (interactive "P")
17200 (if (org-inside-LaTeX-fragment-p)
17201 (call-interactively 'cdlatex-sub-superscript)
17202 (let (org-cdlatex-mode)
17203 (call-interactively (key-binding (vector last-input-event))))))
17205 (defun org-cdlatex-math-modify (&optional arg)
17206 "Execute `cdlatex-math-modify' in LaTeX fragments.
17207 Revert to the normal definition outside of these fragments."
17208 (interactive "P")
17209 (if (org-inside-LaTeX-fragment-p)
17210 (call-interactively 'cdlatex-math-modify)
17211 (let (org-cdlatex-mode)
17212 (call-interactively (key-binding (vector last-input-event))))))
17214 (defvar org-latex-fragment-image-overlays nil
17215 "List of overlays carrying the images of latex fragments.")
17216 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17218 (defun org-remove-latex-fragment-image-overlays ()
17219 "Remove all overlays with LaTeX fragment images in current buffer."
17220 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17221 (setq org-latex-fragment-image-overlays nil))
17223 (defun org-preview-latex-fragment (&optional subtree)
17224 "Preview the LaTeX fragment at point, or all locally or globally.
17225 If the cursor is in a LaTeX fragment, create the image and overlay
17226 it over the source code. If there is no fragment at point, display
17227 all fragments in the current text, from one headline to the next. With
17228 prefix SUBTREE, display all fragments in the current subtree. With a
17229 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17230 the cursor is before the first headline,
17231 display all fragments in the buffer.
17232 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17233 (interactive "P")
17234 (unless buffer-file-name
17235 (error "Can't preview LaTeX fragment in a non-file buffer"))
17236 (org-remove-latex-fragment-image-overlays)
17237 (save-excursion
17238 (save-restriction
17239 (let (beg end at msg)
17240 (cond
17241 ((or (equal subtree '(16))
17242 (not (save-excursion
17243 (re-search-backward org-outline-regexp-bol nil t))))
17244 (setq beg (point-min) end (point-max)
17245 msg "Creating images for buffer...%s"))
17246 ((equal subtree '(4))
17247 (org-back-to-heading)
17248 (setq beg (point) end (org-end-of-subtree t)
17249 msg "Creating images for subtree...%s"))
17251 (if (setq at (org-inside-LaTeX-fragment-p))
17252 (goto-char (max (point-min) (- (cdr at) 2)))
17253 (org-back-to-heading))
17254 (setq beg (point) end (progn (outline-next-heading) (point))
17255 msg (if at "Creating image...%s"
17256 "Creating images for entry...%s"))))
17257 (message msg "")
17258 (narrow-to-region beg end)
17259 (goto-char beg)
17260 (org-format-latex
17261 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17262 (file-name-nondirectory
17263 buffer-file-name)))
17264 default-directory 'overlays msg at 'forbuffer
17265 org-latex-create-formula-image-program)
17266 (message msg "done. Use `C-c C-c' to remove images.")))))
17268 (defvar org-latex-regexps
17269 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17270 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17271 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17272 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17273 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17274 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17275 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17276 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17277 "Regular expressions for matching embedded LaTeX.")
17279 (defvar org-export-have-math nil) ;; dynamic scoping
17280 (defun org-format-latex (prefix &optional dir overlays msg at
17281 forbuffer processing-type)
17282 "Replace LaTeX fragments with links to an image, and produce images.
17283 Some of the options can be changed using the variable
17284 `org-format-latex-options'."
17285 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17286 (let* ((prefixnodir (file-name-nondirectory prefix))
17287 (absprefix (expand-file-name prefix dir))
17288 (todir (file-name-directory absprefix))
17289 (opt org-format-latex-options)
17290 (matchers (plist-get opt :matchers))
17291 (re-list org-latex-regexps)
17292 (org-format-latex-header-extra
17293 (plist-get (org-infile-export-plist) :latex-header-extra))
17294 (cnt 0) txt hash link beg end re e checkdir
17295 executables-checked string
17296 m n block-type block linkfile movefile ov)
17297 ;; Check the different regular expressions
17298 (while (setq e (pop re-list))
17299 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17300 block (if block-type "\n\n" ""))
17301 (when (member m matchers)
17302 (goto-char (point-min))
17303 (while (re-search-forward re nil t)
17304 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17305 (not (get-text-property (match-beginning n)
17306 'org-protected))
17307 (or (not overlays)
17308 (not (eq (get-char-property (match-beginning n)
17309 'org-overlay-type)
17310 'org-latex-overlay))))
17311 (setq org-export-have-math t)
17312 (cond
17313 ((eq processing-type 'verbatim)
17314 ;; Leave the text verbatim, just protect it
17315 (add-text-properties (match-beginning n) (match-end n)
17316 '(org-protected t)))
17317 ((eq processing-type 'mathjax)
17318 ;; Prepare for MathJax processing
17319 (setq string (match-string n))
17320 (if (member m '("$" "$1"))
17321 (save-excursion
17322 (delete-region (match-beginning n) (match-end n))
17323 (goto-char (match-beginning n))
17324 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17325 "\\)")
17326 '(org-protected t))))
17327 (add-text-properties (match-beginning n) (match-end n)
17328 '(org-protected t))))
17329 ((or (eq processing-type 'dvipng)
17330 (eq processing-type 'imagemagick))
17331 ;; Process to an image
17332 (setq txt (match-string n)
17333 beg (match-beginning n) end (match-end n)
17334 cnt (1+ cnt))
17335 (let (print-length print-level) ; make sure full list is printed
17336 (setq hash (sha1 (prin1-to-string
17337 (list org-format-latex-header
17338 org-format-latex-header-extra
17339 org-export-latex-default-packages-alist
17340 org-export-latex-packages-alist
17341 org-format-latex-options
17342 forbuffer txt)))
17343 linkfile (format "%s_%s.png" prefix hash)
17344 movefile (format "%s_%s.png" absprefix hash)))
17345 (setq link (concat block "[[file:" linkfile "]]" block))
17346 (if msg (message msg cnt))
17347 (goto-char beg)
17348 (unless checkdir ; make sure the directory exists
17349 (setq checkdir t)
17350 (or (file-directory-p todir) (make-directory todir t)))
17351 (cond
17352 ((eq processing-type 'dvipng)
17353 (unless executables-checked
17354 (org-check-external-command
17355 "latex" "needed to convert LaTeX fragments to images")
17356 (org-check-external-command
17357 "dvipng" "needed to convert LaTeX fragments to images")
17358 (setq executables-checked t))
17359 (unless (file-exists-p movefile)
17360 (org-create-formula-image-with-dvipng
17361 txt movefile opt forbuffer)))
17362 ((eq processing-type 'imagemagick)
17363 (unless executables-checked
17364 (org-check-external-command
17365 "convert" "you need to install imagemagick")
17366 (setq executables-checked t))
17367 (unless (file-exists-p movefile)
17368 (org-create-formula-image-with-imagemagick
17369 txt movefile opt forbuffer))))
17370 (if overlays
17371 (progn
17372 (mapc (lambda (o)
17373 (if (eq (overlay-get o 'org-overlay-type)
17374 'org-latex-overlay)
17375 (delete-overlay o)))
17376 (overlays-in beg end))
17377 (setq ov (make-overlay beg end))
17378 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17379 (if (featurep 'xemacs)
17380 (progn
17381 (overlay-put ov 'invisible t)
17382 (overlay-put
17383 ov 'end-glyph
17384 (make-glyph (vector 'png :file movefile))))
17385 (overlay-put
17386 ov 'display
17387 (list 'image :type 'png :file movefile :ascent 'center)))
17388 (push ov org-latex-fragment-image-overlays)
17389 (goto-char end))
17390 (delete-region beg end)
17391 (insert (org-add-props link
17392 (list 'org-latex-src
17393 (replace-regexp-in-string
17394 "\"" "" txt)
17395 'org-latex-src-embed-type
17396 (if block-type 'paragraph 'character))))))
17397 ((eq processing-type 'mathml)
17398 ;; Process to MathML
17399 (unless executables-checked
17400 (unless (save-match-data (org-format-latex-mathml-available-p))
17401 (error "LaTeX to MathML converter not configured"))
17402 (setq executables-checked t))
17403 (setq txt (match-string n)
17404 beg (match-beginning n) end (match-end n)
17405 cnt (1+ cnt))
17406 (if msg (message msg cnt))
17407 (goto-char beg)
17408 (delete-region beg end)
17409 (insert (org-format-latex-as-mathml
17410 txt block-type prefix dir)))
17412 (error "Unknown conversion type %s for latex fragments"
17413 processing-type)))))))))
17415 (defun org-create-math-formula (latex-frag &optional mathml-file)
17416 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17417 Use `org-latex-to-mathml-convert-command'. If the conversion is
17418 sucessful, return the portion between \"<math...> </math>\"
17419 elements otherwise return nil. When MATHML-FILE is specified,
17420 write the results in to that file. When invoked as an
17421 interactive command, prompt for LATEX-FRAG, with initial value
17422 set to the current active region and echo the results for user
17423 inspection."
17424 (interactive (list (let ((frag (when (org-region-active-p)
17425 (buffer-substring-no-properties
17426 (region-beginning) (region-end)))))
17427 (read-string "LaTeX Fragment: " frag nil frag))))
17428 (unless latex-frag (error "Invalid latex-frag"))
17429 (let* ((tmp-in-file (file-relative-name
17430 (make-temp-name (expand-file-name "ltxmathml-in"))))
17431 (ignore (write-region latex-frag nil tmp-in-file))
17432 (tmp-out-file (file-relative-name
17433 (make-temp-name (expand-file-name "ltxmathml-out"))))
17434 (cmd (format-spec
17435 org-latex-to-mathml-convert-command
17436 `((?j . ,(shell-quote-argument
17437 (expand-file-name org-latex-to-mathml-jar-file)))
17438 (?I . ,(shell-quote-argument tmp-in-file))
17439 (?o . ,(shell-quote-argument tmp-out-file)))))
17440 mathml shell-command-output)
17441 (when (org-called-interactively-p 'any)
17442 (unless (org-format-latex-mathml-available-p)
17443 (error "LaTeX to MathML converter not configured")))
17444 (message "Running %s" cmd)
17445 (setq shell-command-output (shell-command-to-string cmd))
17446 (setq mathml
17447 (when (file-readable-p tmp-out-file)
17448 (with-current-buffer (find-file-noselect tmp-out-file t)
17449 (goto-char (point-min))
17450 (when (re-search-forward
17451 (concat
17452 (regexp-quote
17453 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17454 "\\(.\\|\n\\)*"
17455 (regexp-quote "</math>")) nil t)
17456 (prog1 (match-string 0) (kill-buffer))))))
17457 (cond
17458 (mathml
17459 (setq mathml
17460 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17461 (when mathml-file
17462 (write-region mathml nil mathml-file))
17463 (when (org-called-interactively-p 'any)
17464 (message mathml)))
17465 ((message "LaTeX to MathML conversion failed")
17466 (message shell-command-output)))
17467 (delete-file tmp-in-file)
17468 (when (file-exists-p tmp-out-file)
17469 (delete-file tmp-out-file))
17470 mathml))
17472 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17473 prefix &optional dir)
17474 "Use `org-create-math-formula' but check local cache first."
17475 (let* ((absprefix (expand-file-name prefix dir))
17476 (print-length nil) (print-level nil)
17477 (formula-id (concat
17478 "formula-"
17479 (sha1
17480 (prin1-to-string
17481 (list latex-frag
17482 org-latex-to-mathml-convert-command)))))
17483 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17484 (formula-cache-dir (file-name-directory formula-cache)))
17486 (unless (file-directory-p formula-cache-dir)
17487 (make-directory formula-cache-dir t))
17489 (unless (file-exists-p formula-cache)
17490 (org-create-math-formula latex-frag formula-cache))
17492 (if (file-exists-p formula-cache)
17493 ;; Successful conversion. Return the link to MathML file.
17494 (org-add-props
17495 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17496 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17497 'org-latex-src-embed-type (if latex-frag-type
17498 'paragraph 'character)))
17499 ;; Failed conversion. Return the LaTeX fragment verbatim
17500 (add-text-properties
17501 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17502 latex-frag)))
17504 ;; This function borrows from Ganesh Swami's latex2png.el
17505 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17506 "This calls dvipng."
17507 (require 'org-latex)
17508 (let* ((tmpdir (if (featurep 'xemacs)
17509 (temp-directory)
17510 temporary-file-directory))
17511 (texfilebase (make-temp-name
17512 (expand-file-name "orgtex" tmpdir)))
17513 (texfile (concat texfilebase ".tex"))
17514 (dvifile (concat texfilebase ".dvi"))
17515 (pngfile (concat texfilebase ".png"))
17516 (fnh (if (featurep 'xemacs)
17517 (font-height (face-font 'default))
17518 (face-attribute 'default :height nil)))
17519 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17520 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17521 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17522 "Black"))
17523 (bg (or (plist-get options (if buffer :background :html-background))
17524 "Transparent")))
17525 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17526 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17527 (with-temp-file texfile
17528 (insert (org-splice-latex-header
17529 org-format-latex-header
17530 org-export-latex-default-packages-alist
17531 org-export-latex-packages-alist t
17532 org-format-latex-header-extra))
17533 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17534 (require 'org-latex)
17535 (org-export-latex-fix-inputenc))
17536 (let ((dir default-directory))
17537 (condition-case nil
17538 (progn
17539 (cd tmpdir)
17540 (call-process "latex" nil nil nil texfile))
17541 (error nil))
17542 (cd dir))
17543 (if (not (file-exists-p dvifile))
17544 (progn (message "Failed to create dvi file from %s" texfile) nil)
17545 (condition-case nil
17546 (if (featurep 'xemacs)
17547 (call-process "dvipng" nil nil nil
17548 "-fg" fg "-bg" bg
17549 "-T" "tight"
17550 "-o" pngfile
17551 dvifile)
17552 (call-process "dvipng" nil nil nil
17553 "-fg" fg "-bg" bg
17554 "-D" dpi
17555 ;;"-x" scale "-y" scale
17556 "-T" "tight"
17557 "-o" pngfile
17558 dvifile))
17559 (error nil))
17560 (if (not (file-exists-p pngfile))
17561 (if org-format-latex-signal-error
17562 (error "Failed to create png file from %s" texfile)
17563 (message "Failed to create png file from %s" texfile)
17564 nil)
17565 ;; Use the requested file name and clean up
17566 (copy-file pngfile tofile 'replace)
17567 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17568 (if (file-exists-p (concat texfilebase e))
17569 (delete-file (concat texfilebase e))))
17570 pngfile))))
17572 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17573 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17574 "This calls convert, which is included into imagemagick."
17575 (require 'org-latex)
17576 (let* ((tmpdir (if (featurep 'xemacs)
17577 (temp-directory)
17578 temporary-file-directory))
17579 (texfilebase (make-temp-name
17580 (expand-file-name "orgtex" tmpdir)))
17581 (texfile (concat texfilebase ".tex"))
17582 (pdffile (concat texfilebase ".pdf"))
17583 (pngfile (concat texfilebase ".png"))
17584 (fnh (if (featurep 'xemacs)
17585 (font-height (face-font 'default))
17586 (face-attribute 'default :height nil)))
17587 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17588 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17589 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17590 "black"))
17591 (bg (or (plist-get options (if buffer :background :html-background))
17592 "white")))
17593 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17594 (setq fg (org-latex-color-format fg)))
17595 (if (eq bg 'default) (setq bg (org-latex-color :background))
17596 (setq bg (org-latex-color-format
17597 (if (string= bg "Transparent")(setq bg "white")))))
17598 (with-temp-file texfile
17599 (insert (org-splice-latex-header
17600 org-format-latex-header
17601 org-export-latex-default-packages-alist
17602 org-export-latex-packages-alist t
17603 org-format-latex-header-extra))
17604 (insert "\n\\begin{document}\n"
17605 "\\definecolor{fg}{rgb}{" fg "}\n"
17606 "\\definecolor{bg}{rgb}{" bg "}\n"
17607 "\n\\pagecolor{bg}\n"
17608 "\n{\\color{fg}\n"
17609 string
17610 "\n}\n"
17611 "\n\\end{document}\n" )
17612 (require 'org-latex)
17613 (org-export-latex-fix-inputenc))
17614 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17615 (condition-case nil
17616 (progn
17617 (cd tmpdir)
17618 (setq cmds org-latex-to-pdf-process)
17619 (while cmds
17620 (setq latex-frags-cmds (pop cmds))
17621 (if (listp latex-frags-cmds)
17622 (setq cmds nil)
17623 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17624 (while latex-frags-cmds
17625 (setq cmd (pop latex-frags-cmds))
17626 (while (string-match "%b" cmd)
17627 (setq cmd (replace-match
17628 (save-match-data
17629 (shell-quote-argument texfile))
17630 t t cmd)))
17631 (while (string-match "%f" cmd)
17632 (setq cmd (replace-match
17633 (save-match-data
17634 (shell-quote-argument (file-name-nondirectory texfile)))
17635 t t cmd)))
17636 (while (string-match "%o" cmd)
17637 (setq cmd (replace-match
17638 (save-match-data
17639 (shell-quote-argument (file-name-directory texfile)))
17640 t t cmd)))
17641 (setq cmd (split-string cmd))
17642 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17643 (error nil))
17644 (cd dir))
17645 (if (not (file-exists-p pdffile))
17646 (progn (message "Failed to create pdf file from %s" texfile) nil)
17647 (condition-case nil
17648 (if (featurep 'xemacs)
17649 (call-process "convert" nil nil nil
17650 "-density" "96"
17651 "-trim"
17652 "-antialias"
17653 pdffile
17654 "-quality" "100"
17655 ;; "-sharpen" "0x1.0"
17656 pngfile)
17657 (call-process "convert" nil nil nil
17658 "-density" dpi
17659 "-trim"
17660 "-antialias"
17661 pdffile
17662 "-quality" "100"
17663 ; "-sharpen" "0x1.0"
17664 pngfile))
17665 (error nil))
17666 (if (not (file-exists-p pngfile))
17667 (if org-format-latex-signal-error
17668 (error "Failed to create png file from %s" texfile)
17669 (message "Failed to create png file from %s" texfile)
17670 nil)
17671 ;; Use the requested file name and clean up
17672 (copy-file pngfile tofile 'replace)
17673 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17674 (if (file-exists-p (concat texfilebase e))
17675 (delete-file (concat texfilebase e))))
17676 pngfile))))
17678 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17679 "Fill a LaTeX header template TPL.
17680 In the template, the following place holders will be recognized:
17682 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17683 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17684 [PACKAGES] \\usepackage statements for PKG
17685 [NO-PACKAGES] do not include PKG
17686 [EXTRA] the string EXTRA
17687 [NO-EXTRA] do not include EXTRA
17689 For backward compatibility, if both the positive and the negative place
17690 holder is missing, the positive one (without the \"NO-\") will be
17691 assumed to be present at the end of the template.
17692 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17693 EXTRA is a string.
17694 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17695 (let (rpl (end ""))
17696 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17697 (setq rpl (if (or (match-end 1) (not def-pkg))
17698 "" (org-latex-packages-to-string def-pkg snippets-p t))
17699 tpl (replace-match rpl t t tpl))
17700 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17702 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17703 (setq rpl (if (or (match-end 1) (not pkg))
17704 "" (org-latex-packages-to-string pkg snippets-p t))
17705 tpl (replace-match rpl t t tpl))
17706 (if pkg (setq end
17707 (concat end "\n"
17708 (org-latex-packages-to-string pkg snippets-p)))))
17710 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17711 (setq rpl (if (or (match-end 1) (not extra))
17712 "" (concat extra "\n"))
17713 tpl (replace-match rpl t t tpl))
17714 (if (and extra (string-match "\\S-" extra))
17715 (setq end (concat end "\n" extra))))
17717 (if (string-match "\\S-" end)
17718 (concat tpl "\n" end)
17719 tpl)))
17721 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17722 "Turn an alist of packages into a string with the \\usepackage macros."
17723 (setq pkg (mapconcat (lambda(p)
17724 (cond
17725 ((stringp p) p)
17726 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17727 (format "%% Package %s omitted" (cadr p)))
17728 ((equal "" (car p))
17729 (format "\\usepackage{%s}" (cadr p)))
17731 (format "\\usepackage[%s]{%s}"
17732 (car p) (cadr p)))))
17734 "\n"))
17735 (if newline (concat pkg "\n") pkg))
17737 (defun org-dvipng-color (attr)
17738 "Return a RGB color specification for dvipng."
17739 (apply 'format "rgb %s %s %s"
17740 (mapcar 'org-normalize-color
17741 (if (featurep 'xemacs)
17742 (color-rgb-components
17743 (face-property 'default
17744 (cond ((eq attr :foreground) 'foreground)
17745 ((eq attr :background) 'background))))
17746 (color-values (face-attribute 'default attr nil))))))
17748 (defun org-latex-color (attr)
17749 "Return a RGB color for the LaTeX color package."
17750 (apply 'format "%s,%s,%s"
17751 (mapcar 'org-normalize-color
17752 (if (featurep 'xemacs)
17753 (color-rgb-components
17754 (face-property 'default
17755 (cond ((eq attr :foreground) 'foreground)
17756 ((eq attr :background) 'background))))
17757 (color-values (face-attribute 'default attr nil))))))
17759 (defun org-latex-color-format (color-name)
17760 "Convert COLOR-NAME to a RGB color value."
17761 (apply 'format "%s,%s,%s"
17762 (mapcar 'org-normalize-color
17763 (color-values color-name))))
17765 (defun org-normalize-color (value)
17766 "Return string to be used as color value for an RGB component."
17767 (format "%g" (/ value 65535.0)))
17769 ;; Image display
17772 (defvar org-inline-image-overlays nil)
17773 (make-variable-buffer-local 'org-inline-image-overlays)
17775 (defun org-toggle-inline-images (&optional include-linked)
17776 "Toggle the display of inline images.
17777 INCLUDE-LINKED is passed to `org-display-inline-images'."
17778 (interactive "P")
17779 (if org-inline-image-overlays
17780 (progn
17781 (org-remove-inline-images)
17782 (message "Inline image display turned off"))
17783 (org-display-inline-images include-linked)
17784 (if org-inline-image-overlays
17785 (message "%d images displayed inline"
17786 (length org-inline-image-overlays))
17787 (message "No images to display inline"))))
17789 (defun org-redisplay-inline-images ()
17790 "Refresh the display of inline images."
17791 (interactive)
17792 (if (not org-inline-image-overlays)
17793 (org-toggle-inline-images)
17794 (org-toggle-inline-images)
17795 (org-toggle-inline-images)))
17797 (defun org-display-inline-images (&optional include-linked refresh beg end)
17798 "Display inline images.
17799 Normally only links without a description part are inlined, because this
17800 is how it will work for export. When INCLUDE-LINKED is set, also links
17801 with a description part will be inlined. This can be nice for a quick
17802 look at those images, but it does not reflect what exported files will look
17803 like.
17804 When REFRESH is set, refresh existing images between BEG and END.
17805 This will create new image displays only if necessary.
17806 BEG and END default to the buffer boundaries."
17807 (interactive "P")
17808 (unless refresh
17809 (org-remove-inline-images)
17810 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17811 (save-excursion
17812 (save-restriction
17813 (widen)
17814 (setq beg (or beg (point-min)) end (or end (point-max)))
17815 (goto-char beg)
17816 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17817 (substring (org-image-file-name-regexp) 0 -2)
17818 "\\)\\]" (if include-linked "" "\\]")))
17819 old file ov img)
17820 (while (re-search-forward re end t)
17821 (setq old (get-char-property-and-overlay (match-beginning 1)
17822 'org-image-overlay))
17823 (setq file (expand-file-name
17824 (concat (or (match-string 3) "") (match-string 4))))
17825 (when (file-exists-p file)
17826 (if (and (car-safe old) refresh)
17827 (image-refresh (overlay-get (cdr old) 'display))
17828 (setq img (save-match-data (create-image file)))
17829 (when img
17830 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17831 (overlay-put ov 'display img)
17832 (overlay-put ov 'face 'default)
17833 (overlay-put ov 'org-image-overlay t)
17834 (overlay-put ov 'modification-hooks
17835 (list 'org-display-inline-remove-overlay))
17836 (push ov org-inline-image-overlays)))))))))
17838 (define-obsolete-function-alias
17839 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17841 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17842 "Remove inline-display overlay if a corresponding region is modified."
17843 (let ((inhibit-modification-hooks t))
17844 (when (and ov after)
17845 (delete ov org-inline-image-overlays)
17846 (delete-overlay ov))))
17848 (defun org-remove-inline-images ()
17849 "Remove inline display of images."
17850 (interactive)
17851 (mapc 'delete-overlay org-inline-image-overlays)
17852 (setq org-inline-image-overlays nil))
17854 ;;;; Key bindings
17856 ;; Outline functions from `outline-mode-prefix-map'
17857 ;; that can be remapped in Org:
17858 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17859 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17860 (define-key org-mode-map [remap outline-forward-same-level]
17861 'org-forward-heading-same-level)
17862 (define-key org-mode-map [remap outline-backward-same-level]
17863 'org-backward-heading-same-level)
17864 (define-key org-mode-map [remap show-branches]
17865 'org-kill-note-or-show-branches)
17866 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17867 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17868 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17870 ;; Outline functions from `outline-mode-prefix-map' that can not
17871 ;; be remapped in Org:
17873 ;; - the column "key binding" shows whether the Outline function is still
17874 ;; available in Org mode on the same key that it has been bound to in
17875 ;; Outline mode:
17876 ;; - "overridden": key used for a different functionality in Org mode
17877 ;; - else: key still bound to the same Outline function in Org mode
17879 ;; | Outline function | key binding | Org replacement |
17880 ;; |------------------------------------+-------------+-----------------------|
17881 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17882 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17883 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17884 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17885 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17886 ;; | `show-entry' | overridden | no replacement |
17887 ;; | `show-children' | `C-c C-i' | visibility cycling |
17888 ;; | `show-branches' | `C-c C-k' | still same function |
17889 ;; | `show-subtree' | overridden | visibility cycling |
17890 ;; | `show-all' | overridden | no replacement |
17891 ;; | `hide-subtree' | overridden | visibility cycling |
17892 ;; | `hide-body' | overridden | no replacement |
17893 ;; | `hide-entry' | overridden | visibility cycling |
17894 ;; | `hide-leaves' | overridden | no replacement |
17895 ;; | `hide-sublevels' | overridden | no replacement |
17896 ;; | `hide-other' | overridden | no replacement |
17898 ;; Make `C-c C-x' a prefix key
17899 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17901 ;; TAB key with modifiers
17902 (org-defkey org-mode-map "\C-i" 'org-cycle)
17903 (org-defkey org-mode-map [(tab)] 'org-cycle)
17904 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17905 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17906 ;; The following line is necessary under Suse GNU/Linux
17907 (unless (featurep 'xemacs)
17908 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17909 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17910 (define-key org-mode-map [backtab] 'org-shifttab)
17912 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17913 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17914 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17916 ;; Cursor keys with modifiers
17917 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17918 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17919 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17920 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17922 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17923 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17924 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17925 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17927 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17928 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17929 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17930 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17932 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17933 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17934 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17935 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17937 ;; Babel keys
17938 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17939 (mapc (lambda (pair)
17940 (define-key org-babel-map (car pair) (cdr pair)))
17941 org-babel-key-bindings)
17943 ;;; Extra keys for tty access.
17944 ;; We only set them when really needed because otherwise the
17945 ;; menus don't show the simple keys
17947 (when (or org-use-extra-keys
17948 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17949 (not window-system))
17950 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17951 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17952 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17953 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17954 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17955 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17956 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17957 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17958 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17959 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17960 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17961 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17962 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17963 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17964 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17965 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17966 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17967 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17968 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17969 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17970 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17971 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17972 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17973 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17974 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17975 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17976 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17977 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17979 ;; All the other keys
17981 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17982 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17983 (if (boundp 'narrow-map)
17984 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17985 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17986 (if (boundp 'narrow-map)
17987 (org-defkey narrow-map "b" 'org-narrow-to-block)
17988 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17989 (if (boundp 'narrow-map)
17990 (org-defkey narrow-map "e" 'org-narrow-to-element)
17991 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17992 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17993 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17994 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17995 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17996 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17997 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17998 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17999 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18000 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18001 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18002 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18003 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18004 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18005 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18006 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18007 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18008 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18009 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18010 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18011 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18012 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18013 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18014 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18015 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18016 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18017 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18018 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18019 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18020 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18021 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18022 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18023 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18024 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18025 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18026 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18027 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18028 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18029 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18030 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18031 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18032 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18033 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18034 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18035 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18036 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18037 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18038 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18039 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18040 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18041 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18042 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18043 (org-defkey org-mode-map "\C-c^" 'org-sort)
18044 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18045 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18046 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18047 (org-defkey org-mode-map "\C-m" 'org-return)
18048 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18049 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18050 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18051 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18052 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18053 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18054 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18055 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18056 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18057 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18058 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18059 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18060 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18061 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18062 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18063 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18064 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18065 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18066 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18067 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18068 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18069 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18070 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18072 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18073 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18074 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18076 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18077 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18078 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18079 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18080 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18081 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18082 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18083 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18084 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18085 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18086 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18087 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18088 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18089 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18090 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18091 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18092 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18093 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18094 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18095 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18096 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18097 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18099 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18100 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18101 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18102 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18103 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18105 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18107 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18109 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18110 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18112 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18115 (when (featurep 'xemacs)
18116 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18119 (defconst org-speed-commands-default
18121 ("Outline Navigation")
18122 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18123 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18124 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18125 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18126 ("u" . (org-speed-move-safe 'outline-up-heading))
18127 ("j" . org-goto)
18128 ("g" . (org-refile t))
18129 ("Outline Visibility")
18130 ("c" . org-cycle)
18131 ("C" . org-shifttab)
18132 (" " . org-display-outline-path)
18133 ("=" . org-columns)
18134 ("Outline Structure Editing")
18135 ("U" . org-shiftmetaup)
18136 ("D" . org-shiftmetadown)
18137 ("r" . org-metaright)
18138 ("l" . org-metaleft)
18139 ("R" . org-shiftmetaright)
18140 ("L" . org-shiftmetaleft)
18141 ("i" . (progn (forward-char 1) (call-interactively
18142 'org-insert-heading-respect-content)))
18143 ("^" . org-sort)
18144 ("w" . org-refile)
18145 ("a" . org-archive-subtree-default-with-confirmation)
18146 ("." . org-mark-subtree)
18147 ("#" . org-toggle-comment)
18148 ("Clock Commands")
18149 ("I" . org-clock-in)
18150 ("O" . org-clock-out)
18151 ("Meta Data Editing")
18152 ("t" . org-todo)
18153 ("," . (org-priority))
18154 ("0" . (org-priority ?\ ))
18155 ("1" . (org-priority ?A))
18156 ("2" . (org-priority ?B))
18157 ("3" . (org-priority ?C))
18158 (":" . org-set-tags-command)
18159 ("e" . org-set-effort)
18160 ("E" . org-inc-effort)
18161 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18162 (org-entry-put (point) "APPT_WARNTIME" m)))
18163 ("Agenda Views etc")
18164 ("v" . org-agenda)
18165 ("/" . org-sparse-tree)
18166 ("Misc")
18167 ("o" . org-open-at-point)
18168 ("?" . org-speed-command-help)
18169 ("<" . (org-agenda-set-restriction-lock 'subtree))
18170 (">" . (org-agenda-remove-restriction-lock))
18172 "The default speed commands.")
18174 (defun org-print-speed-command (e)
18175 (if (> (length (car e)) 1)
18176 (progn
18177 (princ "\n")
18178 (princ (car e))
18179 (princ "\n")
18180 (princ (make-string (length (car e)) ?-))
18181 (princ "\n"))
18182 (princ (car e))
18183 (princ " ")
18184 (if (symbolp (cdr e))
18185 (princ (symbol-name (cdr e)))
18186 (prin1 (cdr e)))
18187 (princ "\n")))
18189 (defun org-speed-command-help ()
18190 "Show the available speed commands."
18191 (interactive)
18192 (if (not org-use-speed-commands)
18193 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18194 (with-output-to-temp-buffer "*Help*"
18195 (princ "User-defined Speed commands\n===========================\n")
18196 (mapc 'org-print-speed-command org-speed-commands-user)
18197 (princ "\n")
18198 (princ "Built-in Speed commands\n=======================\n")
18199 (mapc 'org-print-speed-command org-speed-commands-default))
18200 (with-current-buffer "*Help*"
18201 (setq truncate-lines t))))
18203 (defun org-speed-move-safe (cmd)
18204 "Execute CMD, but make sure that the cursor always ends up in a headline.
18205 If not, return to the original position and throw an error."
18206 (interactive)
18207 (let ((pos (point)))
18208 (call-interactively cmd)
18209 (unless (and (bolp) (org-at-heading-p))
18210 (goto-char pos)
18211 (error "Boundary reached while executing %s" cmd))))
18213 (defvar org-self-insert-command-undo-counter 0)
18215 (defvar org-table-auto-blank-field) ; defined in org-table.el
18216 (defvar org-speed-command nil)
18218 (define-obsolete-function-alias
18219 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18221 (defun org-speed-command-activate (keys)
18222 "Hook for activating single-letter speed commands.
18223 `org-speed-commands-default' specifies a minimal command set.
18224 Use `org-speed-commands-user' for further customization."
18225 (when (or (and (bolp) (looking-at org-outline-regexp))
18226 (and (functionp org-use-speed-commands)
18227 (funcall org-use-speed-commands)))
18228 (cdr (assoc keys (append org-speed-commands-user
18229 org-speed-commands-default)))))
18231 (define-obsolete-function-alias
18232 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18234 (defun org-babel-speed-command-activate (keys)
18235 "Hook for activating single-letter code block commands."
18236 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18237 (cdr (assoc keys org-babel-key-bindings))))
18239 (defcustom org-speed-command-hook
18240 '(org-speed-command-default-hook org-babel-speed-command-hook)
18241 "Hook for activating speed commands at strategic locations.
18242 Hook functions are called in sequence until a valid handler is
18243 found.
18245 Each hook takes a single argument, a user-pressed command key
18246 which is also a `self-insert-command' from the global map.
18248 Within the hook, examine the cursor position and the command key
18249 and return nil or a valid handler as appropriate. Handler could
18250 be one of an interactive command, a function, or a form.
18252 Set `org-use-speed-commands' to non-nil value to enable this
18253 hook. The default setting is `org-speed-command-activate'."
18254 :group 'org-structure
18255 :version "24.1"
18256 :type 'hook)
18258 (defun org-self-insert-command (N)
18259 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18260 If the cursor is in a table looking at whitespace, the whitespace is
18261 overwritten, and the table is not marked as requiring realignment."
18262 (interactive "p")
18263 (org-check-before-invisible-edit 'insert)
18264 (cond
18265 ((and org-use-speed-commands
18266 (setq org-speed-command
18267 (run-hook-with-args-until-success
18268 'org-speed-command-hook (this-command-keys))))
18269 (cond
18270 ((commandp org-speed-command)
18271 (setq this-command org-speed-command)
18272 (call-interactively org-speed-command))
18273 ((functionp org-speed-command)
18274 (funcall org-speed-command))
18275 ((and org-speed-command (listp org-speed-command))
18276 (eval org-speed-command))
18277 (t (let (org-use-speed-commands)
18278 (call-interactively 'org-self-insert-command)))))
18279 ((and
18280 (org-table-p)
18281 (progn
18282 ;; check if we blank the field, and if that triggers align
18283 (and (featurep 'org-table) org-table-auto-blank-field
18284 (member last-command
18285 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18286 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18287 ;; got extra space, this field does not determine column width
18288 (let (org-table-may-need-update) (org-table-blank-field))
18289 ;; no extra space, this field may determine column width
18290 (org-table-blank-field)))
18292 (eq N 1)
18293 (looking-at "[^|\n]* |"))
18294 (let (org-table-may-need-update)
18295 (goto-char (1- (match-end 0)))
18296 (backward-delete-char 1)
18297 (goto-char (match-beginning 0))
18298 (self-insert-command N)))
18300 (setq org-table-may-need-update t)
18301 (self-insert-command N)
18302 (org-fix-tags-on-the-fly)
18303 (if org-self-insert-cluster-for-undo
18304 (if (not (eq last-command 'org-self-insert-command))
18305 (setq org-self-insert-command-undo-counter 1)
18306 (if (>= org-self-insert-command-undo-counter 20)
18307 (setq org-self-insert-command-undo-counter 1)
18308 (and (> org-self-insert-command-undo-counter 0)
18309 buffer-undo-list (listp buffer-undo-list)
18310 (not (cadr buffer-undo-list)) ; remove nil entry
18311 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18312 (setq org-self-insert-command-undo-counter
18313 (1+ org-self-insert-command-undo-counter))))))))
18315 (defun org-check-before-invisible-edit (kind)
18316 "Check is editing if kind KIND would be dangerous with invisible text around.
18317 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18318 ;; First, try to get out of here as quickly as possible, to reduce overhead
18319 (if (and org-catch-invisible-edits
18320 (or (not (boundp 'visible-mode)) (not visible-mode))
18321 (or (get-char-property (point) 'invisible)
18322 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18323 ;; OK, we need to take a closer look
18324 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18325 (invisible-before-point (if (bobp) nil (get-char-property
18326 (1- (point)) 'invisible)))
18327 (border-and-ok-direction
18329 ;; Check if we are acting predictably before invisible text
18330 (and invisible-at-point (not invisible-before-point)
18331 (memq kind '(insert delete-backward)))
18332 ;; Check if we are acting predictably after invisible text
18333 ;; This works not well, and I have turned it off. It seems
18334 ;; better to always show and stop after invisible text.
18335 ;; (and (not invisible-at-point) invisible-before-point
18336 ;; (memq kind '(insert delete)))
18338 (when (or (memq invisible-at-point '(outline org-hide-block t))
18339 (memq invisible-before-point '(outline org-hide-block t)))
18340 (if (eq org-catch-invisible-edits 'error)
18341 (error "Editing in invisible areas is prohibited - make visible first"))
18342 (if (and org-custom-properties-overlays
18343 (y-or-n-p "Display invisible properties in this buffer? "))
18344 (org-toggle-custom-properties-visibility)
18345 ;; Make the area visible
18346 (save-excursion
18347 (if invisible-before-point
18348 (goto-char (previous-single-char-property-change
18349 (point) 'invisible)))
18350 (org-cycle))
18351 (cond
18352 ((eq org-catch-invisible-edits 'show)
18353 ;; That's it, we do the edit after showing
18354 (message
18355 "Unfolding invisible region around point before editing")
18356 (sit-for 1))
18357 ((and (eq org-catch-invisible-edits 'smart)
18358 border-and-ok-direction)
18359 (message "Unfolding invisible region around point before editing"))
18361 ;; Don't do the edit, make the user repeat it in full visibility
18362 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18364 (defun org-fix-tags-on-the-fly ()
18365 (when (and (equal (char-after (point-at-bol)) ?*)
18366 (org-at-heading-p))
18367 (org-align-tags-here org-tags-column)))
18369 (defun org-delete-backward-char (N)
18370 "Like `delete-backward-char', insert whitespace at field end in tables.
18371 When deleting backwards, in tables this function will insert whitespace in
18372 front of the next \"|\" separator, to keep the table aligned. The table will
18373 still be marked for re-alignment if the field did fill the entire column,
18374 because, in this case the deletion might narrow the column."
18375 (interactive "p")
18376 (save-match-data
18377 (org-check-before-invisible-edit 'delete-backward)
18378 (if (and (org-table-p)
18379 (eq N 1)
18380 (string-match "|" (buffer-substring (point-at-bol) (point)))
18381 (looking-at ".*?|"))
18382 (let ((pos (point))
18383 (noalign (looking-at "[^|\n\r]* |"))
18384 (c org-table-may-need-update))
18385 (backward-delete-char N)
18386 (if (not overwrite-mode)
18387 (progn
18388 (skip-chars-forward "^|")
18389 (insert " ")
18390 (goto-char (1- pos))))
18391 ;; noalign: if there were two spaces at the end, this field
18392 ;; does not determine the width of the column.
18393 (if noalign (setq org-table-may-need-update c)))
18394 (backward-delete-char N)
18395 (org-fix-tags-on-the-fly))))
18397 (defun org-delete-char (N)
18398 "Like `delete-char', but insert whitespace at field end in tables.
18399 When deleting characters, in tables this function will insert whitespace in
18400 front of the next \"|\" separator, to keep the table aligned. The table will
18401 still be marked for re-alignment if the field did fill the entire column,
18402 because, in this case the deletion might narrow the column."
18403 (interactive "p")
18404 (save-match-data
18405 (org-check-before-invisible-edit 'delete)
18406 (if (and (org-table-p)
18407 (not (bolp))
18408 (not (= (char-after) ?|))
18409 (eq N 1))
18410 (if (looking-at ".*?|")
18411 (let ((pos (point))
18412 (noalign (looking-at "[^|\n\r]* |"))
18413 (c org-table-may-need-update))
18414 (replace-match (concat
18415 (substring (match-string 0) 1 -1)
18416 " |"))
18417 (goto-char pos)
18418 ;; noalign: if there were two spaces at the end, this field
18419 ;; does not determine the width of the column.
18420 (if noalign (setq org-table-may-need-update c)))
18421 (delete-char N))
18422 (delete-char N)
18423 (org-fix-tags-on-the-fly))))
18425 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18426 (put 'org-self-insert-command 'delete-selection t)
18427 (put 'orgtbl-self-insert-command 'delete-selection t)
18428 (put 'org-delete-char 'delete-selection 'supersede)
18429 (put 'org-delete-backward-char 'delete-selection 'supersede)
18430 (put 'org-yank 'delete-selection 'yank)
18432 ;; Make `flyspell-mode' delay after some commands
18433 (put 'org-self-insert-command 'flyspell-delayed t)
18434 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18435 (put 'org-delete-char 'flyspell-delayed t)
18436 (put 'org-delete-backward-char 'flyspell-delayed t)
18438 ;; Make pabbrev-mode expand after org-mode commands
18439 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18440 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18442 ;; How to do this: Measure non-white length of current string
18443 ;; If equal to column width, we should realign.
18445 (defun org-remap (map &rest commands)
18446 "In MAP, remap the functions given in COMMANDS.
18447 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18448 (let (new old)
18449 (while commands
18450 (setq old (pop commands) new (pop commands))
18451 (if (fboundp 'command-remapping)
18452 (org-defkey map (vector 'remap old) new)
18453 (substitute-key-definition old new map global-map)))))
18455 (when (eq org-enable-table-editor 'optimized)
18456 ;; If the user wants maximum table support, we need to hijack
18457 ;; some standard editing functions
18458 (org-remap org-mode-map
18459 'self-insert-command 'org-self-insert-command
18460 'delete-char 'org-delete-char
18461 'delete-backward-char 'org-delete-backward-char)
18462 (org-defkey org-mode-map "|" 'org-force-self-insert))
18464 (defvar org-ctrl-c-ctrl-c-hook nil
18465 "Hook for functions attaching themselves to `C-c C-c'.
18467 This can be used to add additional functionality to the C-c C-c
18468 key which executes context-dependent commands. This hook is run
18469 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18470 run after the last test.
18472 Each function will be called with no arguments. The function
18473 must check if the context is appropriate for it to act. If yes,
18474 it should do its thing and then return a non-nil value. If the
18475 context is wrong, just do nothing and return nil.")
18477 (defvar org-ctrl-c-ctrl-c-final-hook nil
18478 "Hook for functions attaching themselves to `C-c C-c'.
18480 This can be used to add additional functionality to the C-c C-c
18481 key which executes context-dependent commands. This hook is run
18482 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18483 before the first test.
18485 Each function will be called with no arguments. The function
18486 must check if the context is appropriate for it to act. If yes,
18487 it should do its thing and then return a non-nil value. If the
18488 context is wrong, just do nothing and return nil.")
18490 (defvar org-tab-first-hook nil
18491 "Hook for functions to attach themselves to TAB.
18492 See `org-ctrl-c-ctrl-c-hook' for more information.
18493 This hook runs as the first action when TAB is pressed, even before
18494 `org-cycle' messes around with the `outline-regexp' to cater for
18495 inline tasks and plain list item folding.
18496 If any function in this hook returns t, any other actions that
18497 would have been caused by TAB (such as table field motion or visibility
18498 cycling) will not occur.")
18500 (defvar org-tab-after-check-for-table-hook nil
18501 "Hook for functions to attach themselves to TAB.
18502 See `org-ctrl-c-ctrl-c-hook' for more information.
18503 This hook runs after it has been established that the cursor is not in a
18504 table, but before checking if the cursor is in a headline or if global cycling
18505 should be done.
18506 If any function in this hook returns t, not other actions like visibility
18507 cycling will be done.")
18509 (defvar org-tab-after-check-for-cycling-hook nil
18510 "Hook for functions to attach themselves to TAB.
18511 See `org-ctrl-c-ctrl-c-hook' for more information.
18512 This hook runs after it has been established that not table field motion and
18513 not visibility should be done because of current context. This is probably
18514 the place where a package like yasnippets can hook in.")
18516 (defvar org-tab-before-tab-emulation-hook nil
18517 "Hook for functions to attach themselves to TAB.
18518 See `org-ctrl-c-ctrl-c-hook' for more information.
18519 This hook runs after every other options for TAB have been exhausted, but
18520 before indentation and \t insertion takes place.")
18522 (defvar org-metaleft-hook nil
18523 "Hook for functions attaching themselves to `M-left'.
18524 See `org-ctrl-c-ctrl-c-hook' for more information.")
18525 (defvar org-metaright-hook nil
18526 "Hook for functions attaching themselves to `M-right'.
18527 See `org-ctrl-c-ctrl-c-hook' for more information.")
18528 (defvar org-metaup-hook nil
18529 "Hook for functions attaching themselves to `M-up'.
18530 See `org-ctrl-c-ctrl-c-hook' for more information.")
18531 (defvar org-metadown-hook nil
18532 "Hook for functions attaching themselves to `M-down'.
18533 See `org-ctrl-c-ctrl-c-hook' for more information.")
18534 (defvar org-shiftmetaleft-hook nil
18535 "Hook for functions attaching themselves to `M-S-left'.
18536 See `org-ctrl-c-ctrl-c-hook' for more information.")
18537 (defvar org-shiftmetaright-hook nil
18538 "Hook for functions attaching themselves to `M-S-right'.
18539 See `org-ctrl-c-ctrl-c-hook' for more information.")
18540 (defvar org-shiftmetaup-hook nil
18541 "Hook for functions attaching themselves to `M-S-up'.
18542 See `org-ctrl-c-ctrl-c-hook' for more information.")
18543 (defvar org-shiftmetadown-hook nil
18544 "Hook for functions attaching themselves to `M-S-down'.
18545 See `org-ctrl-c-ctrl-c-hook' for more information.")
18546 (defvar org-metareturn-hook nil
18547 "Hook for functions attaching themselves to `M-RET'.
18548 See `org-ctrl-c-ctrl-c-hook' for more information.")
18549 (defvar org-shiftup-hook nil
18550 "Hook for functions attaching themselves to `S-up'.
18551 See `org-ctrl-c-ctrl-c-hook' for more information.")
18552 (defvar org-shiftup-final-hook nil
18553 "Hook for functions attaching themselves to `S-up'.
18554 This one runs after all other options except shift-select have been excluded.
18555 See `org-ctrl-c-ctrl-c-hook' for more information.")
18556 (defvar org-shiftdown-hook nil
18557 "Hook for functions attaching themselves to `S-down'.
18558 See `org-ctrl-c-ctrl-c-hook' for more information.")
18559 (defvar org-shiftdown-final-hook nil
18560 "Hook for functions attaching themselves to `S-down'.
18561 This one runs after all other options except shift-select have been excluded.
18562 See `org-ctrl-c-ctrl-c-hook' for more information.")
18563 (defvar org-shiftleft-hook nil
18564 "Hook for functions attaching themselves to `S-left'.
18565 See `org-ctrl-c-ctrl-c-hook' for more information.")
18566 (defvar org-shiftleft-final-hook nil
18567 "Hook for functions attaching themselves to `S-left'.
18568 This one runs after all other options except shift-select have been excluded.
18569 See `org-ctrl-c-ctrl-c-hook' for more information.")
18570 (defvar org-shiftright-hook nil
18571 "Hook for functions attaching themselves to `S-right'.
18572 See `org-ctrl-c-ctrl-c-hook' for more information.")
18573 (defvar org-shiftright-final-hook nil
18574 "Hook for functions attaching themselves to `S-right'.
18575 This one runs after all other options except shift-select have been excluded.
18576 See `org-ctrl-c-ctrl-c-hook' for more information.")
18578 (defun org-modifier-cursor-error ()
18579 "Throw an error, a modified cursor command was applied in wrong context."
18580 (error "This command is active in special context like tables, headlines or items"))
18582 (defun org-shiftselect-error ()
18583 "Throw an error because Shift-Cursor command was applied in wrong context."
18584 (if (and (boundp 'shift-select-mode) shift-select-mode)
18585 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18586 (error "This command works only in special context like headlines or timestamps")))
18588 (defun org-call-for-shift-select (cmd)
18589 (let ((this-command-keys-shift-translated t))
18590 (call-interactively cmd)))
18592 (defun org-shifttab (&optional arg)
18593 "Global visibility cycling or move to previous table field.
18594 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18595 on context.
18596 See the individual commands for more information."
18597 (interactive "P")
18598 (cond
18599 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18600 ((integerp arg)
18601 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18602 (message "Content view to level: %d" arg)
18603 (org-content (prefix-numeric-value arg2))
18604 (setq org-cycle-global-status 'overview)))
18605 (t (call-interactively 'org-global-cycle))))
18607 (defun org-shiftmetaleft ()
18608 "Promote subtree or delete table column.
18609 Calls `org-promote-subtree', `org-outdent-item-tree', or
18610 `org-table-delete-column', depending on context. See the
18611 individual commands for more information."
18612 (interactive)
18613 (cond
18614 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18615 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18616 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18617 ((if (not (org-region-active-p)) (org-at-item-p)
18618 (save-excursion (goto-char (region-beginning))
18619 (org-at-item-p)))
18620 (call-interactively 'org-outdent-item-tree))
18621 (t (org-modifier-cursor-error))))
18623 (defun org-shiftmetaright ()
18624 "Demote subtree or insert table column.
18625 Calls `org-demote-subtree', `org-indent-item-tree', or
18626 `org-table-insert-column', depending on context. See the
18627 individual commands for more information."
18628 (interactive)
18629 (cond
18630 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18631 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18632 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18633 ((if (not (org-region-active-p)) (org-at-item-p)
18634 (save-excursion (goto-char (region-beginning))
18635 (org-at-item-p)))
18636 (call-interactively 'org-indent-item-tree))
18637 (t (org-modifier-cursor-error))))
18639 (defun org-shiftmetaup (&optional arg)
18640 "Move subtree up or kill table row.
18641 Calls `org-move-subtree-up' or `org-table-kill-row' or
18642 `org-move-item-up' or `org-timestamp-up', depending on context.
18643 See the individual commands for more information."
18644 (interactive "P")
18645 (cond
18646 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18647 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18648 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18649 ((org-at-item-p) (call-interactively 'org-move-item-up))
18650 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18651 (call-interactively 'org-timestamp-up)))
18652 (t (org-modifier-cursor-error))))
18654 (defun org-shiftmetadown (&optional arg)
18655 "Move subtree down or insert table row.
18656 Calls `org-move-subtree-down' or `org-table-insert-row' or
18657 `org-move-item-down' or `org-timestamp-up', depending on context.
18658 See the individual commands for more information."
18659 (interactive "P")
18660 (cond
18661 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18662 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18663 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18664 ((org-at-item-p) (call-interactively 'org-move-item-down))
18665 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18666 (call-interactively 'org-timestamp-down)))
18667 (t (org-modifier-cursor-error))))
18669 (defsubst org-hidden-tree-error ()
18670 (error
18671 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18673 (defun org-metaleft (&optional arg)
18674 "Promote heading or move table column to left.
18675 Calls `org-do-promote' or `org-table-move-column', depending on context.
18676 With no specific context, calls the Emacs default `backward-word'.
18677 See the individual commands for more information."
18678 (interactive "P")
18679 (cond
18680 ((run-hook-with-args-until-success 'org-metaleft-hook))
18681 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18682 ((org-with-limited-levels
18683 (or (org-at-heading-p)
18684 (and (org-region-active-p)
18685 (save-excursion
18686 (goto-char (region-beginning))
18687 (org-at-heading-p)))))
18688 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18689 (call-interactively 'org-do-promote))
18690 ;; At an inline task.
18691 ((org-at-heading-p)
18692 (call-interactively 'org-inlinetask-promote))
18693 ((or (org-at-item-p)
18694 (and (org-region-active-p)
18695 (save-excursion
18696 (goto-char (region-beginning))
18697 (org-at-item-p))))
18698 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18699 (call-interactively 'org-outdent-item))
18700 (t (call-interactively 'backward-word))))
18702 (defun org-metaright (&optional arg)
18703 "Demote a subtree, a list item or move table column to right.
18704 In front of a drawer or a block keyword, indent it correctly.
18705 With no specific context, calls the Emacs default `forward-word'.
18706 See the individual commands for more information."
18707 (interactive "P")
18708 (cond
18709 ((run-hook-with-args-until-success 'org-metaright-hook))
18710 ((org-at-table-p) (call-interactively 'org-table-move-column))
18711 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18712 ((org-at-block-p) (call-interactively 'org-indent-block))
18713 ((org-with-limited-levels
18714 (or (org-at-heading-p)
18715 (and (org-region-active-p)
18716 (save-excursion
18717 (goto-char (region-beginning))
18718 (org-at-heading-p)))))
18719 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18720 (call-interactively 'org-do-demote))
18721 ;; At an inline task.
18722 ((org-at-heading-p)
18723 (call-interactively 'org-inlinetask-demote))
18724 ((or (org-at-item-p)
18725 (and (org-region-active-p)
18726 (save-excursion
18727 (goto-char (region-beginning))
18728 (org-at-item-p))))
18729 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18730 (call-interactively 'org-indent-item))
18731 (t (call-interactively 'forward-word))))
18733 (defun org-check-for-hidden (what)
18734 "Check if there are hidden headlines/items in the current visual line.
18735 WHAT can be either `headlines' or `items'. If the current line is
18736 an outline or item heading and it has a folded subtree below it,
18737 this function returns t, nil otherwise."
18738 (let ((re (cond
18739 ((eq what 'headlines) org-outline-regexp-bol)
18740 ((eq what 'items) (org-item-beginning-re))
18741 (t (error "This should not happen"))))
18742 beg end)
18743 (save-excursion
18744 (catch 'exit
18745 (unless (org-region-active-p)
18746 (setq beg (point-at-bol))
18747 (beginning-of-line 2)
18748 (while (and (not (eobp)) ;; this is like `next-line'
18749 (get-char-property (1- (point)) 'invisible))
18750 (beginning-of-line 2))
18751 (setq end (point))
18752 (goto-char beg)
18753 (goto-char (point-at-eol))
18754 (setq end (max end (point)))
18755 (while (re-search-forward re end t)
18756 (if (get-char-property (match-beginning 0) 'invisible)
18757 (throw 'exit t))))
18758 nil))))
18760 (org-autoload "org-element" '(org-element-at-point org-element-type))
18762 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18763 (declare-function org-element-type "org-element" (element))
18764 (declare-function org-element-contents "org-element" (element))
18765 (declare-function org-element-property "org-element" (property element))
18766 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18767 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18768 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18769 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18770 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18772 (defun org-metaup (&optional arg)
18773 "Move subtree up or move table row up.
18774 Calls `org-move-subtree-up' or `org-table-move-row' or
18775 `org-move-item-up', depending on context. See the individual commands
18776 for more information."
18777 (interactive "P")
18778 (cond
18779 ((run-hook-with-args-until-success 'org-metaup-hook))
18780 ((org-region-active-p)
18781 (let* ((a (min (region-beginning) (region-end)))
18782 (b (1- (max (region-beginning) (region-end))))
18783 (c (save-excursion (goto-char a)
18784 (move-beginning-of-line 0)))
18785 (d (save-excursion (goto-char a)
18786 (move-end-of-line 0) (point))))
18787 (transpose-regions a b c d)
18788 (goto-char c)))
18789 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18790 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18791 ((org-at-item-p) (call-interactively 'org-move-item-up))
18792 (t (org-drag-element-backward))))
18794 (defun org-metadown (&optional arg)
18795 "Move subtree down or move table row down.
18796 Calls `org-move-subtree-down' or `org-table-move-row' or
18797 `org-move-item-down', depending on context. See the individual
18798 commands for more information."
18799 (interactive "P")
18800 (cond
18801 ((run-hook-with-args-until-success 'org-metadown-hook))
18802 ((org-region-active-p)
18803 (let* ((a (min (region-beginning) (region-end)))
18804 (b (max (region-beginning) (region-end)))
18805 (c (save-excursion (goto-char b)
18806 (move-beginning-of-line 1)))
18807 (d (save-excursion (goto-char b)
18808 (move-end-of-line 1) (1+ (point)))))
18809 (transpose-regions a b c d)
18810 (goto-char d)))
18811 ((org-at-table-p) (call-interactively 'org-table-move-row))
18812 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18813 ((org-at-item-p) (call-interactively 'org-move-item-down))
18814 (t (org-drag-element-forward))))
18816 (defun org-shiftup (&optional arg)
18817 "Increase item in timestamp or increase priority of current headline.
18818 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18819 depending on context. See the individual commands for more information."
18820 (interactive "P")
18821 (cond
18822 ((run-hook-with-args-until-success 'org-shiftup-hook))
18823 ((and org-support-shift-select (org-region-active-p))
18824 (org-call-for-shift-select 'previous-line))
18825 ((org-at-timestamp-p t)
18826 (call-interactively (if org-edit-timestamp-down-means-later
18827 'org-timestamp-down 'org-timestamp-up)))
18828 ((and (not (eq org-support-shift-select 'always))
18829 org-enable-priority-commands
18830 (org-at-heading-p))
18831 (call-interactively 'org-priority-up))
18832 ((and (not org-support-shift-select) (org-at-item-p))
18833 (call-interactively 'org-previous-item))
18834 ((org-clocktable-try-shift 'up arg))
18835 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18836 (org-support-shift-select
18837 (org-call-for-shift-select 'previous-line))
18838 (t (org-shiftselect-error))))
18840 (defun org-shiftdown (&optional arg)
18841 "Decrease item in timestamp or decrease priority of current headline.
18842 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18843 depending on context. See the individual commands for more information."
18844 (interactive "P")
18845 (cond
18846 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18847 ((and org-support-shift-select (org-region-active-p))
18848 (org-call-for-shift-select 'next-line))
18849 ((org-at-timestamp-p t)
18850 (call-interactively (if org-edit-timestamp-down-means-later
18851 'org-timestamp-up 'org-timestamp-down)))
18852 ((and (not (eq org-support-shift-select 'always))
18853 org-enable-priority-commands
18854 (org-at-heading-p))
18855 (call-interactively 'org-priority-down))
18856 ((and (not org-support-shift-select) (org-at-item-p))
18857 (call-interactively 'org-next-item))
18858 ((org-clocktable-try-shift 'down arg))
18859 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18860 (org-support-shift-select
18861 (org-call-for-shift-select 'next-line))
18862 (t (org-shiftselect-error))))
18864 (defun org-shiftright (&optional arg)
18865 "Cycle the thing at point or in the current line, depending on context.
18866 Depending on context, this does one of the following:
18868 - switch a timestamp at point one day into the future
18869 - on a headline, switch to the next TODO keyword.
18870 - on an item, switch entire list to the next bullet type
18871 - on a property line, switch to the next allowed value
18872 - on a clocktable definition line, move time block into the future"
18873 (interactive "P")
18874 (cond
18875 ((run-hook-with-args-until-success 'org-shiftright-hook))
18876 ((and org-support-shift-select (org-region-active-p))
18877 (org-call-for-shift-select 'forward-char))
18878 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18879 ((and (not (eq org-support-shift-select 'always))
18880 (org-at-heading-p))
18881 (let ((org-inhibit-logging
18882 (not org-treat-S-cursor-todo-selection-as-state-change))
18883 (org-inhibit-blocking
18884 (not org-treat-S-cursor-todo-selection-as-state-change)))
18885 (org-call-with-arg 'org-todo 'right)))
18886 ((or (and org-support-shift-select
18887 (not (eq org-support-shift-select 'always))
18888 (org-at-item-bullet-p))
18889 (and (not org-support-shift-select) (org-at-item-p)))
18890 (org-call-with-arg 'org-cycle-list-bullet nil))
18891 ((and (not (eq org-support-shift-select 'always))
18892 (org-at-property-p))
18893 (call-interactively 'org-property-next-allowed-value))
18894 ((org-clocktable-try-shift 'right arg))
18895 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18896 (org-support-shift-select
18897 (org-call-for-shift-select 'forward-char))
18898 (t (org-shiftselect-error))))
18900 (defun org-shiftleft (&optional arg)
18901 "Cycle the thing at point or in the current line, depending on context.
18902 Depending on context, this does one of the following:
18904 - switch a timestamp at point one day into the past
18905 - on a headline, switch to the previous TODO keyword.
18906 - on an item, switch entire list to the previous bullet type
18907 - on a property line, switch to the previous allowed value
18908 - on a clocktable definition line, move time block into the past"
18909 (interactive "P")
18910 (cond
18911 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18912 ((and org-support-shift-select (org-region-active-p))
18913 (org-call-for-shift-select 'backward-char))
18914 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18915 ((and (not (eq org-support-shift-select 'always))
18916 (org-at-heading-p))
18917 (let ((org-inhibit-logging
18918 (not org-treat-S-cursor-todo-selection-as-state-change))
18919 (org-inhibit-blocking
18920 (not org-treat-S-cursor-todo-selection-as-state-change)))
18921 (org-call-with-arg 'org-todo 'left)))
18922 ((or (and org-support-shift-select
18923 (not (eq org-support-shift-select 'always))
18924 (org-at-item-bullet-p))
18925 (and (not org-support-shift-select) (org-at-item-p)))
18926 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18927 ((and (not (eq org-support-shift-select 'always))
18928 (org-at-property-p))
18929 (call-interactively 'org-property-previous-allowed-value))
18930 ((org-clocktable-try-shift 'left arg))
18931 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18932 (org-support-shift-select
18933 (org-call-for-shift-select 'backward-char))
18934 (t (org-shiftselect-error))))
18936 (defun org-shiftcontrolright ()
18937 "Switch to next TODO set."
18938 (interactive)
18939 (cond
18940 ((and org-support-shift-select (org-region-active-p))
18941 (org-call-for-shift-select 'forward-word))
18942 ((and (not (eq org-support-shift-select 'always))
18943 (org-at-heading-p))
18944 (org-call-with-arg 'org-todo 'nextset))
18945 (org-support-shift-select
18946 (org-call-for-shift-select 'forward-word))
18947 (t (org-shiftselect-error))))
18949 (defun org-shiftcontrolleft ()
18950 "Switch to previous TODO set."
18951 (interactive)
18952 (cond
18953 ((and org-support-shift-select (org-region-active-p))
18954 (org-call-for-shift-select 'backward-word))
18955 ((and (not (eq org-support-shift-select 'always))
18956 (org-at-heading-p))
18957 (org-call-with-arg 'org-todo 'previousset))
18958 (org-support-shift-select
18959 (org-call-for-shift-select 'backward-word))
18960 (t (org-shiftselect-error))))
18962 (defun org-shiftcontrolup ()
18963 "Change timestamps synchronously up in CLOCK log lines."
18964 (interactive)
18965 (cond ((and (not org-support-shift-select)
18966 (org-at-clock-log-p)
18967 (org-at-timestamp-p t))
18968 (org-clock-timestamps-up))
18969 (t (org-shiftselect-error))))
18971 (defun org-shiftcontroldown ()
18972 "Change timestamps synchronously down in CLOCK log lines."
18973 (interactive)
18974 (cond ((and (not org-support-shift-select)
18975 (org-at-clock-log-p)
18976 (org-at-timestamp-p t))
18977 (org-clock-timestamps-down))
18978 (t (org-shiftselect-error))))
18980 (defun org-ctrl-c-ret ()
18981 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18982 (interactive)
18983 (cond
18984 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18985 (t (call-interactively 'org-insert-heading))))
18987 (defun org-find-visible ()
18988 (let ((s (point)))
18989 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18990 (get-char-property s 'invisible)))
18992 (defun org-find-invisible ()
18993 (let ((s (point)))
18994 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18995 (not (get-char-property s 'invisible))))
18998 (defun org-copy-visible (beg end)
18999 "Copy the visible parts of the region."
19000 (interactive "r")
19001 (let (snippets s)
19002 (save-excursion
19003 (save-restriction
19004 (narrow-to-region beg end)
19005 (setq s (goto-char (point-min)))
19006 (while (not (= (point) (point-max)))
19007 (goto-char (org-find-invisible))
19008 (push (buffer-substring s (point)) snippets)
19009 (setq s (goto-char (org-find-visible))))))
19010 (kill-new (apply 'concat (nreverse snippets)))))
19012 (defun org-copy-special ()
19013 "Copy region in table or copy current subtree.
19014 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19015 See the individual commands for more information."
19016 (interactive)
19017 (call-interactively
19018 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19020 (defun org-cut-special ()
19021 "Cut region in table or cut current subtree.
19022 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19023 See the individual commands for more information."
19024 (interactive)
19025 (call-interactively
19026 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19028 (defun org-paste-special (arg)
19029 "Paste rectangular region into table, or past subtree relative to level.
19030 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19031 See the individual commands for more information."
19032 (interactive "P")
19033 (if (org-at-table-p)
19034 (org-table-paste-rectangle)
19035 (org-paste-subtree arg)))
19037 (defsubst org-in-fixed-width-region-p ()
19038 "Is point in a fixed-width region?"
19039 (save-match-data
19040 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19042 (defun org-edit-special (&optional arg)
19043 "Call a special editor for the stuff at point.
19044 When at a table, call the formula editor with `org-table-edit-formulas'.
19045 When in a source code block, call `org-edit-src-code'.
19046 When in a fixed-width region, call `org-edit-fixed-width-region'.
19047 When in an #+include line, visit the included file.
19048 On a link, call `ffap' to visit the link at point.
19049 Otherwise, return a user error."
19050 (interactive)
19051 ;; possibly prep session before editing source
19052 (when (and (org-in-src-block-p) arg)
19053 (let* ((info (org-babel-get-src-block-info))
19054 (lang (nth 0 info))
19055 (params (nth 2 info))
19056 (session (cdr (assoc :session params))))
19057 (when (and info session) ;; we are in a source-code block with a session
19058 (funcall
19059 (intern (concat "org-babel-prep-session:" lang)) session params))))
19060 (cond ;; proceed with `org-edit-special'
19061 ((save-excursion
19062 (beginning-of-line 1)
19063 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19064 (find-file (org-trim (match-string 1))))
19065 ((org-at-table.el-p) (org-edit-src-code))
19066 ((or (org-at-table-p)
19067 (save-excursion
19068 (beginning-of-line 1)
19069 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19070 (call-interactively 'org-table-edit-formulas))
19071 ((org-in-block-p '("src" "example" "latex" "html")) (org-edit-src-code))
19072 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19073 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19074 (t (user-error "No special environment to edit here"))))
19076 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19077 (defun org-ctrl-c-ctrl-c (&optional arg)
19078 "Set tags in headline, or update according to changed information at point.
19080 This command does many different things, depending on context:
19082 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19083 this is what we do.
19085 - If the cursor is on a statistics cookie, update it.
19087 - If the cursor is in a headline, prompt for tags and insert them
19088 into the current line, aligned to `org-tags-column'. When called
19089 with prefix arg, realign all tags in the current buffer.
19091 - If the cursor is in one of the special #+KEYWORD lines, this
19092 triggers scanning the buffer for these lines and updating the
19093 information.
19095 - If the cursor is inside a table, realign the table. This command
19096 works even if the automatic table editor has been turned off.
19098 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19099 the entire table.
19101 - If the cursor is at a footnote reference or definition, jump to
19102 the corresponding definition or references, respectively.
19104 - If the cursor is a the beginning of a dynamic block, update it.
19106 - If the current buffer is a capture buffer, close note and file it.
19108 - If the cursor is on a <<<target>>>, update radio targets and
19109 corresponding links in this buffer.
19111 - If the cursor is on a numbered item in a plain list, renumber the
19112 ordered list.
19114 - If the cursor is on a checkbox, toggle it.
19116 - If the cursor is on a code block, evaluate it. The variable
19117 `org-confirm-babel-evaluate' can be used to control prompting
19118 before code block evaluation, by default every code block
19119 evaluation requires confirmation. Code block evaluation can be
19120 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19121 (interactive "P")
19122 (let ((org-enable-table-editor t))
19123 (cond
19124 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19125 org-occur-highlights
19126 org-latex-fragment-image-overlays)
19127 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19128 (org-remove-occur-highlights)
19129 (org-remove-latex-fragment-image-overlays)
19130 (message "Temporary highlights/overlays removed from current buffer"))
19131 ((and (local-variable-p 'org-finish-function (current-buffer))
19132 (fboundp org-finish-function))
19133 (funcall org-finish-function))
19134 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19135 ((org-in-regexp org-ts-regexp-both)
19136 (org-timestamp-change 0 'day))
19137 ((or (looking-at org-property-start-re)
19138 (org-at-property-p))
19139 (call-interactively 'org-property-action))
19140 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19141 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19142 (or (org-at-heading-p) (org-at-item-p)))
19143 (call-interactively 'org-update-statistics-cookies))
19144 ((org-at-heading-p) (call-interactively 'org-set-tags))
19145 ((org-at-table.el-p)
19146 (message "Use C-c ' to edit table.el tables"))
19147 ((org-at-table-p)
19148 (org-table-maybe-eval-formula)
19149 (if arg
19150 (call-interactively 'org-table-recalculate)
19151 (org-table-maybe-recalculate-line))
19152 (call-interactively 'org-table-align)
19153 (orgtbl-send-table 'maybe))
19154 ((or (org-footnote-at-reference-p)
19155 (org-footnote-at-definition-p))
19156 (call-interactively 'org-footnote-action))
19157 ((org-at-item-checkbox-p)
19158 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19159 ;; list only if at top item.
19160 (let* ((cbox (match-string 1))
19161 (struct (org-list-struct))
19162 (old-struct (copy-tree struct))
19163 (parents (org-list-parents-alist struct))
19164 (orderedp (org-entry-get nil "ORDERED"))
19165 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19166 block-item)
19167 ;; Use a light version of `org-toggle-checkbox' to avoid
19168 ;; computing list structure twice.
19169 (let ((new-box (cond
19170 ((equal arg '(16)) "[-]")
19171 ((equal arg '(4)) nil)
19172 ((equal "[X]" cbox) "[ ]")
19173 (t "[X]"))))
19174 (if (and firstp arg)
19175 ;; If at first item of sub-list, remove check-box from
19176 ;; every item at the same level.
19177 (mapc
19178 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19179 (org-list-get-all-items
19180 (point-at-bol) struct (org-list-prevs-alist struct)))
19181 (org-list-set-checkbox (point-at-bol) struct new-box)))
19182 ;; Replicate `org-list-write-struct', while grabbing a return
19183 ;; value from `org-list-struct-fix-box'.
19184 (org-list-struct-fix-ind struct parents 2)
19185 (org-list-struct-fix-item-end struct)
19186 (let ((prevs (org-list-prevs-alist struct)))
19187 (org-list-struct-fix-bul struct prevs)
19188 (org-list-struct-fix-ind struct parents)
19189 (setq block-item
19190 (org-list-struct-fix-box struct parents prevs orderedp)))
19191 (if (equal struct old-struct)
19192 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19193 (org-list-struct-apply-struct struct old-struct)
19194 (org-update-checkbox-count-maybe))
19195 (when block-item
19196 (message
19197 "Checkboxes were removed due to unchecked box at line %d"
19198 (org-current-line block-item)))
19199 (when firstp (org-list-send-list 'maybe))))
19200 ((org-at-item-p)
19201 ;; Cursor at an item: repair list. Do checkbox related actions
19202 ;; only if function was called with an argument. Send list only
19203 ;; if at top item.
19204 (let* ((struct (org-list-struct))
19205 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19206 old-struct)
19207 (when arg
19208 (setq old-struct (copy-tree struct))
19209 (if firstp
19210 ;; If at first item of sub-list, add check-box to every
19211 ;; item at the same level.
19212 (mapc
19213 (lambda (pos)
19214 (unless (org-list-get-checkbox pos struct)
19215 (org-list-set-checkbox pos struct "[ ]")))
19216 (org-list-get-all-items
19217 (point-at-bol) struct (org-list-prevs-alist struct)))
19218 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19219 (org-list-write-struct
19220 struct (org-list-parents-alist struct) old-struct)
19221 (when arg (org-update-checkbox-count-maybe))
19222 (when firstp (org-list-send-list 'maybe))))
19223 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19224 ;; Dynamic block
19225 (beginning-of-line 1)
19226 (save-excursion (org-update-dblock)))
19227 ((save-excursion
19228 (let ((case-fold-search t))
19229 (beginning-of-line 1)
19230 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19231 (cond
19232 ((or (equal (match-string 1) "TBLFM")
19233 (equal (match-string 1) "tblfm"))
19234 ;; Recalculate the table before this line
19235 (save-excursion
19236 (beginning-of-line 1)
19237 (skip-chars-backward " \r\n\t")
19238 (if (org-at-table-p)
19239 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19241 (let ((org-inhibit-startup-visibility-stuff t)
19242 (org-startup-align-all-tables nil))
19243 (when (boundp 'org-table-coordinate-overlays)
19244 (mapc 'delete-overlay org-table-coordinate-overlays)
19245 (setq org-table-coordinate-overlays nil))
19246 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19247 (message "Local setup has been refreshed"))))
19248 ((org-clock-update-time-maybe))
19250 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19251 (error "C-c C-c can do nothing useful at this location"))))))
19253 (defun org-mode-restart ()
19254 "Restart Org-mode, to scan again for special lines.
19255 Also updates the keyword regular expressions."
19256 (interactive)
19257 (org-mode)
19258 (message "Org-mode restarted"))
19260 (defun org-kill-note-or-show-branches ()
19261 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19262 (interactive)
19263 (if (not org-finish-function)
19264 (progn
19265 (hide-subtree)
19266 (call-interactively 'show-branches))
19267 (let ((org-note-abort t))
19268 (funcall org-finish-function))))
19270 (defun org-return (&optional indent)
19271 "Goto next table row or insert a newline.
19272 Calls `org-table-next-row' or `newline', depending on context.
19273 See the individual commands for more information."
19274 (interactive)
19275 (let (org-ts-what)
19276 (cond
19277 ((or (bobp) (org-in-src-block-p))
19278 (if indent (newline-and-indent) (newline)))
19279 ((org-at-table-p)
19280 (org-table-justify-field-maybe)
19281 (call-interactively 'org-table-next-row))
19282 ;; when `newline-and-indent' is called within a list, make sure
19283 ;; text moved stays inside the item.
19284 ((and (org-in-item-p) indent)
19285 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19286 (progn
19287 (save-match-data (newline))
19288 (org-indent-line-to (length (match-string 0))))
19289 (let ((ind (org-get-indentation)))
19290 (newline)
19291 (if (org-looking-back org-list-end-re)
19292 (org-indent-line)
19293 (org-indent-line-to ind)))))
19294 ((and org-return-follows-link
19295 (org-at-timestamp-p t)
19296 (not (eq org-ts-what 'after)))
19297 (org-follow-timestamp-link))
19298 ((and org-return-follows-link
19299 (let ((tprop (get-text-property (point) 'face)))
19300 (or (eq tprop 'org-link)
19301 (and (listp tprop) (memq 'org-link tprop)))))
19302 (call-interactively 'org-open-at-point))
19303 ((and (org-at-heading-p)
19304 (looking-at
19305 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19306 (org-show-entry)
19307 (end-of-line 1)
19308 (newline))
19309 (t (if indent (newline-and-indent) (newline))))))
19311 (defun org-return-indent ()
19312 "Goto next table row or insert a newline and indent.
19313 Calls `org-table-next-row' or `newline-and-indent', depending on
19314 context. See the individual commands for more information."
19315 (interactive)
19316 (org-return t))
19318 (defun org-ctrl-c-star ()
19319 "Compute table, or change heading status of lines.
19320 Calls `org-table-recalculate' or `org-toggle-heading',
19321 depending on context."
19322 (interactive)
19323 (cond
19324 ((org-at-table-p)
19325 (call-interactively 'org-table-recalculate))
19327 ;; Convert all lines in region to list items
19328 (call-interactively 'org-toggle-heading))))
19330 (defun org-ctrl-c-minus ()
19331 "Insert separator line in table or modify bullet status of line.
19332 Also turns a plain line or a region of lines into list items.
19333 Calls `org-table-insert-hline', `org-toggle-item', or
19334 `org-cycle-list-bullet', depending on context."
19335 (interactive)
19336 (cond
19337 ((org-at-table-p)
19338 (call-interactively 'org-table-insert-hline))
19339 ((org-region-active-p)
19340 (call-interactively 'org-toggle-item))
19341 ((org-in-item-p)
19342 (call-interactively 'org-cycle-list-bullet))
19344 (call-interactively 'org-toggle-item))))
19346 (defun org-toggle-item (arg)
19347 "Convert headings or normal lines to items, items to normal lines.
19348 If there is no active region, only the current line is considered.
19350 If the first non blank line in the region is an headline, convert
19351 all headlines to items, shifting text accordingly.
19353 If it is an item, convert all items to normal lines.
19355 If it is normal text, change region into an item. With a prefix
19356 argument ARG, change each line in region into an item."
19357 (interactive "P")
19358 (let ((shift-text
19359 (function
19360 ;; Shift text in current section to IND, from point to END.
19361 ;; The function leaves point to END line.
19362 (lambda (ind end)
19363 (let ((min-i 1000) (end (copy-marker end)))
19364 ;; First determine the minimum indentation (MIN-I) of
19365 ;; the text.
19366 (save-excursion
19367 (catch 'exit
19368 (while (< (point) end)
19369 (let ((i (org-get-indentation)))
19370 (cond
19371 ;; Skip blank lines and inline tasks.
19372 ((looking-at "^[ \t]*$"))
19373 ((looking-at org-outline-regexp-bol))
19374 ;; We can't find less than 0 indentation.
19375 ((zerop i) (throw 'exit (setq min-i 0)))
19376 ((< i min-i) (setq min-i i))))
19377 (forward-line))))
19378 ;; Then indent each line so that a line indented to
19379 ;; MIN-I becomes indented to IND. Ignore blank lines
19380 ;; and inline tasks in the process.
19381 (let ((delta (- ind min-i)))
19382 (while (< (point) end)
19383 (unless (or (looking-at "^[ \t]*$")
19384 (looking-at org-outline-regexp-bol))
19385 (org-indent-line-to (+ (org-get-indentation) delta)))
19386 (forward-line)))))))
19387 (skip-blanks
19388 (function
19389 ;; Return beginning of first non-blank line, starting from
19390 ;; line at POS.
19391 (lambda (pos)
19392 (save-excursion
19393 (goto-char pos)
19394 (skip-chars-forward " \r\t\n")
19395 (point-at-bol)))))
19396 beg end)
19397 ;; Determine boundaries of changes.
19398 (if (org-region-active-p)
19399 (setq beg (funcall skip-blanks (region-beginning))
19400 end (copy-marker (region-end)))
19401 (setq beg (funcall skip-blanks (point-at-bol))
19402 end (copy-marker (point-at-eol))))
19403 ;; Depending on the starting line, choose an action on the text
19404 ;; between BEG and END.
19405 (org-with-limited-levels
19406 (save-excursion
19407 (goto-char beg)
19408 (cond
19409 ;; Case 1. Start at an item: de-itemize. Note that it only
19410 ;; happens when a region is active: `org-ctrl-c-minus'
19411 ;; would call `org-cycle-list-bullet' otherwise.
19412 ((org-at-item-p)
19413 (while (< (point) end)
19414 (when (org-at-item-p)
19415 (skip-chars-forward " \t")
19416 (delete-region (point) (match-end 0)))
19417 (forward-line)))
19418 ;; Case 2. Start at an heading: convert to items.
19419 ((org-at-heading-p)
19420 (let* ((bul (org-list-bullet-string "-"))
19421 (bul-len (length bul))
19422 ;; Indentation of the first heading. It should be
19423 ;; relative to the indentation of its parent, if any.
19424 (start-ind (save-excursion
19425 (cond
19426 ((not org-adapt-indentation) 0)
19427 ((not (outline-previous-heading)) 0)
19428 (t (length (match-string 0))))))
19429 ;; Level of first heading. Further headings will be
19430 ;; compared to it to determine hierarchy in the list.
19431 (ref-level (org-reduced-level (org-outline-level))))
19432 (while (< (point) end)
19433 (let* ((level (org-reduced-level (org-outline-level)))
19434 (delta (max 0 (- level ref-level))))
19435 ;; If current headline is less indented than the first
19436 ;; one, set it as reference, in order to preserve
19437 ;; subtrees.
19438 (when (< level ref-level) (setq ref-level level))
19439 (replace-match bul t t)
19440 (org-indent-line-to (+ start-ind (* delta bul-len)))
19441 ;; Ensure all text down to END (or SECTION-END) belongs
19442 ;; to the newly created item.
19443 (let ((section-end (save-excursion
19444 (or (outline-next-heading) (point)))))
19445 (forward-line)
19446 (funcall shift-text
19447 (+ start-ind (* (1+ delta) bul-len))
19448 (min end section-end)))))))
19449 ;; Case 3. Normal line with ARG: turn each non-item line into
19450 ;; an item.
19451 (arg
19452 (while (< (point) end)
19453 (unless (or (org-at-heading-p) (org-at-item-p))
19454 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19455 (replace-match
19456 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19457 (forward-line)))
19458 ;; Case 4. Normal line without ARG: make the first line of
19459 ;; region an item, and shift indentation of others
19460 ;; lines to set them as item's body.
19461 (t (let* ((bul (org-list-bullet-string "-"))
19462 (bul-len (length bul))
19463 (ref-ind (org-get-indentation)))
19464 (skip-chars-forward " \t")
19465 (insert bul)
19466 (forward-line)
19467 (while (< (point) end)
19468 ;; Ensure that lines less indented than first one
19469 ;; still get included in item body.
19470 (funcall shift-text
19471 (+ ref-ind bul-len)
19472 (min end (save-excursion (or (outline-next-heading)
19473 (point)))))
19474 (forward-line)))))))))
19476 (defun org-toggle-heading (&optional nstars)
19477 "Convert headings to normal text, or items or text to headings.
19478 If there is no active region, only the current line is considered.
19480 With a \\[universal-argument] prefix, convert the whole list at
19481 point into heading.
19483 In a region:
19485 - If the first non blank line is an headline, remove the stars
19486 from all headlines in the region.
19488 - If it is a normal line turn each and every normal line (i.e. not an
19489 heading or an item) in the region into a heading.
19491 - If it is a plain list item, turn all plain list items into headings.
19493 When converting a line into a heading, the number of stars is chosen
19494 such that the lines become children of the current entry. However,
19495 when a prefix argument is given, its value determines the number of
19496 stars to add."
19497 (interactive "P")
19498 (let ((skip-blanks
19499 (function
19500 ;; Return beginning of first non-blank line, starting from
19501 ;; line at POS.
19502 (lambda (pos)
19503 (save-excursion
19504 (goto-char pos)
19505 (while (org-at-comment-p) (forward-line))
19506 (skip-chars-forward " \r\t\n")
19507 (point-at-bol)))))
19508 beg end toggled)
19509 ;; Determine boundaries of changes. If a universal prefix has
19510 ;; been given, put the list in a region. If region ends at a bol,
19511 ;; do not consider the last line to be in the region.
19513 (when (and current-prefix-arg (org-at-item-p))
19514 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19515 (org-mark-element))
19517 (if (org-region-active-p)
19518 (setq beg (funcall skip-blanks (region-beginning))
19519 end (copy-marker (save-excursion
19520 (goto-char (region-end))
19521 (if (bolp) (point) (point-at-eol)))))
19522 (setq beg (funcall skip-blanks (point-at-bol))
19523 end (copy-marker (point-at-eol))))
19524 ;; Ensure inline tasks don't count as headings.
19525 (org-with-limited-levels
19526 (save-excursion
19527 (goto-char beg)
19528 (cond
19529 ;; Case 1. Started at an heading: de-star headings.
19530 ((org-at-heading-p)
19531 (while (< (point) end)
19532 (when (org-at-heading-p t)
19533 (looking-at org-outline-regexp) (replace-match "")
19534 (setq toggled t))
19535 (forward-line)))
19536 ;; Case 2. Started at an item: change items into headlines.
19537 ;; One star will be added by `org-list-to-subtree'.
19538 ((org-at-item-p)
19539 (let* ((stars (make-string
19540 (if nstars
19541 ;; subtract the star that will be added again by
19542 ;; `org-list-to-subtree'
19543 (1- (prefix-numeric-value current-prefix-arg))
19544 (or (org-current-level) 0))
19545 ?*))
19546 (add-stars
19547 (cond (nstars "") ; stars from prefix only
19548 ((equal stars "") "") ; before first heading
19549 (org-odd-levels-only "*") ; inside heading, odd
19550 (t "")))) ; inside heading, oddeven
19551 (while (< (point) end)
19552 (when (org-at-item-p)
19553 ;; Pay attention to cases when region ends before list.
19554 (let* ((struct (org-list-struct))
19555 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19556 (save-restriction
19557 (narrow-to-region (point) list-end)
19558 (insert
19559 (org-list-to-subtree
19560 (org-list-parse-list t)
19561 '(:istart (concat stars add-stars (funcall get-stars depth))
19562 :icount (concat stars add-stars (funcall get-stars depth)))))))
19563 (setq toggled t))
19564 (forward-line))))
19565 ;; Case 3. Started at normal text: make every line an heading,
19566 ;; skipping headlines and items.
19567 (t (let* ((stars (make-string
19568 (if nstars
19569 (prefix-numeric-value current-prefix-arg)
19570 (or (org-current-level) 0))
19571 ?*))
19572 (add-stars
19573 (cond (nstars "") ; stars from prefix only
19574 ((equal stars "") "*") ; before first heading
19575 (org-odd-levels-only "**") ; inside heading, odd
19576 (t "*"))) ; inside heading, oddeven
19577 (rpl (concat stars add-stars " ")))
19578 (while (< (point) end)
19579 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19580 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19581 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19582 (forward-line)))))))
19583 (unless toggled (message "Cannot toggle heading from here"))))
19585 (defun org-meta-return (&optional arg)
19586 "Insert a new heading or wrap a region in a table.
19587 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19588 See the individual commands for more information."
19589 (interactive "P")
19590 (cond
19591 ((run-hook-with-args-until-success 'org-metareturn-hook))
19592 ((or (org-at-drawer-p) (org-at-property-p))
19593 (newline-and-indent))
19594 ((org-at-table-p)
19595 (call-interactively 'org-table-wrap-region))
19596 (t (call-interactively 'org-insert-heading))))
19598 ;;; Menu entries
19600 (defsubst org-in-subtree-not-table-p ()
19601 "Are we in a subtree and not in a table?"
19602 (and (not (org-before-first-heading-p))
19603 (not (org-at-table-p))))
19605 ;; Define the Org-mode menus
19606 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19607 '("Tbl"
19608 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19609 ["Next Field" org-cycle (org-at-table-p)]
19610 ["Previous Field" org-shifttab (org-at-table-p)]
19611 ["Next Row" org-return (org-at-table-p)]
19612 "--"
19613 ["Blank Field" org-table-blank-field (org-at-table-p)]
19614 ["Edit Field" org-table-edit-field (org-at-table-p)]
19615 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19616 "--"
19617 ("Column"
19618 ["Move Column Left" org-metaleft (org-at-table-p)]
19619 ["Move Column Right" org-metaright (org-at-table-p)]
19620 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19621 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19622 ("Row"
19623 ["Move Row Up" org-metaup (org-at-table-p)]
19624 ["Move Row Down" org-metadown (org-at-table-p)]
19625 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19626 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19627 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19628 "--"
19629 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19630 ("Rectangle"
19631 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19632 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19633 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19634 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19635 "--"
19636 ("Calculate"
19637 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19638 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19639 ["Edit Formulas" org-edit-special (org-at-table-p)]
19640 "--"
19641 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19642 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19643 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19644 "--"
19645 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19646 "--"
19647 ["Sum Column/Rectangle" org-table-sum
19648 (or (org-at-table-p) (org-region-active-p))]
19649 ["Which Column?" org-table-current-column (org-at-table-p)])
19650 ["Debug Formulas"
19651 org-table-toggle-formula-debugger
19652 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19653 ["Show Col/Row Numbers"
19654 org-table-toggle-coordinate-overlays
19655 :style toggle
19656 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19657 "--"
19658 ["Create" org-table-create (and (not (org-at-table-p))
19659 org-enable-table-editor)]
19660 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19661 ["Import from File" org-table-import (not (org-at-table-p))]
19662 ["Export to File" org-table-export (org-at-table-p)]
19663 "--"
19664 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19666 (easy-menu-define org-org-menu org-mode-map "Org menu"
19667 '("Org"
19668 ("Show/Hide"
19669 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19670 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19671 ["Sparse Tree..." org-sparse-tree t]
19672 ["Reveal Context" org-reveal t]
19673 ["Show All" show-all t]
19674 "--"
19675 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19676 "--"
19677 ["New Heading" org-insert-heading t]
19678 ("Navigate Headings"
19679 ["Up" outline-up-heading t]
19680 ["Next" outline-next-visible-heading t]
19681 ["Previous" outline-previous-visible-heading t]
19682 ["Next Same Level" outline-forward-same-level t]
19683 ["Previous Same Level" outline-backward-same-level t]
19684 "--"
19685 ["Jump" org-goto t])
19686 ("Edit Structure"
19687 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19688 "--"
19689 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19690 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19691 "--"
19692 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19693 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19694 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19695 "--"
19696 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19697 "--"
19698 ["Copy visible text" org-copy-visible t]
19699 "--"
19700 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19701 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19702 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19703 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19704 "--"
19705 ["Sort Region/Children" org-sort t]
19706 "--"
19707 ["Convert to odd levels" org-convert-to-odd-levels t]
19708 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19709 ("Editing"
19710 ["Emphasis..." org-emphasize t]
19711 ["Edit Source Example" org-edit-special t]
19712 "--"
19713 ["Footnote new/jump" org-footnote-action t]
19714 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19715 ("Archive"
19716 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19717 "--"
19718 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19719 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19720 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19722 "--"
19723 ("Hyperlinks"
19724 ["Store Link (Global)" org-store-link t]
19725 ["Find existing link to here" org-occur-link-in-agenda-files t]
19726 ["Insert Link" org-insert-link t]
19727 ["Follow Link" org-open-at-point t]
19728 "--"
19729 ["Next link" org-next-link t]
19730 ["Previous link" org-previous-link t]
19731 "--"
19732 ["Descriptive Links"
19733 org-toggle-link-display
19734 :style radio
19735 :selected org-descriptive-links
19737 ["Literal Links"
19738 org-toggle-link-display
19739 :style radio
19740 :selected (not org-descriptive-links)])
19741 "--"
19742 ("TODO Lists"
19743 ["TODO/DONE/-" org-todo t]
19744 ("Select keyword"
19745 ["Next keyword" org-shiftright (org-at-heading-p)]
19746 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19747 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19748 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19749 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19750 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19751 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19752 "--"
19753 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19754 :selected org-enforce-todo-dependencies :style toggle :active t]
19755 "Settings for tree at point"
19756 ["Do Children sequentially" org-toggle-ordered-property :style radio
19757 :selected (org-entry-get nil "ORDERED")
19758 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19759 ["Do Children parallel" org-toggle-ordered-property :style radio
19760 :selected (not (org-entry-get nil "ORDERED"))
19761 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19762 "--"
19763 ["Set Priority" org-priority t]
19764 ["Priority Up" org-shiftup t]
19765 ["Priority Down" org-shiftdown t]
19766 "--"
19767 ["Get news from all feeds" org-feed-update-all t]
19768 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19769 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19770 ("TAGS and Properties"
19771 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19772 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19773 "--"
19774 ["Set property" org-set-property (not (org-before-first-heading-p))]
19775 ["Column view of properties" org-columns t]
19776 ["Insert Column View DBlock" org-insert-columns-dblock t])
19777 ("Dates and Scheduling"
19778 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19779 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19780 ("Change Date"
19781 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19782 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19783 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19784 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19785 ["Compute Time Range" org-evaluate-time-range t]
19786 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19787 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19788 "--"
19789 ["Custom time format" org-toggle-time-stamp-overlays
19790 :style radio :selected org-display-custom-times]
19791 "--"
19792 ["Goto Calendar" org-goto-calendar t]
19793 ["Date from Calendar" org-date-from-calendar t]
19794 "--"
19795 ["Start/Restart Timer" org-timer-start t]
19796 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19797 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19798 ["Insert Timer String" org-timer t]
19799 ["Insert Timer Item" org-timer-item t])
19800 ("Logging work"
19801 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19802 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19803 ["Clock out" org-clock-out t]
19804 ["Clock cancel" org-clock-cancel t]
19805 "--"
19806 ["Mark as default task" org-clock-mark-default-task t]
19807 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19808 ["Goto running clock" org-clock-goto t]
19809 "--"
19810 ["Display times" org-clock-display t]
19811 ["Create clock table" org-clock-report t]
19812 "--"
19813 ["Record DONE time"
19814 (progn (setq org-log-done (not org-log-done))
19815 (message "Switching to %s will %s record a timestamp"
19816 (car org-done-keywords)
19817 (if org-log-done "automatically" "not")))
19818 :style toggle :selected org-log-done])
19819 "--"
19820 ["Agenda Command..." org-agenda t]
19821 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19822 ("File List for Agenda")
19823 ("Special views current file"
19824 ["TODO Tree" org-show-todo-tree t]
19825 ["Check Deadlines" org-check-deadlines t]
19826 ["Timeline" org-timeline t]
19827 ["Tags/Property tree" org-match-sparse-tree t])
19828 "--"
19829 ["Export/Publish..." org-export t]
19830 ("LaTeX"
19831 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19832 :selected org-cdlatex-mode]
19833 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19834 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19835 ["Modify math symbol" org-cdlatex-math-modify
19836 (org-inside-LaTeX-fragment-p)]
19837 ["Insert citation" org-reftex-citation t]
19838 "--"
19839 ["Template for BEAMER" (progn (require 'org-beamer)
19840 (org-insert-beamer-options-template)) t])
19841 "--"
19842 ("MobileOrg"
19843 ["Push Files and Views" org-mobile-push t]
19844 ["Get Captured and Flagged" org-mobile-pull t]
19845 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19846 "--"
19847 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19848 "--"
19849 ("Documentation"
19850 ["Show Version" org-version t]
19851 ["Info Documentation" org-info t])
19852 ("Customize"
19853 ["Browse Org Group" org-customize t]
19854 "--"
19855 ["Expand This Menu" org-create-customize-menu
19856 (fboundp 'customize-menu-create)])
19857 ["Send bug report" org-submit-bug-report t]
19858 "--"
19859 ("Refresh/Reload"
19860 ["Refresh setup current buffer" org-mode-restart t]
19861 ["Reload Org (after update)" org-reload t]
19862 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
19865 (defun org-info (&optional node)
19866 "Read documentation for Org-mode in the info system.
19867 With optional NODE, go directly to that node."
19868 (interactive)
19869 (info (format "(org)%s" (or node ""))))
19871 ;;;###autoload
19872 (defun org-submit-bug-report ()
19873 "Submit a bug report on Org-mode via mail.
19875 Don't hesitate to report any problems or inaccurate documentation.
19877 If you don't have setup sending mail from (X)Emacs, please copy the
19878 output buffer into your mail program, as it gives us important
19879 information about your Org-mode version and configuration."
19880 (interactive)
19881 (require 'reporter)
19882 (org-load-modules-maybe)
19883 (org-require-autoloaded-modules)
19884 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19885 (reporter-submit-bug-report
19886 "emacs-orgmode@gnu.org"
19887 (org-version nil 'full)
19888 (let (list)
19889 (save-window-excursion
19890 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19891 (delete-other-windows)
19892 (erase-buffer)
19893 (insert "You are about to submit a bug report to the Org-mode mailing list.
19895 We would like to add your full Org-mode and Outline configuration to the
19896 bug report. This greatly simplifies the work of the maintainer and
19897 other experts on the mailing list.
19899 HOWEVER, some variables you have customized may contain private
19900 information. The names of customers, colleagues, or friends, might
19901 appear in the form of file names, tags, todo states, or search strings.
19902 If you answer yes to the prompt, you might want to check and remove
19903 such private information before sending the email.")
19904 (add-text-properties (point-min) (point-max) '(face org-warning))
19905 (when (yes-or-no-p "Include your Org-mode configuration ")
19906 (mapatoms
19907 (lambda (v)
19908 (and (boundp v)
19909 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19910 (or (and (symbol-value v)
19911 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19912 (and
19913 (get v 'custom-type) (get v 'standard-value)
19914 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19915 (push v list)))))
19916 (kill-buffer (get-buffer "*Warn about privacy*"))
19917 list))
19918 nil nil
19919 "Remember to cover the basics, that is, what you expected to happen and
19920 what in fact did happen. You don't know how to make a good report? See
19922 http://orgmode.org/manual/Feedback.html#Feedback
19924 Your bug report will be posted to the Org-mode mailing list.
19925 ------------------------------------------------------------------------")
19926 (save-excursion
19927 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19928 (replace-match "\\1Bug: \\3 [\\2]")))))
19931 (defun org-install-agenda-files-menu ()
19932 (let ((bl (buffer-list)))
19933 (save-excursion
19934 (while bl
19935 (set-buffer (pop bl))
19936 (if (derived-mode-p 'org-mode) (setq bl nil)))
19937 (when (derived-mode-p 'org-mode)
19938 (easy-menu-change
19939 '("Org") "File List for Agenda"
19940 (append
19941 (list
19942 ["Edit File List" (org-edit-agenda-file-list) t]
19943 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19944 ["Remove Current File from List" org-remove-file t]
19945 ["Cycle through agenda files" org-cycle-agenda-files t]
19946 ["Occur in all agenda files" org-occur-in-agenda-files t]
19947 "--")
19948 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19950 ;;;; Documentation
19952 (defun org-require-autoloaded-modules ()
19953 (interactive)
19954 (mapc 'require
19955 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19956 org-docbook org-exp org-html org-icalendar
19957 org-id org-latex
19958 org-publish org-remember org-table
19959 org-timer org-xoxo)))
19961 ;;;###autoload
19962 (defun org-reload (&optional uncompiled)
19963 "Reload all org lisp files.
19964 With prefix arg UNCOMPILED, load the uncompiled versions."
19965 (interactive "P")
19966 (require 'find-func)
19967 (let* ((file-re "^org\\(-.*\\)?\\.el")
19968 (dir-org (file-name-directory (org-find-library-dir "org")))
19969 (dir-org-contrib (ignore-errors
19970 (file-name-directory
19971 (org-find-library-dir "org-contribdir"))))
19972 (babel-files
19973 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19974 (append (list nil "comint" "eval" "exp" "keys"
19975 "lob" "ref" "table" "tangle")
19976 (delq nil
19977 (mapcar
19978 (lambda (lang)
19979 (when (cdr lang) (symbol-name (car lang))))
19980 org-babel-load-languages)))))
19981 (files
19982 (append babel-files
19983 (and dir-org-contrib
19984 (directory-files dir-org-contrib t file-re))
19985 (directory-files dir-org t file-re)))
19986 (remove-re (concat (if (featurep 'xemacs)
19987 "org-colview" "org-colview-xemacs")
19988 "\\'")))
19989 (setq files (mapcar 'file-name-sans-extension files))
19990 (setq files (mapcar
19991 (lambda (x) (if (string-match remove-re x) nil x))
19992 files))
19993 (setq files (delq nil files))
19994 (mapc
19995 (lambda (f)
19996 (when (featurep (intern (file-name-nondirectory f)))
19997 (if (and (not uncompiled)
19998 (file-exists-p (concat f ".elc")))
19999 (load (concat f ".elc") nil nil 'nosuffix)
20000 (load (concat f ".el") nil nil 'nosuffix))))
20001 files)
20002 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20003 (org-version nil 'full 'message))
20005 ;;;###autoload
20006 (defun org-customize ()
20007 "Call the customize function with org as argument."
20008 (interactive)
20009 (org-load-modules-maybe)
20010 (org-require-autoloaded-modules)
20011 (customize-browse 'org))
20013 (defun org-create-customize-menu ()
20014 "Create a full customization menu for Org-mode, insert it into the menu."
20015 (interactive)
20016 (org-load-modules-maybe)
20017 (org-require-autoloaded-modules)
20018 (if (fboundp 'customize-menu-create)
20019 (progn
20020 (easy-menu-change
20021 '("Org") "Customize"
20022 `(["Browse Org group" org-customize t]
20023 "--"
20024 ,(customize-menu-create 'org)
20025 ["Set" Custom-set t]
20026 ["Save" Custom-save t]
20027 ["Reset to Current" Custom-reset-current t]
20028 ["Reset to Saved" Custom-reset-saved t]
20029 ["Reset to Standard Settings" Custom-reset-standard t]))
20030 (message "\"Org\"-menu now contains full customization menu"))
20031 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20033 ;;;; Miscellaneous stuff
20035 ;;; Generally useful functions
20037 (defun org-get-at-bol (property)
20038 "Get text property PROPERTY at beginning of line."
20039 (get-text-property (point-at-bol) property))
20041 (defun org-find-text-property-in-string (prop s)
20042 "Return the first non-nil value of property PROP in string S."
20043 (or (get-text-property 0 prop s)
20044 (get-text-property (or (next-single-property-change 0 prop s) 0)
20045 prop s)))
20047 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20048 "Display the given MESSAGE as a warning."
20049 (if (fboundp 'display-warning)
20050 (display-warning 'org message
20051 (if (featurep 'xemacs) 'warning :warning))
20052 (let ((buf (get-buffer-create "*Org warnings*")))
20053 (with-current-buffer buf
20054 (goto-char (point-max))
20055 (insert "Warning (Org): " message)
20056 (unless (bolp)
20057 (newline)))
20058 (display-buffer buf)
20059 (sit-for 0))))
20061 (defun org-eval (form)
20062 "Eval FORM and return result."
20063 (condition-case error
20064 (eval form)
20065 (error (format "%%![Error: %s]" error))))
20067 (defun org-in-clocktable-p ()
20068 "Check if the cursor is in a clocktable."
20069 (let ((pos (point)) start)
20070 (save-excursion
20071 (end-of-line 1)
20072 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20073 (setq start (match-beginning 0))
20074 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20075 (>= (match-end 0) pos)
20076 start))))
20078 (defun org-in-commented-line ()
20079 "Is point in a line starting with `#'?"
20080 (equal (char-after (point-at-bol)) ?#))
20082 (defun org-in-indented-comment-line ()
20083 "Is point in a line starting with `#' after some white space?"
20084 (save-excursion
20085 (save-match-data
20086 (goto-char (point-at-bol))
20087 (looking-at "[ \t]*#"))))
20089 (defun org-in-verbatim-emphasis ()
20090 (save-match-data
20091 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20093 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20094 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20095 (if (and marker (marker-buffer marker)
20096 (buffer-live-p (marker-buffer marker)))
20097 (progn
20098 (org-pop-to-buffer-same-window (marker-buffer marker))
20099 (if (or (> marker (point-max)) (< marker (point-min)))
20100 (widen))
20101 (goto-char marker)
20102 (org-show-context 'org-goto))
20103 (if bookmark
20104 (bookmark-jump bookmark)
20105 (error "Cannot find location"))))
20107 (defun org-quote-csv-field (s)
20108 "Quote field for inclusion in CSV material."
20109 (if (string-match "[\",]" s)
20110 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20113 (defun org-force-self-insert (N)
20114 "Needed to enforce self-insert under remapping."
20115 (interactive "p")
20116 (self-insert-command N))
20118 (defun org-string-width (s)
20119 "Compute width of string, ignoring invisible characters.
20120 This ignores character with invisibility property `org-link', and also
20121 characters with property `org-cwidth', because these will become invisible
20122 upon the next fontification round."
20123 (let (b l)
20124 (when (or (eq t buffer-invisibility-spec)
20125 (assq 'org-link buffer-invisibility-spec))
20126 (while (setq b (text-property-any 0 (length s)
20127 'invisible 'org-link s))
20128 (setq s (concat (substring s 0 b)
20129 (substring s (or (next-single-property-change
20130 b 'invisible s) (length s)))))))
20131 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20132 (setq s (concat (substring s 0 b)
20133 (substring s (or (next-single-property-change
20134 b 'org-cwidth s) (length s))))))
20135 (setq l (string-width s) b -1)
20136 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20137 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20140 (defun org-shorten-string (s maxlength)
20141 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20142 If the string is shorter or has length MAXLENGTH, just return the
20143 original string. If it is longer, the functions finds a space in the
20144 string, breaks this string off at that locations and adds three dots
20145 as ellipsis. Including the ellipsis, the string will not be longer
20146 than MAXLENGTH. If finding a good breaking point in the string does
20147 not work, the string is just chopped off in the middle of a word
20148 if necessary."
20149 (if (<= (length s) maxlength)
20151 (let* ((n (max (- maxlength 4) 1))
20152 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20153 (if (string-match re s)
20154 (concat (match-string 1 s) "...")
20155 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20157 (defun org-get-indentation (&optional line)
20158 "Get the indentation of the current line, interpreting tabs.
20159 When LINE is given, assume it represents a line and compute its indentation."
20160 (if line
20161 (if (string-match "^ *" (org-remove-tabs line))
20162 (match-end 0))
20163 (save-excursion
20164 (beginning-of-line 1)
20165 (skip-chars-forward " \t")
20166 (current-column))))
20168 (defun org-get-string-indentation (s)
20169 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20170 (let ((n -1) (i 0) (w tab-width) c)
20171 (catch 'exit
20172 (while (< (setq n (1+ n)) (length s))
20173 (setq c (aref s n))
20174 (cond ((= c ?\ ) (setq i (1+ i)))
20175 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20176 (t (throw 'exit t)))))
20179 (defun org-remove-tabs (s &optional width)
20180 "Replace tabulators in S with spaces.
20181 Assumes that s is a single line, starting in column 0."
20182 (setq width (or width tab-width))
20183 (while (string-match "\t" s)
20184 (setq s (replace-match
20185 (make-string
20186 (- (* width (/ (+ (match-beginning 0) width) width))
20187 (match-beginning 0)) ?\ )
20188 t t s)))
20191 (defun org-fix-indentation (line ind)
20192 "Fix indentation in LINE.
20193 IND is a cons cell with target and minimum indentation.
20194 If the current indentation in LINE is smaller than the minimum,
20195 leave it alone. If it is larger than ind, set it to the target."
20196 (let* ((l (org-remove-tabs line))
20197 (i (org-get-indentation l))
20198 (i1 (car ind)) (i2 (cdr ind)))
20199 (if (>= i i2) (setq l (substring line i2)))
20200 (if (> i1 0)
20201 (concat (make-string i1 ?\ ) l)
20202 l)))
20204 (defun org-remove-indentation (code &optional n)
20205 "Remove the maximum common indentation from the lines in CODE.
20206 N may optionally be the number of spaces to remove."
20207 (with-temp-buffer
20208 (insert code)
20209 (org-do-remove-indentation n)
20210 (buffer-string)))
20212 (defun org-do-remove-indentation (&optional n)
20213 "Remove the maximum common indentation from the buffer."
20214 (untabify (point-min) (point-max))
20215 (let ((min 10000) re)
20216 (if n
20217 (setq min n)
20218 (goto-char (point-min))
20219 (while (re-search-forward "^ *[^ \n]" nil t)
20220 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20221 (unless (or (= min 0) (= min 10000))
20222 (setq re (format "^ \\{%d\\}" min))
20223 (goto-char (point-min))
20224 (while (re-search-forward re nil t)
20225 (replace-match "")
20226 (end-of-line 1))
20227 min)))
20229 (defun org-fill-template (template alist)
20230 "Find each %key of ALIST in TEMPLATE and replace it."
20231 (let ((case-fold-search nil)
20232 entry key value)
20233 (setq alist (sort (copy-sequence alist)
20234 (lambda (a b) (< (length (car a)) (length (car b))))))
20235 (while (setq entry (pop alist))
20236 (setq template
20237 (replace-regexp-in-string
20238 (concat "%" (regexp-quote (car entry)))
20239 (or (cdr entry) "") template t t)))
20240 template))
20242 (defun org-base-buffer (buffer)
20243 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20244 (if (not buffer)
20245 buffer
20246 (or (buffer-base-buffer buffer)
20247 buffer)))
20249 (defun org-trim (s)
20250 "Remove whitespace at beginning and end of string."
20251 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20252 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20255 (defun org-wrap (string &optional width lines)
20256 "Wrap string to either a number of lines, or a width in characters.
20257 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20258 that costs. If there is a word longer than WIDTH, the text is actually
20259 wrapped to the length of that word.
20260 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20261 many lines, whatever width that takes.
20262 The return value is a list of lines, without newlines at the end."
20263 (let* ((words (org-split-string string "[ \t\n]+"))
20264 (maxword (apply 'max (mapcar 'org-string-width words)))
20265 w ll)
20266 (cond (width
20267 (org-do-wrap words (max maxword width)))
20268 (lines
20269 (setq w maxword)
20270 (setq ll (org-do-wrap words maxword))
20271 (if (<= (length ll) lines)
20273 (setq ll words)
20274 (while (> (length ll) lines)
20275 (setq w (1+ w))
20276 (setq ll (org-do-wrap words w)))
20277 ll))
20278 (t (error "Cannot wrap this")))))
20280 (defun org-do-wrap (words width)
20281 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20282 (let (lines line)
20283 (while words
20284 (setq line (pop words))
20285 (while (and words (< (+ (length line) (length (car words))) width))
20286 (setq line (concat line " " (pop words))))
20287 (setq lines (push line lines)))
20288 (nreverse lines)))
20290 (defun org-split-string (string &optional separators)
20291 "Splits STRING into substrings at SEPARATORS.
20292 No empty strings are returned if there are matches at the beginning
20293 and end of string."
20294 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20295 (start 0)
20296 notfirst
20297 (list nil))
20298 (while (and (string-match rexp string
20299 (if (and notfirst
20300 (= start (match-beginning 0))
20301 (< start (length string)))
20302 (1+ start) start))
20303 (< (match-beginning 0) (length string)))
20304 (setq notfirst t)
20305 (or (eq (match-beginning 0) 0)
20306 (and (eq (match-beginning 0) (match-end 0))
20307 (eq (match-beginning 0) start))
20308 (setq list
20309 (cons (substring string start (match-beginning 0))
20310 list)))
20311 (setq start (match-end 0)))
20312 (or (eq start (length string))
20313 (setq list
20314 (cons (substring string start)
20315 list)))
20316 (nreverse list)))
20318 (defun org-quote-vert (s)
20319 "Replace \"|\" with \"\\vert\"."
20320 (while (string-match "|" s)
20321 (setq s (replace-match "\\vert" t t s)))
20324 (defun org-uuidgen-p (s)
20325 "Is S an ID created by UUIDGEN?"
20326 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20328 (defun org-in-src-block-p (&optional inside)
20329 "Whether point is in a code source block.
20330 When INSIDE is non-nil, don't consider we are within a src block
20331 when point is at #+BEGIN_SRC or #+END_SRC."
20332 (let ((case-fold-search t) ov)
20333 (or (and (setq ov (overlays-at (point)))
20334 (memq 'org-block-background
20335 (overlay-properties (car ov))))
20336 (and (not inside)
20337 (save-match-data
20338 (save-excursion
20339 (beginning-of-line)
20340 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20342 (defun org-context ()
20343 "Return a list of contexts of the current cursor position.
20344 If several contexts apply, all are returned.
20345 Each context entry is a list with a symbol naming the context, and
20346 two positions indicating start and end of the context. Possible
20347 contexts are:
20349 :headline anywhere in a headline
20350 :headline-stars on the leading stars in a headline
20351 :todo-keyword on a TODO keyword (including DONE) in a headline
20352 :tags on the TAGS in a headline
20353 :priority on the priority cookie in a headline
20354 :item on the first line of a plain list item
20355 :item-bullet on the bullet/number of a plain list item
20356 :checkbox on the checkbox in a plain list item
20357 :table in an org-mode table
20358 :table-special on a special filed in a table
20359 :table-table in a table.el table
20360 :clocktable in a clocktable
20361 :src-block in a source block
20362 :link on a hyperlink
20363 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20364 :target on a <<target>>
20365 :radio-target on a <<<radio-target>>>
20366 :latex-fragment on a LaTeX fragment
20367 :latex-preview on a LaTeX fragment with overlaid preview image
20369 This function expects the position to be visible because it uses font-lock
20370 faces as a help to recognize the following contexts: :table-special, :link,
20371 and :keyword."
20372 (let* ((f (get-text-property (point) 'face))
20373 (faces (if (listp f) f (list f)))
20374 (case-fold-search t)
20375 (p (point)) clist o)
20376 ;; First the large context
20377 (cond
20378 ((org-at-heading-p t)
20379 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20380 (when (progn
20381 (beginning-of-line 1)
20382 (looking-at org-todo-line-tags-regexp))
20383 (push (org-point-in-group p 1 :headline-stars) clist)
20384 (push (org-point-in-group p 2 :todo-keyword) clist)
20385 (push (org-point-in-group p 4 :tags) clist))
20386 (goto-char p)
20387 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20388 (if (looking-at "\\[#[A-Z0-9]\\]")
20389 (push (org-point-in-group p 0 :priority) clist)))
20391 ((org-at-item-p)
20392 (push (org-point-in-group p 2 :item-bullet) clist)
20393 (push (list :item (point-at-bol)
20394 (save-excursion (org-end-of-item) (point)))
20395 clist)
20396 (and (org-at-item-checkbox-p)
20397 (push (org-point-in-group p 0 :checkbox) clist)))
20399 ((org-at-table-p)
20400 (push (list :table (org-table-begin) (org-table-end)) clist)
20401 (if (memq 'org-formula faces)
20402 (push (list :table-special
20403 (previous-single-property-change p 'face)
20404 (next-single-property-change p 'face)) clist)))
20405 ((org-at-table-p 'any)
20406 (push (list :table-table) clist)))
20407 (goto-char p)
20409 (let ((case-fold-search t))
20410 ;; New the "medium" contexts: clocktables, source blocks
20411 (cond ((org-in-clocktable-p)
20412 (push (list :clocktable
20413 (and (or (looking-at "#\\+BEGIN: clocktable")
20414 (search-backward "#+BEGIN: clocktable" nil t))
20415 (match-beginning 0))
20416 (and (re-search-forward "#\\+END:?" nil t)
20417 (match-end 0))) clist))
20418 ((org-in-src-block-p)
20419 (push (list :src-block
20420 (and (or (looking-at "#\\+BEGIN_SRC")
20421 (search-backward "#+BEGIN_SRC" nil t))
20422 (match-beginning 0))
20423 (and (search-forward "#+END_SRC" nil t)
20424 (match-beginning 0))) clist))))
20425 (goto-char p)
20427 ;; Now the small context
20428 (cond
20429 ((org-at-timestamp-p)
20430 (push (org-point-in-group p 0 :timestamp) clist))
20431 ((memq 'org-link faces)
20432 (push (list :link
20433 (previous-single-property-change p 'face)
20434 (next-single-property-change p 'face)) clist))
20435 ((memq 'org-special-keyword faces)
20436 (push (list :keyword
20437 (previous-single-property-change p 'face)
20438 (next-single-property-change p 'face)) clist))
20439 ((org-at-target-p)
20440 (push (org-point-in-group p 0 :target) clist)
20441 (goto-char (1- (match-beginning 0)))
20442 (if (looking-at org-radio-target-regexp)
20443 (push (org-point-in-group p 0 :radio-target) clist))
20444 (goto-char p))
20445 ((setq o (car (delq nil
20446 (mapcar
20447 (lambda (x)
20448 (if (memq x org-latex-fragment-image-overlays) x))
20449 (overlays-at (point))))))
20450 (push (list :latex-fragment
20451 (overlay-start o) (overlay-end o)) clist)
20452 (push (list :latex-preview
20453 (overlay-start o) (overlay-end o)) clist))
20454 ((org-inside-LaTeX-fragment-p)
20455 ;; FIXME: positions wrong.
20456 (push (list :latex-fragment (point) (point)) clist)))
20458 (setq clist (nreverse (delq nil clist)))
20459 clist))
20461 ;; FIXME: Compare with at-regexp-p Do we need both?
20462 (defun org-in-regexp (re &optional nlines visually)
20463 "Check if point is inside a match of regexp.
20464 Normally only the current line is checked, but you can include NLINES extra
20465 lines both before and after point into the search.
20466 If VISUALLY is set, require that the cursor is not after the match but
20467 really on, so that the block visually is on the match."
20468 (catch 'exit
20469 (let ((pos (point))
20470 (eol (point-at-eol (+ 1 (or nlines 0))))
20471 (inc (if visually 1 0)))
20472 (save-excursion
20473 (beginning-of-line (- 1 (or nlines 0)))
20474 (while (re-search-forward re eol t)
20475 (if (and (<= (match-beginning 0) pos)
20476 (>= (+ inc (match-end 0)) pos))
20477 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20479 (defun org-at-regexp-p (regexp)
20480 "Is point inside a match of REGEXP in the current line?"
20481 (catch 'exit
20482 (save-excursion
20483 (let ((pos (point)) (end (point-at-eol)))
20484 (beginning-of-line 1)
20485 (while (re-search-forward regexp end t)
20486 (if (and (<= (match-beginning 0) pos)
20487 (>= (match-end 0) pos))
20488 (throw 'exit t)))
20489 nil))))
20491 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20492 "Non-nil when point is between matches of START-RE and END-RE.
20494 Also return a non-nil value when point is on one of the matches.
20496 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20497 buffer positions. Default values are the positions of headlines
20498 surrounding the point.
20500 The functions returns a cons cell whose car (resp. cdr) is the
20501 position before START-RE (resp. after END-RE)."
20502 (save-match-data
20503 (let ((pos (point))
20504 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20505 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20506 beg end)
20507 (save-excursion
20508 ;; Point is on a block when on START-RE or if START-RE can be
20509 ;; found before it...
20510 (and (or (org-at-regexp-p start-re)
20511 (re-search-backward start-re limit-up t))
20512 (setq beg (match-beginning 0))
20513 ;; ... and END-RE after it...
20514 (goto-char (match-end 0))
20515 (re-search-forward end-re limit-down t)
20516 (> (setq end (match-end 0)) pos)
20517 ;; ... without another START-RE in-between.
20518 (goto-char (match-beginning 0))
20519 (not (re-search-backward start-re (1+ beg) t))
20520 ;; Return value.
20521 (cons beg end))))))
20523 (defun org-in-block-p (names)
20524 "Non-nil when point belongs to a block whose name belongs to NAMES.
20526 NAMES is a list of strings containing names of blocks.
20528 Return first block name matched, or nil. Beware that in case of
20529 nested blocks, the returned name may not belong to the closest
20530 block from point."
20531 (save-match-data
20532 (catch 'exit
20533 (let ((case-fold-search t)
20534 (lim-up (save-excursion (outline-previous-heading)))
20535 (lim-down (save-excursion (outline-next-heading))))
20536 (mapc (lambda (name)
20537 (let ((n (regexp-quote name)))
20538 (when (org-between-regexps-p
20539 (concat "^[ \t]*#\\+begin_" n)
20540 (concat "^[ \t]*#\\+end_" n)
20541 lim-up lim-down)
20542 (throw 'exit n))))
20543 names))
20544 nil)))
20546 (defun org-occur-in-agenda-files (regexp &optional nlines)
20547 "Call `multi-occur' with buffers for all agenda files."
20548 (interactive "sOrg-files matching: \np")
20549 (let* ((files (org-agenda-files))
20550 (tnames (mapcar 'file-truename files))
20551 (extra org-agenda-text-search-extra-files)
20553 (when (eq (car extra) 'agenda-archives)
20554 (setq extra (cdr extra))
20555 (setq files (org-add-archive-files files)))
20556 (while (setq f (pop extra))
20557 (unless (member (file-truename f) tnames)
20558 (add-to-list 'files f 'append)
20559 (add-to-list 'tnames (file-truename f) 'append)))
20560 (multi-occur
20561 (mapcar (lambda (x)
20562 (with-current-buffer
20563 (or (get-file-buffer x) (find-file-noselect x))
20564 (widen)
20565 (current-buffer)))
20566 files)
20567 regexp)))
20569 (if (boundp 'occur-mode-find-occurrence-hook)
20570 ;; Emacs 23
20571 (add-hook 'occur-mode-find-occurrence-hook
20572 (lambda ()
20573 (when (derived-mode-p 'org-mode)
20574 (org-reveal))))
20575 ;; Emacs 22
20576 (defadvice occur-mode-goto-occurrence
20577 (after org-occur-reveal activate)
20578 (and (derived-mode-p 'org-mode) (org-reveal)))
20579 (defadvice occur-mode-goto-occurrence-other-window
20580 (after org-occur-reveal activate)
20581 (and (derived-mode-p 'org-mode) (org-reveal)))
20582 (defadvice occur-mode-display-occurrence
20583 (after org-occur-reveal activate)
20584 (when (derived-mode-p 'org-mode)
20585 (let ((pos (occur-mode-find-occurrence)))
20586 (with-current-buffer (marker-buffer pos)
20587 (save-excursion
20588 (goto-char pos)
20589 (org-reveal)))))))
20591 (defun org-occur-link-in-agenda-files ()
20592 "Create a link and search for it in the agendas.
20593 The link is not stored in `org-stored-links', it is just created
20594 for the search purpose."
20595 (interactive)
20596 (let ((link (condition-case nil
20597 (org-store-link nil)
20598 (error "Unable to create a link to here"))))
20599 (org-occur-in-agenda-files (regexp-quote link))))
20601 (defun org-uniquify (list)
20602 "Remove duplicate elements from LIST."
20603 (let (res)
20604 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20605 res))
20607 (defun org-delete-all (elts list)
20608 "Remove all elements in ELTS from LIST."
20609 (while elts
20610 (setq list (delete (pop elts) list)))
20611 list)
20613 (defun org-count (cl-item cl-seq)
20614 "Count the number of occurrences of ITEM in SEQ.
20615 Taken from `count' in cl-seq.el with all keyword arguments removed."
20616 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20617 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20618 (while (< cl-start cl-end)
20619 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20620 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20621 (setq cl-start (1+ cl-start)))
20622 cl-count))
20624 (defun org-remove-if (predicate seq)
20625 "Remove everything from SEQ that fulfills PREDICATE."
20626 (let (res e)
20627 (while seq
20628 (setq e (pop seq))
20629 (if (not (funcall predicate e)) (push e res)))
20630 (nreverse res)))
20632 (defun org-remove-if-not (predicate seq)
20633 "Remove everything from SEQ that does not fulfill PREDICATE."
20634 (let (res e)
20635 (while seq
20636 (setq e (pop seq))
20637 (if (funcall predicate e) (push e res)))
20638 (nreverse res)))
20640 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20641 "Reduce two-argument FUNCTION across SEQ.
20642 Taken from `reduce' in cl-seq.el with all keyword arguments but
20643 \":initial-value\" removed."
20644 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20645 (cadr (memq :initial-value cl-keys)))
20646 (cl-seq (pop cl-seq))
20647 (t (funcall cl-func)))))
20648 (while cl-seq
20649 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20650 cl-accum))
20652 (defun org-back-over-empty-lines ()
20653 "Move backwards over whitespace, to the beginning of the first empty line.
20654 Returns the number of empty lines passed."
20655 (let ((pos (point)))
20656 (if (cdr (assoc 'heading org-blank-before-new-entry))
20657 (skip-chars-backward " \t\n\r")
20658 (unless (eobp)
20659 (forward-line -1)))
20660 (beginning-of-line 2)
20661 (goto-char (min (point) pos))
20662 (count-lines (point) pos)))
20664 (defun org-skip-whitespace ()
20665 (skip-chars-forward " \t\n\r"))
20667 (defun org-point-in-group (point group &optional context)
20668 "Check if POINT is in match-group GROUP.
20669 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20670 match. If the match group does not exist or point is not inside it,
20671 return nil."
20672 (and (match-beginning group)
20673 (>= point (match-beginning group))
20674 (<= point (match-end group))
20675 (if context
20676 (list context (match-beginning group) (match-end group))
20677 t)))
20679 (defun org-switch-to-buffer-other-window (&rest args)
20680 "Switch to buffer in a second window on the current frame.
20681 In particular, do not allow pop-up frames.
20682 Returns the newly created buffer."
20683 (org-no-popups
20684 (apply 'switch-to-buffer-other-window args)))
20686 (defun org-combine-plists (&rest plists)
20687 "Create a single property list from all plists in PLISTS.
20688 The process starts by copying the first list, and then setting properties
20689 from the other lists. Settings in the last list are the most significant
20690 ones and overrule settings in the other lists."
20691 (let ((rtn (copy-sequence (pop plists)))
20692 p v ls)
20693 (while plists
20694 (setq ls (pop plists))
20695 (while ls
20696 (setq p (pop ls) v (pop ls))
20697 (setq rtn (plist-put rtn p v))))
20698 rtn))
20700 (defun org-replace-escapes (string table)
20701 "Replace %-escapes in STRING with values in TABLE.
20702 TABLE is an association list with keys like \"%a\" and string values.
20703 The sequences in STRING may contain normal field width and padding information,
20704 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20705 so values can contain further %-escapes if they are define later in TABLE."
20706 (let ((tbl (copy-alist table))
20707 (case-fold-search nil)
20708 (pchg 0)
20709 e re rpl)
20710 (while (setq e (pop tbl))
20711 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20712 (when (and (cdr e) (string-match re (cdr e)))
20713 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20714 (safe "SREF"))
20715 (add-text-properties 0 3 (list 'sref sref) safe)
20716 (setcdr e (replace-match safe t t (cdr e)))))
20717 (while (string-match re string)
20718 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20719 (cdr e)))
20720 (setq string (replace-match rpl t t string))))
20721 (while (setq pchg (next-property-change pchg string))
20722 (let ((sref (get-text-property pchg 'sref string)))
20723 (when (and sref (string-match "SREF" string pchg))
20724 (setq string (replace-match sref t t string)))))
20725 string))
20727 (defun org-sublist (list start end)
20728 "Return a section of LIST, from START to END.
20729 Counting starts at 1."
20730 (let (rtn (c start))
20731 (setq list (nthcdr (1- start) list))
20732 (while (and list (<= c end))
20733 (push (pop list) rtn)
20734 (setq c (1+ c)))
20735 (nreverse rtn)))
20737 (defun org-find-base-buffer-visiting (file)
20738 "Like `find-buffer-visiting' but always return the base buffer and
20739 not an indirect buffer."
20740 (let ((buf (or (get-file-buffer file)
20741 (find-buffer-visiting file))))
20742 (if buf
20743 (or (buffer-base-buffer buf) buf)
20744 nil)))
20746 (defun org-image-file-name-regexp (&optional extensions)
20747 "Return regexp matching the file names of images.
20748 If EXTENSIONS is given, only match these."
20749 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20750 (image-file-name-regexp)
20751 (let ((image-file-name-extensions
20752 (or extensions
20753 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20754 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20755 (concat "\\."
20756 (regexp-opt (nconc (mapcar 'upcase
20757 image-file-name-extensions)
20758 image-file-name-extensions)
20760 "\\'"))))
20762 (defun org-file-image-p (file &optional extensions)
20763 "Return non-nil if FILE is an image."
20764 (save-match-data
20765 (string-match (org-image-file-name-regexp extensions) file)))
20767 (defun org-get-cursor-date ()
20768 "Return the date at cursor in as a time.
20769 This works in the calendar and in the agenda, anywhere else it just
20770 returns the current time."
20771 (let (date day defd)
20772 (cond
20773 ((eq major-mode 'calendar-mode)
20774 (setq date (calendar-cursor-to-date)
20775 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20776 ((eq major-mode 'org-agenda-mode)
20777 (setq day (get-text-property (point) 'day))
20778 (if day
20779 (setq date (calendar-gregorian-from-absolute day)
20780 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20781 (nth 2 date))))))
20782 (or defd (current-time))))
20784 (defun org-mark-subtree (&optional up)
20785 "Mark the current subtree.
20786 This puts point at the start of the current subtree, and mark at
20787 the end. If a numeric prefix UP is given, move up into the
20788 hierarchy of headlines by UP levels before marking the subtree."
20789 (interactive "P")
20790 (org-with-limited-levels
20791 (cond ((org-at-heading-p) (beginning-of-line))
20792 ((org-before-first-heading-p) (error "Not in a subtree"))
20793 (t (outline-previous-visible-heading 1))))
20794 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20795 (if (org-called-interactively-p 'any)
20796 (call-interactively 'org-mark-element)
20797 (org-mark-element)))
20799 ;;; Indentation
20801 (defun org-indent-line ()
20802 "Indent line depending on context."
20803 (interactive)
20804 (let* ((pos (point))
20805 (itemp (org-at-item-p))
20806 (case-fold-search t)
20807 (org-drawer-regexp (or org-drawer-regexp "\000"))
20808 (inline-task-p (and (featurep 'org-inlinetask)
20809 (org-inlinetask-in-task-p)))
20810 (inline-re (and inline-task-p
20811 (org-inlinetask-outline-regexp)))
20812 column)
20813 (if (and orgstruct-is-++ (eq pos (point)))
20814 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20815 (indent-according-to-mode))
20816 (beginning-of-line 1)
20817 (cond
20818 ;; Headings
20819 ((looking-at org-outline-regexp) (setq column 0))
20820 ;; Included files
20821 ((looking-at "#\\+include:") (setq column 0))
20822 ;; Footnote definition
20823 ((looking-at org-footnote-definition-re) (setq column 0))
20824 ;; Literal examples
20825 ((looking-at "[ \t]*:\\( \\|$\\)")
20826 (setq column (org-get-indentation))) ; do nothing
20827 ;; Lists
20828 ((ignore-errors (goto-char (org-in-item-p)))
20829 (setq column (if itemp
20830 (org-get-indentation)
20831 (org-list-item-body-column (point))))
20832 (goto-char pos))
20833 ;; Drawers
20834 ((and (looking-at "[ \t]*:END:")
20835 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20836 (save-excursion
20837 (goto-char (1- (match-beginning 1)))
20838 (setq column (current-column))))
20839 ;; Special blocks
20840 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20841 (save-excursion
20842 (re-search-backward
20843 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20844 (setq column (org-get-indentation (match-string 0))))
20845 ((and (not (looking-at "[ \t]*#\\+begin_"))
20846 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20847 (save-excursion
20848 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20849 (setq column
20850 (cond ((equal (downcase (match-string 1)) "src")
20851 ;; src blocks: let `org-edit-src-exit' handle them
20852 (org-get-indentation))
20853 ((equal (downcase (match-string 1)) "example")
20854 (max (org-get-indentation)
20855 (org-get-indentation (match-string 0))))
20857 (org-get-indentation (match-string 0))))))
20858 ;; This line has nothing special, look at the previous relevant
20859 ;; line to compute indentation
20861 (beginning-of-line 0)
20862 (while (and (not (bobp))
20863 (not (looking-at org-table-line-regexp))
20864 (not (looking-at org-drawer-regexp))
20865 ;; When point started in an inline task, do not move
20866 ;; above task starting line.
20867 (not (and inline-task-p (looking-at inline-re)))
20868 ;; Skip drawers, blocks, empty lines, verbatim,
20869 ;; comments, tables, footnotes definitions, lists,
20870 ;; inline tasks.
20871 (or (and (looking-at "[ \t]*:END:")
20872 (re-search-backward org-drawer-regexp nil t))
20873 (and (looking-at "[ \t]*#\\+end_")
20874 (re-search-backward "[ \t]*#\\+begin_"nil t))
20875 (looking-at "[ \t]*[\n:#|]")
20876 (looking-at org-footnote-definition-re)
20877 (and (ignore-errors (goto-char (org-in-item-p)))
20878 (goto-char
20879 (org-list-get-top-point (org-list-struct))))
20880 (and (not inline-task-p)
20881 (featurep 'org-inlinetask)
20882 (org-inlinetask-in-task-p)
20883 (or (org-inlinetask-goto-beginning) t))))
20884 (beginning-of-line 0))
20885 (cond
20886 ;; There was an heading above.
20887 ((looking-at "\\*+[ \t]+")
20888 (if (not org-adapt-indentation)
20889 (setq column 0)
20890 (goto-char (match-end 0))
20891 (setq column (current-column))))
20892 ;; A drawer had started and is unfinished
20893 ((looking-at org-drawer-regexp)
20894 (goto-char (1- (match-beginning 1)))
20895 (setq column (current-column)))
20896 ;; Else, nothing noticeable found: get indentation and go on.
20897 (t (setq column (org-get-indentation))))))
20898 ;; Now apply indentation and move cursor accordingly
20899 (goto-char pos)
20900 (if (<= (current-column) (current-indentation))
20901 (org-indent-line-to column)
20902 (save-excursion (org-indent-line-to column)))
20903 ;; Special polishing for properties, see `org-property-format'
20904 (setq column (current-column))
20905 (beginning-of-line 1)
20906 (if (looking-at
20907 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20908 (replace-match (concat (match-string 1)
20909 (format org-property-format
20910 (match-string 2) (match-string 3)))
20911 t t))
20912 (org-move-to-column column))))
20914 (defun org-indent-drawer ()
20915 "Indent the drawer at point."
20916 (interactive)
20917 (let ((p (point))
20918 (e (and (save-excursion (re-search-forward ":END:" nil t))
20919 (match-end 0)))
20920 (folded
20921 (save-excursion
20922 (end-of-line)
20923 (when (overlays-at (point))
20924 (member 'invisible (overlay-properties
20925 (car (overlays-at (point)))))))))
20926 (when folded (org-cycle))
20927 (indent-for-tab-command)
20928 (while (and (move-beginning-of-line 2) (< (point) e))
20929 (indent-for-tab-command))
20930 (goto-char p)
20931 (when folded (org-cycle)))
20932 (message "Drawer at point indented"))
20934 (defun org-indent-block ()
20935 "Indent the block at point."
20936 (interactive)
20937 (let ((p (point))
20938 (case-fold-search t)
20939 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20940 (match-end 0)))
20941 (folded
20942 (save-excursion
20943 (end-of-line)
20944 (when (overlays-at (point))
20945 (member 'invisible (overlay-properties
20946 (car (overlays-at (point)))))))))
20947 (when folded (org-cycle))
20948 (indent-for-tab-command)
20949 (while (and (move-beginning-of-line 2) (< (point) e))
20950 (indent-for-tab-command))
20951 (goto-char p)
20952 (when folded (org-cycle)))
20953 (message "Block at point indented"))
20955 (defun org-indent-region (start end)
20956 "Indent region."
20957 (interactive "r")
20958 (save-excursion
20959 (let ((line-end (org-current-line end)))
20960 (goto-char start)
20961 (while (< (org-current-line) line-end)
20962 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20963 (t (call-interactively 'org-indent-line)))
20964 (move-beginning-of-line 2)))))
20967 ;;; Filling
20969 ;; We use our own fill-paragraph and auto-fill functions.
20971 ;; `org-fill-paragraph' relies on adaptive filling and context
20972 ;; checking. Appropriate `fill-prefix' is computed with
20973 ;; `org-adaptive-fill-function'.
20975 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20976 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20977 ;; `org-adaptive-fill-function' value. Internally,
20978 ;; `org-comment-line-break-function' breaks the line.
20980 ;; `org-setup-filling' installs filling and auto-filling related
20981 ;; variables during `org-mode' initialization.
20983 (defun org-setup-filling ()
20984 (interactive)
20985 ;; Prevent auto-fill from inserting unwanted new items.
20986 (when (boundp 'fill-nobreak-predicate)
20987 (org-set-local
20988 'fill-nobreak-predicate
20989 (org-uniquify
20990 (append fill-nobreak-predicate
20991 '(org-fill-paragraph-separate-nobreak-p
20992 org-fill-line-break-nobreak-p
20993 org-fill-paragraph-with-timestamp-nobreak-p)))))
20994 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20995 (org-set-local 'auto-fill-inhibit-regexp nil)
20996 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20997 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20998 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21000 (defvar org-element-paragraph-separate) ; org-element.el
21001 (defun org-fill-paragraph-separate-nobreak-p ()
21002 "Non-nil when a line break at point would insert a new item."
21003 (looking-at (substring org-element-paragraph-separate 1)))
21005 (defun org-fill-line-break-nobreak-p ()
21006 "Non-nil when a line break at point would create an Org line break."
21007 (save-excursion
21008 (skip-chars-backward "[ \t]")
21009 (skip-chars-backward "\\\\")
21010 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21012 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21013 "Non-nil when a line break at point would insert a new item."
21014 (and (org-at-timestamp-p t)
21015 (not (looking-at org-ts-regexp-both))))
21017 (declare-function message-in-body-p "message" ())
21018 (defvar org-element--affiliated-re) ; From org-element.el
21019 (defvar orgtbl-line-start-regexp) ; From org-table.el
21020 (defun org-adaptive-fill-function ()
21021 "Compute a fill prefix for the current line.
21022 Return fill prefix, as a string, or nil if current line isn't
21023 meant to be filled."
21024 (let (prefix)
21025 (catch 'exit
21026 (when (derived-mode-p 'message-mode)
21027 (save-excursion
21028 (beginning-of-line)
21029 (cond ((or (not (message-in-body-p))
21030 (looking-at orgtbl-line-start-regexp))
21031 (throw 'exit nil))
21032 ((looking-at message-cite-prefix-regexp)
21033 (throw 'exit (match-string-no-properties 0)))
21034 ((looking-at org-outline-regexp)
21035 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21036 (org-with-wide-buffer
21037 (let* ((p (line-beginning-position))
21038 (element (save-excursion (beginning-of-line) (org-element-at-point)))
21039 (type (org-element-type element))
21040 (post-affiliated
21041 (save-excursion
21042 (goto-char (org-element-property :begin element))
21043 (while (looking-at org-element--affiliated-re) (forward-line))
21044 (point))))
21045 (unless (< p post-affiliated)
21046 (case type
21047 (comment (looking-at "[ \t]*# ?") (match-string 0))
21048 (footnote-definition "")
21049 ((item plain-list)
21050 (make-string (org-list-item-body-column post-affiliated) ? ))
21051 (paragraph
21052 ;; Fill prefix is usually the same as the current line,
21053 ;; except if the paragraph is at the beginning of an item.
21054 (let ((parent (org-element-property :parent element)))
21055 (cond ((eq (org-element-type parent) 'item)
21056 (make-string (org-list-item-body-column
21057 (org-element-property :begin parent))
21058 ? ))
21059 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21060 (match-string 0))
21061 (t ""))))
21062 (comment-block
21063 ;; Only fill contents if P is within block boundaries.
21064 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21065 (forward-line)
21066 (point)))
21067 (cend (save-excursion
21068 (goto-char (org-element-property :end element))
21069 (skip-chars-backward " \r\t\n")
21070 (line-beginning-position))))
21071 (when (and (>= p cbeg) (< p cend))
21072 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21073 (match-string 0)
21074 "")))))))))))
21076 (declare-function message-goto-body "message" ())
21077 (defvar message-cite-prefix-regexp) ; From message.el
21078 (defvar org-element-all-objects) ; From org-element.el
21079 (defun org-fill-paragraph (&optional justify)
21080 "Fill element at point, when applicable.
21082 This function only applies to comment blocks, comments, example
21083 blocks and paragraphs. Also, as a special case, re-align table
21084 when point is at one.
21086 If JUSTIFY is non-nil (interactively, with prefix argument),
21087 justify as well. If `sentence-end-double-space' is non-nil, then
21088 period followed by one space does not end a sentence, so don't
21089 break a line there. The variable `fill-column' controls the
21090 width for filling.
21092 For convenience, when point is at a plain list, an item or
21093 a footnote definition, try to fill the first paragraph within."
21094 (interactive)
21095 (if (and (derived-mode-p 'message-mode)
21096 (or (not (message-in-body-p))
21097 (save-excursion (move-beginning-of-line 1)
21098 (looking-at message-cite-prefix-regexp))))
21099 ;; First ensure filling is correct in message-mode.
21100 (let ((fill-paragraph-function
21101 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21102 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21103 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21104 (paragraph-separate
21105 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21106 (fill-paragraph nil))
21107 (save-excursion
21108 ;; Move to end of line in order to get the first paragraph
21109 ;; within a plain list or a footnote definition.
21110 (end-of-line)
21111 (let ((element (org-element-at-point)))
21112 ;; First check if point is in a blank line at the beginning of
21113 ;; the buffer. In that case, ignore filling.
21114 (if (< (point) (org-element-property :begin element)) t
21115 (case (org-element-type element)
21116 ;; Use major mode filling function is src blocks.
21117 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21118 ;; Align Org tables, leave table.el tables as-is.
21119 (table-row (org-table-align) t)
21120 (table
21121 (when (eq (org-element-property :type element) 'org)
21122 (org-table-align))
21124 (paragraph
21125 ;; Paragraphs may contain `line-break' type objects.
21126 (let ((beg (max (point-min)
21127 (org-element-property :contents-begin element)))
21128 (end (min (point-max)
21129 (org-element-property :contents-end element))))
21130 ;; Do nothing if point is at an affiliated keyword.
21131 (if (< (point) beg) t
21132 (when (derived-mode-p 'message-mode)
21133 ;; In `message-mode', do not fill following
21134 ;; citation in current paragraph nor text before
21135 ;; message body.
21136 (let ((body-start (save-excursion (message-goto-body))))
21137 (when body-start (setq beg (max body-start beg))))
21138 (when (save-excursion
21139 (re-search-forward
21140 (concat "^" message-cite-prefix-regexp) end t))
21141 (setq end (match-beginning 0))))
21142 ;; Fill paragraph, taking line breaks into
21143 ;; consideration. For that, slice the paragraph
21144 ;; using line breaks as separators, and fill the
21145 ;; parts in reverse order to avoid messing with
21146 ;; markers.
21147 (save-excursion
21148 (goto-char end)
21149 (mapc
21150 (lambda (pos)
21151 (fill-region-as-paragraph pos (point) justify)
21152 (goto-char pos))
21153 ;; Find the list of ending positions for line
21154 ;; breaks in the current paragraph. Add paragraph
21155 ;; beginning to include first slice.
21156 (nreverse
21157 (cons
21159 (org-element-map
21160 (org-element--parse-objects
21161 beg end nil org-element-all-objects)
21162 'line-break
21163 (lambda (lb) (org-element-property :end lb)))))))
21164 t)))
21165 ;; Contents of `comment-block' type elements should be
21166 ;; filled as plain text, but only if point is within block
21167 ;; markers.
21168 (comment-block
21169 (let* ((case-fold-search t)
21170 (beg (save-excursion
21171 (goto-char (org-element-property :begin element))
21172 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21173 (forward-line)
21174 (point)))
21175 (end (save-excursion
21176 (goto-char (org-element-property :end element))
21177 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21178 (line-beginning-position))))
21179 (when (and (>= (point) beg) (< (point) end))
21180 (fill-region-as-paragraph
21181 (save-excursion
21182 (end-of-line)
21183 (re-search-backward "^[ \t]*$" beg 'move)
21184 (line-beginning-position))
21185 (save-excursion
21186 (beginning-of-line)
21187 (re-search-forward "^[ \t]*$" end 'move)
21188 (line-beginning-position))
21189 justify)))
21191 ;; Fill comments.
21192 (comment (fill-comment-paragraph justify))
21193 ;; Ignore every other element.
21194 (otherwise t)))))))
21196 (defun org-auto-fill-function ()
21197 "Auto-fill function."
21198 ;; Check if auto-filling is meaningful.
21199 (let ((fc (current-fill-column)))
21200 (when (and fc (> (current-column) fc))
21201 (let* ((fill-prefix (org-adaptive-fill-function))
21202 ;; Enforce empty fill prefix, if required. Otherwise, it
21203 ;; will be computed again.
21204 (adaptive-fill-mode (not (equal fill-prefix ""))))
21205 (when fill-prefix (do-auto-fill))))))
21207 (defun org-comment-line-break-function (&optional soft)
21208 "Break line at point and indent, continuing comment if within one.
21209 The inserted newline is marked hard if variable
21210 `use-hard-newlines' is true, unless optional argument SOFT is
21211 non-nil."
21212 (if soft (insert-and-inherit ?\n) (newline 1))
21213 (save-excursion (forward-char -1) (delete-horizontal-space))
21214 (delete-horizontal-space)
21215 (indent-to-left-margin)
21216 (insert-before-markers-and-inherit fill-prefix))
21219 ;;; Comments
21221 ;; Org comments syntax is quite complex. It requires the entire line
21222 ;; to be just a comment. Also, even with the right syntax at the
21223 ;; beginning of line, some some elements (i.e. verse-block or
21224 ;; example-block) don't accept comments. Usual Emacs comment commands
21225 ;; cannot cope with those requirements. Therefore, Org replaces them.
21227 ;; Org still relies on `comment-dwim', but cannot trust
21228 ;; `comment-only-p'. So, `comment-region-function' and
21229 ;; `uncomment-region-function' both point
21230 ;; to`org-comment-or-uncomment-region'. Eventually,
21231 ;; `org-insert-comment' takes care of insertion of comments at the
21232 ;; beginning of line.
21234 ;; `org-setup-comments-handling' install comments related variables
21235 ;; during `org-mode' initialization.
21237 (defun org-setup-comments-handling ()
21238 (interactive)
21239 (org-set-local 'comment-use-syntax nil)
21240 (org-set-local 'comment-start "# ")
21241 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21242 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21243 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21244 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21246 (defun org-insert-comment ()
21247 "Insert an empty comment above current line.
21248 If the line is empty, insert comment at its beginning."
21249 (beginning-of-line)
21250 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21251 (org-indent-line)
21252 (insert "# "))
21254 (defvar comment-empty-lines) ; From newcomment.el.
21255 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21256 "Comment or uncomment each non-blank line in the region.
21257 Uncomment each non-blank line between BEG and END if it only
21258 contains commented lines. Otherwise, comment them."
21259 (save-restriction
21260 ;; Restrict region
21261 (narrow-to-region (save-excursion (goto-char beg)
21262 (skip-chars-forward " \r\t\n" end)
21263 (line-beginning-position))
21264 (save-excursion (goto-char end)
21265 (skip-chars-backward " \r\t\n" beg)
21266 (line-end-position)))
21267 (let ((uncommentp
21268 ;; UNCOMMENTP is non-nil when every non blank line between
21269 ;; BEG and END is a comment.
21270 (save-excursion
21271 (goto-char (point-min))
21272 (while (and (not (eobp))
21273 (let ((element (org-element-at-point)))
21274 (and (eq (org-element-type element) 'comment)
21275 (goto-char (min (point-max)
21276 (org-element-property
21277 :end element)))))))
21278 (eobp))))
21279 (if uncommentp
21280 ;; Only blank lines and comments in region: uncomment it.
21281 (save-excursion
21282 (goto-char (point-min))
21283 (while (not (eobp))
21284 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21285 (replace-match "" nil nil nil 1))
21286 (forward-line)))
21287 ;; Comment each line in region.
21288 (let ((min-indent (point-max)))
21289 ;; First find the minimum indentation across all lines.
21290 (save-excursion
21291 (goto-char (point-min))
21292 (while (and (not (eobp)) (not (zerop min-indent)))
21293 (unless (looking-at "[ \t]*$")
21294 (setq min-indent (min min-indent (current-indentation))))
21295 (forward-line)))
21296 ;; Then loop over all lines.
21297 (save-excursion
21298 (goto-char (point-min))
21299 (while (not (eobp))
21300 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21301 (org-move-to-column min-indent t)
21302 (insert comment-start))
21303 (forward-line))))))))
21306 ;;; Other stuff.
21308 (defun org-toggle-fixed-width-section (arg)
21309 "Toggle the fixed-width export.
21310 If there is no active region, the QUOTE keyword at the current headline is
21311 inserted or removed. When present, it causes the text between this headline
21312 and the next to be exported as fixed-width text, and unmodified.
21313 If there is an active region, this command adds or removes a colon as the
21314 first character of this line. If the first character of a line is a colon,
21315 this line is also exported in fixed-width font."
21316 (interactive "P")
21317 (let* ((cc 0)
21318 (regionp (org-region-active-p))
21319 (beg (if regionp (region-beginning) (point)))
21320 (end (if regionp (region-end)))
21321 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21322 (case-fold-search nil)
21323 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21324 off)
21325 (if regionp
21326 (save-excursion
21327 (goto-char beg)
21328 (setq cc (current-column))
21329 (beginning-of-line 1)
21330 (setq off (looking-at re))
21331 (while (> nlines 0)
21332 (setq nlines (1- nlines))
21333 (beginning-of-line 1)
21334 (cond
21335 (arg
21336 (org-move-to-column cc t)
21337 (insert ": \n")
21338 (forward-line -1))
21339 ((and off (looking-at re))
21340 (replace-match "" t t nil 1))
21341 ((not off) (org-move-to-column cc t) (insert ": ")))
21342 (forward-line 1)))
21343 (save-excursion
21344 (org-back-to-heading)
21345 (cond
21346 ((looking-at (format org-heading-keyword-regexp-format
21347 org-quote-string))
21348 (goto-char (match-end 1))
21349 (looking-at (concat " +" org-quote-string))
21350 (replace-match "" t t)
21351 (when (eolp) (insert " ")))
21352 ((looking-at org-outline-regexp)
21353 (goto-char (match-end 0))
21354 (insert org-quote-string " ")))))))
21356 (defun org-reftex-citation ()
21357 "Use reftex-citation to insert a citation into the buffer.
21358 This looks for a line like
21360 #+BIBLIOGRAPHY: foo plain option:-d
21362 and derives from it that foo.bib is the bibliography file relevant
21363 for this document. It then installs the necessary environment for RefTeX
21364 to work in this buffer and calls `reftex-citation' to insert a citation
21365 into the buffer.
21367 Export of such citations to both LaTeX and HTML is handled by the contributed
21368 package org-exp-bibtex by Taru Karttunen."
21369 (interactive)
21370 (let ((reftex-docstruct-symbol 'rds)
21371 (reftex-cite-format "\\cite{%l}")
21372 rds bib)
21373 (save-excursion
21374 (save-restriction
21375 (widen)
21376 (let ((case-fold-search t)
21377 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21378 (if (not (save-excursion
21379 (or (re-search-forward re nil t)
21380 (re-search-backward re nil t))))
21381 (error "No bibliography defined in file")
21382 (setq bib (concat (match-string 1) ".bib")
21383 rds (list (list 'bib bib)))))))
21384 (call-interactively 'reftex-citation)))
21386 ;;;; Functions extending outline functionality
21388 (defun org-beginning-of-line (&optional arg)
21389 "Go to the beginning of the current line. If that is invisible, continue
21390 to a visible line beginning. This makes the function of C-a more intuitive.
21391 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21392 first attempt, and only move to after the tags when the cursor is already
21393 beyond the end of the headline."
21394 (interactive "P")
21395 (let ((pos (point))
21396 (special (if (consp org-special-ctrl-a/e)
21397 (car org-special-ctrl-a/e)
21398 org-special-ctrl-a/e))
21399 refpos)
21400 (if (org-bound-and-true-p visual-line-mode)
21401 (beginning-of-visual-line 1)
21402 (beginning-of-line 1))
21403 (if (and arg (fboundp 'move-beginning-of-line))
21404 (call-interactively 'move-beginning-of-line)
21405 (if (bobp)
21407 (backward-char 1)
21408 (if (org-truely-invisible-p)
21409 (while (and (not (bobp)) (org-truely-invisible-p))
21410 (backward-char 1)
21411 (beginning-of-line 1))
21412 (forward-char 1))))
21413 (when special
21414 (cond
21415 ((and (looking-at org-complex-heading-regexp)
21416 (= (char-after (match-end 1)) ?\ ))
21417 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21418 (point-at-eol)))
21419 (goto-char
21420 (if (eq special t)
21421 (cond ((> pos refpos) refpos)
21422 ((= pos (point)) refpos)
21423 (t (point)))
21424 (cond ((> pos (point)) (point))
21425 ((not (eq last-command this-command)) (point))
21426 (t refpos)))))
21427 ((org-at-item-p)
21428 ;; Being at an item and not looking at an the item means point
21429 ;; was previously moved to beginning of a visual line, which
21430 ;; doesn't contain the item. Therefore, do nothing special,
21431 ;; just stay here.
21432 (when (looking-at org-list-full-item-re)
21433 ;; Set special position at first white space character after
21434 ;; bullet, and check-box, if any.
21435 (let ((after-bullet
21436 (let ((box (match-end 3)))
21437 (if (not box) (match-end 1)
21438 (let ((after (char-after box)))
21439 (if (and after (= after ? )) (1+ box) box))))))
21440 ;; Special case: Move point to special position when
21441 ;; currently after it or at beginning of line.
21442 (if (eq special t)
21443 (when (or (> pos after-bullet) (= (point) pos))
21444 (goto-char after-bullet))
21445 ;; Reversed case: Move point to special position when
21446 ;; point was already at beginning of line and command is
21447 ;; repeated.
21448 (when (and (= (point) pos) (eq last-command this-command))
21449 (goto-char after-bullet))))))))
21450 (org-no-warnings
21451 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21453 (defun org-end-of-line (&optional arg)
21454 "Go to the end of the line.
21455 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21456 tags on the first attempt, and only move to after the tags when
21457 the cursor is already beyond the end of the headline."
21458 (interactive "P")
21459 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21460 org-special-ctrl-a/e))
21461 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21462 'end-of-visual-line)
21463 ((fboundp 'move-end-of-line) 'move-end-of-line)
21464 (t 'end-of-line))))
21465 (if (or (not special) arg) (call-interactively move-fun)
21466 (let* ((element (save-excursion (beginning-of-line)
21467 (org-element-at-point)))
21468 (type (org-element-type element)))
21469 (cond
21470 ((memq type '(headline inlinetask))
21471 (let ((pos (point)))
21472 (beginning-of-line 1)
21473 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21474 (if (eq special t)
21475 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21476 (goto-char (match-beginning 1))
21477 (goto-char (match-end 0)))
21478 (if (or (< pos (match-end 0))
21479 (not (eq this-command last-command)))
21480 (goto-char (match-end 0))
21481 (goto-char (match-beginning 1))))
21482 (call-interactively move-fun))))
21483 ((org-element-property :hiddenp element)
21484 ;; If element is hidden, `move-end-of-line' would put point
21485 ;; after it. Use `end-of-line' to stay on current line.
21486 (call-interactively 'end-of-line))
21487 (t (call-interactively move-fun)))))
21488 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21490 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21491 (define-key org-mode-map "\C-e" 'org-end-of-line)
21493 (defun org-backward-sentence (&optional arg)
21494 "Go to beginning of sentence, or beginning of table field.
21495 This will call `backward-sentence' or `org-table-beginning-of-field',
21496 depending on context."
21497 (interactive "P")
21498 (cond
21499 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21500 (t (call-interactively 'backward-sentence))))
21502 (defun org-forward-sentence (&optional arg)
21503 "Go to end of sentence, or end of table field.
21504 This will call `forward-sentence' or `org-table-end-of-field',
21505 depending on context."
21506 (interactive "P")
21507 (cond
21508 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21509 (t (call-interactively 'forward-sentence))))
21511 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21512 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21514 (defun org-kill-line (&optional arg)
21515 "Kill line, to tags or end of line."
21516 (interactive "P")
21517 (cond
21518 ((or (not org-special-ctrl-k)
21519 (bolp)
21520 (not (org-at-heading-p)))
21521 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21522 org-ctrl-k-protect-subtree)
21523 (if (or (eq org-ctrl-k-protect-subtree 'error)
21524 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21525 (error "C-k aborted - would kill hidden subtree")))
21526 (call-interactively
21527 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21528 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21529 (kill-region (point) (match-beginning 1))
21530 (org-set-tags nil t))
21531 (t (kill-region (point) (point-at-eol)))))
21533 (define-key org-mode-map "\C-k" 'org-kill-line)
21535 (defun org-yank (&optional arg)
21536 "Yank. If the kill is a subtree, treat it specially.
21537 This command will look at the current kill and check if is a single
21538 subtree, or a series of subtrees[1]. If it passes the test, and if the
21539 cursor is at the beginning of a line or after the stars of a currently
21540 empty headline, then the yank is handled specially. How exactly depends
21541 on the value of the following variables, both set by default.
21543 org-yank-folded-subtrees
21544 When set, the subtree(s) will be folded after insertion, but only
21545 if doing so would now swallow text after the yanked text.
21547 org-yank-adjusted-subtrees
21548 When set, the subtree will be promoted or demoted in order to
21549 fit into the local outline tree structure, which means that the level
21550 will be adjusted so that it becomes the smaller one of the two
21551 *visible* surrounding headings.
21553 Any prefix to this command will cause `yank' to be called directly with
21554 no special treatment. In particular, a simple \\[universal-argument] prefix \
21555 will just
21556 plainly yank the text as it is.
21558 \[1] The test checks if the first non-white line is a heading
21559 and if there are no other headings with fewer stars."
21560 (interactive "P")
21561 (org-yank-generic 'yank arg))
21563 (defun org-yank-generic (command arg)
21564 "Perform some yank-like command.
21566 This function implements the behavior described in the `org-yank'
21567 documentation. However, it has been generalized to work for any
21568 interactive command with similar behavior."
21570 ;; pretend to be command COMMAND
21571 (setq this-command command)
21573 (if arg
21574 (call-interactively command)
21576 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21577 (and (org-kill-is-subtree-p)
21578 (or (bolp)
21579 (and (looking-at "[ \t]*$")
21580 (string-match
21581 "\\`\\*+\\'"
21582 (buffer-substring (point-at-bol) (point)))))))
21583 swallowp)
21584 (cond
21585 ((and subtreep org-yank-folded-subtrees)
21586 (let ((beg (point))
21587 end)
21588 (if (and subtreep org-yank-adjusted-subtrees)
21589 (org-paste-subtree nil nil 'for-yank)
21590 (call-interactively command))
21592 (setq end (point))
21593 (goto-char beg)
21594 (when (and (bolp) subtreep
21595 (not (setq swallowp
21596 (org-yank-folding-would-swallow-text beg end))))
21597 (org-with-limited-levels
21598 (or (looking-at org-outline-regexp)
21599 (re-search-forward org-outline-regexp-bol end t))
21600 (while (and (< (point) end) (looking-at org-outline-regexp))
21601 (hide-subtree)
21602 (org-cycle-show-empty-lines 'folded)
21603 (condition-case nil
21604 (outline-forward-same-level 1)
21605 (error (goto-char end))))))
21606 (when swallowp
21607 (message
21608 "Inserted text not folded because that would swallow text"))
21610 (goto-char end)
21611 (skip-chars-forward " \t\n\r")
21612 (beginning-of-line 1)
21613 (push-mark beg 'nomsg)))
21614 ((and subtreep org-yank-adjusted-subtrees)
21615 (let ((beg (point-at-bol)))
21616 (org-paste-subtree nil nil 'for-yank)
21617 (push-mark beg 'nomsg)))
21619 (call-interactively command))))))
21621 (defun org-yank-folding-would-swallow-text (beg end)
21622 "Would hide-subtree at BEG swallow any text after END?"
21623 (let (level)
21624 (org-with-limited-levels
21625 (save-excursion
21626 (goto-char beg)
21627 (when (or (looking-at org-outline-regexp)
21628 (re-search-forward org-outline-regexp-bol end t))
21629 (setq level (org-outline-level)))
21630 (goto-char end)
21631 (skip-chars-forward " \t\r\n\v\f")
21632 (if (or (eobp)
21633 (and (bolp) (looking-at org-outline-regexp)
21634 (<= (org-outline-level) level)))
21635 nil ; Nothing would be swallowed
21636 t))))) ; something would swallow
21638 (define-key org-mode-map "\C-y" 'org-yank)
21640 (defun org-truely-invisible-p ()
21641 "Check if point is at a character currently not visible.
21642 This version does not only check the character property, but also
21643 `visible-mode'."
21644 ;; Early versions of noutline don't have `outline-invisible-p'.
21645 (if (org-bound-and-true-p visible-mode)
21647 (outline-invisible-p)))
21649 (defun org-invisible-p2 ()
21650 "Check if point is at a character currently not visible."
21651 (save-excursion
21652 (if (and (eolp) (not (bobp))) (backward-char 1))
21653 ;; Early versions of noutline don't have `outline-invisible-p'.
21654 (outline-invisible-p)))
21656 (defun org-back-to-heading (&optional invisible-ok)
21657 "Call `outline-back-to-heading', but provide a better error message."
21658 (condition-case nil
21659 (outline-back-to-heading invisible-ok)
21660 (error (error "Before first headline at position %d in buffer %s"
21661 (point) (current-buffer)))))
21663 (defun org-before-first-heading-p ()
21664 "Before first heading?"
21665 (save-excursion
21666 (end-of-line)
21667 (null (re-search-backward org-outline-regexp-bol nil t))))
21669 (defun org-at-heading-p (&optional ignored)
21670 (outline-on-heading-p t))
21671 ;; Compatibility alias with Org versions < 7.8.03
21672 (defalias 'org-on-heading-p 'org-at-heading-p)
21674 (defun org-at-comment-p nil
21675 "Is cursor in a line starting with a # character?"
21676 (save-excursion
21677 (beginning-of-line)
21678 (looking-at "^#")))
21680 (defun org-at-drawer-p nil
21681 "Is cursor at a drawer keyword?"
21682 (save-excursion
21683 (move-beginning-of-line 1)
21684 (looking-at org-drawer-regexp)))
21686 (defun org-at-block-p nil
21687 "Is cursor at a block keyword?"
21688 (save-excursion
21689 (move-beginning-of-line 1)
21690 (looking-at org-block-regexp)))
21692 (defun org-point-at-end-of-empty-headline ()
21693 "If point is at the end of an empty headline, return t, else nil.
21694 If the heading only contains a TODO keyword, it is still still considered
21695 empty."
21696 (and (looking-at "[ \t]*$")
21697 (when org-todo-line-regexp
21698 (save-excursion
21699 (beginning-of-line 1)
21700 (let ((case-fold-search nil))
21701 (looking-at org-todo-line-regexp)
21702 (string= (match-string 3) ""))))))
21704 (defun org-at-heading-or-item-p ()
21705 (or (org-at-heading-p) (org-at-item-p)))
21707 (defun org-at-target-p ()
21708 (or (org-in-regexp org-radio-target-regexp)
21709 (org-in-regexp org-target-regexp)))
21710 ;; Compatibility alias with Org versions < 7.8.03
21711 (defalias 'org-on-target-p 'org-at-target-p)
21713 (defun org-up-heading-all (arg)
21714 "Move to the heading line of which the present line is a subheading.
21715 This function considers both visible and invisible heading lines.
21716 With argument, move up ARG levels."
21717 (if (fboundp 'outline-up-heading-all)
21718 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21719 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21721 (defun org-up-heading-safe ()
21722 "Move to the heading line of which the present line is a subheading.
21723 This version will not throw an error. It will return the level of the
21724 headline found, or nil if no higher level is found.
21726 Also, this function will be a lot faster than `outline-up-heading',
21727 because it relies on stars being the outline starters. This can really
21728 make a significant difference in outlines with very many siblings."
21729 (let (start-level re)
21730 (org-back-to-heading t)
21731 (setq start-level (funcall outline-level))
21732 (if (equal start-level 1)
21734 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21735 (if (re-search-backward re nil t)
21736 (funcall outline-level)))))
21738 (defun org-first-sibling-p ()
21739 "Is this heading the first child of its parents?"
21740 (interactive)
21741 (let ((re org-outline-regexp-bol)
21742 level l)
21743 (unless (org-at-heading-p t)
21744 (error "Not at a heading"))
21745 (setq level (funcall outline-level))
21746 (save-excursion
21747 (if (not (re-search-backward re nil t))
21749 (setq l (funcall outline-level))
21750 (< l level)))))
21752 (defun org-goto-sibling (&optional previous)
21753 "Goto the next sibling, even if it is invisible.
21754 When PREVIOUS is set, go to the previous sibling instead. Returns t
21755 when a sibling was found. When none is found, return nil and don't
21756 move point."
21757 (let ((fun (if previous 're-search-backward 're-search-forward))
21758 (pos (point))
21759 (re org-outline-regexp-bol)
21760 level l)
21761 (when (condition-case nil (org-back-to-heading t) (error nil))
21762 (setq level (funcall outline-level))
21763 (catch 'exit
21764 (or previous (forward-char 1))
21765 (while (funcall fun re nil t)
21766 (setq l (funcall outline-level))
21767 (when (< l level) (goto-char pos) (throw 'exit nil))
21768 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21769 (goto-char pos)
21770 nil))))
21772 (defun org-show-siblings ()
21773 "Show all siblings of the current headline."
21774 (save-excursion
21775 (while (org-goto-sibling) (org-flag-heading nil)))
21776 (save-excursion
21777 (while (org-goto-sibling 'previous)
21778 (org-flag-heading nil))))
21780 (defun org-goto-first-child ()
21781 "Goto the first child, even if it is invisible.
21782 Return t when a child was found. Otherwise don't move point and
21783 return nil."
21784 (let (level (pos (point)) (re org-outline-regexp-bol))
21785 (when (condition-case nil (org-back-to-heading t) (error nil))
21786 (setq level (outline-level))
21787 (forward-char 1)
21788 (if (and (re-search-forward re nil t) (> (outline-level) level))
21789 (progn (goto-char (match-beginning 0)) t)
21790 (goto-char pos) nil))))
21792 (defun org-show-hidden-entry ()
21793 "Show an entry where even the heading is hidden."
21794 (save-excursion
21795 (org-show-entry)))
21797 (defun org-flag-heading (flag &optional entry)
21798 "Flag the current heading. FLAG non-nil means make invisible.
21799 When ENTRY is non-nil, show the entire entry."
21800 (save-excursion
21801 (org-back-to-heading t)
21802 ;; Check if we should show the entire entry
21803 (if entry
21804 (progn
21805 (org-show-entry)
21806 (save-excursion
21807 (and (outline-next-heading)
21808 (org-flag-heading nil))))
21809 (outline-flag-region (max (point-min) (1- (point)))
21810 (save-excursion (outline-end-of-heading) (point))
21811 flag))))
21813 (defun org-get-next-sibling ()
21814 "Move to next heading of the same level, and return point.
21815 If there is no such heading, return nil.
21816 This is like outline-next-sibling, but invisible headings are ok."
21817 (let ((level (funcall outline-level)))
21818 (outline-next-heading)
21819 (while (and (not (eobp)) (> (funcall outline-level) level))
21820 (outline-next-heading))
21821 (if (or (eobp) (< (funcall outline-level) level))
21823 (point))))
21825 (defun org-get-last-sibling ()
21826 "Move to previous heading of the same level, and return point.
21827 If there is no such heading, return nil."
21828 (let ((opoint (point))
21829 (level (funcall outline-level)))
21830 (outline-previous-heading)
21831 (when (and (/= (point) opoint) (outline-on-heading-p t))
21832 (while (and (> (funcall outline-level) level)
21833 (not (bobp)))
21834 (outline-previous-heading))
21835 (if (< (funcall outline-level) level)
21837 (point)))))
21839 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21840 "Goto to the end of a subtree."
21841 ;; This contains an exact copy of the original function, but it uses
21842 ;; `org-back-to-heading', to make it work also in invisible
21843 ;; trees. And is uses an invisible-ok argument.
21844 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21845 ;; Furthermore, when used inside Org, finding the end of a large subtree
21846 ;; with many children and grandchildren etc, this can be much faster
21847 ;; than the outline version.
21848 (org-back-to-heading invisible-ok)
21849 (let ((first t)
21850 (level (funcall outline-level)))
21851 (if (and (derived-mode-p 'org-mode) (< level 1000))
21852 ;; A true heading (not a plain list item), in Org-mode
21853 ;; This means we can easily find the end by looking
21854 ;; only for the right number of stars. Using a regexp to do
21855 ;; this is so much faster than using a Lisp loop.
21856 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21857 (forward-char 1)
21858 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21859 ;; something else, do it the slow way
21860 (while (and (not (eobp))
21861 (or first (> (funcall outline-level) level)))
21862 (setq first nil)
21863 (outline-next-heading)))
21864 (unless to-heading
21865 (if (memq (preceding-char) '(?\n ?\^M))
21866 (progn
21867 ;; Go to end of line before heading
21868 (forward-char -1)
21869 (if (memq (preceding-char) '(?\n ?\^M))
21870 ;; leave blank line before heading
21871 (forward-char -1))))))
21872 (point))
21874 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21875 "Use Org version in org-mode, for dramatic speed-up."
21876 (if (derived-mode-p 'org-mode)
21877 (progn
21878 (org-end-of-subtree nil t)
21879 (unless (eobp) (backward-char 1)))
21880 ad-do-it))
21882 (defun org-end-of-meta-data-and-drawers ()
21883 "Jump to the first text after meta data and drawers in the current entry.
21884 This will move over empty lines, lines with planning time stamps,
21885 clocking lines, and drawers."
21886 (org-back-to-heading t)
21887 (let ((end (save-excursion (outline-next-heading) (point)))
21888 (re (concat "\\(" org-drawer-regexp "\\)"
21889 "\\|" "[ \t]*" org-keyword-time-regexp)))
21890 (forward-line 1)
21891 (while (re-search-forward re end t)
21892 (if (not (match-end 1))
21893 ;; empty or planning line
21894 (forward-line 1)
21895 ;; a drawer, find the end
21896 (re-search-forward "^[ \t]*:END:" end 'move)
21897 (forward-line 1)))
21898 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21899 (point)))
21901 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21902 "Move forward to the arg'th subheading at same level as this one.
21903 Stop at the first and last subheadings of a superior heading.
21904 Normally this only looks at visible headings, but when INVISIBLE-OK is
21905 non-nil it will also look at invisible ones."
21906 (interactive "p")
21907 (org-back-to-heading invisible-ok)
21908 (org-at-heading-p)
21909 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21910 (re (format "^\\*\\{1,%d\\} " level))
21912 (forward-char 1)
21913 (while (> arg 0)
21914 (while (and (re-search-forward re nil 'move)
21915 (setq l (- (match-end 0) (match-beginning 0) 1))
21916 (= l level)
21917 (not invisible-ok)
21918 (progn (backward-char 1) (outline-invisible-p)))
21919 (if (< l level) (setq arg 1)))
21920 (setq arg (1- arg)))
21921 (beginning-of-line 1)))
21923 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21924 "Move backward to the arg'th subheading at same level as this one.
21925 Stop at the first and last subheadings of a superior heading."
21926 (interactive "p")
21927 (org-back-to-heading)
21928 (org-at-heading-p)
21929 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21930 (re (format "^\\*\\{1,%d\\} " level))
21932 (while (> arg 0)
21933 (while (and (re-search-backward re nil 'move)
21934 (setq l (- (match-end 0) (match-beginning 0) 1))
21935 (= l level)
21936 (not invisible-ok)
21937 (outline-invisible-p))
21938 (if (< l level) (setq arg 1)))
21939 (setq arg (1- arg)))))
21941 (defun org-forward-element ()
21942 "Move forward by one element.
21943 Move to the next element at the same level, when possible."
21944 (interactive)
21945 (cond ((eobp) (error "Cannot move further down"))
21946 ((org-with-limited-levels (org-at-heading-p))
21947 (let ((origin (point)))
21948 (org-forward-heading-same-level 1)
21949 (unless (org-with-limited-levels (org-at-heading-p))
21950 (goto-char origin)
21951 (error "Cannot move further down"))))
21953 (let* ((elem (org-element-at-point))
21954 (end (org-element-property :end elem))
21955 (parent (org-element-property :parent elem)))
21956 (if (and parent (= (org-element-property :contents-end parent) end))
21957 (goto-char (org-element-property :end parent))
21958 (goto-char end))))))
21960 (defun org-backward-element ()
21961 "Move backward by one element.
21962 Move to the previous element at the same level, when possible."
21963 (interactive)
21964 (cond ((bobp) (error "Cannot move further up"))
21965 ((org-with-limited-levels (org-at-heading-p))
21966 ;; At an headline, move to the previous one, if any, or stay
21967 ;; here.
21968 (let ((origin (point)))
21969 (org-backward-heading-same-level 1)
21970 (unless (org-with-limited-levels (org-at-heading-p))
21971 (goto-char origin)
21972 (error "Cannot move further up"))))
21974 (let* ((trail (org-element-at-point 'keep-trail))
21975 (elem (car trail))
21976 (prev-elem (nth 1 trail))
21977 (beg (org-element-property :begin elem)))
21978 (cond
21979 ;; Move to beginning of current element if point isn't
21980 ;; there already.
21981 ((/= (point) beg) (goto-char beg))
21982 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21983 ((org-before-first-heading-p) (goto-char (point-min)))
21984 (t (org-back-to-heading)))))))
21986 (defun org-up-element ()
21987 "Move to upper element."
21988 (interactive)
21989 (if (org-with-limited-levels (org-at-heading-p))
21990 (unless (org-up-heading-safe) (error "No surrounding element"))
21991 (let* ((elem (org-element-at-point))
21992 (parent (org-element-property :parent elem)))
21993 (if parent (goto-char (org-element-property :begin parent))
21994 (if (org-with-limited-levels (org-before-first-heading-p))
21995 (error "No surrounding element")
21996 (org-with-limited-levels (org-back-to-heading)))))))
21998 (defvar org-element-greater-elements)
21999 (defun org-down-element ()
22000 "Move to inner element."
22001 (interactive)
22002 (let ((element (org-element-at-point)))
22003 (cond
22004 ((memq (org-element-type element) '(plain-list table))
22005 (goto-char (org-element-property :contents-begin element))
22006 (forward-char))
22007 ((memq (org-element-type element) org-element-greater-elements)
22008 ;; If contents are hidden, first disclose them.
22009 (when (org-element-property :hiddenp element) (org-cycle))
22010 (goto-char (or (org-element-property :contents-begin element)
22011 (error "No content for this element"))))
22012 (t (error "No inner element")))))
22014 (defun org-drag-element-backward ()
22015 "Move backward element at point."
22016 (interactive)
22017 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22018 (let* ((trail (org-element-at-point 'keep-trail))
22019 (elem (car trail))
22020 (prev-elem (nth 1 trail)))
22021 ;; Error out if no previous element or previous element is
22022 ;; a parent of the current one.
22023 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22024 (error "Cannot drag element backward")
22025 (let ((pos (point)))
22026 (org-element-swap-A-B prev-elem elem)
22027 (goto-char (+ (org-element-property :begin prev-elem)
22028 (- pos (org-element-property :begin elem)))))))))
22030 (defun org-drag-element-forward ()
22031 "Move forward element at point."
22032 (interactive)
22033 (let* ((pos (point))
22034 (elem (org-element-at-point)))
22035 (when (= (point-max) (org-element-property :end elem))
22036 (error "Cannot drag element forward"))
22037 (goto-char (org-element-property :end elem))
22038 (let ((next-elem (org-element-at-point)))
22039 (when (or (org-element-nested-p elem next-elem)
22040 (and (eq (org-element-type next-elem) 'headline)
22041 (not (eq (org-element-type elem) 'headline))))
22042 (goto-char pos)
22043 (error "Cannot drag element forward"))
22044 ;; Compute new position of point: it's shifted by NEXT-ELEM
22045 ;; body's length (without final blanks) and by the length of
22046 ;; blanks between ELEM and NEXT-ELEM.
22047 (let ((size-next (- (save-excursion
22048 (goto-char (org-element-property :end next-elem))
22049 (skip-chars-backward " \r\t\n")
22050 (forward-line)
22051 ;; Small correction if buffer doesn't end
22052 ;; with a newline character.
22053 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22054 (org-element-property :begin next-elem)))
22055 (size-blank (- (org-element-property :end elem)
22056 (save-excursion
22057 (goto-char (org-element-property :end elem))
22058 (skip-chars-backward " \r\t\n")
22059 (forward-line)
22060 (point)))))
22061 (org-element-swap-A-B elem next-elem)
22062 (goto-char (+ pos size-next size-blank))))))
22064 (defun org-mark-element ()
22065 "Put point at beginning of this element, mark at end.
22067 Interactively, if this command is repeated or (in Transient Mark
22068 mode) if the mark is active, it marks the next element after the
22069 ones already marked."
22070 (interactive)
22071 (let (deactivate-mark)
22072 (if (and (org-called-interactively-p 'any)
22073 (or (and (eq last-command this-command) (mark t))
22074 (and transient-mark-mode mark-active)))
22075 (set-mark
22076 (save-excursion
22077 (goto-char (mark))
22078 (goto-char (org-element-property :end (org-element-at-point)))))
22079 (let ((element (org-element-at-point)))
22080 (end-of-line)
22081 (push-mark (org-element-property :end element) t t)
22082 (goto-char (org-element-property :begin element))))))
22084 (defun org-narrow-to-element ()
22085 "Narrow buffer to current element."
22086 (interactive)
22087 (let ((elem (org-element-at-point)))
22088 (cond
22089 ((eq (car elem) 'headline)
22090 (narrow-to-region
22091 (org-element-property :begin elem)
22092 (org-element-property :end elem)))
22093 ((memq (car elem) org-element-greater-elements)
22094 (narrow-to-region
22095 (org-element-property :contents-begin elem)
22096 (org-element-property :contents-end elem)))
22098 (narrow-to-region
22099 (org-element-property :begin elem)
22100 (org-element-property :end elem))))))
22102 (defun org-transpose-element ()
22103 "Transpose current and previous elements, keeping blank lines between.
22104 Point is moved after both elements."
22105 (interactive)
22106 (org-skip-whitespace)
22107 (let ((end (org-element-property :end (org-element-at-point))))
22108 (org-drag-element-backward)
22109 (goto-char end)))
22111 (defun org-unindent-buffer ()
22112 "Un-indent the visible part of the buffer.
22113 Relative indentation (between items, inside blocks, etc.) isn't
22114 modified."
22115 (interactive)
22116 (unless (eq major-mode 'org-mode)
22117 (error "Cannot un-indent a buffer not in Org mode"))
22118 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22119 unindent-tree ; For byte-compiler.
22120 (unindent-tree
22121 (function
22122 (lambda (contents)
22123 (mapc
22124 (lambda (element)
22125 (if (memq (org-element-type element) '(headline section))
22126 (funcall unindent-tree (org-element-contents element))
22127 (save-excursion
22128 (save-restriction
22129 (narrow-to-region
22130 (org-element-property :begin element)
22131 (org-element-property :end element))
22132 (org-do-remove-indentation)))))
22133 (reverse contents))))))
22134 (funcall unindent-tree (org-element-contents parse-tree))))
22136 (defun org-show-subtree ()
22137 "Show everything after this heading at deeper levels."
22138 (interactive)
22139 (outline-flag-region
22140 (point)
22141 (save-excursion
22142 (org-end-of-subtree t t))
22143 nil))
22145 (defun org-show-entry ()
22146 "Show the body directly following this heading.
22147 Show the heading too, if it is currently invisible."
22148 (interactive)
22149 (save-excursion
22150 (condition-case nil
22151 (progn
22152 (org-back-to-heading t)
22153 (outline-flag-region
22154 (max (point-min) (1- (point)))
22155 (save-excursion
22156 (if (re-search-forward
22157 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22158 (match-beginning 1)
22159 (point-max)))
22160 nil)
22161 (org-cycle-hide-drawers 'children))
22162 (error nil))))
22164 (defun org-make-options-regexp (kwds &optional extra)
22165 "Make a regular expression for keyword lines."
22166 (concat
22167 "^#\\+\\("
22168 (mapconcat 'regexp-quote kwds "\\|")
22169 (if extra (concat "\\|" extra))
22170 "\\):[ \t]*\\(.*\\)"))
22172 ;; Make isearch reveal the necessary context
22173 (defun org-isearch-end ()
22174 "Reveal context after isearch exits."
22175 (when isearch-success ; only if search was successful
22176 (if (featurep 'xemacs)
22177 ;; Under XEmacs, the hook is run in the correct place,
22178 ;; we directly show the context.
22179 (org-show-context 'isearch)
22180 ;; In Emacs the hook runs *before* restoring the overlays.
22181 ;; So we have to use a one-time post-command-hook to do this.
22182 ;; (Emacs 22 has a special variable, see function `org-mode')
22183 (unless (and (boundp 'isearch-mode-end-hook-quit)
22184 isearch-mode-end-hook-quit)
22185 ;; Only when the isearch was not quitted.
22186 (org-add-hook 'post-command-hook 'org-isearch-post-command
22187 'append 'local)))
22188 (org-fix-ellipsis-at-bol)))
22190 (defun org-isearch-post-command ()
22191 "Remove self from hook, and show context."
22192 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22193 (org-show-context 'isearch))
22196 ;;;; Integration with and fixes for other packages
22198 ;;; Imenu support
22200 (defvar org-imenu-markers nil
22201 "All markers currently used by Imenu.")
22202 (make-variable-buffer-local 'org-imenu-markers)
22204 (defun org-imenu-new-marker (&optional pos)
22205 "Return a new marker for use by Imenu, and remember the marker."
22206 (let ((m (make-marker)))
22207 (move-marker m (or pos (point)))
22208 (push m org-imenu-markers)
22211 (defun org-imenu-get-tree ()
22212 "Produce the index for Imenu."
22213 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22214 (setq org-imenu-markers nil)
22215 (let* ((n org-imenu-depth)
22216 (re (concat "^" (org-get-limited-outline-regexp)))
22217 (subs (make-vector (1+ n) nil))
22218 (last-level 0)
22219 m level head0 head)
22220 (save-excursion
22221 (save-restriction
22222 (widen)
22223 (goto-char (point-max))
22224 (while (re-search-backward re nil t)
22225 (setq level (org-reduced-level (funcall outline-level)))
22226 (when (and (<= level n)
22227 (looking-at org-complex-heading-regexp)
22228 (setq head0 (org-match-string-no-properties 4)))
22229 (setq head (org-link-display-format head0)
22230 m (org-imenu-new-marker))
22231 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22232 (if (>= level last-level)
22233 (push (cons head m) (aref subs level))
22234 (push (cons head (aref subs (1+ level))) (aref subs level))
22235 (loop for i from (1+ level) to n do (aset subs i nil)))
22236 (setq last-level level)))))
22237 (aref subs 1)))
22239 (eval-after-load "imenu"
22240 '(progn
22241 (add-hook 'imenu-after-jump-hook
22242 (lambda ()
22243 (if (derived-mode-p 'org-mode)
22244 (org-show-context 'org-goto))))))
22246 (defun org-link-display-format (link)
22247 "Replace a link with either the description, or the link target
22248 if no description is present"
22249 (save-match-data
22250 (if (string-match org-bracket-link-analytic-regexp link)
22251 (replace-match (if (match-end 5)
22252 (match-string 5 link)
22253 (concat (match-string 1 link)
22254 (match-string 3 link)))
22255 nil t link)
22256 link)))
22258 (defun org-toggle-link-display ()
22259 "Toggle the literal or descriptive display of links."
22260 (interactive)
22261 (if org-descriptive-links
22262 (progn (org-remove-from-invisibility-spec '(org-link))
22263 (org-restart-font-lock)
22264 (setq org-descriptive-links nil))
22265 (progn (add-to-invisibility-spec '(org-link))
22266 (org-restart-font-lock)
22267 (setq org-descriptive-links t))))
22269 ;; Speedbar support
22271 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22272 "Overlay marking the agenda restriction line in speedbar.")
22273 (overlay-put org-speedbar-restriction-lock-overlay
22274 'face 'org-agenda-restriction-lock)
22275 (overlay-put org-speedbar-restriction-lock-overlay
22276 'help-echo "Agendas are currently limited to this item.")
22277 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22279 (defun org-speedbar-set-agenda-restriction ()
22280 "Restrict future agenda commands to the location at point in speedbar.
22281 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22282 (interactive)
22283 (require 'org-agenda)
22284 (let (p m tp np dir txt)
22285 (cond
22286 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22287 'org-imenu t))
22288 (setq m (get-text-property p 'org-imenu-marker))
22289 (with-current-buffer (marker-buffer m)
22290 (goto-char m)
22291 (org-agenda-set-restriction-lock 'subtree)))
22292 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22293 'speedbar-function 'speedbar-find-file))
22294 (setq tp (previous-single-property-change
22295 (1+ p) 'speedbar-function)
22296 np (next-single-property-change
22297 tp 'speedbar-function)
22298 dir (speedbar-line-directory)
22299 txt (buffer-substring-no-properties (or tp (point-min))
22300 (or np (point-max))))
22301 (with-current-buffer (find-file-noselect
22302 (let ((default-directory dir))
22303 (expand-file-name txt)))
22304 (unless (derived-mode-p 'org-mode)
22305 (error "Cannot restrict to non-Org-mode file"))
22306 (org-agenda-set-restriction-lock 'file)))
22307 (t (error "Don't know how to restrict Org-mode's agenda")))
22308 (move-overlay org-speedbar-restriction-lock-overlay
22309 (point-at-bol) (point-at-eol))
22310 (setq current-prefix-arg nil)
22311 (org-agenda-maybe-redo)))
22313 (eval-after-load "speedbar"
22314 '(progn
22315 (speedbar-add-supported-extension ".org")
22316 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22317 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22318 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22319 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22320 (add-hook 'speedbar-visiting-tag-hook
22321 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22323 ;;; Fixes and Hacks for problems with other packages
22325 ;; Make flyspell not check words in links, to not mess up our keymap
22326 (defun org-mode-flyspell-verify ()
22327 "Don't let flyspell put overlays at active buttons, or on
22328 {todo,all-time,additional-option-like}-keywords."
22329 (let ((pos (max (1- (point)) (point-min)))
22330 (word (thing-at-point 'word)))
22331 (and (not (get-text-property pos 'keymap))
22332 (not (get-text-property pos 'org-no-flyspell))
22333 (not (member word org-todo-keywords-1))
22334 (not (member word org-all-time-keywords))
22335 (not (member word org-options-keywords))
22336 (not (member word (mapcar 'car org-startup-options)))
22337 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22339 (defun org-remove-flyspell-overlays-in (beg end)
22340 "Remove flyspell overlays in region."
22341 (and (org-bound-and-true-p flyspell-mode)
22342 (fboundp 'flyspell-delete-region-overlays)
22343 (flyspell-delete-region-overlays beg end))
22344 (add-text-properties beg end '(org-no-flyspell t)))
22346 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22347 (eval-after-load "bookmark"
22348 '(if (boundp 'bookmark-after-jump-hook)
22349 ;; We can use the hook
22350 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22351 ;; Hook not available, use advice
22352 (defadvice bookmark-jump (after org-make-visible activate)
22353 "Make the position visible."
22354 (org-bookmark-jump-unhide))))
22356 ;; Make sure saveplace shows the location if it was hidden
22357 (eval-after-load "saveplace"
22358 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22359 "Make the position visible."
22360 (org-bookmark-jump-unhide)))
22362 ;; Make sure ecb shows the location if it was hidden
22363 (eval-after-load "ecb"
22364 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22365 "Make hierarchy visible when jumping into location from ECB tree buffer."
22366 (if (derived-mode-p 'org-mode)
22367 (org-show-context))))
22369 (defun org-bookmark-jump-unhide ()
22370 "Unhide the current position, to show the bookmark location."
22371 (and (derived-mode-p 'org-mode)
22372 (or (outline-invisible-p)
22373 (save-excursion (goto-char (max (point-min) (1- (point))))
22374 (outline-invisible-p)))
22375 (org-show-context 'bookmark-jump)))
22377 ;; Make session.el ignore our circular variable
22378 (eval-after-load "session"
22379 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22381 ;;;; Experimental code
22383 (defun org-closed-in-range ()
22384 "Sparse tree of items closed in a certain time range.
22385 Still experimental, may disappear in the future."
22386 (interactive)
22387 ;; Get the time interval from the user.
22388 (let* ((time1 (org-float-time
22389 (org-read-date nil 'to-time nil "Starting date: ")))
22390 (time2 (org-float-time
22391 (org-read-date nil 'to-time nil "End date:")))
22392 ;; callback function
22393 (callback (lambda ()
22394 (let ((time
22395 (org-float-time
22396 (apply 'encode-time
22397 (org-parse-time-string
22398 (match-string 1))))))
22399 ;; check if time in interval
22400 (and (>= time time1) (<= time time2))))))
22401 ;; make tree, check each match with the callback
22402 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22404 ;;;; Finish up
22406 (provide 'org)
22408 (run-hooks 'org-load-hook)
22410 ;;; org.el ends here